<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Pradipta</title>
    <description>The latest articles on DEV Community by Pradipta (@pradz13).</description>
    <link>https://dev.to/pradz13</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F579540%2F2f149590-1b96-4818-82e5-175615e538aa.jpeg</url>
      <title>DEV Community: Pradipta</title>
      <link>https://dev.to/pradz13</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/pradz13"/>
    <language>en</language>
    <item>
      <title>Seamless communication between containers - docker compose</title>
      <dc:creator>Pradipta</dc:creator>
      <pubDate>Fri, 21 Jul 2023 17:30:35 +0000</pubDate>
      <link>https://dev.to/pradz13/seamless-communication-between-containers-docker-compose-20pd</link>
      <guid>https://dev.to/pradz13/seamless-communication-between-containers-docker-compose-20pd</guid>
      <description>&lt;p&gt;Let's consider an example of a Spring Boot application which interacts with the MySQL database. Couple of images have been created for MySQL and Spring Boot respectively. The images can be run as containers. But how they going to interact with each other?&lt;/p&gt;

&lt;p&gt;One way is to create a docker network and spin up the containers within that network. This will work but you have to deal with long commands which is difficult to maintain in bigger projects. This is the problem docker compose solves by making the container communication easy to achieve and maintain.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Let's consider the following Spring Boot Application which communicates with a MySQL database and provides a basic JWT implementation for securing Rest service endpoints.&lt;br&gt;
&lt;a href="https://github.com/pradz13/spring-security-jwt.git"&gt;https://github.com/pradz13/spring-security-jwt.git&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Spring Boot Application needs to define a Dockerfile as follows -&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;FROM maven:3.9.3-sapmachine-17
WORKDIR .
COPY . .
RUN mvn clean install -DskipTests
CMD mvn spring-boot:run
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Define the docker compose configuration file as follows -
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;version: "3.8"

services:
  mysqldb:
    image: mysql:5.7
    restart: unless-stopped
    env_file: ./.env
    environment:
      - MYSQL_ROOT_PASSWORD=$MYSQLDB_ROOT_PASSWORD
      - MYSQL_DATABASE=$MYSQLDB_DATABASE
    ports:
      - $MYSQLDB_LOCAL_PORT:$MYSQLDB_DOCKER_PORT
    volumes:
      - db:/var/lib/mysql

  app:
    depends_on:
      - mysqldb
    build: .
    restart: on-failure
    env_file: ./.env
    ports:
      - $SPRING_LOCAL_PORT:$SPRING_DOCKER_PORT
    environment:
      SPRING_APPLICATION_JSON: '{
            "spring.datasource.url"  : "jdbc:mysql://mysqldb:$MYSQLDB_DOCKER_PORT/$MYSQLDB_DATABASE?useSSL=false",
            "spring.datasource.username" : "$MYSQLDB_USER",
            "spring.datasource.password" : "$MYSQLDB_ROOT_PASSWORD",
            "spring.jpa.properties.hibernate.dialect" : "org.hibernate.dialect.MySQLDialect",
            "spring.jpa.hibernate.ddl-auto" : "update"
          }'
    volumes:
      - .m2:/root/.m2
    stdin_open: true
    tty: true

volumes:
  db:
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Create the .env file which will have the configurations.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;MYSQLDB_USER=root
MYSQLDB_ROOT_PASSWORD=123456
MYSQLDB_DATABASE=bezkoder_db
MYSQLDB_LOCAL_PORT=3307
MYSQLDB_DOCKER_PORT=3306

SPRING_LOCAL_PORT=6868
SPRING_DOCKER_PORT=8080
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Run the containers with the following command -
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;docker-compose up -d
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;-d will run it in detached mode.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;To stop the containers following command can be used -
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;docker-compose down
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To stop the containers and delete the images, use the following command -&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;docker-compose down --rmi all
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Please note, when docker compose is used, no need to create docker network explicitly, it is taken care by docker compose internally.&lt;/p&gt;

</description>
      <category>docker</category>
      <category>containers</category>
    </item>
    <item>
      <title>Useful Docker Commands</title>
      <dc:creator>Pradipta</dc:creator>
      <pubDate>Sun, 16 Jul 2023 16:03:32 +0000</pubDate>
      <link>https://dev.to/pradz13/useful-docker-commands-32ja</link>
      <guid>https://dev.to/pradz13/useful-docker-commands-32ja</guid>
      <description>&lt;p&gt;Docker is a platform for developing, shipping and running applications. In this post, we'll discuss about some of the salient Docker commands used in our projects frequently.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;docker pull&lt;/strong&gt;&lt;br&gt;
This command helps to pull the image from docker hub. If we do not specify the tag to be pulled, latest docker image will be pulled.&lt;/p&gt;

&lt;p&gt;docker pull image:tag&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;docker pull mysql:8.0.33
8.0.33: Pulling from library/mysql
e2c03c89dcad: Pull complete 
68eb43837bf8: Pull complete 
796892ddf5ac: Pull complete 
6bca45eb31e1: Pull complete 
ebb53bc0dcca: Pull complete 
2e2c6bdc7a40: Pull complete 
6f27b5c76970: Pull complete 
438533a24810: Pull complete 
e5bdf19985e0: Pull complete 
667fa148337b: Pull complete 
5baa702110e4: Pull complete 
Digest: sha256:232936eb036d444045da2b87a90d48241c60b68b376caf509051cb6cffea6fdc
Status: Downloaded newer image for mysql:8.0.33
docker.io/library/mysql:8.0.33
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;docker images&lt;/strong&gt;&lt;br&gt;
Shows the docker images downloaded to the local machine.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;docker images
REPOSITORY   TAG       IMAGE ID       CREATED       SIZE
mysql        8.0.33    041315a16183   11 days ago   565MB
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;docker run&lt;/strong&gt;&lt;br&gt;
Runs the container from the docker image.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;docker run -p6000:3306 --name some-mysql-new -e MYSQL_ROOT_PASSWORD=my-secret-pw -d mysql:8.0.33
0dacb1101ad336475f7ebcbc5e21cc9fb894f2bfa4c0a805f65d3ef1f39bf7e4
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;-p(host port):(container port) - Host port gets bounded to the container port so that it can be accessible.&lt;br&gt;
-d : Runs the container in the detached mode.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;docker ps&lt;/strong&gt;&lt;br&gt;
Shows the list of running containers.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;docker ps
CONTAINER ID   IMAGE          COMMAND                  CREATED              STATUS              PORTS                               NAMES
0dacb1101ad3   mysql:8.0.33   "docker-entrypoint.s…"   About a minute ago   Up About a minute   33060/tcp, 0.0.0.0:6000-&amp;gt;3306/tcp   some-mysql-new
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;docker stop&lt;/strong&gt;&lt;br&gt;
Stops a running docker container. The container id needs to be passed.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;docker stop 0dacb1101ad3
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;docker start&lt;/strong&gt;&lt;br&gt;
Starts a docker container. The container id needs to be passed.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;docker start 0dacb1101ad3
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;docker logs&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Shows the logs of a Docker container. The container id needs to be passed.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;docker logs 0dacb1101ad3
2023-07-16 14:02:16+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.33-1.el8 started.
2023-07-16 14:02:16+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql'
2023-07-16 14:02:16+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.33-1.el8 started.
2023-07-16 14:02:16+00:00 [Note] [Entrypoint]: Initializing database files
2023-07-16T14:02:16.555166Z 0 [Warning] [MY-011068] [Server] The syntax '--skip-host-cache' is deprecated and will be removed in a future release. Please use SET GLOBAL host_cache_size=0 instead.
2023-07-16T14:02:16.555434Z 0 [System] [MY-013169] [Server] /usr/sbin/mysqld (mysqld 8.0.33) initializing of server in progress as process 81
2023-07-16T14:02:16.562164Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.
2023-07-16T14:02:17.077951Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended.
2023-07-16T14:02:18.844888Z 6 [Warning] [MY-010453] [Server] root@localhost is created with an empty password ! Please consider switching off the --initialize-insecure option.
2023-07-16 14:02:23+00:00 [Note] [Entrypoint]: Database files initialized
2023-07-16 14:02:23+00:00 [Note] [Entrypoint]: Starting temporary server
2023-07-16T14:02:23.967805Z 0 [Warning] [MY-011068] [Server] The syntax '--skip-host-cache' is deprecated and will be removed in a future release. Please use SET GLOBAL host_cache_size=0 instead.
2023-07-16T14:02:23.969395Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.0.33) starting as process 123
2023-07-16T14:02:23.984575Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.
2023-07-16T14:02:24.258224Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended.
2023-07-16T14:02:24.669973Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed.
2023-07-16T14:02:24.670204Z 0 [System] [MY-013602] [Server] Channel mysql_main configured to support TLS. Encrypted connections are now supported for this channel.
2023-07-16T14:02:24.673431Z 0 [Warning] [MY-011810] [Server] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible to all OS users. Consider choosing a different directory.
2023-07-16T14:02:24.732237Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Socket: /var/run/mysqld/mysqlx.sock
2023-07-16T14:02:24.733339Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.33'  socket: '/var/run/mysqld/mysqld.sock'  port: 0  MySQL Community Server - GPL.
2023-07-16 14:02:24+00:00 [Note] [Entrypoint]: Temporary server started.
'/var/lib/mysql/mysql.sock' -&amp;gt; '/var/run/mysqld/mysqld.sock'
Warning: Unable to load '/usr/share/zoneinfo/iso3166.tab' as time zone. Skipping it.
Warning: Unable to load '/usr/share/zoneinfo/leap-seconds.list' as time zone. Skipping it.
Warning: Unable to load '/usr/share/zoneinfo/leapseconds' as time zone. Skipping it.
Warning: Unable to load '/usr/share/zoneinfo/tzdata.zi' as time zone. Skipping it.
Warning: Unable to load '/usr/share/zoneinfo/zone.tab' as time zone. Skipping it.
Warning: Unable to load '/usr/share/zoneinfo/zone1970.tab' as time zone. Skipping it.

2023-07-16 14:02:29+00:00 [Note] [Entrypoint]: Stopping temporary server
2023-07-16T14:02:29.418853Z 10 [System] [MY-013172] [Server] Received SHUTDOWN from user root. Shutting down mysqld (Version: 8.0.33).
2023-07-16T14:02:31.320144Z 0 [System] [MY-010910] [Server] /usr/sbin/mysqld: Shutdown complete (mysqld 8.0.33)  MySQL Community Server - GPL.
2023-07-16 14:02:31+00:00 [Note] [Entrypoint]: Temporary server stopped

2023-07-16 14:02:31+00:00 [Note] [Entrypoint]: MySQL init process done. Ready for start up.

2023-07-16T14:02:31.685058Z 0 [Warning] [MY-011068] [Server] The syntax '--skip-host-cache' is deprecated and will be removed in a future release. Please use SET GLOBAL host_cache_size=0 instead.
2023-07-16T14:02:31.686585Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.0.33) starting as process 1
2023-07-16T14:02:31.694428Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.
2023-07-16T14:02:31.882615Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended.
2023-07-16T14:02:32.331478Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed.
2023-07-16T14:02:32.331559Z 0 [System] [MY-013602] [Server] Channel mysql_main configured to support TLS. Encrypted connections are now supported for this channel.
2023-07-16T14:02:32.334663Z 0 [Warning] [MY-011810] [Server] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible to all OS users. Consider choosing a different directory.
2023-07-16T14:02:32.367684Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Bind-address: '::' port: 33060, socket: /var/run/mysqld/mysqlx.sock
2023-07-16T14:02:32.367707Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.33'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  MySQL Community Server - GPL.
2023-07-16T14:07:21.221136Z 0 [System] [MY-013172] [Server] Received SHUTDOWN from user &amp;lt;via user signal&amp;gt;. Shutting down mysqld (Version: 8.0.33).
2023-07-16T14:07:22.110930Z 0 [System] [MY-010910] [Server] /usr/sbin/mysqld: Shutdown complete (mysqld 8.0.33)  MySQL Community Server - GPL.
2023-07-16 14:07:32+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.33-1.el8 started.
2023-07-16 14:07:32+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql'
2023-07-16 14:07:32+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.33-1.el8 started.
'/var/lib/mysql/mysql.sock' -&amp;gt; '/var/run/mysqld/mysqld.sock'
2023-07-16T14:07:33.176975Z 0 [Warning] [MY-011068] [Server] The syntax '--skip-host-cache' is deprecated and will be removed in a future release. Please use SET GLOBAL host_cache_size=0 instead.
2023-07-16T14:07:33.178454Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.0.33) starting as process 1
2023-07-16T14:07:33.185757Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.
2023-07-16T14:07:33.376968Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended.
2023-07-16T14:07:33.689001Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed.
2023-07-16T14:07:33.689518Z 0 [System] [MY-013602] [Server] Channel mysql_main configured to support TLS. Encrypted connections are now supported for this channel.
2023-07-16T14:07:33.693007Z 0 [Warning] [MY-011810] [Server] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible to all OS users. Consider choosing a different directory.
2023-07-16T14:07:33.743641Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Bind-address: '::' port: 33060, socket: /var/run/mysqld/mysqlx.sock
2023-07-16T14:07:33.744479Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.33'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  MySQL Community Server - GPL.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;docker exec&lt;/strong&gt;&lt;br&gt;
Get into the terminal of the container.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;docker exec -it 0dacb1101ad3 /bin/bash
bash-4.4# ls
bin  boot  dev  docker-entrypoint-initdb.d  entrypoint.sh  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
bash-4.4# exit
exit
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;-it refers to interactive.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;docker image rm&lt;/strong&gt;&lt;br&gt;
Removes an image. Image name along with tag should be mentioned in the command.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;docker image rm mysql:8.0.33 -f    
Untagged: mysql:8.0.33
Untagged: mysql@sha256:232936eb036d444045da2b87a90d48241c60b68b376caf509051cb6cffea6fdc
Deleted: sha256:041315a161837f8bb87361e13390abda7159b98aeedee5e6152a0bb7a9b45f27
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>docker</category>
      <category>container</category>
    </item>
    <item>
      <title>How JWT authentication can be done using the latest release of Spring Security?</title>
      <dc:creator>Pradipta</dc:creator>
      <pubDate>Sat, 15 Jul 2023 09:06:17 +0000</pubDate>
      <link>https://dev.to/pradz13/jwt-implementation-with-spring-boot-3-1k1h</link>
      <guid>https://dev.to/pradz13/jwt-implementation-with-spring-boot-3-1k1h</guid>
      <description>&lt;p&gt;In this article, we will see how to implement JWT implementation using Spring Boot 3 and Java 17.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Go to Spring Initialiser and create a project with  following dependencies. Please note, we are using MySQL database in this project.&lt;br&gt;
&lt;a href="https://start.spring.io/#!type=maven-project&amp;amp;language=java&amp;amp;platformVersion=3.1.1&amp;amp;packaging=jar&amp;amp;jvmVersion=17&amp;amp;groupId=com.example.jwt&amp;amp;artifactId=spring-security-jwt&amp;amp;name=spring-security-jwt&amp;amp;description=Implementation%20of%20JWT%20using%20Spring%20Boot%203&amp;amp;packageName=com.example.jwt&amp;amp;dependencies=web,data-jpa,mysql,security,lombok"&gt;https://start.spring.io/#!type=maven-project&amp;amp;language=java&amp;amp;platformVersion=3.1.1&amp;amp;packaging=jar&amp;amp;jvmVersion=17&amp;amp;groupId=com.example.jwt&amp;amp;artifactId=spring-security-jwt&amp;amp;name=spring-security-jwt&amp;amp;description=Implementation%20of%20JWT%20using%20Spring%20Boot%203&amp;amp;packageName=com.example.jwt&amp;amp;dependencies=web,data-jpa,mysql,security,lombok&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Add the following additional dependencies separately as they are not available in Spring Initialiser for the JWT implementation.&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;dependency&amp;gt;
    &amp;lt;groupId&amp;gt;io.jsonwebtoken&amp;lt;/groupId&amp;gt;
    &amp;lt;artifactId&amp;gt;jjwt-api&amp;lt;/artifactId&amp;gt;
    &amp;lt;version&amp;gt;0.11.5&amp;lt;/version&amp;gt;
&amp;lt;/dependency&amp;gt;
&amp;lt;dependency&amp;gt;
    &amp;lt;groupId&amp;gt;io.jsonwebtoken&amp;lt;/groupId&amp;gt;
    &amp;lt;artifactId&amp;gt;jjwt-impl&amp;lt;/artifactId&amp;gt;
    &amp;lt;version&amp;gt;0.11.5&amp;lt;/version&amp;gt;
&amp;lt;/dependency&amp;gt;
&amp;lt;dependency&amp;gt;
    &amp;lt;groupId&amp;gt;io.jsonwebtoken&amp;lt;/groupId&amp;gt;
    &amp;lt;artifactId&amp;gt;jjwt-jackson&amp;lt;/artifactId&amp;gt;
     &amp;lt;version&amp;gt;0.11.5&amp;lt;/version&amp;gt;
&amp;lt;/dependency&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Define entity class as follows to store the User Details under entities package.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.example.jwt.entities;

import jakarta.persistence.*;
import lombok.*;

@Entity
@Table(name = "USER_DATA")
@Data
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@Builder
public class UserData {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    private String name;

    @Column(unique = true)
    private String email;

    private String password;

    private String roles;

    private boolean isEnabled;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Create a repository interface named UserRepository as follows.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.example.jwt.repository;

import com.example.jwt.entities.UserData;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.Optional;

public interface UserRepository extends JpaRepository&amp;lt;UserData, Long&amp;gt; {
    Optional&amp;lt;UserData&amp;gt; findByEmail(String email);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Create a package called dto and create two classes named AuthRequestDto and UserDto respectively.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.example.jwt.dto;

import lombok.*;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@Builder
public class AuthRequestDto {
    private String email;

    private String password;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.example.jwt.dto;

import lombok.*;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@Builder
public class UserDto {
    private Long id;

    private String name;

    private String email;

    private String password;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Create a UserService interface and its implementation to create the user in the database.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.example.jwt.service;

import com.example.jwt.dto.UserDto;

public interface UserService {
    public UserDto createUser(UserDto userDto);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.example.jwt.service.impl;

import com.example.jwt.dto.UserDto;
import com.example.jwt.entities.UserData;
import com.example.jwt.repository.UserRepository;
import com.example.jwt.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserRepository userRepository;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public UserDto createUser(UserDto userDto) {
        UserData user = convertToEntity(userDto);
        return convertToDto(userRepository.save(user));
    }

    private UserData convertToEntity(UserDto userDto) {
        return UserData.builder()
                .name(userDto.getName())
                .password(passwordEncoder.encode(userDto.getPassword()))
                .email(userDto.getEmail())
                .roles("ROLE_USER")
                .isEnabled(true)
                .build();

    }

    private UserDto convertToDto(UserData user) {
        return UserDto.builder()
                .id(user.getId())
                .name(user.getName())
                .email(user.getEmail())
                .build();

    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Create a controller class for exposing a REST endpoint to create users. Also, add an additional endpoint which will be secured and will help us to test the JWT implementation post the completion of the implementation.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.example.jwt.controller;


import com.example.jwt.dto.UserDto;
import com.example.jwt.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/create")
    public ResponseEntity&amp;lt;UserDto&amp;gt; createUser(@RequestBody UserDto userDto) {
        UserDto createdUserDto = userService.createUser(userDto);
        return new ResponseEntity&amp;lt;&amp;gt;(createdUserDto, HttpStatus.CREATED);
    }

    @GetMapping("/secured")
    public String test() {
        return "secured";
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Create a Service class for JWT implementation as follows under the service package.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.example.jwt.service;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

@Service
public class JwtService {

    private static final String SECRET = "5367566B59703373367639792F423F4528482B4D6251655468576D5A71347437";

    public String extractUsername(String token) {
        return extractClaim(token, Claims::getSubject);
    }

    public Date extractExpiration(String token) {
        return extractClaim(token, Claims::getExpiration);
    }

    public &amp;lt;T&amp;gt; T extractClaim(String token, Function&amp;lt;Claims, T&amp;gt; claimsResolver) {
        final Claims claims = extractAllClaims(token);
        return claimsResolver.apply(claims);
    }

    private Claims extractAllClaims(String token) {
        return Jwts
                .parserBuilder()
                .setSigningKey(getSignKey())
                .build()
                .parseClaimsJws(token)
                .getBody();
    }

    private Boolean isTokenExpired(String token) {
        return extractExpiration(token).before(new Date());
    }

    public Boolean validateToken(String token, UserDetails userDetails) {
        final String username = extractUsername(token);
        return (username.equals(userDetails.getUsername()) &amp;amp;&amp;amp; !isTokenExpired(token));
    }


    public String generateToken(String userName) {
        Map&amp;lt;String, Object&amp;gt; claims = new HashMap&amp;lt;&amp;gt;();
        return createToken(claims, userName);
    }

    private String createToken(Map&amp;lt;String, Object&amp;gt; claims, String userName) {
        return Jwts.builder()
                .setClaims(claims)
                .setSubject(userName)
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + 1000*60*30))
                .signWith(getSignKey(), SignatureAlgorithm.HS256).compact();

    }

    private Key getSignKey() {
        byte[] keyBytes= Decoders.BASE64.decode(SECRET);
        return Keys.hmacShaKeyFor(keyBytes);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Create a filter package and create class called JwtAuthFilter class.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.example.jwt.filter;

import com.example.jwt.configuration.UserInfoUserDetailsService;
import com.example.jwt.service.JwtService;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
public class JwtAuthFilter extends OncePerRequestFilter {

    @Autowired
    private JwtService jwtService;

    @Autowired
    private UserInfoUserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String authHeader = request.getHeader("Authorization");
        String token = null;
        String username = null;
        if (authHeader != null &amp;amp;&amp;amp; authHeader.startsWith("Bearer ")) {
            token = authHeader.substring(7);
            username = jwtService.extractUsername(token);
        }

        if (username != null &amp;amp;&amp;amp; SecurityContextHolder.getContext().getAuthentication() == null) {
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            if (jwtService.validateToken(token, userDetails)) {
                UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authToken);
            }
        }
        filterChain.doFilter(request, response);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Create a new package configuration and create the class UserInfoUserDetailsService.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.example.jwt.configuration;

import com.example.jwt.entities.UserData;
import com.example.jwt.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Optional;

@Component
public class UserInfoUserDetailsService implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Optional&amp;lt;UserData&amp;gt; userInfo = userRepository.findByEmail(username);
        return userInfo
                .map(UserInfoUserDetails::new)
                .orElseThrow(() -&amp;gt; new UsernameNotFoundException("User not found :" + username));

    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Create UserInfoUserDetails class under the configuration package.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.example.jwt.configuration;

import com.example.jwt.entities.UserData;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

public class UserInfoUserDetails implements UserDetails {

    private String email;
    private String password;
    private List&amp;lt;GrantedAuthority&amp;gt; authorityList;

    private boolean isEnabled;

    public UserInfoUserDetails(UserData user) {
        this.email = user.getEmail();
        this.password = user.getPassword();
        this.authorityList = Arrays.stream(user.getRoles().split(","))
                .map(SimpleGrantedAuthority::new).collect(Collectors.toList());

        this.isEnabled = user.isEnabled();

    }

    @Override
    public Collection&amp;lt;? extends GrantedAuthority&amp;gt; getAuthorities() {
        return authorityList;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return email;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return isEnabled;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Create the SecurityConfiguration class under the configuration package for defining the security configuration of the application. Please note that WebSecurityConfigurerAdapter class is removed from latest released version of Spring Security. So, not required to extend any class now. We need to define the bean definition of SecurityFilterChain and provide the security configuration inside it.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.example.jwt.configuration;

import com.example.jwt.filter.JwtAuthFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfiguration {

    @Autowired
    private JwtAuthFilter jwtAuthFilter;

    @Bean
    public UserDetailsService userDetailsService() {
        return new UserInfoUserDetailsService();
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
        return httpSecurity
                .csrf(AbstractHttpConfigurer::disable)
                .authorizeHttpRequests(auth -&amp;gt; {
                    auth.requestMatchers("/users/create", "/authenticate/**").permitAll();
                    auth.requestMatchers("/users/**").authenticated();
                })
                .sessionManagement(session -&amp;gt; session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .authenticationProvider(authenticationProvider())
                .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class)
                .build();

    }

    @Bean
    public AuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
        authenticationProvider.setUserDetailsService(userDetailsService());
        authenticationProvider.setPasswordEncoder(passwordEncoder());
        return authenticationProvider;
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration configuration) throws Exception {
        return configuration.getAuthenticationManager();
    }

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Create the AuthenticationController class and define a Rest endpoint to pass the credentials. In case of successful authentication against the database, a JWT token will be issued to the user for accessing the secured endpoints.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.example.jwt.controller;

import com.example.jwt.dto.AuthRequestDto;
import com.example.jwt.service.JwtService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/authenticate")
public class AuthenticationController {

    @Autowired
    private JwtService jwtService;

    @Autowired
    private AuthenticationManager authenticationManager;

    @PostMapping("/")
    public String authenticateUserAndGetToken(@RequestBody AuthRequestDto authRequestDto) {
        Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(authRequestDto.getEmail(), authRequestDto.getPassword()));
        if(authentication.isAuthenticated())
            return jwtService.generateToken(authRequestDto.getEmail());
        else
            throw new UsernameNotFoundException("User not found!");
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Define the application configurations in the application.yml file.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;server:
  port: 9002
  servlet:
    context-path: /jwt-implementation/

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/&amp;lt;Database name goes here&amp;gt;
    username: &amp;lt;User Name goes here&amp;gt;
    password: &amp;lt;Password goes here&amp;gt;
    driver-class-name: com.mysql.cj.jdbc.Driver
  jpa:
    properties:
      hibernate:
        dialect: org.hibernate.dialect.MySQLDialect
    hibernate:
      ddl-auto: update

logging:
  level:
    org:
      hibernate:
        SQL: DEBUG
        type:
          descriptor:
            sql:
              BasicBinder: TRACE
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Testing the implementation&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Create the user.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmsgs369cgmh99qmfpu16.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmsgs369cgmh99qmfpu16.png" alt="Image description" width="800" height="516"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Hit the /authenticate endpoint with the credentials to get the JWT token.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frnlmt3vo30uxjobdpdvt.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frnlmt3vo30uxjobdpdvt.png" alt="Image description" width="800" height="525"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Hit the /secured endpoint with the JWT token received from the previous step. You should be able to access it successfully if the implementation has been done properly as per the above steps mentioned.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5c1w8ywerx75ca4vouxh.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5c1w8ywerx75ca4vouxh.png" alt="Image description" width="800" height="525"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Source Code&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/pradz13/spring-security-jwt.git"&gt;https://github.com/pradz13/spring-security-jwt.git&lt;/a&gt;&lt;/p&gt;

</description>
      <category>springsecurity</category>
      <category>springboot</category>
      <category>spring</category>
      <category>java</category>
    </item>
    <item>
      <title>Deploy Spring Boot Crud Application with MySQL Database to Minikube</title>
      <dc:creator>Pradipta</dc:creator>
      <pubDate>Wed, 28 Dec 2022 16:24:06 +0000</pubDate>
      <link>https://dev.to/pradz13/deploy-spring-boot-crud-application-with-mysql-database-to-minikube-14f1</link>
      <guid>https://dev.to/pradz13/deploy-spring-boot-crud-application-with-mysql-database-to-minikube-14f1</guid>
      <description>&lt;p&gt;Source Code : &lt;a href="https://github.com/pradz13/K8S/tree/main/SpringBootCrudRest"&gt;https://github.com/pradz13/K8S/tree/main/SpringBootCrudRest&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;K8S Scripts :&lt;br&gt;
&lt;a href="https://github.com/pradz13/K8S/tree/main/SpringBootCrudRest-scripts"&gt;https://github.com/pradz13/K8S/tree/main/SpringBootCrudRest-scripts&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Following are the steps to deploy Spring Boot Crud Application with MySQL Database in K8S Minikube cluster :&lt;/p&gt;

&lt;p&gt;Create a Spring Boot Crud project with MySQL DB and test it locally.&lt;/p&gt;

&lt;p&gt;Create the DB Deployment YML file. Please refer - &lt;a href="https://github.com/pradz13/K8S/blob/main/SpringBootCrudRest-scripts/db-deployment.yaml"&gt;https://github.com/pradz13/K8S/blob/main/SpringBootCrudRest-scripts/db-deployment.yaml&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Persistent Volume Claim is created for providing storage space for the database. Deployment and Service concepts we have already discussed in the previous tutorial.&lt;/p&gt;

&lt;p&gt;Start the Minikube - minikube start&lt;/p&gt;

&lt;p&gt;Check Minikube status - minikube status&lt;/p&gt;

&lt;p&gt;Allow Kubernetes to read our local Docker repository - eval $(minikube docker-env)&lt;/p&gt;

&lt;p&gt;Deploy the MySQL Deployment created above in Minikube with the command - kubectl apply -f db-deployment.yaml&lt;/p&gt;

&lt;p&gt;Get the MySQL running POD with the command - kubectl get pods&lt;/p&gt;

&lt;p&gt;Connect to the Node inside the cluster using the following command - kubectl exec -it  bash&lt;/p&gt;

&lt;p&gt;Then use the following command to connect to MySQL Server : mysql -h mysql -u root -p&lt;/p&gt;

&lt;p&gt;Use the command to see all databases :&lt;br&gt;
show databases;&lt;/p&gt;

&lt;p&gt;It should have created a database mentioned in our db-deployment.yaml file(mysql in this example). Change the database with the following command :&lt;/p&gt;

&lt;p&gt;use database_name;&lt;/p&gt;

&lt;p&gt;Build the Docker image of the Spring Boot application :&lt;br&gt;
docker build -t springbootcrudrest:1.0 .&lt;/p&gt;

&lt;p&gt;Check if the image has been build or not with the command : docker images&lt;/p&gt;

&lt;p&gt;Write the Deployment and Service for Spring Boot application -&lt;br&gt;
&lt;a href="https://github.com/pradz13/K8S/blob/main/SpringBootCrudRest-scripts/app-deployment.yaml"&gt;https://github.com/pradz13/K8S/blob/main/SpringBootCrudRest-scripts/app-deployment.yaml&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Deploy the Spring Boot Deployment created in Minikube with the command - kubectl apply -f app-deployment.yaml&lt;/p&gt;

</description>
      <category>kubernetes</category>
    </item>
    <item>
      <title>Deploy simple SpringBoot application in Minikube</title>
      <dc:creator>Pradipta</dc:creator>
      <pubDate>Thu, 22 Dec 2022 18:10:02 +0000</pubDate>
      <link>https://dev.to/pradz13/deploy-simple-springboot-application-in-minikube-3mic</link>
      <guid>https://dev.to/pradz13/deploy-simple-springboot-application-in-minikube-3mic</guid>
      <description>&lt;p&gt;Source Code repository -&lt;br&gt;
&lt;a href="https://github.com/pradz13/K8S/tree/main/kubernetes-demo" rel="noopener noreferrer"&gt;https://github.com/pradz13/K8S/tree/main/kubernetes-demo&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Kubernetes Scripts repository -&lt;br&gt;
&lt;a href="https://github.com/pradz13/K8S/tree/main/kubernetes-demo-scripts" rel="noopener noreferrer"&gt;https://github.com/pradz13/K8S/tree/main/kubernetes-demo-scripts&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Please follow the following steps to deploy the Spring Boot application in Minikube -&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Start the Minikube - minikube start&lt;/li&gt;
&lt;li&gt;Check Minikube status - minikube status&lt;/li&gt;
&lt;li&gt;Allow Kubernetes to read our local Docker repository - eval $(minikube docker-env)&lt;/li&gt;
&lt;li&gt;List all the Docker images - docker images&lt;/li&gt;
&lt;li&gt;Navigate to project folder and create the image of the application
docker build -t kubernetes-demo:1.0 .&lt;/li&gt;
&lt;li&gt;Again check the list of Docker images - docker images&lt;/li&gt;
&lt;li&gt;Create the K8S deployment file - deployment.yaml&lt;/li&gt;
&lt;li&gt;Deploy the deployment file in the cluster with command : kubectl apply -f deployment.yaml&lt;/li&gt;
&lt;li&gt;Check the deployment status : kubectl get depoyments&lt;/li&gt;
&lt;li&gt;Check the running pods : kubectl get pods&lt;/li&gt;
&lt;li&gt;Fetch the logs of running PODs : kubectl logs &lt;/li&gt;
&lt;li&gt;Create a service.yaml for Service discovery, it will also act as a Load Balancer&lt;/li&gt;
&lt;li&gt;Expose the app creating the service : kubectl apply -f service.yaml&lt;/li&gt;
&lt;li&gt;Check the service status : kubectl get service&lt;/li&gt;
&lt;li&gt;To get the URL type the command : minikube service kubernetes-demo-svc  --url&lt;/li&gt;
&lt;li&gt;Application can be accessed by the URL retrieved at step 15&lt;/li&gt;
&lt;li&gt;Dashboard can be launched using the command : minikube dashboard&lt;/li&gt;
&lt;/ol&gt;

</description>
      <category>ai</category>
    </item>
    <item>
      <title>Kubernetes local environment set up in Mac</title>
      <dc:creator>Pradipta</dc:creator>
      <pubDate>Wed, 21 Dec 2022 16:10:26 +0000</pubDate>
      <link>https://dev.to/pradz13/kubernetes-local-environment-set-up-in-mac-4nfb</link>
      <guid>https://dev.to/pradz13/kubernetes-local-environment-set-up-in-mac-4nfb</guid>
      <description>&lt;p&gt;Environment Setup in Mac :&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
kubctl : It is a command line tool that helps to connect to K8S Cluster. Run the following command -
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;brew install kubectl
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After installation check the version with the following command -&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;kubectl version
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
Hyperkit : Install a Hypervisor
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;brew install hyperkit
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;See the installations done already using the command -&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;brew list
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
Minikube : Minikube is a tool that helps to run K8S Cluster in local machine. It runs Single Node K8S cluster on local machine which eases the process of development.
Install -
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;brew install minikube
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Verify installation -&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;minikube version
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Start Minikube(prerequisite - Docker Daemon should be up and running) -&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;minikube start
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Status of Minikube -&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;minikube status
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Check the Cluster Information -&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;kubectl cluster-info
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Check nodes -&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;kubectl get nodes
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Stop Minikube -&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;minikube stop
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Delete cluster&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;minikube delete
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>kubernetes</category>
    </item>
    <item>
      <title>Architecture of Kubernetes on a high level</title>
      <dc:creator>Pradipta</dc:creator>
      <pubDate>Wed, 21 Dec 2022 11:30:17 +0000</pubDate>
      <link>https://dev.to/pradz13/architecture-of-kubernetes-on-a-high-level-1lg2</link>
      <guid>https://dev.to/pradz13/architecture-of-kubernetes-on-a-high-level-1lg2</guid>
      <description>&lt;p&gt;As discussed in the previous post of the series, Kubernetes has one Master node and multiple Worker nodes. Master node monitors all Worker nodes. In Kubernetes, there must be at least one Cluster, one Master node and one Worker node.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Master Node&lt;/em&gt; : It has four components. They are API Manager, Scheduler, Controller Manager and ETCD.&lt;/p&gt;

&lt;p&gt;API Server acts as a Cluster Gateway. It can be used using command line tool kubectl or through Kubernetes Dashboard.&lt;/p&gt;

&lt;p&gt;Scheduler schedules PODs in the Worker nodes based of availability of CPU and Memory. Scheduler gets the information of Worker nodes from ETCD.&lt;/p&gt;

&lt;p&gt;Whenever a POD or Node gets crashed, ReplicaSet creates a new one. Controller Manager manages the process of Scheduling the same as per availability working with the Scheduler.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Worker Node&lt;/em&gt; : It has three components. They are kubelet, kube-proxy and Container runtime.&lt;/p&gt;

&lt;p&gt;Kubelet is an agent that runs on each Worker node and communicates with Master node using API Server.&lt;/p&gt;

&lt;p&gt;Kube-Proxy is a network agent that runs on each Worker node.&lt;/p&gt;

&lt;p&gt;Container runtime helps to run container inside PODs.&lt;/p&gt;

</description>
      <category>kubernetes</category>
    </item>
    <item>
      <title>Kubernetes and its main components</title>
      <dc:creator>Pradipta</dc:creator>
      <pubDate>Wed, 21 Dec 2022 10:58:00 +0000</pubDate>
      <link>https://dev.to/pradz13/kubernetes-and-its-main-components-1j81</link>
      <guid>https://dev.to/pradz13/kubernetes-and-its-main-components-1j81</guid>
      <description>&lt;p&gt;&lt;em&gt;Kubernetes(K8S)&lt;/em&gt; is a Container Orchestration Engine. It automates the process of deploying, scaling and managing containerized applications. &lt;/p&gt;

&lt;p&gt;There are many components of Kubernetes. Following are the key components - &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;em&gt;POD&lt;/em&gt; : Containers are wrapped into a functional unit known as PODs. Each POD has single IP address.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;em&gt;Node&lt;/em&gt; : PODs(one or multiple) are clubbed into a virtual machine known as Node.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;em&gt;Cluster&lt;/em&gt; : Multiple nodes are clubbed into Cluster. Kubernetes cluster comprises of one Master node and many Worker nodes.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;em&gt;ReplicaSet&lt;/em&gt; : Creates replicas of PODs to ensure no downtime of the application.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;em&gt;Service&lt;/em&gt; : One or more PODs can associate with a single Service. Service provides static IP and DNS name. Service also plays the role of Load Balancer by forwarding the traffic to the appropriate POD. There are three types of Services -&lt;br&gt;
       Cluster IP&lt;br&gt;
       NodePort&lt;br&gt;
       LoadBalancer&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;em&gt;Deployment&lt;/em&gt; : Kubernetes objects for managing PODs. Deployments can be created using commands or YML files.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;em&gt;ConfigMap and Secrets&lt;/em&gt; : Configurable properties of the application are stored in ConfigMap. Sensitive Configurable properties of the application are stored in Secrets.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;em&gt;ETCD&lt;/em&gt; : It is a key-vale datastore. Kubernetes cluster configuration is stored in ETCD.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;em&gt;Volumes&lt;/em&gt; : Volumes are used for persistent datastore like database.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>kubernetes</category>
    </item>
    <item>
      <title>What is Record in Java? What problem does it solve?</title>
      <dc:creator>Pradipta</dc:creator>
      <pubDate>Sat, 11 Jun 2022 16:40:22 +0000</pubDate>
      <link>https://dev.to/pradz13/what-is-record-in-java-what-problem-does-it-solve-3d8b</link>
      <guid>https://dev.to/pradz13/what-is-record-in-java-what-problem-does-it-solve-3d8b</guid>
      <description>&lt;p&gt;For any data intensive applications, we write Java classes that can hold the data as per our requirement.&lt;/p&gt;

&lt;p&gt;We need to define the following in most cases :&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Define the variables&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Define the constructor&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Define the getter and setter methods&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Override equals() and hashCode() methods&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Override the toString() method&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Although some of these can be auto-generated from IDEs, but lines of code increases with the increasing number of data elements.&lt;/p&gt;

&lt;p&gt;Record comes to the rescue and reduces all the boilerplate code we had to write thus far. Record was introduced in Java language as a preview feature in Java SE 14.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;How to define a record?&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public record EmployeeRecord(String name, int employeeNumber) {
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Records can be instantiated like a class and attributes can be accessed by getter methods[please note that the the getter method names do not start with getXXXX()]&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class RecordExampleTest {
    public static void main(String[] args) {
        EmployeeRecord employeeRecord = new EmployeeRecord("Pradipta", 123);
        System.out.println(String.format("Employee Name : %s , Employee Number : %s",
                employeeRecord.name(), employeeRecord.employeeNumber()));
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Constructor gets automatically generated which is known as &lt;em&gt;Cannonical Constructor&lt;/em&gt;. The methods like toString(), equals() and hashCode() methods are also automatically generated implicitly.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Some points to remember :&lt;/em&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Instance methods and static methods can be created inside a Record.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Static fields can be declared inside a Record.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Instance fields cannot be declared inside a Record.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Records cannot extend any other class as it implicitly extends Record class. As Java does not support Multiple Inheritance, Records cannot extend any other class.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Records are implicitly final - they cannot be extended by any other classes.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Records can implement interfaces.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Although Records provide Cannonical constructor by default, custom constructors can be created as well. It is not necessary to mention the arguments and set them explicitly if  all the arguments to be set as mentioned in the Record. This is also known as &lt;em&gt;Compact Constructor&lt;/em&gt;. Compact Constructors may be useful if some custom logic needs to be implemented.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The points mentioned above can be represented like below :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public record EmployeeRecord(String name, int employeeNumber) {
    private static final String DEFAULT_VALUE = "default-value";

    public EmployeeRecord {
        if(employeeNumber &amp;lt; 0)
            throw new IllegalStateException("Employee Numbers cannot be negative");
    }
    public String generateUniqueNumber() {
        return name + "-" + employeeNumber;
    }

    public static void printSomething() {
        System.out.println("Print anything here...." + DEFAULT_VALUE);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>record</category>
      <category>corejava</category>
      <category>productivity</category>
      <category>lesscode</category>
    </item>
    <item>
      <title>Regular Expressions - Cheat Sheet</title>
      <dc:creator>Pradipta</dc:creator>
      <pubDate>Fri, 23 Jul 2021 17:39:01 +0000</pubDate>
      <link>https://dev.to/pradz13/regex-cheat-sheet-33p2</link>
      <guid>https://dev.to/pradz13/regex-cheat-sheet-33p2</guid>
      <description>&lt;h1&gt;
  
  
  Metacharacters -
&lt;/h1&gt;

&lt;p&gt;a. Wildcard - dot(.) matches any character except line breaks&lt;br&gt;
b. Escaping - Backslash(\) allows use of metachacaters as literal characters&lt;br&gt;
c. Special characters - Space, Tab(\t)&lt;/p&gt;

&lt;h1&gt;
  
  
  Character Sets -
&lt;/h1&gt;

&lt;p&gt;[aeiou] - Matches one character from within the character set&lt;br&gt;
[a-zA-Z0-9] - Character range&lt;br&gt;
[^a-e] - Negative character set&lt;/p&gt;

&lt;p&gt;Shorthand - &lt;br&gt;
\d - [0-9]&lt;br&gt;
\w - [a-zA-Z0-9_]&lt;br&gt;
\s - Whitespace[\t\r\n]&lt;br&gt;
\D - No digit&lt;br&gt;
\W - Non word character&lt;br&gt;
\S - Not Whitespace&lt;/p&gt;

&lt;h1&gt;
  
  
  Repetition -
&lt;/h1&gt;

&lt;ul&gt;
&lt;li&gt;- Preciding item, 0 or more times&lt;/li&gt;
&lt;li&gt;- Preciding item, 1 or more times
? - Preciding item, 0 or 1 time&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Ex : Good .+. - matches Good morning. Good day.&lt;br&gt;
     \d+ - Matches any number of characters&lt;br&gt;
     \s[a-z]+ed\s - Matches any word ending with ed. &lt;br&gt;
It should have leading and trailing spaces.&lt;/p&gt;

&lt;p&gt;Quantified repition -&lt;br&gt;
{min, max}&lt;/p&gt;

&lt;p&gt;\d{4,8} - 4 to 8 digits&lt;br&gt;
\d{4} - Exactly 4 digits&lt;br&gt;
\d{4,} - With 4 or more digits&lt;/p&gt;

&lt;p&gt;Ex : \d{1}.\s\w{0,6}&lt;/p&gt;

&lt;p&gt;a. a&lt;br&gt;
b. ab&lt;br&gt;
c. abc&lt;br&gt;
d. abcd&lt;br&gt;
e. abcde&lt;br&gt;
f. abcdef&lt;/p&gt;

&lt;p&gt;(+\d{1})&lt;em&gt;\d{3}-&lt;/em&gt;\d{3}-*\d{4}&lt;br&gt;
111-233-3455&lt;br&gt;
1112333455&lt;br&gt;
+1111-233-3455&lt;/p&gt;

&lt;p&gt;Greedy Expression - Tries to match longest possible string&lt;/p&gt;

&lt;p&gt;Lazy Expression - ? - Make preceding quantifier lazy&lt;/p&gt;

&lt;p&gt;"(.|\n)+?" - Find anything within quotes including new line.&lt;/p&gt;

&lt;h1&gt;
  
  
  Grouping and Alteration
&lt;/h1&gt;

&lt;p&gt;(in)?dependent - Matches independent and dependent&lt;br&gt;
(abc)+ - Matches abc and abcabcabc&lt;/p&gt;

&lt;p&gt;(\d{3})-(\d{3})-(\d{4}) - 555-666-8767&lt;br&gt;
$1.($2).$3 - Gives 555.(666).8767&lt;/p&gt;

&lt;p&gt;Alternation Metacharacter - |&lt;br&gt;
apple|orange - Matches apple or orange&lt;/p&gt;

&lt;p&gt;peanut(butter)? - Matches peanutbutter (Greedy)&lt;br&gt;
peanut(butter)?? - Matches peanut (Lazy)&lt;/p&gt;

&lt;h1&gt;
  
  
  Anchors
&lt;/h1&gt;

&lt;p&gt;^ - Start of String/Line&lt;br&gt;
$ - End of String/Line&lt;br&gt;
\A - Start of String, never end of line&lt;br&gt;
\Z - End of String, never end of line&lt;/p&gt;

&lt;p&gt;^\w+.\w+@\w+.[a-z]{3}$ - Email validation(^ and $ added to ensure it matches entire regular expression)&lt;br&gt;
Word Boundary - \b - Word Boundary(Start/End of Word)&lt;br&gt;
        \B - Not a Word Boundary&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Secure your Restful WebServices using JWT | Spring Boot</title>
      <dc:creator>Pradipta</dc:creator>
      <pubDate>Sun, 21 Mar 2021 05:37:05 +0000</pubDate>
      <link>https://dev.to/pradz13/secure-your-restful-webservices-using-jwt-spring-boot-5f7p</link>
      <guid>https://dev.to/pradz13/secure-your-restful-webservices-using-jwt-spring-boot-5f7p</guid>
      <description>&lt;p&gt;JWT(JSON Web Token) is the most popular way of securing your Restful Web Services. If you want to learn more about JWT, please refer the following website -&lt;/p&gt;

&lt;p&gt;&lt;a href="https://jwt.io/"&gt;JWT Reference&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This article is intended towards a working example of how JWT can be implemented using Spring Boot, Spring Security and Relational Database(MySQL in this example).&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Create a new Spring Boot project and add the following dependencies -
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;dependency&amp;gt;
            &amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;
            &amp;lt;artifactId&amp;gt;spring-boot-starter-security&amp;lt;/artifactId&amp;gt;
        &amp;lt;/dependency&amp;gt;
        &amp;lt;dependency&amp;gt;
            &amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;
            &amp;lt;artifactId&amp;gt;spring-boot-starter-web&amp;lt;/artifactId&amp;gt;
        &amp;lt;/dependency&amp;gt;
        &amp;lt;dependency&amp;gt;
            &amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;
            &amp;lt;artifactId&amp;gt;spring-boot-starter-data-jpa&amp;lt;/artifactId&amp;gt;
        &amp;lt;/dependency&amp;gt;
        &amp;lt;dependency&amp;gt;
            &amp;lt;groupId&amp;gt;javax.xml.bind&amp;lt;/groupId&amp;gt;
            &amp;lt;artifactId&amp;gt;jaxb-api&amp;lt;/artifactId&amp;gt;
        &amp;lt;/dependency&amp;gt;
        &amp;lt;dependency&amp;gt;
            &amp;lt;groupId&amp;gt;io.jsonwebtoken&amp;lt;/groupId&amp;gt;
            &amp;lt;artifactId&amp;gt;jjwt&amp;lt;/artifactId&amp;gt;
            &amp;lt;version&amp;gt;0.9.1&amp;lt;/version&amp;gt;
        &amp;lt;/dependency&amp;gt;
        &amp;lt;dependency&amp;gt;
            &amp;lt;groupId&amp;gt;org.projectlombok&amp;lt;/groupId&amp;gt;
            &amp;lt;artifactId&amp;gt;lombok&amp;lt;/artifactId&amp;gt;
            &amp;lt;optional&amp;gt;true&amp;lt;/optional&amp;gt;
        &amp;lt;/dependency&amp;gt;
        &amp;lt;dependency&amp;gt;
            &amp;lt;groupId&amp;gt;mysql&amp;lt;/groupId&amp;gt;
            &amp;lt;artifactId&amp;gt;mysql-connector-java&amp;lt;/artifactId&amp;gt;
            &amp;lt;scope&amp;gt;runtime&amp;lt;/scope&amp;gt;
        &amp;lt;/dependency&amp;gt;
        &amp;lt;dependency&amp;gt;
            &amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;
            &amp;lt;artifactId&amp;gt;spring-boot-starter-test&amp;lt;/artifactId&amp;gt;
            &amp;lt;scope&amp;gt;test&amp;lt;/scope&amp;gt;
            &amp;lt;exclusions&amp;gt;
                &amp;lt;exclusion&amp;gt;
                    &amp;lt;groupId&amp;gt;org.junit.vintage&amp;lt;/groupId&amp;gt;
                    &amp;lt;artifactId&amp;gt;junit-vintage-engine&amp;lt;/artifactId&amp;gt;
                &amp;lt;/exclusion&amp;gt;
            &amp;lt;/exclusions&amp;gt;
        &amp;lt;/dependency&amp;gt;
        &amp;lt;dependency&amp;gt;
            &amp;lt;groupId&amp;gt;org.springframework.security&amp;lt;/groupId&amp;gt;
            &amp;lt;artifactId&amp;gt;spring-security-test&amp;lt;/artifactId&amp;gt;
            &amp;lt;scope&amp;gt;test&amp;lt;/scope&amp;gt;
        &amp;lt;/dependency&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Add the following properties in application.properties that resides in src/main/resources -
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;server.port=9091
jwtdemo.secretKey=jWtSpRiNgBoOtExAmPlE

spring.datasource.url = jdbc:mysql://localhost:3306/&amp;lt;Database Name&amp;gt;?useSSL=false
spring.datasource.username = &amp;lt;DB User Name&amp;gt;
spring.datasource.password = &amp;lt;DB Password&amp;gt;


## Hibernate Properties
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect

# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = update
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Add the following Configuration class to read the values from properties file -
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConfigurationProperties(prefix = "jwtdemo")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ConfigProperties {
    private String secretKey;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Add the following Security Configuration.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import com.springboot.jwt.filter.JWTFilter;
import com.springboot.jwt.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserService userService;

    @Autowired
    private JWTFilter jwtFilter;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService);
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf()
                .disable()
                .authorizeRequests()
                .antMatchers("/authenticate", "/add-user")
                .permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        http.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Add the following Entity class which corresponding to the database table -
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.*;

@Entity
@Table(name = "userdetails")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Column(name = "first_name")
    private String firstName;

    @Column(name = "last_name")
    private String lastName;

    @Column(name = "email")
    private String email;

    @Column(name = "user_name")
    private String userName;

    @Column(name = "password")
    private String password;
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Add the database repository interface
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import com.springboot.jwt.entity.UserEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface UserRepository extends JpaRepository&amp;lt;UserEntity, Long&amp;gt; {
    UserEntity findByUserName(String userName);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Add the following JWT Utility class -
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import com.springboot.jwt.config.ConfigProperties;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

@Component
public class JWTUtility implements Serializable {

    private static final long serialVersionUID = 1L;

    public static final long JWT_TOKEN_VALIDITY = 5 * 60 * 60;

    @Autowired
    private ConfigProperties configProperties;

    //retrieve username from jwt token
    public String getUsernameFromToken(String token) {
        return getClaimFromToken(token, Claims::getSubject);
    }

    //retrieve expiration date from jwt token
    public Date getExpirationDateFromToken(String token) {
        return getClaimFromToken(token, Claims::getExpiration);
    }


    public &amp;lt;T&amp;gt; T getClaimFromToken(String token, Function&amp;lt;Claims, T&amp;gt; claimsResolver) {
        final Claims claims = getAllClaimsFromToken(token);
        return claimsResolver.apply(claims);
    }


    //for retrieving any information from token we will need the secret key
    private Claims getAllClaimsFromToken(String token) {
        return Jwts.parser().setSigningKey(configProperties.getSecretKey()).parseClaimsJws(token).getBody();
    }


    //check if the token has expired
    private Boolean isTokenExpired(String token) {
        final Date expiration = getExpirationDateFromToken(token);
        return expiration.before(new Date());
    }


    //generate token for user
    public String generateToken(UserDetails userDetails) {
        Map&amp;lt;String, Object&amp;gt; claims = new HashMap&amp;lt;&amp;gt;();
        return doGenerateToken(claims, userDetails.getUsername());
    }


    //while creating the token -
    //1. Define  claims of the token, like Issuer, Expiration, Subject, and the ID
    //2. Sign the JWT using the HS512 algorithm and secret key.
    private String doGenerateToken(Map&amp;lt;String, Object&amp;gt; claims, String subject) {
        return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + JWT_TOKEN_VALIDITY * 1000))
                .signWith(SignatureAlgorithm.HS512, configProperties.getSecretKey()).compact();
    }


    //validate token
    public Boolean validateToken(String token, UserDetails userDetails) {
        final String username = getUsernameFromToken(token);
        return (username.equals(userDetails.getUsername()) &amp;amp;&amp;amp; !isTokenExpired(token));
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Add the following model objects for sending and receiving JWT Request and Response data simultaneously.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class JWTRequest {

    private String userName;
    private String password;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class JWTResponse {

    private String jwtToken;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Add the JWT Request Filter for performing the authentication.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import com.springboot.jwt.service.UserService;
import com.springboot.jwt.utility.JWTUtility;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JWTFilter extends OncePerRequestFilter {

    @Autowired
    private JWTUtility jwtUtility;

    @Autowired
    private UserService userService;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest,
                                    HttpServletResponse httpServletResponse,
                                    FilterChain filterChain) throws ServletException, IOException {

        String authorization = httpServletRequest.getHeader("Authorization");
        String token = null;
        String userName = null;

        if(null != authorization &amp;amp;&amp;amp; authorization.startsWith("Bearer ")) {
            token = authorization.substring(7);
            userName = jwtUtility.getUsernameFromToken(token);
        }

        if(null != userName &amp;amp;&amp;amp; SecurityContextHolder.getContext().getAuthentication() == null) {
            UserDetails userDetails = userService.loadUserByUsername(userName);

            if(jwtUtility.validateToken(token,userDetails)) {
                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken
                        = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());

                usernamePasswordAuthenticationToken.setDetails(
                        new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));

                SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            }

        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Add the Service class -
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import com.springboot.jwt.entity.UserEntity;
import com.springboot.jwt.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

@Service
public class UserService implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        UserEntity userEntity = userRepository.findByUserName(s);
        return new User(userEntity.getUserName(), userEntity.getPassword(), new ArrayList&amp;lt;&amp;gt;());
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Add the Controller class with three endpoints- /add-user endpoint is used for adding user to database, /authenticate is used for JWT Authentication, /restricted-access-rest-endpoint is a restricted endpoint which can be used post successful JWT authentication -
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import com.springboot.jwt.entity.UserEntity;
import com.springboot.jwt.model.JWTRequest;
import com.springboot.jwt.model.JWTResponse;
import com.springboot.jwt.repository.UserRepository;
import com.springboot.jwt.service.UserService;
import com.springboot.jwt.utility.JWTUtility;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
public class UserController {

    @Autowired
    private JWTUtility jwtUtility;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserService userService;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @PostMapping("/add-user")
    public UserEntity createUser(@RequestBody UserEntity userEntity) {
        log.info("Saving the new user with user name : " + userEntity.getUserName());
        userEntity.setPassword(passwordEncoder.encode(userEntity.getPassword()));
        return userRepository.save(userEntity);
    }

    @GetMapping("/restricted-access-rest-endpoint")
    public String restrictedAccessEndpoint() {
        return "Welcome to the demo of JWT with Spring Boot!!!!";
    }

    @PostMapping("/authenticate")
    public JWTResponse authenticate(@RequestBody JWTRequest jwtRequest) throws Exception {
        try {
            authenticationManager.authenticate
                    (new UsernamePasswordAuthenticationToken(jwtRequest.getUserName(), jwtRequest.getPassword()));

        } catch (BadCredentialsException e) {
            throw new Exception("INVALID_CREDENTIALS", e);
        }
        final UserDetails userDetails = userService.loadUserByUsername(jwtRequest.getUserName());
        final String token = jwtUtility.generateToken(userDetails);
        return new JWTResponse(token);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;The entire source code is available in the following link - 
&lt;a href="https://github.com/pradz13/JWTDemoSpringBoot"&gt;JWTCodebase&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>springboot</category>
      <category>java</category>
      <category>rest</category>
      <category>jwt</category>
    </item>
    <item>
      <title>Important IntelliJ Idea Shortcuts I use in my day-to-day coding</title>
      <dc:creator>Pradipta</dc:creator>
      <pubDate>Sun, 21 Feb 2021 16:04:09 +0000</pubDate>
      <link>https://dev.to/pradz13/important-intellij-idea-shortcuts-i-use-in-my-day-to-day-coding-g9g</link>
      <guid>https://dev.to/pradz13/important-intellij-idea-shortcuts-i-use-in-my-day-to-day-coding-g9g</guid>
      <description>&lt;p&gt;IntelliJ Idea IDE is the most popular IDE among Java Developers now-a-days. I use it for my day-to-day coding assignments. I use the following shortcuts quite heavily to improve my productivity while using IntelliJ Idea.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Alt + 1 - Show/Hide Project Explorer&lt;/li&gt;
&lt;li&gt;Double Shift - Search Anything in IntelliJ Idea&lt;/li&gt;
&lt;li&gt;Increase Fonts - Double Shift and Search 'Increase Fonts'&lt;/li&gt;
&lt;li&gt;Decrease  Fonts - Double Shift and Search 'Decrease Fonts'&lt;/li&gt;
&lt;li&gt;Ctrl + E - Navigate between files opened in Explorer&lt;/li&gt;
&lt;li&gt;Ctrl + Shift + E - Shows the last changed files&lt;/li&gt;
&lt;li&gt;Ctrl + Shift + N - Search all files&lt;/li&gt;
&lt;li&gt;Ctrl + N - Search only class files&lt;/li&gt;
&lt;li&gt;Ctrl +  Alt + L - Reformat Code&lt;/li&gt;
&lt;li&gt;Ctrl + B - Open Declaration&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;I hope these shortcuts will also help you to improve your productivity. For complete list of shortcuts, please refer to the Jetbrains official website - &lt;/p&gt;

&lt;p&gt;(&lt;a href="https://www.jetbrains.com/help/idea/mastering-keyboard-shortcuts.html"&gt;https://www.jetbrains.com/help/idea/mastering-keyboard-shortcuts.html&lt;/a&gt;)&lt;/p&gt;

</description>
      <category>productivity</category>
      <category>java</category>
      <category>development</category>
      <category>spring</category>
    </item>
  </channel>
</rss>
