<?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 Bhagya Akalanka on Medium]]></title>
        <description><![CDATA[Stories by Bhagya Akalanka on Medium]]></description>
        <link>https://medium.com/@bsakalanka9?source=rss-5e44518f4da5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Qqgy0COq8w1YmbU4C4GR0Q.jpeg</url>
            <title>Stories by Bhagya Akalanka on Medium</title>
            <link>https://medium.com/@bsakalanka9?source=rss-5e44518f4da5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 06:42:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bsakalanka9/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[A Journey on Spring Boot | Introduction to CRUD Operations]]></title>
            <link>https://medium.com/@bsakalanka9/a-journey-on-spring-boot-introduction-to-crud-operations-3472a136e728?source=rss-5e44518f4da5------2</link>
            <guid isPermaLink="false">https://medium.com/p/3472a136e728</guid>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Bhagya Akalanka]]></dc:creator>
            <pubDate>Fri, 19 Jan 2024 19:10:56 GMT</pubDate>
            <atom:updated>2024-01-19T19:10:56.881Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello There,</p><p>In this article, lets find-out what are CRUD operations and how we can perform these CRUD operations using our spring boot application. I will initialize a new project by going to <a href="https://start.spring.io/">Spring Initializer</a>. You can learn more about how to initialize a spring boot project and setup your basic working environment by checking <a href="https://medium.com/@bsakalanka9/a-journey-on-spring-boot-introduction-caee3160c8b7">this article</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GVe1BiL7jdqrXIIAk6Sj5w.jpeg" /><figcaption>CRUD Operations</figcaption></figure><p>First lets see what is this fancy word CRUD Operations and what it means.</p><p>CRUD stand for CREATE, READ, UPDATE and DELETE. So CRUD operations means, performing these create, read, update and delete operations on data.</p><p>CREATE : Creating new resources. We will use POST requests to create new resources</p><p>READ : Reading / fetching resources. We will use GET requests to read resources</p><p>UPDATE : Updating / modifying existing resources. We will use PUT and PATCH requests to update resources</p><p>DELETE : Deleting / removing resources. We will use DELETE requests to delete resources.</p><p>In the <a href="https://medium.com/@bsakalanka9/a-journey-on-spring-boot-introduction-caee3160c8b7">previous article</a>, we saw how we can implement a Rest API to get data. In this article, lets see how we can implement all these above CRUD operations and manipulate our data using Spring boot application.</p><p>When working with spring boot, we need to manage our code in proper structure. In the first article, I just create a controller and service class in the root directory and show the magic. But that is not a good practice going forward. So, lets create better folder structure for this project. And follow best practices while coding 😃</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*yltM7mNr6G9Sf6ZJmaPd9A.png" /><figcaption>Folder structure</figcaption></figure><p>For this project, I will use my folder structure as in the above image. I will have separate folders for my controllers, services and model classes.</p><p>Typically, when we talk about CRUD operations it involves databases because most of the data we have will be stored in databases. But since we have not yet discuss about how to connect to a database, I will use a small hack. I will be using a static Map object to show you how each CRUD operation works in spring boot. Once we learn about databases in the coming articles, we can replace this hack with the proper way.</p><p>Using a static object to perform CRUD operations in not a good solution because of multiple reasons.</p><ul><li>Data loss when restart the application</li><li>Synchronization issues</li><li>Memory issues</li></ul><p>But bear with me. One reason I am using this method is to show you what is good and what is bad.</p><p>So, first, let’s design our controller class with our APIs. For this application, we are considering a use case as below.</p><p>A: We are managing users. A user can have following attributes</p><ul><li>Username</li><li>UserId</li><li>First Name</li><li>Last Name</li><li>Emails</li></ul><p>B: We should be able to do following operations</p><ul><li>Create new users</li><li>Get all users</li><li>Get users by their name</li><li>Get users by their id</li><li>Update users using their id — Patch</li><li>Update users using their id — Put</li><li>Delete users using their id</li></ul><p>So, for above cases, lets write our controller class. But before creating the controller class, let’s first define our model class.</p><p>I named my model class as User.Java</p><pre>package com.b1zt.springboot.crud.model;<br><br>import java.util.List;<br><br>public class User {<br><br>    private String username;<br>    private int userId;<br>    private String firstName;<br>    private String lastName;<br>    private List&lt;String&gt; emails;<br><br>    public User(String username, int userId, String firstName, String lastName, List&lt;String&gt; emails) {<br>        this.username = username;<br>        this.userId = userId;<br>        this.firstName = firstName;<br>        this.lastName = lastName;<br>        this.emails = emails;<br>    }<br><br>    // getters and setters<br><br>    public String getUsername() {<br><br>        return username;<br>    }<br><br>    public void setUsername(String username) {<br><br>        this.username = username;<br>    }<br><br>    public int getUserId() {<br><br>        return userId;<br>    }<br><br>    public void setUserId(int userId) {<br><br>        this.userId = userId;<br>    }<br><br>    public String getFirstName() {<br><br>        return firstName;<br>    }<br><br>    public void setFirstName(String firstName) {<br><br>        this.firstName = firstName;<br>    }<br><br>    public String getLastName() {<br><br>        return lastName;<br>    }<br><br>    public void setLastName(String lastName) {<br><br>        this.lastName = lastName;<br>    }<br><br>    public List&lt;String&gt; getEmails() {<br><br>        return emails;<br>    }<br><br>    public void setEmails(List&lt;String&gt; emails) {<br><br>        this.emails = emails;<br>    }<br>}</pre><p>I added a simple class with the attributes we discussed in A. Added get and set methods to read and update these attributes. Also, I have added all attribute constructor for the class.</p><p>Now lets check the controller class and try to understand what is happening there. I named my controller class as UserController.java</p><pre>package com.b1zt.springboot.crud.controller;<br><br>import com.b1zt.springboot.crud.model.User;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.web.bind.annotation.DeleteMapping;<br>import org.springframework.web.bind.annotation.GetMapping;<br>import org.springframework.web.bind.annotation.PatchMapping;<br>import org.springframework.web.bind.annotation.PathVariable;<br>import org.springframework.web.bind.annotation.PostMapping;<br>import org.springframework.web.bind.annotation.PutMapping;<br>import org.springframework.web.bind.annotation.RequestBody;<br>import org.springframework.web.bind.annotation.RequestMapping;<br>import org.springframework.web.bind.annotation.RequestParam;<br>import org.springframework.web.bind.annotation.RestController;<br><br>import java.util.List;<br><br>@RestController<br>@RequestMapping(&quot;/api/users&quot;)<br>public class UserController {<br><br>    @Autowired<br>    private UserService userService;<br><br>    @GetMapping(&quot;/&quot;)<br>    public List&lt;User&gt; getUsers() {<br><br>        return userService.getUsers();<br>    }<br><br>    @GetMapping(&quot;/{userId}&quot;)<br>    public User getUserById(@PathVariable int userId) {<br><br>        return userService.getUserById(userId);<br>    }<br><br>    @GetMapping(&quot;/name&quot;)<br>    public User getUserByName(@RequestParam String username) {<br><br>        return userService.getUserByName(username);<br>    }<br><br>    @PostMapping(&quot;/&quot;)<br>    public User createUser(@RequestBody User user) {<br><br>        return userService.createUser(user);<br>    }<br><br>    @PutMapping(&quot;/{userId}&quot;)<br>    public User updateUser(@PathVariable int userId, @RequestBody User user) {<br><br>        return userService.updateUser(userId, user);<br>    }<br><br>    @PatchMapping(&quot;/{userId}&quot;)<br>    public User patchUser(@PathVariable int userId, @RequestBody User user) {<br><br>        return userService.patchUser(userId, user);<br>    }<br><br>    @DeleteMapping(&quot;/{userId}&quot;)<br>    public void deleteUser(@PathVariable int userId) {<br><br>        userService.deleteUser(userId);<br>    }<br>}</pre><p>I have seven methods defined in this class to do the operations we dicussed in B.</p><p>In the top of the class, we defined a @RequestMapping annotation with api/user as the value to defined our endpoint URL.</p><p>We inject the UserService class using @Autowired annotation. We are yet to implement the UserService class.</p><ul><li>getUsers() : We use this method to list all the users</li><li>getUserById(@PathVariable int userId) : We use this method to fetch a user using the userId. Here we pass the userId as a path variable. For example, our URI looks something like this ../api/users/1</li><li>getUserByName(@RequestParam String username) : We use this method to fetch a user using the username. Here we pass the username as a query param. For example, our URI looks something like this ../api/users/name?username=b1zt</li><li>createUser(@RequestBody User user) : We use this method to create a new user. Here we pass the user object along with the request body.</li><li>updateUser(@PathVariable int userId, @RequestBody User user) : We use this method to replace a user with the new user object using the userId. So, existing user will fully replaced with the new user object we send in the request body for the given userId</li><li>patchUser(@PathVariable int userId, @RequestBody User user) : We use this method to partially / fully update a user for the given userId. Here, we will not fully replace the user with the new User object in the request body. Instead, we will update the existing user object with only the not null attributes of the new User object.</li><li>deleteUser(@PathVariable int userId) : We use this method to delete/ remove a user using the userId.</li></ul><p>Now, let’s implement our service class. The service class is named as UserService.java</p><pre>package com.b1zt.springboot.crud.service;<br><br>import com.b1zt.springboot.crud.model.User;<br>import org.springframework.stereotype.Service;<br><br>import java.util.ArrayList;<br>import java.util.HashMap;<br>import java.util.List;<br>import java.util.Map;<br><br>@Service<br>public class UserService {<br><br>    private static final Map&lt;Integer, User&gt; userRepository = new HashMap&lt;&gt;();<br>    public List&lt;User&gt; getUsers() {<br>            <br>        return new ArrayList&lt;&gt;(userRepository.values());<br>    }<br><br>    public User getUserById(Long userId) {<br><br>        return userRepository.get(userId);<br>    }<br><br>    public User getUserByName(String username) {<br><br>        return userRepository.values().stream().filter(user -&gt; user.getUsername().equals(username)).findFirst().orElse(null);<br>    }<br><br>    public User createUser(User user) {<br>        if (userRepository.containsKey(user.getUserId())) {<br>            throw new RuntimeException(&quot;User already exists&quot;);<br>        }<br>        userRepository.put(user.getUserId(), user);<br>        return user;<br>    }<br><br>    public User updateUser(int userId, User user) {<br><br>        if (!userRepository.containsKey(userId)) {<br>            throw new RuntimeException(&quot;User does not exist&quot;);<br>        }<br>        userRepository.put(user.getUserId(), user);<br>        return user;<br>    }<br><br>    public User patchUser(int userId, User user) {<br><br>        if (!userRepository.containsKey(userId)) {<br>            throw new RuntimeException(&quot;User does not exist&quot;);<br>        }<br>        User existingUser = userRepository.get(userId);<br>        if (user.getFirstName() != null) {<br>            existingUser.setFirstName(user.getFirstName());<br>        }<br>        if (user.getLastName() != null) {<br>            existingUser.setLastName(user.getLastName());<br>        }<br>        if (user.getEmails() != null) {<br>            existingUser.setEmails(user.getEmails());<br>        }<br>        userRepository.put(userId, existingUser);<br>        return existingUser;<br>    }<br><br>    public void deleteUser(int userId) {<br><br>        if (userRepository.containsKey(userId)) {<br>            userRepository.remove(userId);<br>        }<br>    }<br>}</pre><p>As I told before, I will be using a static Map as my user repository to store my users. I have not handled any synchronization issues as this is a simple demonstration. In this class I have added the business logic to our 7 operations in B.</p><ul><li>getUsers: Get all the users in user repository and return as an array list</li><li>getUserById: Get the user by userId. In the user repository, we use the userId as the key. So we can directly access the user object via the userId</li><li>getUserByName: Get the user by username. Here, we are using java stream and filter APIs to check if a user with the given username exists in the user repository. If found, return the user. Otherwise returns null</li><li>createUser: We create new users using this method. Here, we first check if a user already exists with the given id. If so, we don’t create the new user. Also, we could check for the existence of the username as well. (A job for you 😜)</li><li>updateUser: We use this method with the PUT request to completely replace the existing user with new user. Here also, we check for the existence of the user before updating. Main reason for this check is, <strong>we should not use PUT / PATCH to create new resources</strong></li><li>patchUser: We use this method with the PATCH request to partially update the existing user. Here, we check if the first name, last name and emails separately and update the user object if those are not null. Here I did not update the username mainly because it could make duplicate usernames if the validation is not done properly. (You can improve the code)</li><li>deleteUser: We use this method to remove user from the user repository based on the userId</li></ul><p>Now, it is time for testing 😀</p><pre>{<br> &quot;info&quot;: {<br>  &quot;_postman_id&quot;: &quot;da712ae4-7d46-40b7-9a30-73c16d01d1dc&quot;,<br>  &quot;name&quot;: &quot;CRUD&quot;,<br>  &quot;schema&quot;: &quot;https://schema.getpostman.com/json/collection/v2.1.0/collection.json&quot;,<br>  &quot;_exporter_id&quot;: &quot;26449406&quot;<br> },<br> &quot;item&quot;: [<br>  {<br>   &quot;name&quot;: &quot;Get Users&quot;,<br>   &quot;request&quot;: {<br>    &quot;method&quot;: &quot;GET&quot;,<br>    &quot;header&quot;: [],<br>    &quot;url&quot;: {<br>     &quot;raw&quot;: &quot;http://localhost:8080/crud/api/users/&quot;,<br>     &quot;protocol&quot;: &quot;http&quot;,<br>     &quot;host&quot;: [<br>      &quot;localhost&quot;<br>     ],<br>     &quot;port&quot;: &quot;8080&quot;,<br>     &quot;path&quot;: [<br>      &quot;crud&quot;,<br>      &quot;api&quot;,<br>      &quot;users&quot;,<br>      &quot;&quot;<br>     ]<br>    }<br>   },<br>   &quot;response&quot;: []<br>  },<br>  {<br>   &quot;name&quot;: &quot;Get User By UserId&quot;,<br>   &quot;request&quot;: {<br>    &quot;method&quot;: &quot;GET&quot;,<br>    &quot;header&quot;: [],<br>    &quot;url&quot;: {<br>     &quot;raw&quot;: &quot;http://localhost:8080/crud/api/users/1&quot;,<br>     &quot;protocol&quot;: &quot;http&quot;,<br>     &quot;host&quot;: [<br>      &quot;localhost&quot;<br>     ],<br>     &quot;port&quot;: &quot;8080&quot;,<br>     &quot;path&quot;: [<br>      &quot;crud&quot;,<br>      &quot;api&quot;,<br>      &quot;users&quot;,<br>      &quot;1&quot;<br>     ]<br>    }<br>   },<br>   &quot;response&quot;: []<br>  },<br>  {<br>   &quot;name&quot;: &quot;Get User By Username&quot;,<br>   &quot;request&quot;: {<br>    &quot;method&quot;: &quot;GET&quot;,<br>    &quot;header&quot;: [],<br>    &quot;url&quot;: {<br>     &quot;raw&quot;: &quot;http://localhost:8080/crud/api/users/name?username=b1zt&quot;,<br>     &quot;protocol&quot;: &quot;http&quot;,<br>     &quot;host&quot;: [<br>      &quot;localhost&quot;<br>     ],<br>     &quot;port&quot;: &quot;8080&quot;,<br>     &quot;path&quot;: [<br>      &quot;crud&quot;,<br>      &quot;api&quot;,<br>      &quot;users&quot;,<br>      &quot;name&quot;<br>     ],<br>     &quot;query&quot;: [<br>      {<br>       &quot;key&quot;: &quot;username&quot;,<br>       &quot;value&quot;: &quot;b1zt&quot;<br>      }<br>     ]<br>    }<br>   },<br>   &quot;response&quot;: []<br>  },<br>  {<br>   &quot;name&quot;: &quot;Create User&quot;,<br>   &quot;request&quot;: {<br>    &quot;method&quot;: &quot;POST&quot;,<br>    &quot;header&quot;: [],<br>    &quot;body&quot;: {<br>     &quot;mode&quot;: &quot;raw&quot;,<br>     &quot;raw&quot;: &quot;{\n    \&quot;username\&quot; : \&quot;b1zt\&quot;,\n    \&quot;userId\&quot; : 1,\n    \&quot;firstName\&quot; : \&quot;Bhagya\&quot;,\n    \&quot;lastName\&quot; : \&quot;Akalanka\&quot;,\n    \&quot;emails\&quot; : [\&quot;bsakalanka9@gmail.com\&quot;, \&quot;bhagyaa@wso2.com\&quot;]\n}&quot;,<br>     &quot;options&quot;: {<br>      &quot;raw&quot;: {<br>       &quot;language&quot;: &quot;json&quot;<br>      }<br>     }<br>    },<br>    &quot;url&quot;: {<br>     &quot;raw&quot;: &quot;http://localhost:8080/crud/api/users/&quot;,<br>     &quot;protocol&quot;: &quot;http&quot;,<br>     &quot;host&quot;: [<br>      &quot;localhost&quot;<br>     ],<br>     &quot;port&quot;: &quot;8080&quot;,<br>     &quot;path&quot;: [<br>      &quot;crud&quot;,<br>      &quot;api&quot;,<br>      &quot;users&quot;,<br>      &quot;&quot;<br>     ]<br>    }<br>   },<br>   &quot;response&quot;: []<br>  },<br>  {<br>   &quot;name&quot;: &quot;Update User&quot;,<br>   &quot;request&quot;: {<br>    &quot;method&quot;: &quot;PUT&quot;,<br>    &quot;header&quot;: [],<br>    &quot;body&quot;: {<br>     &quot;mode&quot;: &quot;raw&quot;,<br>     &quot;raw&quot;: &quot;{\n    \&quot;username\&quot; : \&quot;b1zt\&quot;,\n    \&quot;userId\&quot; : 1,\n    \&quot;firstName\&quot; : \&quot;Bhagya\&quot;,\n    \&quot;lastName\&quot; : \&quot;Shiran\&quot;,\n    \&quot;emails\&quot; : [\&quot;abc@gmail.com\&quot;]\n}&quot;,<br>     &quot;options&quot;: {<br>      &quot;raw&quot;: {<br>       &quot;language&quot;: &quot;json&quot;<br>      }<br>     }<br>    },<br>    &quot;url&quot;: {<br>     &quot;raw&quot;: &quot;http://localhost:8080/crud/api/users/1&quot;,<br>     &quot;protocol&quot;: &quot;http&quot;,<br>     &quot;host&quot;: [<br>      &quot;localhost&quot;<br>     ],<br>     &quot;port&quot;: &quot;8080&quot;,<br>     &quot;path&quot;: [<br>      &quot;crud&quot;,<br>      &quot;api&quot;,<br>      &quot;users&quot;,<br>      &quot;1&quot;<br>     ]<br>    }<br>   },<br>   &quot;response&quot;: []<br>  },<br>  {<br>   &quot;name&quot;: &quot;Patch User&quot;,<br>   &quot;request&quot;: {<br>    &quot;method&quot;: &quot;PATCH&quot;,<br>    &quot;header&quot;: [],<br>    &quot;body&quot;: {<br>     &quot;mode&quot;: &quot;raw&quot;,<br>     &quot;raw&quot;: &quot;{\n    \&quot;username\&quot; : \&quot;b1zt\&quot;,\n    \&quot;userId\&quot; : 1,\n    \&quot;lastName\&quot; : \&quot;Akalanka\&quot;,\n    \&quot;emails\&quot; : [\&quot;bsakalanka9@gmail.com\&quot;, \&quot;bhagyaa@wso2.com\&quot;]\n}&quot;,<br>     &quot;options&quot;: {<br>      &quot;raw&quot;: {<br>       &quot;language&quot;: &quot;json&quot;<br>      }<br>     }<br>    },<br>    &quot;url&quot;: {<br>     &quot;raw&quot;: &quot;http://localhost:8080/crud/api/users/1&quot;,<br>     &quot;protocol&quot;: &quot;http&quot;,<br>     &quot;host&quot;: [<br>      &quot;localhost&quot;<br>     ],<br>     &quot;port&quot;: &quot;8080&quot;,<br>     &quot;path&quot;: [<br>      &quot;crud&quot;,<br>      &quot;api&quot;,<br>      &quot;users&quot;,<br>      &quot;1&quot;<br>     ]<br>    }<br>   },<br>   &quot;response&quot;: []<br>  },<br>  {<br>   &quot;name&quot;: &quot;Delete User&quot;,<br>   &quot;request&quot;: {<br>    &quot;method&quot;: &quot;GET&quot;,<br>    &quot;header&quot;: []<br>   },<br>   &quot;response&quot;: []<br>  }<br> ]<br>}</pre><p>Above is a simple postman collection I created to test these API calls. You can import this collection to your postman and try out these APIs easily.</p><p>One thing to notice is, I deployed my application in tomcat and I gave the war file the name crud . That’s why my API endpoints are in this format http://localhost:8080/crud/api/users/..</p><p>Try out the APIs, Modify the code and test.</p><p>So in this article, we learn about CRUD operations and how to perform these operations from spring boot applications. Now you should be able to write a simple controller class and expose your own APIs. In the next section, let’s find out how to integrate a database with a spring boot application.</p><p>If you have any question, suggestions or feedback feel free to ask. 😉😉😉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3472a136e728" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Journey on Spring Boot | Introduction]]></title>
            <link>https://medium.com/@bsakalanka9/a-journey-on-spring-boot-introduction-caee3160c8b7?source=rss-5e44518f4da5------2</link>
            <guid isPermaLink="false">https://medium.com/p/caee3160c8b7</guid>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring-boot-introduction]]></category>
            <dc:creator><![CDATA[Bhagya Akalanka]]></dc:creator>
            <pubDate>Mon, 01 Jan 2024 18:30:43 GMT</pubDate>
            <atom:updated>2024-01-01T18:30:43.067Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello all,</p><p>In this series, I will write about Spring boot. I will go from the very beginning of creating a spring project to many complex parts of spring boot. You will be able to learn very basic concepts to complex concepts.</p><p>In this article, let’s see how we can setup a simple Spring boot project and write our first API</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*o5FmjKTPdJTbhGE2MIjo6w.jpeg" /><figcaption>Spring boot</figcaption></figure><p>First, lets go to <a href="https://start.spring.io/">Spring Initializer</a> and setup our project.</p><p>Select followings:</p><pre>* Project: Maven<br>* Language: Java<br>* Spring Boot: 3.2.1 (3.2.x)<br><br>* Under project metadata, provide details about your project<br><br>* Packaging: war (Lets create a war file and deploy in tomcat)<br>* Java: 17</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wNSEWwcc8jPswc3hE7n1Sg.png" /><figcaption>Sample initial configurations</figcaption></figure><p>Now lets click on the <strong>Generate</strong> button and download our project file</p><p>I will be using Intellij as my IDE.</p><p>Lets now see how we can import this downloaded project as an intellij project</p><ol><li>Extract the downloaded zip file</li><li>Open Intellij</li><li>File -&gt; New -&gt; Project from existing sources …</li><li>Click next until the project is opened in intellij</li></ol><p>Now we are ready for coding. Lets write our first API.</p><p>For that, we need a controller class. The controller class will be responsible for <strong>handling a request and returning a model and a view.</strong> The controller class should be very simple and we should not write our business logics within the controller class.</p><p>For writing our business logics, we use service class. The service class will be responsible for performing business logic of the application.</p><p>In this article, lets create a controller class and a service class.</p><p>Controller class</p><pre>package com.b1zt.springboot.introduction;<br><br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.stereotype.Controller;<br>import org.springframework.web.bind.annotation.GetMapping;<br>import org.springframework.web.bind.annotation.RequestMapping;<br>import org.springframework.web.bind.annotation.RequestParam;<br>import org.springframework.web.bind.annotation.RestController;<br><br>@RestController()<br>@RequestMapping(&quot;/api&quot;)<br>public class IntroductoryController {<br><br>    @Autowired<br>    private IntroductoryService introductoryService;<br><br>    @GetMapping(&quot;/hello&quot;)<br>    public String hello() {<br>        return introductoryService.hello();<br>    }<br><br>    @GetMapping(&quot;/helloWithName&quot;)<br>    public String helloWithName(@RequestParam String name) {<br>        return introductoryService.helloWithName(name);<br>    }<br><br>}</pre><p>In the above class, I want to highlight following annotations</p><p>@RestController: When a class is annotated with @RestController, it is treated as a controller where every method returns a domain object, and the object is automatically serialized into JSON or XML response by Spring.</p><p>@RequestMapping: This can be used in both class level and method level. When used at the class level, @RequestMapping is often used to define a common base path for all handler methods within that controller. At the method level, it is used to specify the endpoint path and HTTP method(s) that a particular method should handle.</p><p>@Autowired: The @Autowired annotation in Spring is used to automatically inject dependencies into a Spring bean. With @Autowired annotation, we do not need to explicitly initialize objects. In our code, we use this annotation to create a variable of IntroductoryService but we have not initialized that that variable anywhere. Spring will automatically initialized this object for us.</p><p>@GetMapping: The @GetMapping annotation is a specialized form of the more general @RequestMapping annotation in the Spring Framework. It is used to map HTTP GET requests to a specific method or handler in a controller class. This annotation is commonly used when building RESTful web services or applications where you want to handle HTTP GET requests for specific endpoints.</p><p>In the above code, I have defined two methods</p><p>public String hello(): This method is a simple get method. Once we make a get request to the path defined by the @RequestMapping annotation, we will be able to invoke this method</p><p>public String helloWithname(@RequestParam String name): This method expect a query parameter called name. If we make a get request to the path defined by the @RequestMapping annotation with a query parameter called name we will be able to invoke this method.</p><p>Service Class</p><pre>package com.b1zt.springboot.introduction;<br><br>import org.springframework.stereotype.Service;<br><br>@Service<br>public class IntroductoryService {<br><br>    public String hello() {<br>        return &quot;Hello World!&quot;;<br>    }<br><br>    public String helloWithName(String name) {<br><br>        if (name == null || name.isEmpty()) {<br>            return &quot;Hello World!&quot;;<br>        }<br><br>        return &quot;Hello &quot; + name + &quot;!&quot;;<br>    }<br>}</pre><p>In this service class, I have used only one annotation</p><p>@Service: <br>The @Service annotation in Spring is used to indicate that a class is a service and its instances are intended to be managed by the Spring IoC (Inversion of Control) container. Services are typically used to encapsulate business logic, and they act as a middle layer between controllers and data access logic.</p><p>In this code, I have defined two methods. Those are very simple methods which will return hello world and hello ${name}</p><p>If you check the controller class again, you will see, I have called these methods.</p><p>Now our coding is mostly done, Now lets build the project. Before building the project, we need to give a name to the final war file. For this, lets modify our pom.xml file and add following line to the pom.xml file</p><p>&lt;finalName&gt;Introduction&lt;/finalName&gt;</p><pre>&lt;build&gt;<br>    &lt;finalName&gt;introduction&lt;/finalName&gt;<br>    &lt;plugins&gt;<br>       &lt;plugin&gt;<br>          &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>          &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;<br>       &lt;/plugin&gt;<br>    &lt;/plugins&gt;<br>&lt;/build&gt;</pre><p>you can try building the project with and without this line and see the difference in the final war file</p><p>Now, lets build the project</p><p>open a terminal in the root of the project where pom.xml file exists</p><p>mvn clean install</p><p>Run above command to build the project</p><p>Now, if you check the target folder in the root of the project, you will see a war file called introduction.war.</p><p>Now we are going to deploy this war file in tomcat,</p><ol><li>First setup your tomcat environment.</li><li>Copy the introduction.war file to the $TOMCAT_HOME/webapps directory</li><li>Go to $TOMCAT_HOME/bin and run bash catalina.sh run Depending on your OS, this command might vary.</li></ol><p>Now, your war file is deployed in tomcat.</p><p>By default tomcat will open in 8080 port. So, lets try to access our web service from a browser.</p><p>The URL for our get APIs will be as followed.</p><p><a href="http://localhost:8080/introduction">http://localhost:8080/introduction</a> + /api + /hello -&gt; http://localhost:8080/introduction/api/hello</p><p><a href="http://localhost:8080/introduction">http://localhost:8080/introduction</a> + /api + /helloWithName + ?name=B1zt -&gt; <a href="http://localhost:8080/introduction/api/hello">http://localhost:8080/introduction/api/hello</a>?name=B1zt</p><p>As you can see, we build our URL as few parts. Lets try to understand how our URL is built</p><p>First part, <a href="http://localhost:8080/">http://localhost:8080</a> is where our tomcat server is running. <em>introduction</em> is the name of our webapp, so tomcat deploy this webapp with this name. So, we can identify our webapp as following url http://localhost:8080/introduction</p><p>The second part is /api We give a class level request mapping in our controller class. The value we gave was /api That’s where we get /api in our URL</p><p>The third part is /hello or /helloWithName We have defined get mapping for both our methods, the value we passed to that annotation is above values, so we get above values to our URL</p><p>Finally, for the helloWithName method, we are passing a query parameter as the input. So, a query param with will be added to that url ?name={name}</p><p>Now lets try to access these urls from our browser and see the results</p><ol><li><a href="http://localhost:8080/introduction/api/hello">http://localhost:8080/introduction/api/hello</a></li><li><a href="http://localhost:8080/introduction/api/helloWithName?name=b1zt">http://localhost:8080/introduction/api/helloWithName?name=b1zt</a></li></ol><p>Now you see the magic, you should be able to see the response from the browser. Now, you can try changing paths and business logic and see how things are working</p><p>This is the introductory article on spring boot, I will be hoping to cover more complex and interesting parts of spring boot in coming articles. Appriciate your feedback on the article and my writing style. Let me know how I can improve. Stay tuned for the next article on this series. Thank you</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=caee3160c8b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A beginners guide to GitHub]]></title>
            <link>https://medium.com/@bsakalanka9/a-beginners-guide-to-github-5ff13e77862e?source=rss-5e44518f4da5------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ff13e77862e</guid>
            <category><![CDATA[guides-and-tutorials]]></category>
            <category><![CDATA[pr]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[Bhagya Akalanka]]></dc:creator>
            <pubDate>Tue, 11 Oct 2022 19:36:07 GMT</pubDate>
            <atom:updated>2022-10-11T19:36:07.783Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*QEpduO7IaOXym50gsDlQlA.png" /></figure><p>Hi all,</p><p>In this article I am going to give you a introduction to GitHub. This article focus more about beginners.</p><p>In this article, I will explain all the steps, GitHub commands you might need and some additional details and best practices as a beginner you should follow in order to send a PR to a GitHub repository.</p><p>For this tutorial I will be using <a href="https://github.com/wso2/product-is">product-is</a> repository in wso2. I will explain all details that you need to know when sending a PR.</p><ol><li>In industry when we want to send a PR to some repository, the first thing we need to do is to fork that repository. In WSO2 as well, we follow the same approach. So in order to send a PR to product-is, first we need to fork the repository.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*NhJ0eEo5S3zqwFhrXuqKYg.jpeg" /></figure><p>Like in the image below, we need to click on the fork button on top right corner of the github. Once it is pressed, you will be able to fork the repository.</p><p>What fork basically does is, it create a copy of the repository on your github account.</p><p>2. Now that we have forked the repository, we need to clone the forked repository to your local machine. How we can do this is as below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*alztqDBBglObEiW6Vsr4uQ.jpeg" /></figure><p>First, we need to go to the fork repository. If you look at the green colored circle, you will see my GitHub id. It says this is a fork of wso2/product-is</p><p>Now that I am in the fork, I will click the red colored number 1 button. Then I will be able to get the link as in second circled view. Now I will copy that link.</p><p>3. Now that we have the clone link of the fork repository, we need to clone the repository to our local machine. We can simple do that with following command</p><pre>git clone <a href="https://github.com/bhagyasakalanka/product-is.git">https://github.com/testuser/product-is.git</a></pre><p>what you just need to do is to paste the copied link after git clone command. Then it will take some time to download and clone the repository in your local environment</p><p>4. Now that we clone the repository, we need to understand few things. First thing is, now there are two product-is repositories. One in your github account. The other (original) one on wso2 repository. As you remember, we clone the repository in your account.</p><p>But when we need to do a change, we need to send that change to the product-is in wso2. So we need to make a connection between your repository and wso2 repository.</p><p>That we can achieve by setting a remote url to access different repositories.</p><p>Since you clone the repository from the fork, it is already identity as the origin. Now we need to set a remote connection to original wso2/product-is repo. We can do that by following command.</p><pre>git remote add upstream <a href="https://github.com/wso2/product-is.git">https://github.com/wso2/product-is.git</a></pre><p>Now what this command does is, it setup a new remote connection with wso2/product-is repository. We can identify that remote connection by the name upstream . If you wish, you can rename that to some other name like wso2. For example,</p><pre>git remote add wso2 <a href="https://github.com/wso2/product-is.git">https://github.com/wso2/product-is.git</a></pre><p>Now if you run below command, you will be able to see, origin is pointed at your fork and the upstream is pointed at wso2/product-is</p><pre>git remote -v</pre><p>Result is as below</p><pre>origin <a href="https://github.com/bhagyasakalanka/product-is.git">https://github.com/</a><a href="https://github.com/bhagyasakalanka/product-is.git">testuser</a><a href="https://github.com/bhagyasakalanka/product-is.git">/product-is.git</a> (fetch)<br>origin <a href="https://github.com/bhagyasakalanka/product-is.git">https://github.com/</a><a href="https://github.com/bhagyasakalanka/product-is.git">testuser</a><a href="https://github.com/bhagyasakalanka/product-is.git">/product-is.git</a> (push)<br>upstream <a href="https://github.com/wso2/product-is.git">https://github.com/wso2/product-is.git</a> (fetch)<br>upstream <a href="https://github.com/wso2/product-is.git">https://github.com/wso2/product-is.git</a> (push)</pre><p>5. Now that we have setup the remote connection, we can work on doing our changes. First thing we need to do is to pull latest changes from the upstream</p><p>In this example, we are going to send a update to the master branch of the product-is. So first, we need to checkout to the master branch</p><pre>git checkout master</pre><p>Then we can pull the latest changes in the upstream to our local machine</p><pre>git pull upstream master</pre><p>Now that we have the latest changes, we can apply our changes</p><p>6. So the first thing we need to do before doing our changes is to create a new local branch from the master branch(from the branch which you send the PR). We can do that with the following command</p><pre>git checkout -b master-update-readme</pre><p>The above command will create a new branch from the master branch and checkout you to that branch. The new branch name is master-update-readme Usually, when you create the new branch, give it a short and sweet but meaningful name which reflect the task you are doing. If you read my branch name, you can understand, I am going to update the readme file in master branch.</p><p>7. Now DO YOUR CHANGES. Update files, add new files, change content… Anything you want, you can do in this phase. But obviously, everything you do will not be accepted by wso2. So make the necessary changes.</p><p>8. Then you need to add those changed files to your local github. That you can do with following commands</p><pre>git add . // Add all the changed files. Careful when using this command as it could add unrelated files as well</pre><pre>git add &lt;file_name&gt; // Add a specific file</pre><pre>git add &lt;directory name&gt; // Add all the changed files in the direcotry</pre><p>9. Now that you have added the changed files, we need to commit those changes to the github. That we can do with following command.</p><pre>git commit -m &quot;&lt;commit message&gt;&quot; </pre><pre>ex: git commit -m &quot;update readme file&quot;</pre><p>The above command will add your changes to GitHub commit history with a random identifier and the message you put.</p><p>10. Now that you have committed the changes in your local machine, we need to push those changes to your fork. We can do that with following command.</p><pre>git push --set-upstream origin master-update-readme // Push changes to the fork</pre><p>Note if you look at the above command, you will see, we are pushing those changes to the origin(your fork).</p><p>Also, do not worry, you do not need to remember this long command. just remember the git push command only. Once you type git push and press enter, GitHub will suggest the above command ;).</p><p>11. Now that you have push your changes to your fork, let’s create the PR now. There are two ways to create the PR.</p><h3>Create PR from auto suggest option original repository.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WnwP5H4MQP327InuMi1E1w.png" /></figure><ul><li>Go to wso2/product-is (original repo)</li><li>In there, you will be able to see Compare &amp; pull request . Click on that to create the PR. But you will not be able to see this view if the PR is bit older. In that case, you can follow the second option.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nZwVBtpyWxUBVNIiVkyCvA.png" /></figure><ul><li>Once click on Compare &amp; pull request you will see above screen. From that, select repository and branch details.</li><li>Then add a title to the PR and add relevant descriptions.</li><li>Finally Click Create pull request</li></ul><h3>Create PR from the fork</h3><ul><li>First go to your fork repository. (<a href="https://github.com/bhagyasakalanka/product-is.git">testuser/product-is</a>)</li><li>Then click on Pull requests</li><li>Click on New pull request</li><li>Provide repository and branch details</li><li>Click on Create pull request</li><li>Provide PR title and description</li><li>Click on Create pull request</li></ul><p>12. Here are few points to remember when creating a PR</p><ul><li>Add a good title that self explain the PR content</li><li>Add a detailed description of the PR.</li><li>Mention relevant git issues and relevant PRs in the description</li><li>Follow templates if available when creating the PR. If not applicable parts presents in the template, remove them</li></ul><p>Congrats….</p><p>You have successfully created a PR. Now let’s see few other important git commands which helpful when working with PRs.</p><ol><li>git commit --amend</li></ol><p>This command allows you to merge your new changes with the last commit. This command is pretty useful. If you want to do simple change like formatting a line, you can simply add that format change to your last commit instead of adding a new commit.</p><p>Usually in WSO2, we do not add lots of commits in a single PR unless it is necessary. When there are small changes need to be done, we can amend the new changes to last commit.</p><p>One thing to remember is, if you use amend, you need to force push the changes. git push -f</p><p>2. git reset --soft HEAD~1</p><p>This command will reset the latest commit. What it basically does is, it will remove the last commit from the local commit history. When we use soft, the changes related to that commit will not be removed, you will be able to see those changes as uncommitted changes</p><p>3. git reset --hard HEAD~1</p><p>This command will reset the latest commit. What it basically does is, it will remove the last commit from the local commit history. When we use hard, the changes related to that commit will be removed, you will not be able to see those changes anymore.</p><p>4. git cherry-pick &lt;commit-id&gt;</p><p>As we know, a commit contain certain file changes. Now let’s assume, we need to add those changes in commit-1 on branch-1 to the branch-2. In such cases, we can use cherry-pick to copy the changes related to the commit in branch-1 to branch-2.</p><p>First we need to copy the commit id of the commit we need to copy in branch-1</p><p>Then we need to checkout to branch-2 and use the above command</p><p>5. git rebase &lt;original-branch&gt;</p><p>As I told, initially, when we create PR, we always create a new local branch from the branch we are going the send the PR.</p><p>After we send a PR, it would take few days sometimes before it gets merged. In such cases, your new branch might not updated with the latest changes of the original branch(There could be other PRs getting merged to the original branch). In such cases, we need to sync new branch with the original branch. Also when we do that, our commits should be placed on top of the commit history.</p><p>We can achieve this scenario with following commands</p><ul><li>checkout to original branch (master in our case)</li></ul><pre>git checkout master</pre><ul><li>Pull new changes from original repo</li></ul><pre>git pull upstream master</pre><ul><li>Checkout back to your new local branch</li></ul><pre>git checkout master-update-readme</pre><ul><li>Rebase</li></ul><pre>git rebase master</pre><p>Now if you check the commit, history, you will see your changes are applied on top of the latest change of the original branch.</p><ul><li>Make sure to force push your changes if you have already create the PR.</li></ul><p>6. git log</p><p>This will show commit history of the branch</p><p>In this article, we discussed how to create a PR and very simple but frequently used git commands. You can try out these familiar with GitHub easily. In the beginning, you might feel these are hard to understand, but once you have a good understanding on what is a commit and some experience on different commands, things will be more clear.</p><p>If you have any questions, feel free to raise them here.</p><p>Lets meet again with a new interesting topic</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ff13e77862e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Debug a war file hosted in Tomcat Using Intellij]]></title>
            <link>https://medium.com/@bsakalanka9/debug-a-war-file-hosted-in-tomcat-using-intellij-b79ddbc49fc5?source=rss-5e44518f4da5------2</link>
            <guid isPermaLink="false">https://medium.com/p/b79ddbc49fc5</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[intellij]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[tomcat]]></category>
            <category><![CDATA[debug]]></category>
            <dc:creator><![CDATA[Bhagya Akalanka]]></dc:creator>
            <pubDate>Tue, 11 Oct 2022 16:32:32 GMT</pubDate>
            <atom:updated>2022-10-11T16:32:32.511Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello all</p><p>Welcome to a quick article on how to debug a war file hosted in Tomcat using intellij IDEA.</p><p>This is actually pretty easy, but hey, we all face trouble when we tryout something in the first time. So let’s see how we can enable debugging.</p><p>Now we are running a war file in tomcat, we have the source code of the war file. Since there is a bug, we need to debug the source code to find out the issue,</p><p>For this, lets refer tomcat installed location as TOMCAT_HOME</p><ol><li>First thing we need to do is, open the catalina.sh in the TOMCAT_HOME/bin</li><li>Add the following line to catalina.sh file.</li></ol><pre>JAVA_OPTS=&quot;$JAVA_OPTS -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=9999&quot;</pre><p>3. Start tomcat server</p><pre>cd TOMCAT_HOME/bin<br>sh catalina.sh run</pre><p>4. Open your source code in intellij</p><p>5. Go to run -&gt; Edit Configurations</p><p>6. Click Add New</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q9F3_2d1MOezDCKv_D7RBw.png" /></figure><p>7. Select Remote JVM Debug</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W7SarwgVbe_kPDXrB4DX1Q.png" /></figure><p>8. Give a name (optional). For this example let’s assume name as TOMCAT.</p><p>9. Change port to 9999 (Value added as address in step 2)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DsgQbNSP0W9SW0UPXh-Bfw.png" /></figure><p>10. Click Ok</p><p>11. Click run and select debug TOMCAT</p><p>Now we are all set. Just add debug points on the source code and you will be able to debug the war file.</p><p>Hope you learn new thing from this article. Stay tune for more interesting articles.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b79ddbc49fc5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Useful Docker Commands]]></title>
            <link>https://medium.com/@bsakalanka9/useful-docker-commands-ca185aa36adf?source=rss-5e44518f4da5------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca185aa36adf</guid>
            <category><![CDATA[image]]></category>
            <category><![CDATA[commands]]></category>
            <category><![CDATA[wso2is]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Bhagya Akalanka]]></dc:creator>
            <pubDate>Wed, 05 Oct 2022 18:22:59 GMT</pubDate>
            <atom:updated>2022-10-05T18:22:59.149Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4JwXQzhvYKoZpr3qAHdL2g.png" /></figure><p>Hello all,</p><p>Welcome to another interesting article. In this article I’m going to give you some useful docker commands and how you can you those commands</p><p>I will discuss about most common commands I used everyday and some of the commands I found useful when work with docker.</p><ol><li>Docker Pull</li></ol><p>Of course let’s begin with the basic command. If you want to get some docker image from a docker registry, you can use the following command</p><pre>docker pull docker.wso2.com/wso2is</pre><pre>docker pull docker.wso2.com/wso2is:6.0.0.0</pre><p>In the first command, we pull the docker image from docker.wso2.com/wso2is. Here we are not defined any tag. So the image with latest tag will be pulled.</p><p>In the second command, we pull the docker image by giving the tag. In this case, we are pulling the image specified with the tag name.</p><p>2. Docker build</p><p>If you want to build a docker image, you can use following commands. Note that you need to have you dockerfile ready to build a docker image.</p><pre>docker build -t wso2is:6.0.0.0 // Build the image with a tag</pre><pre>docker build -t wso2is:6.0.0.0 --build-arg WSO2_SERVER_DIST_URL=<a href="http://127.0.0.1:8000/wso2is-5.11.0.zip">http://127.0.0.1:8000/wso2is-6.0.0.zip</a> // Replace dockerfile variable by providing values when building the image.</pre><p>Using above commands, you will be able to build docker images. For that, you need to have you dockerfile in the same location where you run the commands.</p><p>3. Docker Push</p><p>Now lets see, how we can upload a image to a docker registry. We use following command to upload a docker image to a docker registry</p><pre>docker image tag wso2is:6.0.0.0 docker.wso2.com/wso2is:6.0.0.0</pre><pre>docker image push docker.wso2.com:6.0.0.0</pre><p>In above commands, I’m going to upload a docker image called wso2is:6.0.0.0 to docker.wso2.com registry. But before I upload the image, I need to tag the image correctly. So I used the first command to tag the image. Once you tag the image correctly, then you can push the image using the second command</p><p>4. List Images</p><p>Now let’s see how you can list docker images. You can use following commands to list down all available docker images in your system</p><pre>docker image ls    // List down images with all details.</pre><pre>docker image ls -q // List down image ids.</pre><p>If you have a lot of images and need to delete some docker images, you can easily get the image ids of the docker images from the second command ;)</p><p>5. Docker run</p><p>If you want to run a docker image, you can use following commands to run docker images</p><pre>docker run docker.wso2.com/wso2is:6.0.0.0 // Run docker image with its tag.</pre><pre>docker run &lt;image id&gt; // Run docker image with its id.</pre><pre>docker run &lt;image id&gt; --user root // Run the image as root.</pre><pre>docker run &lt;image id&gt; --network host // Run the image on the host. In this case, docker container will not get separate IP address.</pre><pre>docker run &lt;image id&gt; -p 8085:8080 // Expose docker container port 8080 on host&#39;s port 8085.</pre><pre>docker run --name identity_server_v6 // Give a name to docker container.</pre><p>6. Docker start</p><p>Docker start is the command to start a docker container again. If you had a docker container running and after you restart your machine, if you want to run the same container again, you can use docker start command. Lets see how we can use docker start command</p><pre>docker start &lt;container id&gt; // Start the docker container using container id.</pre><pre>docker start &lt;container name&gt; // Start the docker container using the container name.</pre><p>The difference between docker start and docker run is that, we use docker run to start a new container from a image. If we use run, then it will create a new container always. docker start is used to start a already created container.</p><p>7. Docker stop</p><p>Docker stop is the command we used to stop a docker container. Lets see how we can use this command</p><pre>docker stop &lt;container id&gt; // Stop a container with the container id.</pre><pre>docker stop &lt;container name&gt; // Stop a container with the container name.</pre><p>8. List down containers</p><p>Now lets see how we can see the existing docker containers. How to list down docker containers to get more information about each container</p><pre>docker ps // List down currently running container details.</pre><pre>docker ps -s // List down container details including the size of the container.</pre><pre>docker ps -a // List down all the containers created in the system. This will show currently running and stopped container details.</pre><p>We can use docker ps command to get details about docker container id / container name etc which will be used when starting and stopping docker containers</p><p>9. Inspect docker containers and images</p><p>We can use following commands to inspect and get more details about docker images and docker containers</p><pre>docker inspect &lt;image id&gt; // Provide more details about the image.</pre><pre>docker inspect &lt;container id&gt; // Provide more details about the container.</pre><p>we could use the second command to find out the IP address of the container. There are more details you could see when you run those commands</p><p>10. View inside of a docker container</p><p>Now we get our container running. But now we need to go inside this container and do some modifications to the application running on the container. So lets see how we can go inside a container.</p><pre>docker exec -t &lt;container id&gt; /bin/bash // Enter inside a ubuntu docker container</pre><pre>docker exec -t &lt;container id&gt; /bin/ash // Enter inside a alpine docker container.</pre><pre>docker exec -t -i -u root &lt;container id&gt; /bin/bash // Enter inside the container as the root.</pre><p>11. Restart a docker container</p><p>We can use below command to restart a docker container</p><pre>docker restart &lt;container id&gt; // Restart the docker container. </pre><p>12. Delete docker images</p><p>We can use below command to delete docker images</p><pre>docker rmi &lt;image id&gt; // Delete a docker image by id</pre><pre>docker rmi -f &lt;image id&gt; // Delete a docker image forcefully</pre><p>I hope you learn new thing from this article. Stay tuned for more new interesting articles</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca185aa36adf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to write a custom adaptive authentication script in WSO2 Identity Server 5.11.0]]></title>
            <link>https://medium.com/@bsakalanka9/how-to-write-a-custom-adaptive-authentication-script-in-wso2-identity-server-5-11-0-f1601fae74ab?source=rss-5e44518f4da5------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1601fae74ab</guid>
            <category><![CDATA[adaptive-scripts]]></category>
            <category><![CDATA[asgardeo]]></category>
            <category><![CDATA[js-api-reference]]></category>
            <category><![CDATA[wso2is]]></category>
            <category><![CDATA[adaptive-authentication]]></category>
            <dc:creator><![CDATA[Bhagya Akalanka]]></dc:creator>
            <pubDate>Tue, 01 Mar 2022 19:36:16 GMT</pubDate>
            <atom:updated>2022-03-01T19:36:16.583Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s find out the how to write custom adaptive authentication scripts in <a href="https://wso2.com/identity-server/">WSO2 IS-5.11.0</a> with examples.</p><h4><strong>First, let’s find out what is adaptive authentication is,</strong></h4><p>Adaptive authentication, often called risk based authentication is an access method that attempts to match the required user credentials to the perceived risk of the authorizations requested. It is main goal is to reduced the authentication burden on end user while enforcing strong authentication when required.</p><p>Adaptive authentication is built around multi factor authentication(MFA) which used few factors of authentications if there is a need to strong authentication for a certain user. For example, in a system, if the user is an admin user, we may enforce second factor authentication when the user is logged into the system. But for normal users, we may use username/password only. As another example, based on the IP address which the user is logged in, we could enforce additional layers of authentication. Another way is, if the user failed to enter his/her credentials within a given number of times, then we could enforce additional authentication steps.</p><p>So, when looking at these examples, we could see, adaptive authentication is used to increase the security if there is a suspicious login attempts, or high valued user login attempts etc. So based on the user credentials, user types, user locations, and based on many other factors, we could implement new authentication mechanism to support and increase security when logged into the system.</p><h4><strong>How to setup adaptive authentication in Identity server</strong></h4><ol><li>First download and setup identity server. Then start the server and logged into the console (<a href="https://localhost:9443/console"><em>https://localhost:9443/console</em></a>).</li><li>Move to <strong><em>Develop -&gt; Application -&gt; New Application</em></strong></li><li>follow the guide given in <a href="https://is.docs.wso2.com/en/latest/learn/deploying-the-sample-app/"><em>Deploying the sample apps</em></a><em> </em>set up pickup-dispatch or any other application.</li><li>Move to sign-in methods in the newly created application.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VTV_Zmy03cfRk3lFJxyBmQ.png" /><figcaption>Figure 1: Current view after step 4</figcaption></figure><p>Now from this place, we can enable adaptive authentication for the application users.</p><h4><strong>Readily Available adaptive scripts in identity server</strong></h4><p>Now from the above view, if you scroll down, you will be able to see to toggle button to enable Conditional authentication. Once you enable the conditional authentication, you will be able to see the available adaptive scripts as well as you will be able to write your own adaptive scripts</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CPfiPmg7TEnHB6fuxv8sHw.png" /><figcaption>Figure 2: Adaptive Authentication Scripts</figcaption></figure><p>As in the above Figure 2, you can select available adaptive authentication script templates from the right side and use them as it is or, modify and use them.</p><h4><strong>How to write a custom adaptive authentication script</strong></h4><p>In this section I will go though how to modify an adaptive script template or how to write a new custom script.</p><p>As in the figure 2, in the middle, black colored section can be used to write your own scripts. We use JavaScript to write authentication scripts.</p><p>First, let’s go though and familiarized with available main functions and how to use them.</p><p>To keep everything consistent, for the rest of the article, I would use following steps and authenticators as in the figure 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lHB_LJ2eYIy0X2O3dlqGNA.png" /><figcaption>Figure 3: Authentication steps and authenticators</figcaption></figure><h4><strong>Custom Scripts</strong></h4><p>So lets start writing custom adaptive scripts</p><ol><li>executeStep(1)</li></ol><pre>var onLoginRequest = function(context) {<br>    executeStep(1);<br>};</pre><p>First and the most simple adaptive script we could write is the above script. In this case, we are telling to execute the first step when the user try to log in to the application. So in this case, a user will be able to login with basic authenticator(username/password) or using social logins(GitHub,Google). The parameter we are passing to the function is the step number.</p><p>So for example if we use call the function with 2 as the parameter, in the login screen, user will see the basic authenticator only.</p><p>2. executeStep with onSuccess</p><pre>var onLoginRequest = function(context) {<br>    executeStep(1, {<br>        onSuccess: function(context) {<br>            executeStep(4)<br>        }<br>    }<br>}</pre><p>In this case, First we are executing step 1. And then, we calling “onSuccess” event callback function. What happen there is that, once the user successfully authenticated with the first step, the onSuccess part will execute. So in this scenario, once the user authenticate with step 1, the 4th step, which is TOTP, EMAIL_OTP authenticators will be prompt as the second factor authenticators.</p><p>In the similar way, we can modify the script to handle “onFail” event callback as well. So with that callback function, once the step is failed for some reason, code segmetn under “OnFail” will be executed.</p><p>3. authenticationOptions</p><pre>var onLoginRequest = function(context) { <br>    executeStep(1, {        <br>         onSuccess: function (context) {<br>             var user = context.steps[1].subject;<br>             var username = user.username;<br>             var authenticators = [];<br>if (username === &quot;admin&quot;) {<br>                 authenticators.push({authenticator:&#39;TOTP&#39;});<br>             }<br>             <br>             executeStep(4, {   <br>                authenticationOptions: authenticators<br>             }, {});<br>         }<br>    });<br>};</pre><p>We can use authenticationOptions to filter out some of the authenticators based on conditions. So in this example, I’m only going to promt TOTP authenticator for admin user. For other users, TOTP and Email OTP authenticators will prompt. If the authenticationOptions contains an invalid authenticator or an empty list, all the defined authenticators will be shown as the second factor.</p><p>If we are going to pass a local authenticator, then we need to enter a element to authenticationOptions with authenticatorkey word. For example {authenticator: &#39;TOTP&#39;} . If we need to pass IDP, then we need to enter a element with idp keyword. For example {idp: &#39;Google&quot;}</p><p>Also keep in mind, when we are passing the IDP/Authenticator to authenticationOptions, we need to provide the friendly name of the authenticator.</p><pre>Authenticator     Friendly Name<br>TOTP          -    TOTP<br>EMAIL OTP     -    Email OTP Authenticato<br>FIDO          -    fido<br>SMS OTP       -    SMS OTP<br>Google        -    Google<br>GitHub        -    Github<br>Facebook      -    facebook</pre><p>4. stepOptions</p><pre>var onLoginRequest = function(context) { <br>    executeStep(1, {     <br>        stepOptions: {         <br>            forceAuth: &#39;true&#39; <br>        } <br>    }, {});<br>};</pre><p>The forceAuth in stepOption will force the authenticator in the steps to prompt again even if it was already authenticated.</p><h4>Support Functions</h4><p>Now I’m quickly go through few of the available support functions</p><ol><li>hasRole(user, role)</li></ol><p>This function requires 2 parameters. The user object and the role we need to check for. The function will return true if the user has the role. otherwise return false.</p><pre><strong>var</strong> user = context.steps[1].subject; <br><strong>var</strong> isAdmin = hasRole(user, &#39;admin&#39;); <br>Log.info(&#39;--------------- Has Admin &#39; + isAdmin); <br><strong>if</strong> (isAdmin) {     <br>    executeStep(4); <br>}</pre><p>In this code segment, we are using hasRole function to decide if the user has admin role or not. So if the user has the admin role, then the second factor will be prompt for that user.</p><p>2. assignUserRoles(user, [role1, role2])</p><p>This function can be used to assign roles to users</p><pre>executeStep(1, {     <br>    onSuccess: function (context) {         <br>    // Extracting authenticated subject from the first step.         <br>        let user = context.currentKnownSubject;<br>        assignUserRoles(user, [&#39;exampleRole1&#39;, &#39;exampleRole2&#39;]);    <br>    } <br>});</pre><p>So in this example, we are assgining exampleRole1 and exampleRole2 roles to the user</p><p>3. removeUserRoles(user, [role1, role2])</p><p>Using this function, we can remove assigned roles from a user</p><pre>executeStep(1, {     <br>    onSuccess: function (context) {         <br>    // Extracting authenticated subject from the first step.         <br>        let user = context.currentKnownSubject;<br>        removeUserRoles(user, [&#39;exampleRole1&#39;, &#39;exampleRole2&#39;]);    <br>    } <br>});</pre><p>4. sendError(url, paramMap)</p><p>We can use this function to redirect a user to error pages. We need to pass the url of the error page and additional parameters if required. In case of the url is not given, user will be redirect to default error page</p><pre><strong>var</strong> user = context.steps[1].subject; <br><strong>var</strong> isAdmin = hasRole(user, &#39;admin&#39;); <br><strong>if</strong> (!isAdmin) {     <br>    sendError(&#39;http://www.example.com/error&#39;,{<br>         &#39;errorcode&#39;:&#39;000403&#39;,<br>         &#39;errorMsg&#39;:&#39;You are not allowed to login to this app.&#39;}); <br>}</pre><p>So as in this example, if the user does not have admin role, then the user will be redirect to the error page.</p><p>In addition to these functions you can find many other useful support functions from [1]</p><h4>Object References</h4><p>Now let’s find out about object references</p><ol><li>context object</li></ol><ul><li>context.step[n] — With this, we can get the stepObject for the given n th step.</li><li>context.request — This will return the request object</li><li>context.response — This will return the response object</li><li>context.serviceProviderName — This will return the service providers name.</li></ul><p>2. step object</p><p>Contains the authentication step information.</p><ul><li>step.subject — Returns the authenticated subject (user object) from the step</li><li>step.idp — Returns the idp which used to authenticate this user</li></ul><p>3. user object</p><ul><li>user.username — Returns the username of the user</li><li>user.tenantDomain — Returns the tenant domain of the user</li><li>user.userStoreDomain — Return the userstore domain of the user</li><li>user.roles — Returns a list of roles assigned to the user</li><li>user.localClaims[“&lt;local-claim-uri&gt;”] — Returns the value for the given local-claim-uri.</li><li>user.claims[“&lt;claim-uri&gt;”] = “temp value” — Set a temporary claims for the session. We can retrieve the value using user.claims[“&lt;claim-uri&gt;”] later if needed.</li><li>user.remoteClaims[“&lt;remote-claim-uri&gt;”] — User’s attribute (claim) as returned by IdP for the given “remote-claim-url</li></ul><p>There are more details you could find from the [1] about other supported Object references.</p><p>So, now lets look at a more complex script to understand how each of these functions are working</p><pre>var maxAllowedFailedAttempts = 3;</pre><pre>var failedLoginAttemptsBeforeSuccessClaim= &#39;<a href="http://wso2.org/claims/identity/failedLoginAttemptsBeforeSuccess&#39;">http://wso2.org/claims/identity/failedLoginAttemptsBeforeSuccess&#39;</a>;<br>var onLoginRequest = function(context) {<br>  doLogin(context);<br>};</pre><pre>var doLogin = function(context) {<br>   executeStep(1, {<br>       onSuccess : function(context){<br>           var user = context.steps[1].subject;<br>           if (isExceedInvalidAttempts(user)) {<br>               executeStep(4, {<br>                 onSuccess : function(context) {<br>                   var user = context.steps[1].subject;<br>                   user.localClaims[failedLoginAttemptsBeforeSuccessClaim] = &quot;0&quot;;<br>                 }<br>               });<br>           }<br>       },<br>       onFail : function(context) {<br>           // Retry the login..<br>           doLogin(context);<br>       }<br>   });<br>};</pre><pre>var isExceedInvalidAttempts  = function(user) {<br>   if (user.localClaims[failedLoginAttemptsBeforeSuccessClaim] &gt;= maxAllowedFailedAttempts) {<br>       return true;<br>   } else {<br>       return false;<br>   }<br>};</pre><p>This is the adaptive script we used to prompt second factor authentication if the user failed to enter the correct credentials in a given number of attempts. In default, if the user failed to enter the correct credentials within 3 attempts, the user will be prompt for a second factor authentication.</p><p>So if we carefully go through the code, first you can see, we defined a variable to keep the claim-uri of the failedLoginAttemptsBeforeSuccess claim. We use this claim to keep how many failed attempts are there before the user enter the correct credentials. So when the user entered an invalid credentials, we are increasing the claim value by 1. And if the claim value is equal or higher than the maxAllowedFailedAttempts , then we are going to prompt for the second factor authentication.</p><p>Important things to remember in this are,</p><ul><li>How we read a claim value</li><li>How we update a claim value</li><li>How we get the user object</li><li>How to use conditions</li><li>How to use callback functions such as onSuccess and onFail</li></ul><h4><strong>How to log content from adaptive scripts</strong></h4><p>We can use following functions to log inside adaptive scripts. Logs are really helpful when debugging complex adaptive scripts.</p><ul><li>Log.info(msg);</li><li>Log.error(“errorMgs”);</li></ul><p>When we log a message using above functions, we could see the results in the server logs.</p><p>There are some limitations with these log functions. We can log only primitive types these log functions</p><p>For example</p><pre>Log.info(&quot;test&quot;)  - Success<br>Log.info(2)       - Success<br>Log.info(context) - Failed</pre><p>So always remember to Log primitive types such as integers, strings only. If you try to log other complex objects (even arrays) the adaptive script will fail and/or not work as expected.</p><p>I hope with this article you learn something new and this article will help you when you try to write custom adaptive scripts.</p><p>Thank you all and let’s meet again with another interesting article.</p><p>[1] <a href="https://is.docs.wso2.com/en/latest/references/adaptive-authentication-js-api-reference/">https://is.docs.wso2.com/en/latest/references/adaptive-authentication-js-api-reference/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1601fae74ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[All SCIM2.0 Protocols in WSO2 Identity Server 5.11.0]]></title>
            <link>https://medium.com/@bsakalanka9/all-scim2-0-protocols-in-wso2-identity-server-5-11-0-af73bcd86b59?source=rss-5e44518f4da5------2</link>
            <guid isPermaLink="false">https://medium.com/p/af73bcd86b59</guid>
            <category><![CDATA[protocol]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[wso2]]></category>
            <category><![CDATA[endpoints]]></category>
            <category><![CDATA[scim]]></category>
            <dc:creator><![CDATA[Bhagya Akalanka]]></dc:creator>
            <pubDate>Sun, 03 Oct 2021 18:33:54 GMT</pubDate>
            <atom:updated>2021-10-03T18:33:54.744Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s find out the how to use SCIM2.0 protocols using <a href="https://wso2.com/identity-server/">WSO2 IS-5.11.0</a> with samples from one place.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pnAngGxnyfB6GyqDhp_BBA.png" /></figure><p>I thought of writing this blog to keep every SCIM2.0 endpoints in a single place. This blog contains easy to understand explanation on all SCIM endpoints and how to use them in WSO2 Identity Server.</p><p>More details about SCIM protocols can be found in the <a href="https://datatracker.ietf.org/doc/html/rfc7644"><em>RFC7644 Specification</em></a></p><h3>1. Manage User Resources</h3><h4>1.1 Create User</h4><p>To create a new user, we need to perform a POST request on /scim2/users endpoint.</p><p>This sample request is to create a new user whose username is “Joey”.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5dbe32dbf43929b223951c118e03b0f3/href">https://medium.com/media/5dbe32dbf43929b223951c118e03b0f3/href</a></iframe><p>Please note that, the response body for this call is much similar to the request body but with slight changes. The password attribute in request body will not be returned in the response as the “returned” characteristic of “password” is “never”.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2cd7af64d9a77afe123dd18330fe47d1/href">https://medium.com/media/2cd7af64d9a77afe123dd18330fe47d1/href</a></iframe><h4>1.2 Get User</h4><p>To get a user, we need to perform a GET operation on /scim2/users/{userId} endpoint.</p><p>Now, let’s try to get the previously created user.</p><p>So I am going to perform a GET operation on /scim2/users/198413c1–03bf-4ac4-b59c-f83a347aa9b3 endpoint.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b3ebef160d59b21852e92b5dbe6bed3d/href">https://medium.com/media/b3ebef160d59b21852e92b5dbe6bed3d/href</a></iframe><p>Please note that, in this response as well, Password attribute will not be returned.</p><p>Now let’s say, we need to get only the name and the emails of the user.</p><p>So let’s perform a GET request to the above endpoint with following parameters.</p><p>/scim2/Users/198413c1–03bf-4ac4-b59c-f83a347aa9b3?attributes=name,emails</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/34f3c4b47a8b5a45b65efeae2d88755c/href">https://medium.com/media/34f3c4b47a8b5a45b65efeae2d88755c/href</a></iframe><p>In this response, we can see, name and the emails of the user is returned. But when we look closer, we can see, “id” attribute is also returned. This is because the “returned” characteristic of “id” is “default”. So “id” will be returned by default even though we did not request.</p><h4>1.3 Get Users</h4><p>To get users, we need to perform a GET operation on /scim2/users endpoint.</p><p>Let’s now try to get the users.</p><p>So I am going to perform a GET request on /scim2/users endpoint.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2922b93bf8066d6a5f7302114511c2a2/href">https://medium.com/media/2922b93bf8066d6a5f7302114511c2a2/href</a></iframe><p>In the response, we can see, there are two results. Identity Server has a default admin user and the user joey, we created previously.</p><p>When retrieving users, we can set optional parameters to perform filtering and pagination as below request.</p><p>scim2/Users?filter=username%20eq%20joey&amp;count=2&amp;attributes=name,emails</p><p>The above request will return name and emails of up to 2 users whose username equals to joey.</p><h4>1.4 Search Users</h4><p>In addition to the GET requests, we can initiate a search request to retrieve users. Search request uses POST method to create the request. In the request body, we can configure optional parameters. To perform a search request, we need to send a POST request to scim2/Users/.search endpoint.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d9ce00bdd8c70f1d113e23db3dcf53a/href">https://medium.com/media/5d9ce00bdd8c70f1d113e23db3dcf53a/href</a></iframe><p>There are few advantage of using a search request over a GET request.</p><ul><li>If we add multiple additional parameters in a GET request, the URL will be much longer. Sometimes browsers will not be able to handle larger URLs. In such cases, we can use a search request.</li><li>If we use additional parameters in the GET request, there is a possibility of exposing sensitive information directly to outside. To avoid such cases, we can use a search request.</li></ul><h4>1.5 Update User</h4><p>There are two main ways of updating a user resource.</p><ul><li>Partial update with patch request.</li><li>Replace with put request.</li></ul><h4>1.5.1 Update with Patch Request</h4><p>We can use patch requests to partially update a resource. To perform user update request, we need to send a patch request to /scim2/users/{userId} .</p><p>SCIM patch support 3 operations.</p><ul><li>Add</li><li>Remove</li><li>Replace</li></ul><p>In this step, I’m going to perform the three SCIM patch operations on previously created user “joey”.</p><ol><li>I’m going to give joey a new nick name “Ken Adams”. This is a add operation.</li><li>Remove home email. This is a remove operation.</li><li>Change joey’s givenName to Joseph. This is a replace operation.</li></ol><p>Now lets try to send a patch request to the /scim2/users/198413c1–03bf-4ac4-b59c-f83a347aa9b3endpoint.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/81268b6d74d3d017ee3d8673d6f7e890/href">https://medium.com/media/81268b6d74d3d017ee3d8673d6f7e890/href</a></iframe><p>If we look at the response, We can see those changes are effected on the user resource. Now, joey has only the work email under emails attribute. He has a nickname now. Also his givenName under name attribute is changed to Joseph.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/89c286f7a8199bc18b94e04cf18aedc1/href">https://medium.com/media/89c286f7a8199bc18b94e04cf18aedc1/href</a></iframe><h4>1.5.2 Update with Put Request</h4><p>With a put request, we can completely replace an existing resource. To perform a update request (replace), we need to send a put request to /scim2/users/{userId}</p><p>Note that, we should not use put request to create a new user.</p><p>Now let’s send a put request to /scim2/users/198413c1–03bf-4ac4-b59c-f83a347aa9b3 and replace the existing user joey with the below request body.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b4cd41f5973244d5c2249559e942ee6/href">https://medium.com/media/3b4cd41f5973244d5c2249559e942ee6/href</a></iframe><p>Now if we look at the response, we can see, joey’s nickname is removed, his givenName is changed to “Joey” as well as he has a home email now.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4838ad7d3863f2ca439d0462c5f52ca8/href">https://medium.com/media/4838ad7d3863f2ca439d0462c5f52ca8/href</a></iframe><h4>1.6 Delete User</h4><p>To delete a user, we need to perform a DELETE request on /scim2/users/{userId} endpoint.</p><p>Let’s now try to delete the user joey by calling a DELETE request on /scim2/users/198413c1–03bf-4ac4-b59c-f83a347aa9b3 endpoint.</p><h4>1.7 Bulk Operation on Users</h4><p>Bulk operation allowed us to perform multiple resource operations in a single request. To perform a bulk request, we need to send a POST request to/scim2/Bulk endpoint.</p><p><em>Imagine you have to create 100 users. Then you may have to send 100 user creation requests which is very troublesome and costly or you can send bulk request as explained below.</em></p><p>Bulk operation is not just perform a single type of operation. We can use a single bulk request to perform operations on multiple resources (Users, Groups) as well as perform multiple type of operations (Create, Delete, Update) on resources.</p><p>In the next example I’m going to perform multiple operations on Users resource.</p><p>First I will create a user named “Pheobe” using user create request (We can use create user request and create a new user).</p><p>When creating a bulk request, there are some other facts to know as well.</p><ul><li>If we specify the failOnErrors in the request, then the bulk operation will stop it is execution if the number of failed operations is equal to the specified value for the failOnErrors field. But this is an optional field. If we do not specify this field, then every operation will run even there are failures.</li><li>If the operation is a POST operation, then the “bulkId is required”.</li></ul><p>Now I’m going to perform following operations.</p><ol><li>Create user - Ross</li><li>Create user - Chandler</li><li>Delete user - Joey</li><li>Add a nick name and delete home email of the user - Pheobe</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6130f6d477409c390a51ff3adbc746a5/href">https://medium.com/media/6130f6d477409c390a51ff3adbc746a5/href</a></iframe><h3>2. Manage Group Resources</h3><p>To manage group resources, we need to send requests to /scim2/groups endpoint. We can perform all CRUD operations we discussed under “Manage User Resources” in this section as well. Since this section is almost similar to the previous section, I’m not going to discuss more details about this part.</p><h3>3. Working With “me” Endpoint.</h3><p>Self or the me endpoint is used to perform CRUD operations against a resource mapped to an authenticated subject. We need to send requests to /scim2/me endpoint.</p><p>When We send requests to me endpoint, the resource will be the authenticated subject. So we do not need to specify the resource by providing the resource id.</p><h3>4. Other Endpoints</h3><h4>4.1 Resource Types Endpoint</h4><p>By calling this endpoint, we can retrieve all supported resources by the SCIM service provider. To perform this request, we need to call /scim2/ResourceTypes endpoint.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b297228711e3923a9a52660e7cb6f2c2/href">https://medium.com/media/b297228711e3923a9a52660e7cb6f2c2/href</a></iframe><p>If we take a look at the response, we can see there are two resources supported by Identity Server. The User and Group resource. Also we can see, the User resource has a schema Extension called Enterprise</p><h4>4.2 Schemas Endpoint</h4><p>This endpoint return the supported schemas by the Service provider. We need to call /scim2/schemas endpoint to get the schemas.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e00954f378b6b05df8385c51dc80ec2/href">https://medium.com/media/9e00954f378b6b05df8385c51dc80ec2/href</a></iframe><p>This is a part of the schemas response. As we can see, this is a part of User schema. In the schema, we can see each of the attributes of the user and the characteristics of the attributes.</p><h4>4.3 Service Provider Config Endpoint</h4><p>Using this endpoint, we can retrieve service provider’s configurations. We need to call /scim2/serviceProviderConfig endpoint.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/017695f716051a4ec9da17ef5c98a4e8/href">https://medium.com/media/017695f716051a4ec9da17ef5c98a4e8/href</a></iframe><p>When we look at the response, we can see following information.</p><ul><li>Filtering is supported by Identity server</li><li>Sorting is not supported</li><li>Bulk operation is supported</li><li>Password changing is not supported via SCIM</li><li>OAuth bearer tokens and HTTP Basic authentication schemas are supported for SCIM by Identity Server.</li></ul><p>Find the postman collection here: <a href="https://app.getpostman.com/run-collection/31187c283d25ca4e8824"><em>https://app.getpostman.com/run-collection/31187c283d25ca4e8824</em></a></p><p>I Hope you learn how to use SCIM2.0 using WSO2 Identity Server. See you next time with another interesting article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af73bcd86b59" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>