<?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 Duleep Alwis on Medium]]></title>
        <description><![CDATA[Stories by Duleep Alwis on Medium]]></description>
        <link>https://medium.com/@duleepalwis0?source=rss-545804491dfd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zAPPLSeyeywYldegW9_rGA.jpeg</url>
            <title>Stories by Duleep Alwis on Medium</title>
            <link>https://medium.com/@duleepalwis0?source=rss-545804491dfd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 17:30:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@duleepalwis0/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[Javascript | Hoisting Concept]]></title>
            <link>https://medium.com/@duleepalwis0/javascript-hoisting-concept-a218de91f582?source=rss-545804491dfd------2</link>
            <guid isPermaLink="false">https://medium.com/p/a218de91f582</guid>
            <category><![CDATA[hoisting]]></category>
            <category><![CDATA[javacript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript-hoisting]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Duleep Alwis]]></dc:creator>
            <pubDate>Sun, 12 Jul 2026 15:25:53 GMT</pubDate>
            <atom:updated>2026-07-12T15:25:53.583Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*95JdeJLzE6Guit-_zLUt-w.png" /></figure><p>Hi there… In this article I am going to explain a Javascript concept called <strong>Hoisting</strong>.</p><p>What is Hoisting?</p><ul><li>This is a mechanism related to declarations of variables, functions, and classes are conceptually moved to the top of their containing scope during the compilation phase. Because only declarations are hoisted (not assignments), you can use these elements before they are written in the code or assigning values in the code.</li><li>When we define variables, functions, classes there is a way to access them before initializing a value.</li></ul><p>Let see variable hoisting with var , let , const</p><pre>console.log(a);<br>var a = 1;<br><br>--&gt; Output -&gt; undefined. (No errors)<br><br>What happens internally.<br><br>var a; //hoisted declaration.<br>console.log(a); //undefined<br>a = 1 //Initialization happens later<br><br>----------------------------------------------<br>console.log(b);<br>let b = 1;<br><br>---&gt; Output -&gt; ReferenceError: b is not defined </pre><ul><li><strong>var:</strong> Hoisted to the top of its scope and initialized with a default value of undefined. If you log the variable before its declaration line, it will return undefined rather than throwing an error.</li><li><strong>let &amp; </strong><strong>const:</strong> Hoisted to the top of their scope but <em>not</em> initialized. They enter a <a href="https://www.geeksforgeeks.org/javascript/javascript-hoisting/">Temporal Dead Zone (TDZ)</a> and will throw a ReferenceError if you try to access them before their declaration line is executed.</li></ul><p>Now let’s see functional hoisting with var, let ,const…</p><pre>sayHi();<br>var sayHi = function(){<br>  console.log(&quot;Say Hi&quot;);<br>}<br><br>//This will say sayHi() is not a function because Function expression Hoisting<br>//Not fully hoisted.<br><br>---------------------------------------------------------------<br><br>sayHiHi();<br>function sayHiHi(){<br>  console.log(&quot;Say Hi Hi&quot;);<br>}<br><br>//This works because this is Function Declaration Hoisting (Fully Hoisted)<br><br>Internally <br><br>function sayHiHi(){<br>  console.log(&quot;Say Hi Hi&quot;);<br>}<br><br>sayHiHi();<br><br>//Entire function definition is hoisted.<br><br>-----------------------------------------------------------------<br><br>For let , const<br><br>sayLet();<br><br>let sayLet = function(){<br>  console.log(&quot;Hi sayLet&quot;);<br>}<br><br>---&gt; This will give this | ReferenceError: Cannot access <br>---&gt; &#39;sayLet&#39; before initialization<br><br></pre><p>So hoisting concept is a very important concept in Javascript . When writing codes in large javascript code bases , you will have to keep this in mind.</p><p>Let’s meetup in a another article … Until then happy coding with JS.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a218de91f582" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Headless Java rendering]]></title>
            <link>https://towardsdev.com/headless-java-rendering-64f07b44ac4f?source=rss-545804491dfd------2</link>
            <guid isPermaLink="false">https://medium.com/p/64f07b44ac4f</guid>
            <category><![CDATA[excel]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[headless-java-rendering]]></category>
            <dc:creator><![CDATA[Duleep Alwis]]></dc:creator>
            <pubDate>Mon, 16 Jun 2025 15:51:31 GMT</pubDate>
            <atom:updated>2025-07-28T16:33:14.287Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi all, today I am going to write about an issue I met when I was trying to generate a excel sheet in a spring boot app which runs inside a docker container.</p><p>When I try to generate the xsel sheet from the spring boot app which runs inside of a docker container it gave me this error ,</p><p><em>java.lang.RuntimeException: Fontconfig head is null, check your fonts or fonts configuration</em></p><p>When I executed the spring boot app locally without building the docker image and the container it generated the excel sheet, but when I try it with docker container it didn’t and gave me the above error.</p><p>For this my conclusion was it might happen because we have not installed the needed fonts inside the docker container. In the research of this I found this error called “<strong>Headless Java rendering</strong>” . Let’s see what is this,</p><p>Java normally relies on the <strong>Abstract Window Toolkit (AWT) </strong>or <strong>Swing </strong>for rendering graphics, fonts, images and GUIs. But in environments like servers or containers like Docker where there is no display or GUI , Java runs in <strong>headless mode</strong>, which means,</p><ul><li>There is no screen</li><li>No mouse/keyboard interaction</li><li>No system font or UI components loaded by default.</li></ul><p>This happens when you try to generate ,</p><ul><li>Images (ex.:- captchas, charts)</li><li>PDFs (with embedded fonts)</li><li>Excel with grpahical content</li><li>Anything using Graphics2D in memory.</li></ul><p>Since we were trying to create sheets in the workbook created using apache poi library in the code we called a method called <strong>autoSizeColumn() </strong>which uses Java AWT’s FontMetrics and Graphics2D internally to measure the width of the text, so it requires graphical (non-headless) environment with fonts installed.</p><p>Therefore when running headless mode (Docker , Linux server) when fonts are missing you get the above error.</p><p>Therefor my solution was to install required fonts inside the docker container . This is how it can be done in the DockerFile of the spring boot project.</p><p>We were using <strong>amazoncorretto:21.0.4-alpine </strong>this base image for creating the docker image, therefore our package manager for this will be <strong>apk.</strong></p><pre># Use Alpine-based Amazon Corretto (Java 21)<br>FROM amazoncorretto:21.0.4-alpine<br><br># Install system fonts for AWT, POI, iText, etc.<br>RUN apk add --no-cache \<br>    fontconfig \<br>    ttf-dejavu \<br>    &amp;&amp; fc-cache -fv<br><br># Set headless mode to avoid AWT GUI errors in POI/iText<br>ENV JAVA_TOOL_OPTIONS=&quot;-Djava.awt.headless=true&quot;<br><br># Create directory for the app<br>WORKDIR /app<br><br># Copy the Spring Boot JAR<br>COPY target/your-app.jar app.jar<br><br># Run the app<br>ENTRYPOINT [&quot;java&quot;, &quot;-jar&quot;, &quot;app.jar&quot;]</pre><p>With this kind of solution we were able to fix the issue and generate the excel sheet successfully.</p><p>You better try this in your local machine and get the experience of this. I will meet you with another article like this next time. Until then enjoy your life………</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64f07b44ac4f" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/headless-java-rendering-64f07b44ac4f">Headless Java rendering</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL query optimization techniques]]></title>
            <link>https://towardsdev.com/sql-query-optimization-techniques-c16efe2bfde0?source=rss-545804491dfd------2</link>
            <guid isPermaLink="false">https://medium.com/p/c16efe2bfde0</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[query-optimization]]></category>
            <category><![CDATA[rdbms]]></category>
            <category><![CDATA[index]]></category>
            <dc:creator><![CDATA[Duleep Alwis]]></dc:creator>
            <pubDate>Sun, 15 Jun 2025 09:44:47 GMT</pubDate>
            <atom:updated>2025-07-21T19:10:34.804Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi there today I am going to write about SQL queries and how we can optimize them. This is a crucial topic for software engineers who work in the backend side of a project which include lot of work with database.</p><p><strong>Using indexes.</strong></p><p>When we create tables, it is better to create indexes on frequently queried columns.</p><p>Indexes use separate look up tables. Hence for write, update, delete operations it has 2 operations, having new values. They have to update the relevant table and at the same time update the lookup table. Therefor we don’t create indexes for frequently updating columns.</p><p>We create indexes for ,</p><ul><li>Columns which are frequently used in search.</li><li>Columns which are used to join tables.</li><li>Values which use short length data types.</li></ul><p>We don’t create indexes for columns such as,</p><ul><li>Which has low cardinality. Less value such as {true, false}.</li><li>Frequently updating columns.</li><li>High length data types.</li></ul><p><strong>Remove * from queries. Instead specify the columns you need in the query.</strong></p><p><em>“Select * from employee_tb</em>” is slower compared to “<em>Select name, age from employee_tb</em>”</p><p><strong>Using inner queries before joining them.</strong></p><p>In this method we can filter results before joining them. Otherwise filtering happens on joined table. Before that we can sort the result list based on the where condition values.</p><pre>SELECT e.first_name,e.salary,d.name FROM employee_tb e INNER JOIN department_tb d ON e.department=d.id WHERE e.salary&gt;200000</pre><p>above query is slower compared to the below query,</p><pre>SELECT e.first_name,e.salary,d.name FROM (SELECT first_name,salary,department FROM employee_tb WHERE salary&gt;200000) e INNER JOIN department_tb d ON e.department=d.id</pre><p>Below query is faster compared to above both,</p><pre>WITH filtered_emps AS (SELECT * FROM employee_tb WHERE salary&gt;200000) SELECT e.first_name,e.salary,d.name FROM department_tb d INNER JOIN filtered_emps e ON e.department = d.id;</pre><p>Like this we can optimize a query.</p><p>If you want to check the query plan use this <strong>EXPLAIN ANALYZE</strong> command in front of your query.</p><pre>EXPLAIN ANALYZE WITH filtered_emps AS (SELECT * FROM employee_tb WHERE salary&gt;200000) SELECT e.first_name,e.salary,d.name FROM department_tb d <br>INNER JOIN filtered_emps e ON E.department = d.id;</pre><p>Below I will give you a simple python code I used to feed data to a database and do these examples. With that you can try this alone.</p><pre>import mysql.connector<br>import random<br><br>#This application is for seed data into the comapny_db mysql database<br># Create a connection<br>conn = mysql.connector.connect(<br>    host=&quot;localhost&quot;,      # or your DB host<br>    user=&quot;user1&quot;,           # your DB username<br>    password=&quot;user1&quot;,  # your DB password<br>    database=&quot;company&quot;     # your DB name<br>)<br><br># Create a cursor object<br>cursor = conn.cursor()<br><br>#Departments<br>departments = [<br>    {&quot;id&quot;:4,&quot;name&quot;:&quot;Engineering&quot;,&quot;location&quot;:&quot;New Building&quot;},<br>    {&quot;id&quot;:5,&quot;name&quot;:&quot;Financial&quot;,&quot;location&quot;:&quot;3rd floor&quot;},<br>    {&quot;id&quot;:6,&quot;name&quot;:&quot;Marketing&quot;,&quot;location&quot;:&quot;4th floor&quot;},<br>    {&quot;id&quot;:7,&quot;name&quot;:&quot;Admin&quot;,&quot;location&quot;:&quot;5th floor&quot;},<br>    {&quot;id&quot;:8,&quot;name&quot;:&quot;Legal&quot;,&quot;location&quot;:&quot;7th floor&quot;}<br>]<br><br>districts = [&quot;Colombo&quot;,&quot;Gampaha&quot;,&quot;Kaluthara&quot;,&quot;Galle&quot;,&quot;Mathara&quot;]<br>city = [&quot;Wellawatha&quot;,&quot;Ramboda&quot;,&quot;Panadura&quot;,&quot;Dehiwala&quot;,&quot;Bambalapitiya&quot;]<br>address = [&quot;A&quot;,&quot;B&quot;,&quot;C&quot;,&quot;D&quot;,&quot;E&quot;]<br><br>def create_deps():<br>    sql = &quot;INSERT INTO department_tb(id,name,location) values(%s,%s,%s);&quot;<br>    for d in departments:<br>        values = (d[&#39;id&#39;],d[&#39;name&#39;],d[&#39;location&#39;]);<br>        cursor.execute(sql,values)<br>        conn.commit()<br><br>    print(f&quot;{cursor.rowcount} Department records inserted&quot;)<br><br><br>def create_users():<br>    sql = &quot;INSERT INTO employee_tb(first_name,last_name,salary,address,city,district,department,manager) values(%s,%s,%s,%s,%s,%s,%s,%s)&quot;<br><br>    for m in range(1,6):<br>        num = random.randint(1, 5)<br>        <br>        <br>        values = (&quot;Head-&quot;+str(m),&quot;Dep&quot;,50000*(num),address[num-1]+&quot;-&quot;+str(m),city[num-1],<br>                  districts[num-1],num+3,None)<br>        cursor.execute(sql,values)<br>        #conn.commit()<br><br>    print(f&quot;{cursor.rowcount} Managers records inserted&quot;)<br><br>    sql = &quot;INSERT INTO employee_tb(first_name,last_name,salary,address,city,district,department,manager) values(%s,%s,%s,%s,%s,%s,%s,%s)&quot;<br>    for m in range(1,1000):<br>        num = random.randint(0, 4)<br>        man = random.randint(1,5)<br>        print(num)<br>        values = (&quot;EMP-&quot;+str(m),&quot;Employee&quot;,50000*(num+1),address[num]+&quot;-&quot;+str(m),city[num],<br>                  districts[num],num+4,man)<br>        cursor.execute(sql,values)<br>        #conn.commit()<br><br>    print(f&quot;{cursor.rowcount} Employee records inserted&quot;)<br><br>create_deps()<br>create_users()<br>conn.commit()</pre><p>Thank you !!! I will come with a new article next time. Until then enjoy your life.!!!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c16efe2bfde0" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/sql-query-optimization-techniques-c16efe2bfde0">SQL query optimization techniques</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Patterns — Part 1]]></title>
            <link>https://towardsdev.com/design-patterns-part-1-1f138a1480e1?source=rss-545804491dfd------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f138a1480e1</guid>
            <category><![CDATA[best-practice-programming]]></category>
            <category><![CDATA[core-java]]></category>
            <category><![CDATA[strategy-design-pattern]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[design-pattern-in-java]]></category>
            <dc:creator><![CDATA[Duleep Alwis]]></dc:creator>
            <pubDate>Sat, 12 Apr 2025 19:02:47 GMT</pubDate>
            <atom:updated>2025-07-28T16:27:14.883Z</atom:updated>
            <content:encoded><![CDATA[<h3>Design Patterns — Part 1</h3><p>Strategy design pattern</p><p>Today I am going to start a new article series on design patterns in software engineering and their implementation with java.</p><p>Here I am going to talk about strategy design pattern.</p><p>Have a look on this diagram,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*JLWh4ViZKtgc32wXHZn_3w.png" /><figcaption>image 1.0</figcaption></figure><p>In strategy design pattern a class or algorithm’s behavior can be changed in the runtime. This kind of design patterns come under behavior design patterns.</p><p>Here we create a common interface for both the service class which send email and sms. After that we implement the service respectively, their implementation differs based on the class. Context is a solid java class and it decides what is the service should be implemented based on the variable set in the constructor injection.</p><p>Below is the code for this,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*lUfxoyoO0jgpcYCjlyKCyQ.png" /></figure><pre>public interface NotificationService{<br><br>    public void sendNotification(String to,String message);<br>}<br><br>public class EmailService implements NotificationService{<br>    @Override<br>    public void sendNotification(String to, String message) {<br>        System.out.println(&quot;***********Email notification***************&quot;);<br>        System.out.println(to+&quot; MSG : &quot;+message);<br>    }<br>}<br><br>public class SMSService implements NotificationService{<br>    @Override<br>    public void sendNotification(String to, String message) {<br>        System.out.println(&quot;***********Sms notification***************&quot;);<br>        System.out.println(to+&quot; MSG : &quot;+message);<br>    }<br>}<br><br><br>public class Context {<br><br>    private final NotificationService notificationService;<br><br>    public Context(final NotificationService notificationService){<br>        this.notificationService = notificationService;<br>    }<br><br>    public void sendNotification(String to,String message){<br>        this.notificationService.sendNotification(to,message);<br>    }<br>}<br>public class DesignPatterns{<br><br>  public static void main(String [] args){<br>    strategyDesignPattern();<br>  }<br>  <br>  public static void strategyDesignPattern(){<br><br>        System.out.println(&quot;======Strategy Design pattern=======&quot;);<br><br>        String toEmail = &quot;kasun@gmail.com&quot;;<br>        String messageEmail = &quot;Notification is an email&quot;;<br><br>        Context context = new Context(new EmailService());<br>        context.sendNotification(toEmail,messageEmail);<br>        System.out.println(&quot;=============================&quot;);<br><br>        String smsNumber = &quot;0712346789&quot;;<br>        String messageSms = &quot;Notification is a sms&quot;;<br><br>        Context context1 = new Context(new SMSService());<br>        context1.sendNotification(smsNumber,messageSms);<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f138a1480e1" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/design-patterns-part-1-1f138a1480e1">Design Patterns — Part 1</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Essential Linux Snacks: Must-Know Commands for Every Developer’s Toolkit and some bash scripts]]></title>
            <link>https://towardsdev.com/essential-linux-snacks-must-know-commands-for-every-developers-toolkit-and-some-bash-scripts-221714298966?source=rss-545804491dfd------2</link>
            <guid isPermaLink="false">https://medium.com/p/221714298966</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[bash-scripting]]></category>
            <category><![CDATA[commands]]></category>
            <category><![CDATA[ubuntu]]></category>
            <dc:creator><![CDATA[Duleep Alwis]]></dc:creator>
            <pubDate>Sun, 17 Nov 2024 07:31:48 GMT</pubDate>
            <atom:updated>2025-07-28T16:33:05.721Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*klpTvR6MXoGyKpqfCPC-Uw.png" /></figure><p><strong>ls </strong>command :- This list down all the files and directories in the current location.</p><p>There are optional flags we could pass for this command,</p><ul><li>-a :- list down all the files , directories and hidden files in the current location.</li><li>-l :- Long listing of the files with their inner details such as permissions.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ke8YQA2769dJowwWRkHU1w.png" /></figure><p><strong>pwd </strong>command :- This prints the current working directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*d1HFh1dbECrmIZaPYestuA.png" /></figure><p><strong>cd </strong>&lt;path&gt; command :- This command change the directory we currently in and move to the directory we want to go.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*tVeIomahZTeammIu5MUiZg.png" /></figure><p><strong>mkdir &lt;directory_name&gt; </strong>command :- This will create a new directory in the current location with the given name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*2MjJ9roq9YU9VWZ3UAxfiQ.png" /></figure><p><strong>nano </strong>&lt;file_name&gt; command :- nano is a command line editor used in linux. We can open this editor with this command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*1z1H47sLKzTQhjA8894umA.png" /></figure><p><strong>cp &lt;file_name&gt; &lt;destination_folder&gt; / cp -r &lt;directory_name&gt; &lt;destination folder&gt;</strong>:- This cp command will copy paste the given file or directory to the destination path. For a directroy we should use -r flag. The option<strong> -r</strong> stands for <strong>recursive</strong>. It tells <strong>cp</strong> to copy directories and their contents recursively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*4YgikHD573wRXvouzU6RmA.png" /></figure><p><strong>mv &lt;file_name&gt; &lt;destination_path&gt; / mv &lt;directory_name&gt; &lt;destination_path&gt;:- </strong>This command will move or as in windows cut paste the source to destination path.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*Errs0nrU25BwN2ONBMdjVA.png" /></figure><p>There is another use case of this command.</p><p><strong>mv &lt;current_file_name&gt; &lt;new_file_name&gt; :- </strong>This use case of this mv command it will rename the file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*M_kL9WBEuSy4TC2pVROfSA.png" /></figure><p><strong>chmod +x &lt;file_name&gt; :- </strong>This command will give executable permission to a file. We can execute that file with <strong>./file_name </strong>in linux.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*vU-Bf09Ray0FAhD-FXdj5Q.png" /></figure><p><strong>rm &lt;file_name&gt; / rm -r &lt;directory_name&gt;</strong> :- This rm command will delete the file or the directory. The <strong>-r </strong>flag stands for recursive when deleting a directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*9Q-gSb5YfJ5j8FECshFegA.png" /></figure><p>Now let’s move in to some file handling linux commands.</p><p><strong>touch &lt;file_name&gt; :- </strong>This command will create an empty file in the current location or updates the timestamp of an existing file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*IZTfT81QYvT0la6uh8f6Jw.png" /></figure><p><strong>cat &lt;file_name&gt; :- </strong>This command will print the content of the file given in the terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*Luo-SimPIyFlplFGh09Beg.png" /></figure><p><strong>echo “text”</strong> :- Rewriting a file or appending a new line to file through command line can be done with this command.</p><p>echo “text” &gt; test1.txt :- Rewrite the test1.txt with string “text”</p><p>echo “text” &gt;&gt; test1.txt :- Append the string “text” to the test1.txt file as a new line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*GHtN2SptqjvLTGrq3_ecrA.png" /></figure><p><strong>cat &lt;source_file_name&gt; &gt; &lt;destination_file_name&gt; :- </strong>This command will rewrite the destination file with the content of the source file content.</p><p><strong>cat &lt;source_file_name&gt; &gt;&gt; &lt;destination_file_name&gt; :- </strong>This command will append the content of the source file to the destination file .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*12tj5uEJ6rZlRPuTKOifjA.png" /></figure><p><strong>less</strong> command :- This command is used with the cat command using the pipe (|) operator. The <strong>less </strong>command is used when the output printed by any command is larger than the screen space and needs scrolling. The <strong>less </strong>command allows the user to break down the output and scroll through it with the use of the enter or space keys. Here there some flags we can use with this <strong>less </strong>command.<strong> -N </strong>is such a flag. We can have the content of the file with line numbers with this command.</p><pre>/Documents/linux_notes$ cat /boot/grub/grub.cfg | less<br>/Documents/linux_notes$ cat /boot/grub/grub.cfg | less -N</pre><p><strong>head</strong> and <strong>tail</strong> commands :- These commands will output the first 10 lines by default(head) and last 10 lines by default(tail) in the console. We can use <strong>-n </strong>flag with number of lines we want to get the number of lines we want.</p><pre>~/Documents/linux_notes$ head /boot/grub/grub.cfg<br>~/Documents/linux_notes$ tail /boot/grub/grub.cfg<br>~/Documents/linux_notes$ head /boot/grub/grub.cfg -n 20<br>~/Documents/linux_notes$ tail /boot/grub/grub.cfg -n 20</pre><p>These head and tail commands are very important when reading log files in linux servers. Since they contain very large content.</p><p>How to find a specific string in a file or a in a output given by a command.</p><p><strong>grep</strong> command we can use for this purpose with the <strong>pipe(|) </strong>operator.</p><p>Here are few examples of it.</p><pre>cat test1.txt | grep &#39;Hello&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*sWduiXAtLOAh_chfkB_WbQ.png" /><figcaption>The above command will search the ‘Hello’ string in the content of the file</figcaption></figure><pre>ps -ef | grep &#39;java&#39;<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SFy2sVyoSLJaQTqKzxEMOQ.png" /><figcaption>The above command will search the ‘java’ string in the processes list with the ps -ef command.</figcaption></figure><p>Now I will show you some sample bash scripts , how to write them.</p><pre>!/bin/bash <br> <br>  <br> <br>echo -n &quot;Enter the first number : &quot; <br>read num1 <br>echo -n &quot;Enter the second number : &quot; <br> <br>read num2 <br> <br>sum=`expr $num1 + $num2` <br>echo &quot;sum of two value is $sum&quot; </pre><p>This bash script is to get the 2 numbers from the console as inputs and print the result of the sum of it in the console. Save this file as &lt;file_name&gt;.sh and use this command to run it .<strong> ./&lt;file_name&gt;.sh</strong></p><p>I have shown in the above how to make this kind of file executable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*jgBKLIsCXNj1s8KLbp1Wvg.png" /></figure><pre>#!/bin/bash<br><br># List all processes, sort by memory usage in ascending order, exclude processes with [ ] in their name<br>process=$(ps aux --sort=+%mem | awk &#39;NR &gt; 1 &amp;&amp; $11 !~ /\[.*\]/ {print $2, $11; exit}&#39;)<br><br><br>if [ -n &quot;$process&quot; ]; then<br>  echo &quot;User-level process with the least RAM usage:&quot;<br>  echo &quot;PID   Process Name&quot;<br>  echo &quot;$process&quot;<br>else<br>  echo &quot;No user-level processes found.&quot;<br>fi</pre><p>This bash script will output the process with the least ram usage. It excludes all the kernal level threads. The output I got for this is a system service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*qvIm-uhU_tGtIDFFvVkyJw.png" /></figure><p>The line <strong>#!/bin/bash</strong> at the top of a Bash script is called a <strong>shebang</strong> or <strong>hashbang</strong>. It’s used to tell the operating system which interpreter to use to execute the script.</p><p>I think this content is enough for this article. I will come up with another linux and bash scripting article on another day. Until then have a pleasant time!.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=221714298966" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/essential-linux-snacks-must-know-commands-for-every-developers-toolkit-and-some-bash-scripts-221714298966">Essential Linux Snacks: Must-Know Commands for Every Developer’s Toolkit and some bash scripts</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring boot security with JWT Token — Article 2]]></title>
            <link>https://medium.com/@duleepalwis0/spring-boot-security-with-jwt-token-article-2-b5ea8ffabeef?source=rss-545804491dfd------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5ea8ffabeef</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[spring-security]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Duleep Alwis]]></dc:creator>
            <pubDate>Sat, 16 Nov 2024 18:07:20 GMT</pubDate>
            <atom:updated>2024-11-16T18:08:45.208Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Spring boot security with JWT Token — Article 2</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W_F0JtMSmN8GaQL552OeJQ.png" /></figure><p>Hi all, in my last article about spring boot security I wrote about what is Jwt token , parts of it and it’s use cases. Today I am going to write about how the jwt token creation happens , cors configuration and how the jwt validation happens and how it allows certain services, with code examples and diagrams . I am using Java 17, Spring boot version 3.3.1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rhuCRpsBvcet9Xn3Ecjh3w.png" /><figcaption>Seqeuence diagram for jwt and cors</figcaption></figure><p>Above is the sequence diagram for jwt authentication and cors validation. I hope you could get a clear idea of it with the above image.</p><p>Now I will give you the needed java code samples for this.</p><p>For this you need to create a spring boot project with above versions.</p><p>Add these dependencies to your pom.xml file.</p><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-security&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br>&lt;dependency&gt;<br>   &lt;groupId&gt;io.jsonwebtoken&lt;/groupId&gt;<br>   &lt;artifactId&gt;jjwt-api&lt;/artifactId&gt;<br>   &lt;version&gt;0.11.5&lt;/version&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;io.jsonwebtoken&lt;/groupId&gt;<br>   &lt;artifactId&gt;jjwt-impl&lt;/artifactId&gt;<br>   &lt;version&gt;0.11.5&lt;/version&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;io.jsonwebtoken&lt;/groupId&gt;<br>   &lt;artifactId&gt;jjwt-jackson&lt;/artifactId&gt;<br>   &lt;version&gt;0.11.5&lt;/version&gt;<br>  &lt;/dependency&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*A3uqcQm_TbFGLTidtORZbg.png" /><figcaption>Create a config package and have these classes there.</figcaption></figure><p>In the AppConfig.java class have this code. Here <strong>UserService </strong>class is service layer class which has the method <strong>getUserByEmail(String email)</strong>. This method queries the database and check whether the user exists.</p><pre>package com.school.studentms.config;<br><br>import com.school.studentms.dto.UserDTO;<br>import com.school.studentms.exception.ResourceNotFound;<br>import com.school.studentms.service.UserService;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br>import org.springframework.security.core.userdetails.UserDetailsService;<br><br>@Configuration<br>public class AppConfig {<br><br>    @Autowired<br>    private UserService userService;<br><br>    @Bean<br>    public UserDetailsService userDetailsService() throws ResourceNotFound {<br>        return username -&gt; {<br>            // Load user details from the database<br>            // This is just an example; replace it with your actual User repository logic<br>            UserDTO user = userService.getUserByEmail(username);<br>            if (user == null) {<br>                throw new ResourceNotFound(&quot;User not found&quot;);<br>            }<br>            return user;<br><br>        };<br>    }<br>}</pre><p>In the JwtAuthenticationFilter.java class have this code.</p><pre>package com.school.studentms.config;<br><br>import java.io.IOException;<br><br>import org.apache.logging.log4j.LogManager;<br>import org.apache.logging.log4j.Logger;<br>import org.springframework.lang.NonNull;<br>import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;<br>import org.springframework.security.core.Authentication;<br>import org.springframework.security.core.context.SecurityContextHolder;<br>import org.springframework.security.core.userdetails.UserDetails;<br>import org.springframework.security.core.userdetails.UserDetailsService;<br>import org.springframework.stereotype.Component;<br>import org.springframework.web.filter.OncePerRequestFilter;<br>import org.springframework.web.servlet.HandlerExceptionResolver;<br><br>import jakarta.servlet.FilterChain;<br>import jakarta.servlet.ServletException;<br>import jakarta.servlet.http.HttpServletRequest;<br>import jakarta.servlet.http.HttpServletResponse;<br><br>@Component<br>public class JwtAuthenticationFilter extends OncePerRequestFilter {<br>    private final HandlerExceptionResolver handlerExceptionResolver;<br><br>    private static final Logger logger = LogManager.getLogger(JwtAuthenticationFilter.class);<br><br>    private final JwtService jwtService;<br>    private final UserDetailsService userDetailsService;<br><br>    public JwtAuthenticationFilter(<br>        JwtService jwtService,<br>        UserDetailsService userDetailsService,<br>        HandlerExceptionResolver handlerExceptionResolver<br>    ) {<br>        this.jwtService = jwtService;<br>        this.userDetailsService = userDetailsService;<br>        this.handlerExceptionResolver = handlerExceptionResolver;<br>    }<br><br>    @Override<br>    protected void doFilterInternal(<br>        @NonNull HttpServletRequest request,<br>        @NonNull HttpServletResponse response,<br>        @NonNull FilterChain filterChain<br>    ) throws ServletException, IOException {<br><br>        try {<br><br><br>            String authorizationHeader = request.getHeader(&quot;Authorization&quot;);<br>            String token = null;<br>            String username = null;<br><br>            if (authorizationHeader != null &amp;&amp; authorizationHeader.startsWith(&quot;Bearer &quot;)) {<br>                token = authorizationHeader.substring(7);<br>                username = jwtService.extractUsername(token);<br>            }<br><br><br>            logger.info(&quot;Auth point hits User name and token {}&quot;, username);<br><br>            if (username != null &amp;&amp; SecurityContextHolder.getContext().getAuthentication() == null) {<br>                UserDetails userDetails = userDetailsService.loadUserByUsername(username);<br><br>                if (jwtService.isTokenValid(token, userDetails)) {<br>                    UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(<br>                            userDetails, null, userDetails.getAuthorities());<br>                    SecurityContextHolder.getContext().setAuthentication(authToken);<br>                }<br>            }<br>        } catch (Exception ex) {<br>            logger.error(ex.getMessage());<br>        }<br>        filterChain.doFilter(request, response);<br>    }<br><br>}</pre><p>In the above code there is some important parts to explain. Check out the below screen shot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*NEajDJWM91UaA8H-AOm-Vw.png" /></figure><p>Here’s what each part does:</p><ol><li><strong>if (username != null &amp;&amp; SecurityContextHolder.getContext().getAuthentication() == null)</strong>:</li></ol><p>This checks if:</p><ul><li>A valid username was extracted from the JWT token (username != null).</li><li>There is no existing authentication in the SecurityContext (SecurityContextHolder.getContext().getAuthentication() == null). This ensures that you’re not overwriting an existing authentication, which can avoid redundancy or conflicts.</li></ul><p>2.<strong>UserDetails userDetails = userDetailsService.loadUserByUsername(username);</strong>:</p><ul><li>Loads the user details from the UserDetailsService implementation using the username. This allows the application to fetch user-specific details, such as roles and authorities, to set up authorization correctly.</li></ul><p>3.<strong>if (jwtService.isTokenValid(token, userDetails))</strong>:</p><ul><li>Checks if the JWT token is valid for the given user details. This usually includes verifying that the token is correctly signed, has not expired, and matches the username and roles.</li></ul><p>4.<strong>UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(...)</strong>:</p><ul><li>Creates an UsernamePasswordAuthenticationToken object, which represents the authenticated user with credentials (null here since no password is used at this stage) and authorities (user roles and permissions from userDetails.getAuthorities()).</li><li>This token is what Spring Security uses internally to represent authenticated users.</li></ul><p>5.<strong>SecurityContextHolder.getContext().setAuthentication(authToken);</strong>:</p><ul><li>Sets the authToken in the SecurityContext, which makes the authenticated user available throughout the current request.</li><li>Once set, Spring Security will consider the request authenticated, and any secured endpoints will use this authentication to check authorization.</li></ul><p>6.<strong>filterChain.doFilter(request, response);</strong>:</p><ul><li>Passes control to the next filter in the chain (if any) or to the target endpoint if it’s the last filter.</li><li>This is required to allow the request to proceed after the JWT processing.</li></ul><p>In the JwtService.java class have this code,</p><pre>package com.school.studentms.config;<br><br>import java.security.Key;<br>import java.util.Date;<br>import java.util.HashMap;<br>import java.util.Map;<br>import java.util.function.Function;<br><br>import org.springframework.beans.factory.annotation.Value;<br>import org.springframework.security.core.userdetails.UserDetails;<br>import org.springframework.stereotype.Service;<br><br>import io.jsonwebtoken.Claims;<br>import io.jsonwebtoken.Jwts;<br>import io.jsonwebtoken.SignatureAlgorithm;<br>import io.jsonwebtoken.io.Decoders;<br>import io.jsonwebtoken.security.Keys;<br><br>@Service<br>public class JwtService {<br><br>  @Value(&quot;${security.jwt.secret-key}&quot;)<br>     private String secretKey;<br><br>     @Value(&quot;${security.jwt.expiration-time}&quot;)<br>     private long jwtExpiration;<br><br>     public String extractUsername(String token) {<br>         return extractClaim(token, Claims::getSubject);<br>     }<br><br>     public &lt;T&gt; T extractClaim(String token, Function&lt;Claims, T&gt; claimsResolver) {<br>         final Claims claims = extractAllClaims(token);<br>         return claimsResolver.apply(claims);<br>     }<br><br>     public String generateToken(UserDetails userDetails) {<br>         return generateToken(new HashMap&lt;&gt;(), userDetails);<br>     }<br><br>     public String generateToken(Map&lt;String, Object&gt; extraClaims, UserDetails userDetails) {<br>         return buildToken(extraClaims, userDetails, jwtExpiration);<br>     }<br><br>     public long getExpirationTime() {<br>         return jwtExpiration;<br>     }<br><br>     private String buildToken(<br>             Map&lt;String, Object&gt; extraClaims,<br>             UserDetails userDetails,<br>             long expiration<br>     ) {<br>         return Jwts<br>                 .builder()<br>                 .setClaims(extraClaims)<br>                 .setSubject(userDetails.getUsername())<br>                 .setIssuedAt(new Date(System.currentTimeMillis()))<br>                 .setExpiration(new Date(System.currentTimeMillis() + expiration))<br>                 .signWith(getSignInKey(), SignatureAlgorithm.HS256)<br>                 .compact();<br>     }<br><br>     public boolean isTokenValid(String token, UserDetails userDetails) {<br>         final String username = extractUsername(token);<br>         return (username.equals(userDetails.getUsername())) &amp;&amp; !isTokenExpired(token);<br>     }<br><br>     private boolean isTokenExpired(String token) {<br>         return extractExpiration(token).before(new Date());<br>     }<br><br>     private Date extractExpiration(String token) {<br>         return extractClaim(token, Claims::getExpiration);<br>     }<br><br>     private Claims extractAllClaims(String token) {<br>         return Jwts<br>                 .parserBuilder()<br>                 .setSigningKey(getSignInKey())<br>                 .build()<br>                 .parseClaimsJws(token)<br>                 .getBody();<br>     }<br><br>     private Key getSignInKey() {<br>         byte[] keyBytes = Decoders.BASE64.decode(secretKey);<br>         return Keys.hmacShaKeyFor(keyBytes);<br>     }<br>}</pre><p>In SecurityConfig.java class have this code,</p><pre>package com.school.studentms.config;<br><br>import com.school.studentms.constants.RestEndPoints;<br>import com.school.studentms.dto.UserDTO;<br>import com.school.studentms.exception.ResourceNotFound;<br>import com.school.studentms.service.UserService;<br>import jakarta.annotation.Resource;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.beans.factory.annotation.Value;<br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br>import org.springframework.security.authentication.AuthenticationManager;<br>import org.springframework.security.authentication.dao.DaoAuthenticationProvider;<br>import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;<br>import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;<br>import org.springframework.security.config.annotation.web.builders.HttpSecurity;<br>import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;<br>import org.springframework.security.config.http.SessionCreationPolicy;<br>import org.springframework.security.core.userdetails.UserDetailsService;<br>import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;<br>import org.springframework.security.crypto.password.PasswordEncoder;<br>import org.springframework.security.web.SecurityFilterChain;<br>import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;<br>import org.springframework.web.cors.CorsConfiguration;<br><br>import java.util.List;<br><br>@Configuration<br>@EnableWebSecurity<br>public class SecurityConfig {<br><br>    @Value(&quot;${allowed.frontend.origins}&quot;)<br>    private String allowedOrigin;<br><br><br><br>    private final JwtAuthenticationFilter jwtAuthenticationFilter;<br>    private final UserDetailsService userDetailsService;<br><br>    public SecurityConfig(JwtAuthenticationFilter jwtAuthenticationFilter, UserDetailsService userDetailsService) {<br>        this.jwtAuthenticationFilter = jwtAuthenticationFilter;<br>        this.userDetailsService = userDetailsService;<br>    }<br><br>    @Bean<br>    public AuthenticationManager authenticationManager(AuthenticationConfiguration configuration) throws Exception {<br>        return configuration.getAuthenticationManager();<br>    }<br><br>    @Bean<br>    public PasswordEncoder passwordEncoder() {<br>        return new BCryptPasswordEncoder();<br>    }<br><br>    @Bean<br>    public DaoAuthenticationProvider authenticationProvider() {<br>        DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();<br>        authProvider.setUserDetailsService(userDetailsService);<br>        authProvider.setPasswordEncoder(passwordEncoder());<br>        return authProvider;<br>    }<br><br>    @Bean<br>    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {<br>        http.cors(cors -&gt; cors.configurationSource(request -&gt; {<br>                    CorsConfiguration configuration = new CorsConfiguration();<br>                    configuration.setAllowedOrigins(List.of(allowedOrigin));<br>                    configuration.setAllowedMethods(List.of(&quot;GET&quot;, &quot;POST&quot;, &quot;PUT&quot;, &quot;DELETE&quot;));<br>                    configuration.setAllowedHeaders(List.of(&quot;Authorization&quot;, &quot;Content-Type&quot;));<br>                    return configuration;<br>                }))<br>                .csrf(csrf -&gt; csrf.disable())<br>                .authorizeHttpRequests(auth -&gt; auth<br>                        //.requestMatchers(&quot;/**&quot;).permitAll()<br>                        .requestMatchers( RestEndPoints.AUTH_EP+RestEndPoints.AUTH_LOGIN_EP).permitAll()<br>                        .requestMatchers( RestEndPoints.ORGANIZATION_EP+RestEndPoints.ORGANIZATION_CREATE_EP).permitAll()<br>                        .anyRequest().authenticated())<br>                .sessionManagement(session -&gt; session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));<br><br>        http.authenticationProvider(authenticationProvider());<br>        http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);<br><br>        return http.build();<br>    }<br><br><br>}<br><br></pre><pre> .requestMatchers( RestEndPoints.AUTH_EP+RestEndPoints.AUTH_LOGIN_EP).permitAll()</pre><p>In the above code it allows the request to reach the mentioned end point and all the http methods(POST,PUT,GET,DELETE).</p><pre>.anyRequest().authenticated())</pre><p>In the above code line other requests that doesn’t match the previous url pattern should be authenticated.</p><h4><strong>How </strong><strong>.anyRequest().authenticated() Works</strong></h4><p>The .anyRequest().authenticated() configuration ensures that <strong>every incoming request</strong> is checked for an authenticated user before proceeding. For Spring Security to consider a request authenticated, there must be a valid Authentication object present in the SecurityContextHolder.</p><p>When a user is authenticated (typically through the UsernamePasswordAuthenticationToken in your JWT filter), Spring Security will:</p><ol><li><strong>Store the </strong><strong>Authentication object in </strong><strong>SecurityContextHolder</strong>: This is done with SecurityContextHolder.getContext().setAuthentication(authToken); in your JWT authentication filter.</li><li><strong>Use </strong><strong>SecurityContextHolder for all subsequent checks</strong>: When .anyRequest().authenticated() is invoked, it checks the SecurityContextHolder to see if an Authentication object is present and whether it is authenticated (authToken.isAuthenticated()).</li></ol><p>If SecurityContextHolder has a valid Authentication:</p><ul><li>The request proceeds to the next filter or controller.</li></ul><p>If SecurityContextHolder does not have a valid Authentication (e.g., the token is missing, invalid, or expired):</p><ul><li>The request is blocked, and a 401 Unauthorized response is returned.</li></ul><h4>How the JWT Filter Fits In</h4><p>The custom JWT filter you created (extending OncePerRequestFilter) sets this Authentication in the SecurityContextHolder if a valid JWT token is found in the request header. Here’s the flow:</p><ol><li><strong>JWT Filter Executes First</strong>: This filter is typically registered before UsernamePasswordAuthenticationFilter, so it runs before other authentication checks.</li></ol><pre>http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);</pre><p>2.<strong>JWT Filter Sets Authentication</strong>: If the JWT token is valid, the filter creates an Authentication token and sets it in SecurityContextHolder.</p><p>3. <strong>Spring Security Checks </strong><strong>SecurityContextHolder</strong>: When .anyRequest().authenticated() is configured, Spring Security looks at SecurityContextHolder to confirm the user’s authentication.</p><p>4. <strong>Request Proceeds if Authenticated</strong>: If SecurityContextHolder contains a valid Authentication, the request is allowed through; otherwise, it’s blocked.</p><h4>Summary</h4><p><em>In short, </em><em>.anyRequest().authenticated() relies on </em><em>SecurityContextHolder to verify whether the current request is authenticated. The JWT filter you configured sets this authentication by populating </em><em>SecurityContextHolder with an </em><em>Authentication object, enabling </em><em>.anyRequest().authenticated() to allow or block the request based on the presence and validity of this object.</em></p><p><strong>Let’s see to which filter the request comes first and how the flow goes on,</strong></p><p>The JwtAuthenticationFilter class, which extends OncePerRequestFilter, is designed to intercept every HTTP request entering your Spring Boot application. This filter will be the first to handle requests if configured at the appropriate point in the Spring Security filter chain, typically before the default UsernamePasswordAuthenticationFilter.</p><p>Here’s how the request flow works with JwtAuthenticationFilter:</p><ol><li><strong>Request Originates</strong>: The client (e.g., a browser or mobile app) makes a request to your application, including a JWT token in the request headers for authorization.</li></ol><p>2.<strong>Filter Chain Interception</strong>: When the request reaches your Spring Boot application, it enters the Spring Security filter chain.</p><p>3.<strong>JwtAuthenticationFilter Execution</strong>: The JwtAuthenticationFilter, registered early in the filter chain, is one of the first to handle the request. This filter:</p><ul><li>Extracts the JWT token from the request header.</li><li>Validates the token (e.g., checks its signature, expiry, and claims).</li><li>Loads user details if the token is valid.</li><li>Sets an Authentication object in the SecurityContextHolder to mark the request as authenticated for this session.</li></ul><p>4. <strong>Security Context and Authorization</strong>: After the JwtAuthenticationFilter:</p><ul><li>Other filters and security configurations (such as anyRequest().authenticated()) rely on the SecurityContextHolder to check if the user is authenticated.</li><li>If the token is valid, and SecurityContextHolder has the authenticated user’s details, the request is authorized to proceed to the target endpoint.</li><li>If the token is invalid or missing, Spring Security prevents further processing and may return a 401 Unauthorized or 403 Forbidden response.</li></ul><p>5.<strong>Target Controller Handling</strong>: If the request passes all security checks, it reaches the designated controller to handle the actual business logic.</p><p><em>In summary, </em><em>JwtAuthenticationFilter is the first point of processing for each incoming request in your application (after being routed through the Spring Security filter chain). Its job is to authenticate the request based on the provided JWT token before it reaches any secured endpoints.</em></p><pre>http.cors(cors -&gt; cors.configurationSource(request -&gt; {<br>                    CorsConfiguration configuration = new CorsConfiguration();<br>                    configuration.setAllowedOrigins(List.of(allowedOrigin));<br>                    configuration.setAllowedMethods(List.of(&quot;GET&quot;, &quot;POST&quot;, &quot;PUT&quot;, &quot;DELETE&quot;));<br>                    configuration.setAllowedHeaders(List.of(&quot;Authorization&quot;, &quot;Content-Type&quot;));<br>                    return configuration;<br>                }))</pre><p>Above is the code snippet for cors configuration. In the <strong>allowedOrigin </strong>place you need to mention the front end url from where the request comes.</p><p>With this Spring security with jwt token article series comes to an end. Hope you got a good understanding here. Reading the article is not enough, if you want to get hands on experience on this you need to do these things.</p><p>With a new article let’s meet again . Until then have a pleasant week!.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5ea8ffabeef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring boot security with JWT Token — Article 1]]></title>
            <link>https://medium.com/@duleepalwis0/spring-boot-security-with-jwt-token-article-1-f13e4d99f14f?source=rss-545804491dfd------2</link>
            <guid isPermaLink="false">https://medium.com/p/f13e4d99f14f</guid>
            <category><![CDATA[spring-security]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[programmin]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Duleep Alwis]]></dc:creator>
            <pubDate>Sat, 16 Nov 2024 06:51:22 GMT</pubDate>
            <atom:updated>2024-11-16T06:53:23.319Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Spring boot security with JWT Token — Article 1</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AFLEcUFl3oDhG76LZ_WTUg.png" /></figure><p>Here I am going to explain you about how the jwt token creation happens and why jwt token is used in spring boot instead of sessions.</p><p><strong>What is jwt?</strong></p><p>Jwt stands for Jason Web Token.</p><p>JWT is a compact, URL-safe token format that securely transmits information between two parties — typically a server and a client. The token is a <strong>JSON object</strong> encoded as a long string, and it consists of three parts:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*xCczXBfa0xaOGQ11lc3TiQ.png" /><figcaption>jwt token 3 parts</figcaption></figure><p>JWT example token:-</p><p><em>eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c</em></p><p><strong>Why Use JWT in Authentication?</strong></p><p>1. <strong>Stateless and Scalable</strong>: Unlike traditional session-based authentication (which stores sessions on the server), JWT is <strong>stateless</strong>. Once generated, the token is stored client-side (usually in a browser’s local storage or as a cookie) and sent with each request. This reduces the load on the server and allows for easier horizontal scaling.</p><p><strong>2. Security</strong>: JWTs are typically signed using algorithms like HMAC or RSA. The server can verify the token’s authenticity by checking its signature without needing to look up a session in a database. Only the server (or services sharing the same signing key) can generate valid JWTs, so clients can’t tamper with them.</p><p><strong>3. Compact and Efficient</strong>: JWTs are compact and base64-encoded, making them efficient to pass in HTTP headers. This is ideal for web applications where data should be kept minimal and requests fast.</p><p><strong>4. Self-contained</strong>: JWTs are self-contained, meaning all necessary information (such as user roles or permissions) is included within the token. This makes it easy for the server to validate and authorize requests without additional database lookups.</p><p><strong>5. Cross-Domain and Microservices Friendly</strong>: Since JWT is URL-safe and doesn’t rely on server-side sessions, it’s particularly suited for:</p><ul><li><strong>Single-Page Applications (SPAs)</strong> where front-end and back-end are separate.</li><li><strong>Microservices architectures</strong> where different services may need to validate the same user identity independently.</li></ul><h4>Typical Flow of JWT Authentication in a Spring Boot App</h4><ol><li><strong>User Logs In</strong>: The user sends their credentials (username and password) to the server’s authentication endpoint.</li><li><strong>Server Generates JWT</strong>: If the credentials are correct, the server generates a JWT with the user’s details and signs it.</li><li><strong>Client Stores Token</strong>: The client stores this token (e.g., in local storage or a cookie).</li><li><strong>Token Sent with Requests</strong>: For each subsequent request, the client includes the JWT in the Authorization header (Authorization: Bearer &lt;token&gt;).</li><li><strong>Server Validates JWT</strong>: The server extracts the token, verifies its signature, and checks the claims within the token.</li><li><strong>Access Granted/Denied</strong>: Based on the token’s validity and claims, the server either allows access to the requested resource or denies it.</li></ol><h4>Why JWT is Used Here</h4><p>In your Spring Boot application, JWT is being used because it:</p><ul><li>Provides a <strong>secure, stateless way to authenticate users</strong>.</li><li>Reduces the need for session storage, which is helpful for scaling and performance.</li><li>Allows different services or parts of the app (e.g., RESTful APIs) to <strong>share a common authentication mechanism</strong> without needing to access a central session store.</li></ul><p>In Spring Security, JWT is commonly paired with filters (like JwtAuthenticationFilter) to validate the token on each request and ensure that only authorized users can access protected resources.</p><p>I will explain how the cors validation happens and the code examples for this in another article . Until then have pleasant time!.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f13e4d99f14f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Avoiding SSL validation in spring boot rest template]]></title>
            <link>https://medium.com/@duleepalwis0/avoiding-ssl-validation-in-spring-boot-rest-template-ae43c2ac4df5?source=rss-545804491dfd------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae43c2ac4df5</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[resttemplate]]></category>
            <category><![CDATA[ssl-certificate]]></category>
            <category><![CDATA[java17]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Duleep Alwis]]></dc:creator>
            <pubDate>Sun, 08 Sep 2024 08:22:50 GMT</pubDate>
            <atom:updated>2024-09-08T08:22:50.276Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi all after quite a sometime, Today I am going to say a situation where I faced when working with the spring boot rest remplate when accessing a 3rd party api.</p><p><strong>Situation I had to face .</strong></p><p>In the situation I faced I had to pass some data to another HTTPS end point and I used spring boot 3, Java 17 and the rest template object to send the rest request .</p><p>There I got a ssl validation issue when trying to access the 3rd party api.</p><p>When using the <strong>RestTemplate </strong>to make api calls to HTTPS end point , we may run into certificate issue. <strong>RestTemplate </strong>normally do the SSL check.</p><p>In production , solution for this issue and the proper way to handle this kind of scenarios is , add the required certificates to your application keystore. Then you will be able to make HTTPS requests successfully.</p><p>However, in development environment this can be a little messy thing. In the development environment we want to test our api intergration.</p><p>So , it is desired to skip the SSL verification in the development environment.</p><p>So I searched on the internet for a solution for this and here is the solution I found . We need to do some changes to the rest template object for this.</p><p>The below is the java code for that,</p><pre>  public RestTemplate getRestTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException { <br>// Create an SSL context that bypasses certificate validation<br><br>        RestTemplateBuilder builder = new RestTemplateBuilder();<br><br>        // Create an SSLContext that bypasses SSL validation<br>        SSLContext sslContext = SSLContextBuilder.create()<br>                .loadTrustMaterial((X509Certificate[] chain, String authType) -&gt; true) // Trust all certificates<br>                .build();<br><br>        // Create SSLConnectionSocketFactory with the SSLContext and NoopHostnameVerifier<br>        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(<br>                sslContext, NoopHostnameVerifier.INSTANCE);<br><br>        // Create a registry of custom connection socket factories for both HTTP and HTTPS<br>        Registry&lt;ConnectionSocketFactory&gt; socketFactoryRegistry = RegistryBuilder.&lt;ConnectionSocketFactory&gt;create()<br>                .register(&quot;http&quot;, PlainConnectionSocketFactory.INSTANCE)<br>                .register(&quot;https&quot;, sslSocketFactory)<br>                .build();<br><br>        // Create a connection manager using the custom registry<br>        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);<br>        connectionManager.setMaxTotal(100);  // Set max total connections<br>        connectionManager.setDefaultMaxPerRoute(20);  // Set max connections per route<br>        connectionManager.setValidateAfterInactivity(TimeValue.ofSeconds(30));  // Validate connections after 30 seconds of inactivity<br><br>        // Create the CloseableHttpClient with the custom connection manager<br>        CloseableHttpClient httpClient = HttpClients.custom()<br>                .setConnectionManager(connectionManager)<br>                .evictIdleConnections(TimeValue.ofMinutes(5))  // Evict idle connections after 5 minutes<br>                .build();<br><br>        // Use HttpComponentsClientHttpRequestFactory to integrate the custom HttpClient with RestTemplate<br>        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);<br><br>        // Build the RestTemplate using the custom request factory<br>        return builder<br>                .requestFactory(() -&gt; factory)<br>                .build();<br>}</pre><p>The below is the imports I made for this,</p><pre>import java.security.KeyManagementException;<br>import java.security.KeyStoreException;<br>import java.security.NoSuchAlgorithmException;<br>import java.security.cert.X509Certificate;<br>import javax.net.ssl.SSLContext;<br><br><br><br><br>import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;<br>import org.apache.hc.client5.http.impl.classic.HttpClients;<br>import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;<br>import org.apache.hc.client5.http.socket.ConnectionSocketFactory;<br>import org.apache.hc.client5.http.socket.PlainConnectionSocketFactory;<br>import org.apache.hc.client5.http.ssl.NoopHostnameVerifier;<br>import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory;<br>import org.apache.hc.core5.http.config.Registry;<br>import org.apache.hc.core5.http.config.RegistryBuilder;<br>import org.apache.hc.core5.ssl.SSLContextBuilder;<br>import org.apache.hc.core5.util.TimeValue;<br>import org.springframework.web.client.RestTemplate;</pre><p>The pom.xml changes ,</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.apache.httpcomponents.client5&lt;/groupId&gt;<br>    &lt;artifactId&gt;httpclient5&lt;/artifactId&gt;<br>    &lt;version&gt;5.2&lt;/version&gt; &lt;!-- Use the latest stable version --&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;org.apache.httpcomponents.core5&lt;/groupId&gt;<br>    &lt;artifactId&gt;httpcore5&lt;/artifactId&gt;<br>    &lt;version&gt;5.2&lt;/version&gt; &lt;!-- Use the latest stable version --&gt;<br>&lt;/dependency&gt;</pre><p><em>Note: This is the option for development environment. When going for production environment we need to have those certificates in our key store and do the HTTPS call without bypassing the SSL verification. Bypassing the SSL verification will lead to security issues.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae43c2ac4df5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Architecture -]]></title>
            <link>https://towardsdev.com/java-architecture-b7deb68ebb78?source=rss-545804491dfd------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7deb68ebb78</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[java-code-implementation]]></category>
            <category><![CDATA[compilers]]></category>
            <category><![CDATA[java-architecture]]></category>
            <category><![CDATA[jvm-architecture]]></category>
            <dc:creator><![CDATA[Duleep Alwis]]></dc:creator>
            <pubDate>Sun, 25 Aug 2024 12:43:38 GMT</pubDate>
            <atom:updated>2025-07-21T19:10:13.946Z</atom:updated>
            <content:encoded><![CDATA[<h3>Java Architecture</h3><p>Hi there, after a long time I started writing again.</p><p>Today I am going to write about java architecture , describe about how java language works.</p><p>In the first part of the article I will discuss about the overall architecture of a Java, such as how the compilation works , how the program loads to memory and executes , those things.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*Bf_OSL0jSXONAErGrnSBAw.png" /></figure><p>As in the above diagram the java source file which contains the .java extension is compiled by the java compiler and create the byte code file which has the .class extension. After that java virtual machine interprets this compiled java source code into relevant machine code (Windows, Linux, Macos) and executes the code.</p><p>Compiler :- This is a program used to read the source file as whole and create the byte code from it. If it found any syntax errors there it will return error and stop the compilation. This comes with the JDK tool kit.</p><p>Interpreter:- This is a program used to read the source file line by line and convert it to another language. If it encounters an error it will return the error and stop the interpretation.</p><p>Java use both compiler and interpreter as explained in the above diagram.</p><p>Java commands for compile and execute a java program are,</p><p>If the source file <strong>Summary.java</strong></p><p>compilation :- javac Summary.java</p><p>calling the jvm :- java Summary</p><p><strong>Components of the Java architecture.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*rHC3YglP6kTaiuVZLi1AyA.png" /></figure><p><strong>Java virtual machine(JVM)</strong></p><p>This JVM differs from platform to platform. It is responsible for executing the java class file or the program.</p><p>As in the first figure it interprets the java byte code line by line in the runtime to the machine code.</p><p>Due to above mentioned things java is called <strong>WORA</strong>(Write once Runs anywhere).</p><p>Now let’s see how the class file is loaded in to the memory and executed.</p><p><strong>JVM architecture</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*PNTNGiYwXUV34MLwfsZtLQ.png" /></figure><p>Here I am not going to explain all the components in this diagram.</p><p>I will share a link in the article for that you to refer.</p><p>Link:- <a href="https://www.geeksforgeeks.org/jvm-works-jvm-architecture/">https://www.geeksforgeeks.org/jvm-works-jvm-architecture/</a></p><p>This is about java architecture . Let’s meet with a new article about java next time. Until then have a pleasant time</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7deb68ebb78" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/java-architecture-b7deb68ebb78">Java Architecture -</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring boot with React (Part 2)]]></title>
            <link>https://towardsdev.com/spring-boot-with-react-part-2-49fd001a615a?source=rss-545804491dfd------2</link>
            <guid isPermaLink="false">https://medium.com/p/49fd001a615a</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[fullstack-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Duleep Alwis]]></dc:creator>
            <pubDate>Sun, 21 May 2023 16:03:47 GMT</pubDate>
            <atom:updated>2025-07-28T16:27:31.714Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi there, this is the 2nd blog post of the building a react js application with spring boot application.</p><p>Today I will discuss about how to build the front end react js application.</p><p>To do this we need some prerequisites.</p><ol><li>We need to install node js .</li><li>We need to install npm. Create React App requires at least version 5.2 of NPM.</li><li>You need to have a good editor.(I am using vs code).</li></ol><p>It would be better to have the latest versions of node and npm.</p><p>To create the react app we need a tool called <strong>create-react-app. </strong>We can install it by typing this command in our command prompt or shell. (Better to use shell or powershell when running the below commands)</p><pre>npm install -g create-react-app (-g flag is used to install it globally)</pre><p>After the above tool is installed, we can start creating our 1st react application.</p><p>Type the below command in command prompt or shell.</p><pre>create-react-app react-frontend</pre><p>To run the react application we can use the below command in the <strong>react-frontend</strong> folder.</p><pre>npm start</pre><p>For the rest of the work of creating our application EmployeeManagement System we need the following libraries. Versions I have mentioned are the versions I have used in my sample project.</p><p>react-dom:v 18.2.0 (ReactDOM is used to render components and elements on the web.)</p><p>react-router: v5.2.0 (It enables the creation of single-page web or mobile apps that allow navigating without refreshing the page. It also allows us to use browser history features while preserving the right application view.)</p><p>react-router-dom: v5.2.0 (It enables routing in React applications and allows defining multiple routes in an application.)</p><p>axios: v1.4.0 (This library is used to send http request to the backend rest api)</p><p>bootstrap: v5.2.3 (This is the css library used)</p><p>Use the following commands in your shell to install the above libraries.</p><pre>npm install bootstrap --save<br>npm install react-router-dom@5.2.0 --save<br>npm install axios --save</pre><p>In your project folder you can find a file called package.json. It is the file which contains entries for the libraries ,dependencies you have used in your project.</p><p><em>When you committing the project to the github, node_modules folder won’t be committed. Those node_modules are the dependencies you require to run your react application. After you clone the github repository of this project, run the </em><strong><em>npm install </em></strong><em>command in the shell ,by navigating to the project folder. That command will read package.json file and download the required libraries to the node_modules folder.</em></p><p>Now create the following folder structure in your project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*vXC_cuiXJ1U5BHBIjWTAiA.png" /></figure><p>Create the following javascript files in the components and services folder.</p><p>You can find the source code from the below github repositroy.</p><ul><li><a href="https://github.com/DuleepAlwis/spring-boot_react-demo-app-frontend">GitHub - DuleepAlwis/spring-boot_react-demo-app-frontend: React front end application for the demo app</a></li><li><a href="https://github.com/DuleepAlwis/spring-boot_react-demo-app">GitHub - DuleepAlwis/spring-boot_react-demo-app: spring boot react js demo application</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49fd001a615a" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/spring-boot-with-react-part-2-49fd001a615a">Spring boot with React (Part 2)</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>