[
  {
    "path": ".gitignore",
    "content": "_site\n.sass-cache\n.jekyll-cache\n.jekyll-metadata\nvendor\ndelivery.zip\n.DS_Store\n_old-posts/\n~$presentation.pptx\n\n# See http://help.github.com/ignore-files/ for more about ignoring files.\n\n# compiled output\n/dist\n/tmp\n/out-tsc\n\n# dependencies\n/node_modules\n\n# IDEs and editors\n/.idea\n.project\n.classpath\n.c9/\n*.launch\n.settings/\n*.sublime-workspace\n\n# IDE - VSCode\n.vscode/*\n!.vscode/settings.json\n!.vscode/tasks.json\n!.vscode/launch.json\n!.vscode/extensions.json\n\n# misc\n/.sass-cache\n/connect.lock\n/coverage\n/libpeerconnection.log\nnpm-debug.log\nyarn-error.log\ntestem.log\n/typings\n\n# System Files\n.DS_Store\nThumbs.db\n\n# Compiled class file\n*.class\n\n# Log file\n*.log\n\n# BlueJ files\n*.ctxt\n\n# Mobile Tools for Java (J2ME)\n.mtj.tmp/\n\n# Package Files #\n*.jar\n*.war\n*.ear\n*.tar.gz\n*.rar\n*.cmd\n*.classpath\n*.settings\n*.project\n*.mvn\nmvnw\ntarget\n*.DS_Store\n\n# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml\nhs_err_pid*\n"
  },
  {
    "path": "404.html",
    "content": "---\npermalink: /404.html\nlayout: page\ntitle: Oops!\n---\n<style>\n  *,\n  *:after,\n  *:before {\n    box-sizing: border-box;\n  }\n\n  main {\n    align-items: center;\n    display: flex;\n    flex-direction: column;\n    height: 50vh;\n    justify-content: center;\n    text-align: center;\n  }\n\n  h1 {\n    color: #3d3d3d;\n    font-size: 12.5rem;\n    letter-spacing: 0.1em;\n    margin: 0.025em 0;\n    text-shadow: 0.05em 0.05em 0 rgba(0, 0, 0, 0.25);\n    white-space: nowrap;\n  }\n\n  @media (max-width: 30rem) {\n    h1 {\n      font-size: 8.5rem;\n    }\n  }\n\n  h1>span {\n    -webkit-animation: spooky 2s alternate infinite linear;\n    animation: spooky 2s alternate infinite linear;\n    color: #528cce;\n    display: inline-block;\n  }\n\n  h2 {\n    color: #e7ebf2;\n    margin-bottom: 0.4em;\n  }\n\n  p {\n    color: #ccc;\n    margin-top: 0;\n  }\n\n  @-webkit-keyframes spooky {\n    from {\n      transform: translatey(0.15em) scaley(0.95);\n    }\n\n    to {\n      transform: translatey(-0.15em);\n    }\n  }\n\n  @keyframes spooky {\n    from {\n      transform: translatey(0.15em) scaley(0.95);\n    }\n\n    to {\n      transform: translatey(-0.15em);\n    }\n  }\n</style>\n<div class=\"container mb-5\">\n  <div class=\"row\">\n    <div class=\"col text-center\">\n      <main>\n        <h1>4<span><i class=\"lni lni-code\"></i></span>4</h1>\n        <h2>OOPSSSSS..: We are searching!</h2>\n        <p>Sorry, the page you're looking for cannot be accessed</p>\n      </main>\n    </div>\n  </div>\n</div>\n\n{% include newsletter.html %}"
  },
  {
    "path": "CNAME",
    "content": "www.springboottutorial.com"
  },
  {
    "path": "Gemfile",
    "content": "source \"https://rubygems.org\"\ngem \"jekyll\", \"~> 4.2.2\"\ngroup :jekyll_plugins do\n  gem \"jekyll-feed\"\n  gem \"jekyll-seo-tag\"\n  # gem 'jekyll-analytics'\nend\nplatforms :mingw, :x64_mingw, :mswin, :jruby do\n  gem \"tzinfo\", \"~> 1.2\"\n  gem \"tzinfo-data\"\nend\ngem \"wdm\", \"~> 0.1.1\", :platforms => [:mingw, :x64_mingw, :mswin]\ngem \"http_parser.rb\", \"~> 0.6.0\", :platforms => [:jruby]\n\ngem \"webrick\", \"~> 1.7\"\n"
  },
  {
    "path": "_blog/1-springboot.md",
    "content": "---\nlayout: category\ntitle: Spring Boot\nslug: SpringBoot\nimage: /images/spring-boot-category.png\n---\n"
  },
  {
    "path": "_blog/2-spring-framework.md",
    "content": "---\nlayout: category\ntitle: Spring Framework\nslug: SpringFramework\nimage: /images/spring-framework-category.png\n---\n"
  },
  {
    "path": "_blog/3-springboot-jpa.md",
    "content": "---\nlayout: category\ntitle: Spring Boot JPA\nslug: SpringBootJPA\nimage: /images/spring-data-category.png\n---\n"
  },
  {
    "path": "_blog/4-springboot-microservices.md",
    "content": "---\nlayout: category\ntitle: Spring Boot Microservices\nslug: SpringBootMicroservices\nimage: /images/microservices-category.png\n---\n"
  },
  {
    "path": "_blog/5-springboot-unit-testing.md",
    "content": "---\nlayout: category\ntitle: Spring Boot Unit Testing\nslug: SpringBootUnitTesting\nimage: /images/unit-test-category.png\n---\n"
  },
  {
    "path": "_blog/articles/2016-01-01-article-template-full-stack.md",
    "content": "---\nlayout:     post\ntitle:      TODO\ndate:       2025-03-09 12:31:19\nsummary:    TODO\ncategories:  ZZZZZZ\npermalink:  /full-stack-url\n---\n\nIn this guide, you’ll learn how to create a full-stack application with **Angular**, **React**, or **Vue.js** on the frontend, and **Spring Boot** powering the backend REST API.\n\n## Todo\n- How to import and run projects from git repository?\n- Create videos based on full stack articles.\n\nWe will and create a TODO***. \n \n## You will learn\n\n- What?\n- Why?\n- How?\n- Where?\n- When?\n\n## Resources/URLs/Entities Overview\n\nIn this guide, we’ll be building **TODO services** step by step.\n\n> The REST API can be extended to integrate with other microservice infrastructure components and function as an independent microservice.\n\n\n## Complete Maven Project With Code Examples\n\n> All the code examples from this guide are available in our GitHub Repo- https://github.com/in28minutes/spring-boot-examples/tree/master/TODO_URL\n\n\n## Project Structure\n\nThe following screenshot illustrates the structure of the project we will create.\n\n![Image](/images/SpringBootRestService-ProjectStructure.png \"Spring Boot Rest Service - Project Structure\") \n\nA few important files in this project:\n\n- **`StudentController.java`** – REST controller exposing the three service methods discussed above.\n- **`Course.java`, `Student.java`, `StudentService.java`** – Business logic layer.\n    - `StudentService` provides methods that are consumed by the REST controller.\n- **`StudentControllerIT.java`** – Integration tests for the REST services.\n- **`StudentControllerTest.java`** – Unit tests for the REST services.\n- **`StudentServicesApplication.java`** – Entry point for the Spring Boot application.\n    - To run the application, launch this file as a **Java Application**.\n- **`pom.xml`** – Project configuration and dependencies.\n    - Includes **Spring Boot Starter Web** for building REST APIs.\n\n\n## Tools You Will Need\n\n- **Maven 3.0+** – for building the Spring Boot API project\n- **npm** and **webpack** – for building the frontend\n- **IDE of your choice**\n    - *Eclipse* or *IntelliJ IDEA* for Java\n    - *Visual Studio Code* for JavaScript, TypeScript, Angular, or React\n- **JDK 17+** – required for running the Spring Boot backend\n- **Node v8+** – required for running the frontend\n- **Embedded Tomcat** – comes built into Spring Boot Starter Web\n\n#### Installing Node.js (npm) & Visual Studio Code\n\n- 🎥 **Playlist**: [YouTube – Node.js & VS Code Setup](https://www.youtube.com/playlist?list=PLBBog2r6uMCQN4X3Aa_jM9qVjgMCHMWx6)\n- **Steps**\n    - Step 01 – Install **Node.js** and **npm** (Node Package Manager)\n    - Step 02 – Quick introduction to **npm**\n    - Step 03 – Install **Visual Studio Code** (Frontend JavaScript Editor)\n\n---\n\n#### Installing Java, Eclipse, IntelliJ IDEA & Embedded Maven\n\n- 🎥 **Playlist**: [YouTube – Java, Eclipse & Maven Setup](https://www.youtube.com/playlist?list=PLBBog2r6uMCSmMVTW_QmDLyASBvovyAO3)\n- **Steps**\n    - Step 00 – Overview: Installing **Java**, **Eclipse**, and **Maven**\n    - Step 01 – Install **Java JDK**\n    - Step 02 – Install **Eclipse IDE** or **IntelliJ IDEA**\n    - Step 03 – Use **Embedded Maven** in Eclipse\n    - Step 04 – Troubleshooting Java, Eclipse, and Maven setup\n\n\n## Article Begins\nSome theory\n\n## Bootstrapping Spring Boot REST API with Spring Initializr\n\nCreating a REST service with **Spring Initializr** is simple and straightforward.  \nIn this guide, we’ll use **Spring Web MVC** as our web framework.\n\n[Spring Initializr](http://start.spring.io/) is an excellent tool for bootstrapping Spring Boot projects, allowing you to generate a ready-to-run application in just a few clicks.\n\n\n![Image](/images/Spring-Initializr-Web.png \"Web, Actuator and Developer Tools\")   \n\n![Image](/images/Spring-Initializr-Web-JPA.png \"Web, JPA, Hibernate and Developer Tools\")\n\nAs shown in the image above, follow these steps:\n\n1. Launch **Spring Initializr** and configure the project:\n    - Set **Group** as `TODO`\n    - Set **Artifact** as `TODO`\n    - Add the following dependencies:\n        - Spring Web\n        - Spring Boot DevTools\n        - `TODO`\n\n2. Click **Generate Project** to download the project archive.\n\n3. Import the project into **Eclipse** or **IntelliJ IDEA**\n    - `File` → `Import` → `Existing Maven Project`\n\n4. To understand all the files included in this project, refer to: `TODO`\n\n\n## Bootstrapping Angular Frontend with Create React App\n\nChange title to '<title>My Full Stack Application with Spring Boot and React</title>' in index.html\n\n```typescript\nimport React, { Component } from 'react';\n\nclass InstructorApp extends Component {\n    render() {\n        return (\n\n            <div className=\"InstructorApp\">\n                <h1>Instructor Application</h1>\n            </div>\n        )\n    }\n}\n\nexport default InstructorApp\n```\n\nnpm add axios\nnpm add react-router-dom\nnpm add formik\n\n## 📺 Recommended Watch\n\n### 🔹 Angular + Spring Boot\n- [Full Stack Application Architecture - Angular + Spring Boot](https://youtu.be/7ZsHQNlkF2g)\n- [Installing Angular CLI - Awesome Tool to Create Angular Projects](https://youtu.be/e9JhAwtW9Hk)\n- [Using Angular CLI to Create and Launch an Angular Application](https://youtu.be/0PlPY0wlNaw)\n- [Importing Angular App into Visual Studio Code](https://youtu.be/rMZNsb685r4)\n- [Angular Project Structure](https://youtu.be/ZOq9S8nSCF0)\n- [Generating an Angular Component with `ng generate`](https://youtu.be/8YC-4u3jm94)\n\n---\n\n### 🔹 React + Spring Boot\n- [Full Stack Application Architecture - Spring Boot and React](https://youtu.be/TTWH_Q7uSlY)\n- [Create React App - Create and Launch a React Application](https://youtu.be/PR1pXhesetg)\n- [Importing React App into Visual Studio Code](https://youtu.be/Cw-bSD6Q8xI)\n- [React Project Structure](https://youtu.be/wI5G8FNFrto)\n- [React Components](https://youtu.be/OmwcVGZWM98)\n\n\n\n## STEP 1 : TODO\n\n\n## Step N : Executing the TODO Service \n\nHere’s how you can run this **GET service** in **Postman**—my favorite tool for testing REST APIs (see image below).\n\n![Image](/images/ExecutingGetRestServiceUsingPostman.png \"Executing Rest Service From Postman\")   \n\n## Executing a POST Rest Service\n\nHere’s an example request you can try out: \n\n```json\n```\n\nThe image below demonstrates how to execute this **POST service** using **Postman**, a widely used tool for testing REST APIs.\n\nSteps:\n1. Open the **Body** tab and select **raw**.\n2. From the dropdown menu, choose **JSON**.\n3. Paste the example request into the body.\n\n![Image](/images/ExecutingPostRestServiceUsingPostman.png \"Executing Post Rest Service From Postman\")   \n\n\n## Complete Code Example\n- TODO\n"
  },
  {
    "path": "_blog/articles/2016-01-01-article-template.md",
    "content": "---\nlayout:     post\ntitle:      TODO\ndate:       2025-03-09 12:31:19\nsummary:    TODO\ncategories: SpringBootMicroservices\npermalink:  /url\n---\n\nThis guide will help you create a TODO***. \n \n## You will learn\n- What?\n- Why?\n- How?\n- Where?\n- When?\n\n\n## Resources/URLs/Entities Overview\n\nIn this guide, we will create three services using proper URIs and HTTP methods:\n\n## Project Code Structure\n\nFollowing screenshot shows the structure of the project we will create.\n\n![Image](/images/TODO.png \"TODO-DESC\") \n\nA few details:\n- SpringBootTutorialBasicsApplication.java - The Spring Boot Application class generated with Spring Initializer. This class acts as the launching point for application.\n- `pom.xml` - Contains all the dependencies needed to build this project. We will use Spring Boot Starter AOP.\n\n\n## Tools you will need\n- Maven 3.0+ is your build tool\n- Your favorite IDE. We use IntelliJ, Eclipse.\n- JDK 17+\n\n## Complete Maven Project With Code Examples\n> Our GitHub repository has all the code examples - https://github.com/in28minutes/spring-boot-examples/tree/master/TODO_URL\n\n## Article Begins\nSome theory\n\n## Bootstrapping with Spring Initializr\n\nCreating a REST service with **Spring Initializr** is quick and efficient. In this example, we will use **Spring Web MVC** as our web framework.  \nThe [Spring Initializr](http://start.spring.io/) provides an excellent way to bootstrap Spring Boot projects, enabling developers to generate a fully functional application setup in just a few steps.\n\n![Image](/images/Spring-Initializr-Web.png \"Web, Actuator and Developer Tools\")   \n\n![Image](/images/Spring-Initializr-Web-JPA.png \"Web, JPA, Hibernate and Developer Tools\")\n\nAs illustrated in the image above, the following steps need to be performed:\n\n- Launch **Spring Initializr** and configure the project:\n    - Set **Group** as `TODO`\n    - Set **Artifact** as `TODO`\n    - Add the following dependencies:\n        - Spring Web\n        - Spring Boot DevTools\n        - `TODO`\n- Click **Generate Project** to download the starter zip.\n- Import the project into your IDE (Eclipse or IntelliJ IDEA):\n    - `File` → `Import` → `Existing Maven Project`\n- To explore and understand all the files included in this project, refer to: `TODO`\n\n\n## STEP 1 : TODO\n\n\n## Step N : Executing the TODO Service \n\nThe image below demonstrates how to execute this **GET service** using **Postman**, a popular tool for testing REST APIs.\n\n![Image](/images/ExecutingGetRestServiceUsingPostman.png \"Executing Rest Service From Postman\")   \n\n## Executing a POST Rest Service\n\nAn example request is shown below: \n\n```json\n```\n\nThe image below demonstrates how to execute this **POST service** using **Postman**, a popular tool for testing REST APIs.  \nMake sure to:\n- Go to the **Body** tab and select **raw**.\n- Choose **JSON** from the dropdown menu.\n- Copy the above request into the request body.\n\n![Image](/images/ExecutingPostRestServiceUsingPostman.png \"Executing Post Rest Service From Postman\")   \n\n\n\n## Complete Code Example\n- TODO"
  },
  {
    "path": "_blog/articles/2017-01-17-spring-boot-basic-rest-service-top20.md",
    "content": "---\nlayout: post\ntitle: Creating a REST Service with Spring Boot\ndate: 2025-03-09 07:14:13\nsummary: Setting up a basic example REST Service with Spring Boot. Its a cake walk.\ncategories: SpringBoot\npermalink: /creating-rest-service-with-spring-boot\nimage: /images/rest-api-category.png\n---\n\n![Image](/images/ExecutingPostRestServiceUsingPostman.png \"'Executing Post Rest Service From Postman'\")\n\nIn this guide, you’ll learn how to build a simple **REST service** with **Spring Boot**.\n\n![Image](/images/SpringBootRestService-ProjectStructure.png 'Spring Boot Rest Service - Project Structure')\n\n## You will learn\n\n- **What is a REST Service?**\n- **How to bootstrap a REST service application with Spring Initializr?**\n- **How to create a GET REST service** for retrieving the courses that a student is registered for?\n- **How to create a POST REST service** for registering a course for a student?\n- **How to execute REST services using Postman?**\n\n## Rest Services in this Guide\n\nIn this guide, we will create three services using proper URIs and HTTP methods:\n\n- **`@GetMapping(\"/students/{studentId}/courses\")`**  \n  Retrieve all the courses a specific student has registered for.\n    - **HTTP Method:** GET\n    - **Example URI:** `/students/Student1/courses`\n\n- **`@GetMapping(\"/students/{studentId}/courses/{courseId}\")`**  \n  Retrieve details of a specific course for a specific student.\n    - **HTTP Method:** GET\n    - **Example URI:** `/students/Student1/courses/Course1`\n\n- **`@PostMapping(\"/students/{studentId}/courses\")`**  \n  Register a student for a new course.\n    - **HTTP Method:** POST\n    - **Example URI:** `/students/Student1/courses`\n\n## Tools You Will Need\n\n- **Maven 3.0+** – Build tool for managing dependencies and building the project\n- **IDE of your choice** – We recommend *Eclipse* or *IntelliJ IDEA*\n- **JDK 17+** – Required to run the Spring Boot application\n\n## Complete Maven Project with Code Examples\n\nYou can find the complete project with code samples in our GitHub repository:  \n👉 [Browse Code Examples](https://github.com/in28minutes/in28minutes.github.io/tree/master/code-zip-files)\n\n### Available Project\n\n- **REST Services with Unit and Integration Tests**  \n  Download: `Website-springbootrestservices-simplerestserviceswithunitandintegrationtests.zip`\n\n## What is REST?\n\nREST stands for **REpresentational State Transfer**.  \nIt is an architectural style that defines a set of constraints for building scalable web services.  \nAny service following these rules is called a **RESTful Service**.\n\n### Key Constraints of REST\n\n- **Client–Server**: Clear separation between the service provider (server) and the consumer (client).\n- **Uniform Interface**: Resources are identified using URIs (e.g., `/students/1/courses`).\n- **Stateless**: Each request is independent; the server does not store client state.\n- **Cacheable**: Responses can be cached (e.g., using HTTP caching).\n- **Layered System**: Clients don’t need to know if they are talking directly to the server or through intermediaries (\n  like caches, proxies, or load balancers).\n\n## Richardson Maturity Model\n\nThe **Richardson Maturity Model (RMM)** helps identify how mature a RESTful Web Service is, based on how well it follows\nREST principles.  \nIt defines four levels (0–3):\n\n- **Level 0: The Swamp of POX**\n    - REST in name only — action-based URIs.\n    - Example:\n        - `http://server/getPosts`\n        - `http://server/deletePosts`\n        - `http://server/doThis`\n\n- **Level 1: Resources**\n    - Use of resource-based URIs (nouns instead of actions).\n    - Still missing proper use of HTTP methods.\n    - Example:\n        - `http://server/accounts`\n        - `http://server/accounts/10`\n\n- **Level 2: HTTP Verbs**\n    - Combine resources with proper HTTP methods (GET, POST, PUT, DELETE).\n    - Example:\n        - `GET /accounts/10` → Retrieve account\n        - `POST /accounts` → Create account\n        - `PUT /accounts/10` → Update account\n        - `DELETE /accounts/10` → Delete account\n    - URIs can look like:\n        - `/posts/1/comments/5`\n        - `/accounts/1/friends/1`\n\n- **Level 3: HATEOAS (Hypermedia as the Engine of Application State)**\n    - Responses include not just data, but also links to possible next actions.\n    - Example (Facebook user resource):\n        - Returns user details **plus links** for:\n            - Recent posts\n            - Recent comments\n            - Friend list\n\n## Using Appropriate Request Methods\n\nWhen designing RESTful APIs, always use the correct **HTTP methods** for clarity and consistency.  \nBest practices for each method:\n\n- **GET**\n    - Purpose: Retrieve data (read-only).\n    - Should not update anything.\n    - Should be **idempotent** (multiple identical requests return the same result).\n    - Possible Response Codes:\n        - `200 OK` → Success\n        - `404 Not Found` → Resource not found\n        - `400 Bad Request` → Invalid request\n\n- **POST**\n    - Purpose: Create a **new resource**.\n    - Response should ideally include JSON with a link to the newly created resource.\n    - Possible Response Codes:\n        - `200 OK` → Success (less common)\n        - `201 Created` → Resource successfully created\n        - `400 Bad Request` → Invalid input\n\n- **PUT**\n    - Purpose: Update an **existing known resource**.\n    - Example: Update client details.\n    - Possible Response Codes:\n        - `200 OK` → Successfully updated\n        - `404 Not Found` → Resource not found\n\n- **DELETE**\n    - Purpose: Delete a resource.\n    - Possible Response Codes:\n        - `200 OK` → Successfully deleted\n        - `404 Not Found` → Resource not found\n\n## Project Structure\n\nThe following screenshot shows the structure of the project we will create:\n\n![Image](/images/SpringBootRestService-ProjectStructure.png 'Spring Boot Rest Service - Project Structure')\n\n### A Few Details\n\n- **`StudentController.java`** – REST controller exposing the three service methods discussed earlier.\n- **`Course.java`, `Student.java`, `StudentService.java`** – Business logic for the application. `StudentService`\n  provides methods consumed by the REST controller.\n- **`StudentControllerIT.java`** – Integration tests for the REST services.\n- **`StudentControllerTest.java`** – Unit tests for the REST services.\n- **`StudentServicesApplication.java`** – Launcher for the Spring Boot application. Run this file as a Java Application\n  to start the service.\n- **`pom.xml`** – Maven build file containing all dependencies. We use **Spring Boot Starter Web** here.\n\n## Bootstrapping Spring Boot REST API with Spring Initializr\n\nCreating a REST service with **Spring Initializr** is very simple.  \nWe will use **Spring Web MVC** as our web framework.\n\n[Spring Initializr](http://start.spring.io/) is a great tool to quickly bootstrap your Spring Boot projects.\n\n![Image](/images/Spring-Initializr-Web.png 'Web, Actuator and Developer Tools')\n\nAs shown in the image above, follow these steps:\n\n- Launch **Spring Initializr** and choose the following:\n    - **Group**: `com.in28minutes.springboot`\n    - **Artifact**: `student-services`\n    - **Dependencies**:\n        - Spring Web\n        - Spring Boot Actuator\n        - Spring Boot DevTools\n- Click **Generate Project**.\n- Import the project into **Eclipse**:  \n  `File -> Import -> Existing Maven Project`\n- If you want to explore all the files that are part of this project, you can go here: [Project Files](#)\n\n## Implementing Business Service for Your Application\n\nEvery application needs data. Instead of connecting to a real database, we will use an `ArrayList` as an **in-memory\ndata store**.\n\n### Domain Model\n\n- A **Student** can register for multiple **Courses**.\n- A **Course** has:\n    - `id`\n    - `name`\n    - `description`\n    - a list of steps to complete the course\n- A **Student** has:\n    - `id`\n    - `name`\n    - `description`\n    - a list of courses they are currently registered for\n\n### StudentService Methods\n\nThe `StudentService` provides the following methods:\n\n- `public List<Student> retrieveAllStudents()` → Retrieve details of all students\n- `public Student retrieveStudent(String studentId)` → Retrieve details of a specific student\n- `public List<Course> retrieveCourses(String studentId)` → Retrieve all courses for a student\n- `public Course retrieveCourse(String studentId, String courseId)` → Retrieve details of a specific course for a\n  student\n- `public Course addCourse(String studentId, Course course)` → Add a new course for a student\n\n### Reference Implementation\n\nCheck the exact implementation of the `StudentService` and model classes in the following files:\n\n- `src/main/java/com/in28minutes/springboot/model/Course.java`\n- `src/main/java/com/in28minutes/springboot/model/Student.java`\n- `src/main/java/com/in28minutes/springboot/service/StudentService.java`\n\n## Adding a Couple of GET REST Services\n\nThe `StudentController` exposes two GET services:\n\n```java\nprivate final StudentService studentService;\n\npublic StudentController(StudentService studentService) {\n    this.studentService = studentService;\n}\n```  \n\n- Uses Spring **Dependency Injection** to wire the `StudentService` into the controller.\n\n- `@GetMapping(\"/students/{studentId}/courses\")`  \n  Exposes a GET service to retrieve all courses for a given student, where `studentId` is provided as a path variable.\n\n- `@GetMapping(\"/students/{studentId}/courses/{courseId}\")`  \n  Exposes a GET service to retrieve details of a **specific course** for a given student.\n\n- `@PathVariable String studentId`  \n  The `studentId` from the URI is automatically mapped to this parameter in the controller method.\n\n```java\npackage com.in28minutes.springboot.controller;\n\nimport com.in28minutes.springboot.model.Course;\nimport com.in28minutes.springboot.service.StudentService;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.web.bind.annotation.*;\nimport org.springframework.web.servlet.support.ServletUriComponentsBuilder;\n\nimport java.net.URI;\nimport java.util.List;\n\n@RestController\n@RequestMapping(\"/students/{studentId}/courses\")\npublic class StudentController {\n\n    private final StudentService studentService;\n\n    public StudentController(StudentService studentService) {\n        this.studentService = studentService;\n    }\n\n    @GetMapping()\n    public List<Course> retrieveCoursesForStudent(@PathVariable String studentId) {\n        return studentService.retrieveCourses(studentId);\n    }\n\n    @GetMapping(\"/{courseId}\")\n    public Course retrieveDetailsForCourse(\n            @PathVariable String studentId,\n            @PathVariable String courseId) {\n\n        return studentService.retrieveCourse(studentId, courseId);\n    }\n}\n```\n\n## Executing the Http Get Operation Using Postman\n\nWe will access a request to http://localhost:8080/students/Student1/courses/Course1 to test the service. And will\nreceive the following response shown in the below.\n\n```json\n{\n  \"id\": \"Course1\",\n  \"name\": \"Spring\",\n  \"description\": \"10 Steps\",\n  \"steps\": [\n    \"Learn Maven\",\n    \"Import Project\",\n    \"First Example\",\n    \"Second Example\"\n  ]\n}\n```\n\nThe screenshot below shows how you can execute this **GET service** in **Postman** — my favorite tool for testing REST\nAPIs.\n\n![Image](/images/ExecutingGetRestServiceUsingPostman.png 'Executing Rest Service From Postman')\n\n## Adding an HTTP POST Operation REST Service\n\nAn **HTTP POST** operation should return a **201 (Created)** status when the resource is successfully created.\n\nKey elements in our implementation:\n\n- `@PostMapping(\"/students/{studentId}/courses\")`  \n  Maps the URI for handling **POST requests**.\n\n- `@RequestBody Course newCourse`  \n  Binds the request body to a `Course` object.\n\n- `ResponseEntity.created(location).build()`  \n  Returns a **201 Created** response along with the **Location** header pointing to the newly created resource.\n\n```java\n\n@PostMapping()\npublic ResponseEntity<Void> registerStudentForCourse(@PathVariable String studentId,\n        @RequestBody Course newCourse) {\n\n    var course = studentService.addCourse(studentId, newCourse);\n\n    if (course == null)\n        return ResponseEntity.noContent().build();\n\n    URI location = ServletUriComponentsBuilder.fromCurrentRequest()\n            .path(\"/{id}\")\n            .buildAndExpand(course.id())\n            .toUri();\n\n    return ResponseEntity.created(location)\n            .build();\n}\n\n```\n\n## Executing a Http POST Operation Rest Service\n\nThe example request below demonstrates how to register a new course for a student.  \nIt includes all the required course details in the request body.\n\n```json\n{\n  \"name\": \"Microservices\",\n  \"description\": \"10 Steps\",\n  \"steps\": [\n    \"Learn How to Break Things Up\",\n    \"Automate the hell out of everything\",\n    \"Have fun\"\n  ]\n}\n```\n\nThe screenshot below shows how to execute this **POST operation** in **Postman** — my favorite tool for testing REST\nservices.\n\nMake sure to:\n\n- Go to the **Body** tab.\n- Select **raw**.\n- Choose **JSON** from the dropdown.\n- Copy the request JSON (shown above) into the body.\n\nThe URL we use is http://localhost:8080/students/Student1/courses.\n\n![Image](/images/ExecutingPostRestServiceUsingPostman.png 'Executing Post Rest Service From Postman')\n\n## Complete Code Example\n\nOur GitHub repository has all the code\nexamples - [https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-rest-services-with-unit-and-integration-tests](https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-rest-services-with-unit-and-integration-tests)\n"
  },
  {
    "path": "_blog/articles/2017-01-21-spring-initializr-web-application.md",
    "content": "---\nlayout: post\ntitle: Spring Initializr - Bootstrap Your Spring Boot Applications at F1 speed!\ndate: 2025-09-06 06:14:13\nsummary: Discover what Spring Initializr is and how to rapidly Bootstrap a Spring Boot Web Application.\ncategories: SpringBoot\npermalink: /spring-initialzr-bootstrap-spring-boot-applications\nimage: /images/spring-boot-category.png\n---\n\n![Image](/images/Spring-Initializr-Web.png 'Web, Actuator and Developer Tools')\n\n[Spring Initializr](http://start.spring.io/) is a great tool to quickly bootstrap your Spring Boot projects.\n\n\n![Image](/images/Spring-Initializr-Web-ApplicationStructure.png 'Spring Initializr Web Application - Folder Structure')\n\nIt enables you to construct a wide range of **Spring Boot-based applications** using a simple user interface.  \nWith Spring Initializr, you can bootstrap applications such as:\n\n- Web Applications\n- RESTful Applications\n- Batch Applications\n\nSpring Boot provides a diverse set of starter projects, and Spring Initializr is compatible with all of them (and more).  \nSome commonly used starters include:\n\n- `spring-boot-starter-web-services` – Build applications exposing **SOAP Web Services**\n- `spring-boot-starter-web` – Build **Web applications** & **RESTful services**\n- `spring-boot-starter-test` – Write Unit and Integration Tests\n- `spring-boot-starter-jdbc` – Build traditional **JDBC applications**\n- `spring-boot-starter-hateoas` – Add **HATEOAS** features to make your services more RESTful\n- `spring-boot-starter-security` – Implement **authentication and authorization** using Spring Security\n- `spring-boot-starter-data-jpa` – Use **Spring Data JPA with Hibernate**\n- `spring-boot-starter-cache` – Enable caching support in your applications\n- `spring-boot-starter-data-rest` – Quickly expose simple REST services using Spring Data REST\n\n---\n\n👉 In this guide, we will focus on creating a **simple web application** with **Spring Initializr**.\n\n\n## Bootstrapping a Web Application with Spring Initializr\n\nCreating a web application with **Spring Initializr** is straightforward and fast.  \nWith just a few clicks, you can generate a fully working Spring Boot project and import it into your IDE.\n\n\n![Image](/images/Spring-Initializr-Web.png 'Web, Actuator and Developer Tools')\n\nAs shown in the image above, follow these steps:\n\n- Launch **Spring Initializr** [http://start.spring.io/](http://start.spring.io/) and choose the following:\n    - **Group**: `com.in28minutes.springboot`\n    - **Artifact**: `student-services`\n    - **Dependencies**:\n        - Spring Web\n        - Spring Boot Actuator\n        - Spring Boot DevTools\n- Click the **Generate Project** button at the bottom of the page.\n- Import the project into **Eclipse** or **IntelliJ IDEA**.\n\n\n## Project Structure Established\n\nAfter importing the Maven project, the following project structure is created (as shown in the screenshot).\n\n![Image](/images/Spring-Initializr-Web-ApplicationStructure.png \"'Spring Initializr Web Application - Folder Structure'\")\n\n### Key Project Files\n\n- **StudentServicesApplication.java** – The main launcher class for Spring Boot. It initializes Auto Configuration and the Spring Application Context.\n- **application.properties** – Central configuration file for the application.\n- **StudentServicesApplicationTests.java** – Basic test launcher for running unit tests.\n- **pom.xml** – Declares project dependencies such as Spring Boot Starter Web, Actuator, and DevTools. It also uses the Spring Boot Starter Parent as the parent POM.\n\n\n## Completely Created Code\n\nWhen the project is generated, the following key files are included.\n\n### /pom.xml\n\nThe `pom.xml` is the backbone of the project, managing dependencies and build configuration. Three important configurations are included:\n\n- **Spring Boot Parent POM** – Provides default configuration for dependency versions and plugins.  \n  👉 [Learn more](http://www.springboottutorial.com/spring-boot-starter-parent)\n\n- **Spring Boot Starter Web** – Adds support for building web applications and RESTful services.  \n  👉 [Learn more](http://www.springboottutorial.com/spring-boot-starter-projects)\n\n- **Spring Boot Maven Plugin** – Simplifies building and running Spring Boot applications directly from Maven.\n\n\n```xml\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n         xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd\">\n    <modelVersion>4.0.0</modelVersion>\n    <parent>\n        <groupId>org.springframework.boot</groupId>\n        <artifactId>spring-boot-starter-parent</artifactId>\n        <version>4.0.0-M2</version>\n        <relativePath/> <!-- lookup parent from repository -->\n    </parent>\n    <groupId>com.in28minutes.springboot</groupId>\n    <artifactId>student-services</artifactId>\n    <version>0.0.1-SNAPSHOT</version>\n    <name>student-services</name>\n    <description>Demo project for Spring Boot</description>\n    <url/>\n    <licenses>\n        <license/>\n    </licenses>\n    <developers>\n        <developer/>\n    </developers>\n    <scm>\n        <connection/>\n        <developerConnection/>\n        <tag/>\n        <url/>\n    </scm>\n    <properties>\n        <java.version>21</java.version>\n    </properties>\n    <dependencies>\n        <dependency>\n            <groupId>org.springframework.boot</groupId>\n            <artifactId>spring-boot-starter-actuator</artifactId>\n        </dependency>\n        <dependency>\n            <groupId>org.springframework.boot</groupId>\n            <artifactId>spring-boot-starter-web</artifactId>\n        </dependency>\n\n        <dependency>\n            <groupId>org.springframework.boot</groupId>\n            <artifactId>spring-boot-devtools</artifactId>\n            <scope>runtime</scope>\n            <optional>true</optional>\n        </dependency>\n        <dependency>\n            <groupId>org.springframework.boot</groupId>\n            <artifactId>spring-boot-starter-test</artifactId>\n            <scope>test</scope>\n        </dependency>\n    </dependencies>\n\n    <build>\n        <plugins>\n            <plugin>\n                <groupId>org.springframework.boot</groupId>\n                <artifactId>spring-boot-maven-plugin</artifactId>\n            </plugin>\n        </plugins>\n    </build>\n\n</project>\n\n```\n\n---\n\n### /src/main/java/com/in28minutes/springboot/StudentServicesApplication.java\n\nThis is the **main entry point** of the Spring Boot application.\n\n- **`@SpringBootApplication`** – A convenience annotation that enables:\n    - Auto Configuration\n    - Component Scanning\n    - Configuration support  \n      👉 [Learn more about Auto Configuration](http://www.springboottutorial.com/spring-boot-auto-configuration)\n    - Signifies that this is a Spring Boot application\n    - It is a composite annotation that combines the following annotations\n      - `@SpringBootConfiguration` + `@EnableAutoConfiguration` + `@ComponentScanning`\n- **`SpringApplication.run(...)`** – A static method to bootstrap and launch the Spring Boot application.\n\n\n```java\npackage com.in28minutes.springboot.studentservices;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\n@SpringBootApplication\npublic class StudentServicesApplication {\n\n  public static void main(String[] args) {\n    SpringApplication.run(StudentServicesApplication.class, args);\n  }\n}\n```\n\n---\n\n### /src/main/resources/application.properties\n\n```\n\n```\n\n---\n\n### /src/test/java/com/in28minutes/springboot/StudentServicesApplicationTests.java\n\nThis is the **default test class** generated by Spring Initializr.\n\n- It uses **Spring Boot Test support** to start the entire application context.\n- Provides a simple way to verify that the Spring Boot application loads successfully.\n- Serves as a good starting point to add **integration tests** for your services and controllers.\n\n👉 [Learn more about Integration Testing in Spring Boot](http://www.springboottutorial.com/integration-testing-for-spring-boot-rest-services)\n\n\n```java\npackage com.in28minutes.springboot.student_services;\n\nimport org.junit.jupiter.api.Test;\nimport org.springframework.boot.test.context.SpringBootTest;\n\n@SpringBootTest\nclass StudentServicesApplicationTests {\n\n    @Test\n    void contextLoads() {\n    }\n\n}\n```\n\n---\n\n## Running the application\n\nWhen you execute StudentServicesApplication.java as a Java application, the following log is generated.\n\n```\n\n /Users/puneethsai/Library/Java/JavaVirtualMachines/corretto-21.0.7/Contents/Home/bin/java -XX:TieredStopAtLevel=1 -Dspring.output.ansi.enabled=always -Dcom.sun.management.jmxremote -Dspring.jmx.enabled=true -Dspring.liveBeansView.mbeanDomain -Dspring.application.admin.enabled=true -Dmanagement.endpoints.jmx.exposure.include=* -javaagent:/Users/puneethsai/Applications/IntelliJ IDEA Ultimate.app/Contents/lib/idea_rt.jar=58604 -Dfile.encoding=UTF-8 -Dsun.stdout.encoding=UTF-8 -Dsun.stderr.encoding=UTF-8 -classpath /Users/puneethsai/Downloads/student-services/target/classes:/Users/puneethsai/.m2/repository/org/springframework/boot/spring-boot-starter-actuator/4.0.0-M2/spring-boot-starter-actuator-4.0.0-M2.jar:/Users/puneethsai/.m2/repository/org/springframework/boot/spring-boot-starter/4.0.0-M2/spring-boot-starter-4.0.0-M2.jar:/Users/puneethsai/.m2/repository/org/springframework/boot/spring-boot-starter-logging/4.0.0-M2/spring-boot-starter-logging-4.0.0-M2.jar:/Users/puneethsai/.m2/repository/ch/qos/logback/logback-classic/1.5.18/logback-classic-1.5.18.jar:/Users/puneethsai/.m2/repository/ch/qos/logback/logback-core/1.5.18/logback-core-1.5.18.jar:/Users/puneethsai/.m2/repository/org/apache/logging/log4j/log4j-to-slf4j/2.24.3/log4j-to-slf4j-2.24.3.jar:/Users/puneethsai/.m2/repository/org/apache/logging/log4j/log4j-api/2.24.3/log4j-api-2.24.3.jar:/Users/puneethsai/.m2/repository/org/slf4j/jul-to-slf4j/2.0.17/jul-to-slf4j-2.0.17.jar:/Users/puneethsai/.m2/repository/jakarta/annotation/jakarta.annotation-api/3.0.0/jakarta.annotation-api-3.0.0.jar:/Users/puneethsai/.m2/repository/org/yaml/snakeyaml/2.4/snakeyaml-2.4.jar:/Users/puneethsai/.m2/repository/org/springframework/boot/spring-boot-actuator-autoconfigure/4.0.0-M2/spring-boot-actuator-autoconfigure-4.0.0-M2.jar:/Users/puneethsai/.m2/repository/org/springframework/boot/spring-boot-actuator/4.0.0-M2/spring-boot-actuator-4.0.0-M2.jar:/Users/puneethsai/.m2/repository/com/fasterxml/jackson/core/jackson-databind/2.20.0-rc1/jackson-databind-2.20.0-rc1.jar:/Users/puneethsai/.m2/repository/com/fasterxml/jackson/core/jackson-annotations/2.20-rc1/jackson-annotations-2.20-rc1.jar:/Users/puneethsai/.m2/repository/com/fasterxml/jackson/core/jackson-core/2.20.0-rc1/jackson-core-2.20.0-rc1.jar:/Users/puneethsai/.m2/repository/com/fasterxml/jackson/datatype/jackson-datatype-jsr310/2.20.0-rc1/jackson-datatype-jsr310-2.20.0-rc1.jar:/Users/puneethsai/.m2/repository/org/springframework/boot/spring-boot-health/4.0.0-M2/spring-boot-health-4.0.0-M2.jar:/Users/puneethsai/.m2/repository/org/springframework/boot/spring-boot-micrometer-metrics/4.0.0-M2/spring-boot-micrometer-metrics-4.0.0-M2.jar:/Users/puneethsai/.m2/repository/org/springframework/boot/spring-boot-micrometer-observation/4.0.0-M2/spring-boot-micrometer-observation-4.0.0-M2.jar:/Users/puneethsai/.m2/repository/io/micrometer/micrometer-core/1.16.0-M2/micrometer-core-1.16.0-M2.jar:/Users/puneethsai/.m2/repository/org/hdrhistogram/HdrHistogram/2.2.2/HdrHistogram-2.2.2.jar:/Users/puneethsai/.m2/repository/org/latencyutils/LatencyUtils/2.0.3/LatencyUtils-2.0.3.jar:/Users/puneethsai/.m2/repository/org/springframework/boot/spring-boot-micrometer-tracing/4.0.0-M2/spring-boot-micrometer-tracing-4.0.0-M2.jar:/Users/puneethsai/.m2/repository/io/micrometer/micrometer-tracing/1.6.0-M2/micrometer-tracing-1.6.0-M2.jar:/Users/puneethsai/.m2/repository/io/micrometer/context-propagation/1.2.0-M1/context-propagation-1.2.0-M1.jar:/Users/puneethsai/.m2/repository/io/micrometer/micrometer-observation/1.16.0-M2/micrometer-observation-1.16.0-M2.jar:/Users/puneethsai/.m2/repository/org/jspecify/jspecify/1.0.0/jspecify-1.0.0.jar:/Users/puneethsai/.m2/repository/io/micrometer/micrometer-commons/1.16.0-M2/micrometer-commons-1.16.0-M2.jar:/Users/puneethsai/.m2/repository/io/micrometer/micrometer-jakarta9/1.16.0-M2/micrometer-jakarta9-1.16.0-M2.jar:/Users/puneethsai/.m2/repository/org/springframework/boot/spring-boot-starter-web/4.0.0-M2/spring-boot-starter-web-4.0.0-M2.jar:/Users/puneethsai/.m2/repository/org/springframework/boot/spring-boot-starter-jackson/4.0.0-M2/spring-boot-starter-jackson-4.0.0-M2.jar:/Users/puneethsai/.m2/repository/org/springframework/boot/spring-boot-jackson/4.0.0-M2/spring-boot-jackson-4.0.0-M2.jar:/Users/puneethsai/.m2/repository/com/fasterxml/jackson/datatype/jackson-datatype-jdk8/2.20.0-rc1/jackson-datatype-jdk8-2.20.0-rc1.jar:/Users/puneethsai/.m2/repository/com/fasterxml/jackson/module/jackson-module-parameter-names/2.20.0-rc1/jackson-module-parameter-names-2.20.0-rc1.jar:/Users/puneethsai/.m2/repository/org/springframework/boot/spring-boot-starter-tomcat/4.0.0-M2/spring-boot-starter-tomcat-4.0.0-M2.jar:/Users/puneethsai/.m2/repository/org/springframework/boot/spring-boot-tomcat/4.0.0-M2/spring-boot-tomcat-4.0.0-M2.jar:/Users/puneethsai/.m2/repository/org/springframework/boot/spring-boot-web-server/4.0.0-M2/spring-boot-web-server-4.0.0-M2.jar:/Users/puneethsai/.m2/repository/org/apache/tomcat/embed/tomcat-embed-core/11.0.10/tomcat-embed-core-11.0.10.jar:/Users/puneethsai/.m2/repository/org/apache/tomcat/embed/tomcat-embed-el/11.0.10/tomcat-embed-el-11.0.10.jar:/Users/puneethsai/.m2/repository/org/apache/tomcat/embed/tomcat-embed-websocket/11.0.10/tomcat-embed-websocket-11.0.10.jar:/Users/puneethsai/.m2/repository/org/springframework/boot/spring-boot-http-converter/4.0.0-M2/spring-boot-http-converter-4.0.0-M2.jar:/Users/puneethsai/.m2/repository/org/springframework/spring-web/7.0.0-M8/spring-web-7.0.0-M8.jar:/Users/puneethsai/.m2/repository/org/springframework/spring-beans/7.0.0-M8/spring-beans-7.0.0-M8.jar:/Users/puneethsai/.m2/repository/org/springframework/boot/spring-boot-webmvc/4.0.0-M2/spring-boot-webmvc-4.0.0-M2.jar:/Users/puneethsai/.m2/repository/org/springframework/boot/spring-boot-servlet/4.0.0-M2/spring-boot-servlet-4.0.0-M2.jar:/Users/puneethsai/.m2/repository/org/springframework/spring-webmvc/7.0.0-M8/spring-webmvc-7.0.0-M8.jar:/Users/puneethsai/.m2/repository/org/springframework/spring-aop/7.0.0-M8/spring-aop-7.0.0-M8.jar:/Users/puneethsai/.m2/repository/org/springframework/spring-expression/7.0.0-M8/spring-expression-7.0.0-M8.jar:/Users/puneethsai/.m2/repository/org/springframework/boot/spring-boot-devtools/4.0.0-M2/spring-boot-devtools-4.0.0-M2.jar:/Users/puneethsai/.m2/repository/org/springframework/boot/spring-boot/4.0.0-M2/spring-boot-4.0.0-M2.jar:/Users/puneethsai/.m2/repository/org/springframework/spring-context/7.0.0-M8/spring-context-7.0.0-M8.jar:/Users/puneethsai/.m2/repository/org/springframework/boot/spring-boot-autoconfigure/4.0.0-M2/spring-boot-autoconfigure-4.0.0-M2.jar:/Users/puneethsai/.m2/repository/org/slf4j/slf4j-api/2.0.17/slf4j-api-2.0.17.jar:/Users/puneethsai/.m2/repository/org/springframework/spring-core/7.0.0-M8/spring-core-7.0.0-M8.jar:/Users/puneethsai/.m2/repository/commons-logging/commons-logging/1.3.5/commons-logging-1.3.5.jar com.in28minutes.springboot.student_services.StudentServicesApplication\n\n  .   ____          _            __ _ _\n /\\\\ / ___'_ __ _ _(_)_ __  __ _ \\ \\ \\ \\\n( ( )\\___ | '_ | '_| | '_ \\/ _` | \\ \\ \\ \\\n \\\\/  ___)| |_)| | | | | || (_| |  ) ) ) )\n  '  |____| .__|_| |_|_| |_\\__, | / / / /\n =========|_|==============|___/=/_/_/_/\n\n :: Spring Boot ::             (v4.0.0-M2)\n\n2025-09-06T16:17:54.722+05:30  INFO 13610 --- [student-services] [  restartedMain] [                                                 ] c.i.s.s.StudentServicesApplication       : Starting StudentServicesApplication using Java 21.0.7 with PID 13610 (/Users/puneethsai/Downloads/student-services/target/classes started by puneethsai in /Users/puneethsai/Downloads/student-services)\n2025-09-06T16:17:54.728+05:30  INFO 13610 --- [student-services] [  restartedMain] [                                                 ] c.i.s.s.StudentServicesApplication       : No active profile set, falling back to 1 default profile: \"default\"\n2025-09-06T16:17:54.792+05:30  INFO 13610 --- [student-services] [  restartedMain] [                                                 ] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable\n2025-09-06T16:17:54.793+05:30  INFO 13610 --- [student-services] [  restartedMain] [                                                 ] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'\n2025-09-06T16:17:55.942+05:30  INFO 13610 --- [student-services] [  restartedMain] [                                                 ] o.s.boot.tomcat.TomcatWebServer          : Tomcat initialized with port 8080 (http)\n2025-09-06T16:17:55.958+05:30  INFO 13610 --- [student-services] [  restartedMain] [                                                 ] o.apache.catalina.core.StandardService   : Starting service [Tomcat]\n2025-09-06T16:17:55.959+05:30  INFO 13610 --- [student-services] [  restartedMain] [                                                 ] o.apache.catalina.core.StandardEngine    : Starting Servlet engine: [Apache Tomcat/11.0.10]\n2025-09-06T16:17:55.993+05:30  INFO 13610 --- [student-services] [  restartedMain] [                                                 ] b.w.c.s.WebApplicationContextInitializer : Root WebApplicationContext: initialization completed in 1200 ms\n2025-09-06T16:17:56.617+05:30  INFO 13610 --- [student-services] [  restartedMain] [                                                 ] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729\n2025-09-06T16:17:56.658+05:30  INFO 13610 --- [student-services] [  restartedMain] [                                                 ] o.s.b.a.e.web.EndpointLinksResolver      : Exposing 1 endpoint beneath base path '/actuator'\n2025-09-06T16:17:56.720+05:30  INFO 13610 --- [student-services] [  restartedMain] [                                                 ] o.s.boot.tomcat.TomcatWebServer          : Tomcat started on port 8080 (http) with context path '/'\n2025-09-06T16:17:56.729+05:30  INFO 13610 --- [student-services] [  restartedMain] [                                                 ] c.i.s.s.StudentServicesApplication       : Started StudentServicesApplication in 2.524 seconds (process running for 3.535)\n2025-09-06T16:17:58.404+05:30  INFO 13610 --- [student-services] [on(3)-127.0.0.1] [                                                 ] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'\n2025-09-06T16:17:58.405+05:30  INFO 13610 --- [student-services] [on(3)-127.0.0.1] [                                                 ] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'\n2025-09-06T16:17:58.407+05:30  INFO 13610 --- [student-services] [on(3)-127.0.0.1] [                                                 ] o.s.web.servlet.DispatcherServlet        : Completed initialization in 2 ms\n\n```\n"
  },
  {
    "path": "_blog/articles/2017-01-28-spring-boot-unit-testing-with-junit-top20.md",
    "content": "---\nlayout:     post\ntitle:      Unit Testing Rest Services with Spring Boot and JUnit\ndate:       2025-09-06 12:31:19\nsummary:    It's a piece of cake to set up a basic REST service with Spring Boot. We'll take it a step further and add excellent unit tests to our RESTful Service.\ncategories:  SpringBootUnitTesting\npermalink:  /unit-testing-for-spring-boot-rest-services\nimage: /images/unit-test-category.png\n---\n\nThis article will guide you through writing **effective unit tests** for your Spring Boot REST services.\n\nTo keep things simple and practical, we’ll start by creating a few basic REST endpoints using a sample Spring Boot project. Once the services are ready, we’ll explore how to write **clean, reliable unit tests** for them.\n\n![Image](/images/SpringBootRestService-ProjectStructure.png \"Spring Boot Rest Services - Project Structure\")\n\n## You will learn\n\n- What Unit Testing is and why it matters\n- How to create a **GET REST Service** to retrieve the courses registered by a student\n- How to write a **Unit Test** for the GET REST Service\n- How to create a **POST REST Service** to register a course for a student\n- How to write a **Unit Test** for the POST REST Service\n\n## Tools you will need\n\n- **Maven 3.0+** – Build and dependency management tool\n- **An IDE of your choice** – Eclipse, IntelliJ IDEA, or any other Java IDE\n- **JDK 17+** – Java Development Kit to compile and run the application\n\n\n## Complete Maven Project With Code Examples\n\nYou can find all the code examples in our GitHub repository:  \n[https://github.com/in28minutes/in28minutes.github.io/tree/master/code-zip-files](https://github.com/in28minutes/in28minutes.github.io/tree/master/code-zip-files)\n\n- **REST Services with Unit and Integration Tests**  \n  👉 Download: `Website-springbootrestservices-simplerestserviceswithunitandintegrationtests.zip`\n\n\n## Unit Testing\n\nThe following screenshot shows the Eclipse project structure with all the files we will create as part of this tutorial.\n\nWe will cover:\n- Writing a simple **GET REST Service** and its **unit test**\n- Writing a **POST REST Service** and its **unit test**\n\n\n![Image](/images/SpringBootRestService-ProjectStructure.png \"Spring Boot Rest Services - Project Structure\")\n\n## Writing Unit Tests for `StudentController`\n\nThe `StudentController` exposes two service methods — **GET** and **POST**.  \nWe will create unit tests for both of these methods.\n\nIn the unit tests:\n- The `StudentService` dependency will be **mocked using Mockito**.\n- We will use the **MockMvc** framework to launch only the `StudentController`.\n\n⚡ Key Principle:  \nA critical aspect of unit testing is **limiting the scope**.  \nHere, we only want to test the logic inside `StudentController`, without involving the actual `StudentService` implementation or other layers.\n\n\n## Overview\n\nIn this guide, we will walk through the process of building and testing a simple Spring Boot REST API.  \nThe steps we will follow are:\n\n1. **Bootstrap the Project**  \n   Use **Spring Initializr** to quickly set up the base project.\n\n2. **Implement the Business Service**  \n   Create the `StudentService` class to provide business logic for our API.\n\n3. **Build the REST API**  \n   Develop the `StudentController`:\n    - First, implement the **GET endpoints**.\n    - Then, implement the **POST endpoint**.\n\n4. **Write Unit Tests**  \n   Use **Mockito** and **MockMvc** to unit test the `StudentController`.\n\n## Bootstrap REST Services Application with Spring Initializr\n\n> [Spring Initializr](http://start.spring.io/) is an excellent tool for bootstrapping Spring Boot projects with just a few clicks.\n\nWith Spring Initializr, you can quickly generate a project structure by selecting:\n\n- **Group**: `com.in28minutes.springboot`\n- **Artifact**: `student-services`\n- **Dependencies**:\n    - Spring Web\n    - Spring Boot Actuator\n    - Spring Boot DevTools\n\nOnce generated, download the project, unzip it, and import it into your favorite IDE (Eclipse, IntelliJ, or VS Code).\n\n\n![Image](/images/Spring-Initializr-Web.png \"Web, Actuator and Developer Tools\")   \n\nAs shown in the image above, follow these steps to create your project:\n\n- Launch **Spring Initializr** and choose the following:\n    - **Group**: `com.in28minutes.springboot`\n    - **Artifact**: `student-services`\n    - **Dependencies**:\n        - Spring Web\n        - Spring Boot Actuator\n        - Spring Boot DevTools\n- Click **Generate Project** to download the starter project.\n- Import the project into Eclipse (**File → Import → Existing Maven Project**).\n- To explore and understand all the files generated by Spring Initializr, you can refer [here](#).\n\n## Adding Business Services to Your Application\n\nEvery application needs data. In this example, instead of connecting to a real database, we’ll use an `ArrayList` as an in-memory data store.\n\n- A **student** can enroll in multiple **courses**.\n- A **course** has an `id`, `name`, `description`, and a list of `steps` to complete the course.\n- A **student** has an `id`, `name`, `description`, and a list of registered courses.\n\nWe’ll implement a `StudentService` that provides the following methods:\n\n- `public List<Student> retrieveAllStudents()` – Retrieve details for all students\n- `public Student retrieveStudent(String studentId)` – Retrieve details of a specific student\n- `public List<Course> retrieveCourses(String studentId)` – Retrieve all courses a student is registered for\n- `public Course retrieveCourse(String studentId, String courseId)` – Retrieve a specific course for a student\n- `public Course addCourse(String studentId, Course course)` – Add a new course for an existing student\n\nYou can find the actual implementation of the service and models in these files:\n\n- `src/main/java/com/in28minutes/springboot/model/Course.java`\n- `src/main/java/com/in28minutes/springboot/model/Student.java`\n- `src/main/java/com/in28minutes/springboot/service/StudentService.java`\n\n---\n\n## Adding a Couple of GET Operations\n\nThe `StudentController` exposes two GET REST endpoints:\n\n```java\nprivate final StudentService studentService;\n\npublic StudentController(StudentService studentService) {\n    this.studentService = studentService;\n}\n```\n-  Uses Spring **Dependency Injection** to wire the `StudentService` into the controller.\n- `@GetMapping(\"/students/{studentId}/courses\")` – Retrieves all courses for a given student (`studentId` is passed as a path variable).\n- `@GetMapping(\"/students/{studentId}/courses/{courseId}\")` – Retrieves details of a specific course (`courseId`) for a student.\n- `@PathVariable String studentId` – Maps the value of `studentId` from the URI to this parameter.\n\n\n\n```java\npackage com.in28minutes.springboot.controller;\n\nimport java.util.List;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.RestController;\n\nimport com.in28minutes.springboot.model.Course;\nimport com.in28minutes.springboot.service.StudentService;\n\n@RestController\npublic class StudentController {\n\n    private final StudentService studentService;\n\n    public StudentController(StudentService studentService) {\n        this.studentService = studentService;\n    }\n\n    @GetMapping(\"/students/{studentId}/courses\")\n    public List<Course> retrieveCoursesForStudent(@PathVariable String studentId) {\n        return studentService.retrieveCourses(studentId);\n    }\n    \n    @GetMapping(\"/students/{studentId}/courses/{courseId}\")\n    public Course retrieveDetailsForCourse(@PathVariable String studentId,\n            @PathVariable String courseId) {\n        return studentService.retrieveCourse(studentId, courseId);\n    }\n\n}\n\n```\n\n## Executing the Http Get Operation Using Postman\nWe will fire a request to http://localhost:8080/students/Student1/courses/Course1 to test the service. Response is as shown below.\n\n```json\n{\n  \"id\": \"Course1\",\n  \"name\": \"Spring\",\n  \"description\": \"10Steps\",\n  \"steps\": [\n    \"Learn Maven\",\n    \"Import Project\",\n    \"First Example\",\n    \"Second Example\"\n  ]\n}\n```\n\nBelow screenshot demonstrates how to execute this **GET** operation using Postman — a popular tool for testing RESTful services.\n\n\n![Image](/images/ExecutingGetRestServiceUsingPostman.png \"Executing Rest Service From Postman\")   \n\n## Add spring-security-test for disabling security in unit tests\n\n```\n<dependency>\n\t<groupId>org.springframework.security</groupId>\n\t<artifactId>spring-security-test</artifactId>\n\t<scope>test</scope>\n</dependency>\n```\n\n## Unit Testing Http Get Operation\n\n## Unit Testing a Spring MVC Controller\n\nWhen unit testing a REST service, we want to **launch only the relevant controller** and the associated MVC components.  \nThe annotation `@WebMvcTest` is used for this purpose. It focuses the test exclusively on Spring MVC components. Using this annotation disables full auto-configuration and loads only the configuration relevant for MVC tests.\n\nKey components in our test setup:\n\n- `@ExtendWith(SpringExtension.class)`\n    - Registers Spring extensions with JUnit 5.\n    - Integrates the Spring TestContext Framework into JUnit Jupiter.\n    - Supports annotated arguments in constructors, test methods, and lifecycle methods (`@BeforeAll`, `@BeforeEach`, `@AfterAll`, `@AfterEach`).\n\n- `@WebMvcTest(value = StudentController.class)`\n    - Used to unit test Spring MVC components.\n    - Launches only `StudentController` for testing.\n    - No other controllers or mappings are started.\n\n- `@Autowired private MockMvc mockMvc`\n    - Entry point for server-side Spring MVC test support.\n    - Allows executing HTTP requests against the test context.\n\n- `@MockBean private StudentService studentService`\n    - Mocks the `StudentService` and injects it into `StudentController`.\n    - Ensures the unit test only focuses on controller behavior.\n\n- `Mockito.when(studentService.retrieveCourse(Mockito.anyString(), Mockito.anyString())).thenReturn(mockCourse)`\n    - Mocks the behavior of `retrieveCourse()` to return a predefined `mockCourse`.\n\n- `MockMvcRequestBuilders.get(\"/students/Student1/courses/Course1\").accept(MediaType.APPLICATION_JSON)`\n    - Creates a GET request to the specified URI with an `Accept` header of `application/json`.\n\n- `mockMvc.perform(requestBuilder).andReturn()`\n    - Executes the request using `MockMvc` and returns the response.\n\n- `JSONAssert.assertEquals(expected, result.getResponse().getContentAsString(), false)`\n    - Uses `org.skyscreamer.jsonassert.JSONAssert` to assert JSON responses.\n    - Passing `strict=false` allows partial checks without requiring all fields to match.\n\n\n```java\npackage com.in28minutes.springboot.controller;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\nimport java.util.Arrays;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.mockito.Mockito;\nimport org.skyscreamer.jsonassert.JSONAssert;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;\nimport org.springframework.boot.test.mock.mockito.MockBean;\nimport org.springframework.http.MediaType;\nimport org.springframework.test.context.junit4.SpringRunner;\nimport org.springframework.test.web.servlet.MockMvc;\nimport org.springframework.test.web.servlet.MvcResult;\nimport org.springframework.test.web.servlet.RequestBuilder;\nimport org.springframework.test.web.servlet.request.MockMvcRequestBuilders;\n\nimport com.in28minutes.springboot.model.Course;\nimport com.in28minutes.springboot.service.StudentService;\n\n@ExtendWith(SpringExtension.class)\n@WebMvcTest(value = StudentController.class)\n@WithMockUser\npublic class StudentControllerTest {\n\n\t@Autowired\n\tprivate MockMvc mockMvc;\n\n\t@MockBean\n\tprivate StudentService studentService;\n\n\tCourse mockCourse = new Course(\"Course1\", \"Spring\", \"10Steps\",\n\t\t\tArrays.asList(\"Learn Maven\", \"Import Project\", \"First Example\", \"Second Example\"));\n\n\tString exampleCourseJson = \"{\\\"name\\\":\\\"Spring\\\",\\\"description\\\":\\\"10Steps\\\",\\\"steps\\\":[\\\"Learn Maven\\\",\\\"Import Project\\\",\\\"First Example\\\",\\\"Second Example\\\"]}\";\n\n\t@Test\n\tpublic void retrieveDetailsForCourse() throws Exception {\n\n\t\tMockito.when(studentService.retrieveCourse(Mockito.anyString(),\n\t\t\t\t\t\tMockito.anyString())).thenReturn(mockCourse);\n\n\t\tRequestBuilder requestBuilder = MockMvcRequestBuilders.get(\n\t\t\t\t\"/students/Student1/courses/Course1\").accept(\n\t\t\t\tMediaType.APPLICATION_JSON);\n\n\t\tMvcResult result = mockMvc.perform(requestBuilder).andReturn();\n\n\t\tSystem.out.println(result.getResponse());\n\t\tString expected = \"{\\\"id\\\":\\\"Course1\\\",\\\"name\\\":\\\"Spring\\\",\\\"description\\\":\\\"10 Steps\\\"}\";\n\n\n\t\t// {\"id\":\"Course1\",\"name\":\"Spring\",\"description\":\"10 Steps, 25 Examples and 10K Students\",\"steps\":[\"Learn Maven\",\"Import Project\",\"First Example\",\"Second Example\"]}\n\n\t\tJSONAssert.assertEquals(expected, result.getResponse()\n\t\t\t\t.getContentAsString(), false);\n\t}\n\n}\n\n```\n\n## Adding Http POST Operation\n\n## Implementing a HTTP POST Operation\n\nAn HTTP POST operation should return a **201 Created** status when the resource is successfully created.\n\nKey components of the POST implementation:\n\n- `@PostMapping(\"/students/{studentId}/courses\")`  \n  Maps the URL to handle POST requests for adding a course to a student.\n\n- `@RequestBody Course newCourse`  \n  Binds the JSON body of the request to a `Course` object.\n\n- `ResponseEntity.created(location).build()`  \n  Returns a **201 Created** status and sets the **Location header** pointing to the URI of the newly created resource.\n\nExample:  \nWhen adding a course to `Student1`, the POST request might look like:\n\n```java\n@PostMapping(\"/students/{studentId}/courses\")\npublic ResponseEntity<Void> registerStudentForCourse(\n        @PathVariable String studentId, @RequestBody Course newCourse) {\n\n    Course course = studentService.addCourse(studentId, newCourse);\n\n    if (course == null)\n        return ResponseEntity.noContent().build();\n\n    URI location = ServletUriComponentsBuilder.fromCurrentRequest().path(\n            \"/{id}\").buildAndExpand(course.getId()).toUri();\n\n    return ResponseEntity.created(location).build();\n}\n\n```\n\n## Executing the Http POST Operation\n\nAn example request is shown below. It provides all of the information needed to enrol a student for a course.\n```json\n{\n  \"name\": \"Microservices\",\n  \"description\": \"10Steps\",\n  \"steps\": [\n    \"Learn How to Break Things Up\",\n    \"Automate the hell out of everything\",\n    \"Have fun\"\n  ]\n}\n```\n\n## Executing the HTTP POST Operation Using Postman\n\nThe image below demonstrates how to perform this POST operation using Postman — my preferred tool for testing REST services.\n\nSteps to follow:\n1. Go to the **Body** tab in Postman.\n2. Select **raw**.\n3. From the dropdown menu, choose **JSON**.\n4. Copy and paste the JSON request (shown above) into the body.\n5. Click **Send** to execute the POST request.\n\nIf successful, the server will return a **201 Created** status along with the location of the newly created resource in the response headers.\n\nThe URL we use is http://localhost:8080/students/Student1/courses.\n\n![Image](/images/ExecutingPostRestServiceUsingPostman.png \"Executing Post Rest Service From Postman\")   \n\n## Writing Unit Test for the Http POST Operation\n\n## Unit Testing the HTTP POST Operation\n\nIn the unit test, we want to send a POST request to `/students/Student1/courses` and validate that:\n\n1. The HTTP status returned is **201 Created**.\n2. The **Location** header contains the URI of the newly created resource.\n\nKey components in the test:\n\n- `MockMvcRequestBuilders.post(\"/students/Student1/courses\").accept(MediaType.APPLICATION_JSON)`  \n  Creates a POST request with an `Accept` header set to `application/json`.\n\n- `content(exampleCourseJson).contentType(MediaType.APPLICATION_JSON)`  \n  Sets the request body to `exampleCourseJson` and specifies the content type as JSON.\n\n- `assertEquals(HttpStatus.CREATED.value(), response.getStatus())`  \n  Verifies that the response status is **201 Created**.\n\n- `response.getHeader(HttpHeaders.LOCATION)`  \n  Retrieves the **Location** header from the response. You can then assert that it contains the URI of the newly created course.\n\n```java\n\t@Test\n\tpublic void createStudentCourse() throws Exception {\n\t\tvar mockCourse = new Course(\"1\", \"Smallest Number\", \"1\", Arrays.asList(\"1\", \"2\", \"3\", \"4\"));\n\n\t\t// studentService.addCourse to respond back with mockCourse\n\t\tMockito.when(studentService.addCourse(Mockito.anyString(),\n\t\t\t\t\t\tMockito.any(Course.class))).thenReturn(mockCourse);\n\n\t\t// Send course as body to /students/Student1/courses\n\t\tRequestBuilder requestBuilder = MockMvcRequestBuilders\n\t\t\t\t.post(\"/students/Student1/courses\")\n\t\t\t\t.accept(MediaType.APPLICATION_JSON).content(exampleCourseJson)\n\t\t\t\t.contentType(MediaType.APPLICATION_JSON);\n\n\t\tMvcResult result = mockMvc.perform(requestBuilder).andReturn();\n\n\t\tMockHttpServletResponse response = result.getResponse();\n\n\t\tassertEquals(HttpStatus.CREATED.value(), response.getStatus());\n\n\t\tassertEquals(\"http://localhost/students/Student1/courses/1\",\n\t\t\t\tresponse.getHeader(HttpHeaders.LOCATION));\n\n\t}\n\n```"
  },
  {
    "path": "_blog/articles/2017-01-29-spring-boot-autoconfiguration-top20.md",
    "content": "---\nlayout:     post\ntitle:      What is Spring Boot Auto Configuration?\ndate:       2025-09-06 12:31:19\nsummary:    Auto Configuration is the most important feature in Spring Boot. In this tutorial, we will learn important concepts about Auto Configuration with a couple of examples. \ncategories:  SpringBoot\npermalink:  /spring-boot-auto-configuration\nimage: /images/spring-framework-category.png\n---\n\n![Image](/images/Spring-Initializr-Web.png \"Web, Actuator and Developer Tools\")   \n\nThrough examples, this guide will help you understand **Spring Boot Auto Configuration**. We will create a few basic REST services using simple code samples.\n\n![Image](/images/spring-boot-autoconfigure-jar.png \"Spring Boot Auto Configure Jar\")\n\n## What You Will Learn\n\n- Why **Auto Configuration** is needed in Spring Boot\n- What **Auto Configuration** actually is\n- Examples of **Spring Boot Auto Configuration** in action\n- How **Auto Configuration** is implemented under the hood\n- Techniques to **debug Auto Configuration**\n\n## Tools You Will Need\n\n- **Maven 3.0+** – Build tool for your Spring Boot project\n- **IDE** – Your favorite IDE; we recommend Eclipse or IntelliJ IDEA\n- **JDK 17+** – Java Development Kit for compiling and running the application\n\n\n## Complete Maven Project with Code Examples\n\n> Our GitHub repository contains all the code examples: [https://github.com/in28minutes/in28minutes.github.io/tree/master/code-zip-files](https://github.com/in28minutes/in28minutes.github.io/tree/master/code-zip-files)\n\n- **Restful Web Services Examples**\n    - `Website-springbootrestservices-all-examples.zip`\n\n## Why Do We Need Spring Boot Auto Configuration?\n\nSpring-based applications often require extensive configuration.\n\nFor example, in a typical Spring MVC application, you need to configure:\n\n- Component scanning\n- Dispatcher Servlet\n- View resolver\n- WebJars (for serving static content)\n- And other required beans and settings\n\nSpring Boot Auto Configuration helps reduce this boilerplate by automatically configuring many of these components for you.\n\n```xml\n  <bean\n        class=\"org.springframework.web.servlet.view.InternalResourceViewResolver\">\n        <property name=\"prefix\">\n            <value>/WEB-INF/views/</value>\n        </property>\n        <property name=\"suffix\">\n            <value>.jsp</value>\n        </property>\n  </bean>\n  \n  <mvc:resources mapping=\"/webjars/**\" location=\"/webjars/\"/>\n    \n```\n\nA typical configuration of a **Dispatcher Servlet** in a Spring web application is shown in the code snippet below.\n\n```xml\n    <servlet>\n        <servlet-name>dispatcher</servlet-name>\n        <servlet-class>\n            org.springframework.web.servlet.DispatcherServlet\n        </servlet-class>\n        <init-param>\n            <param-name>contextConfigLocation</param-name>\n            <param-value>/WEB-INF/todo-servlet.xml</param-value>\n        </init-param>\n        <load-on-startup>1</load-on-startup>\n    </servlet>\n\n    <servlet-mapping>\n        <servlet-name>dispatcher</servlet-name>\n        <url-pattern>/</url-pattern>\n    </servlet-mapping>\n```\n\nWhen using Hibernate/JPA, you need to configure a **data source**, an **EntityManagerFactory**, and a **transaction manager**, among other components.\n\n```xml\n    <bean id=\"dataSource\" class=\"com.mchange.v2.c3p0.ComboPooledDataSource\"\n        destroy-method=\"close\">\n        <property name=\"driverClass\" value=\"${db.driver}\" />\n        <property name=\"jdbcUrl\" value=\"${db.url}\" />\n        <property name=\"user\" value=\"${db.username}\" />\n        <property name=\"password\" value=\"${db.password}\" />\n    </bean>\n\n    <jdbc:initialize-database data-source=\"dataSource\">\n        <jdbc:script location=\"classpath:config/schema.sql\" />\n        <jdbc:script location=\"classpath:config/data.sql\" />\n    </jdbc:initialize-database>\n\n    <bean\n        class=\"org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean\"\n        id=\"entityManagerFactory\">\n        <property name=\"persistenceUnitName\" value=\"hsql_pu\" />\n        <property name=\"dataSource\" ref=\"dataSource\" />\n    </bean>\n\n    <bean id=\"transactionManager\" class=\"org.springframework.orm.jpa.JpaTransactionManager\">\n        <property name=\"entityManagerFactory\" ref=\"entityManagerFactory\" />\n        <property name=\"dataSource\" ref=\"dataSource\" />\n    </bean>\n\n    <tx:annotation-driven transaction-manager=\"transactionManager\"/>\n\n``` \n\nThe examples shown here are representative of typical Spring Framework setups or integrations with other frameworks.\n\n## Spring Boot: Can We Think Differently?\n\nSpring Boot introduces a new approach to application development, simplifying configuration and reducing boilerplate code.\n\n> Can we make this smarter? For example, when a Spring MVC JAR is added to an application, can certain beans be **auto-configured automatically** without explicit setup by the developer?\n\n- Automatically configure a **Data Source** if the Hibernate JAR is present on the classpath.\n- Automatically configure a **Dispatcher Servlet** if the Spring MVC JAR is present on the classpath.\n\nThere are provisions to **override the default autoconfiguration** when custom behavior is needed. \n\n> Spring Boot inspects:\n1. The **frameworks present on the classpath**\n2. The **current settings of the application**\n\nBased on these, Spring Boot provides the **necessary default configurations** to set up the application with the detected frameworks. This process is called **Auto Configuration**.\n\nTo explore **Auto Configuration** in action, let's bootstrap a simple Spring Boot application using **Spring Initializr**.\n\n## Creating a REST Services Application with Spring Initializr\n\n> **Spring Initializr** [http://start.spring.io/](http://start.spring.io/) is a powerful tool to quickly bootstrap your Spring Boot projects.\n\n![Image](/images/Spring-Initializr-Web.png \"Web, Actuator and Developer Tools\")   \n\nAs shown in the image above, follow these steps to bootstrap your Spring Boot project:\n\n1. Launch **Spring Initializr** and configure the project:\n    - **Group**: `com.in28minutes.springboot`\n    - **Artifact**: `student-services`\n    - **Dependencies**:\n        - Web\n        - Actuator\n        - DevTools\n\n2. Click **Generate Project**.\n3. Import the generated project into **Eclipse**.\n4. To understand all the files included in this project, refer to the provided documentation.\n\n### Spring Boot Auto Configuration in Action\n\nWhen you run `StudentServicesApplication.java` as a Java application, you will notice several important messages in the log that demonstrate Spring Boot's **auto-configuration** at work.\n\n```\n- **Mapping servlet**: `'dispatcherServlet'` is mapped to `/`  \n- **Error mapping**: `{/error}` is mapped to the `BasicErrorController.error()` method  \n- **WebJars mapping**: `/webjars/**` is mapped to the `ResourceHttpRequestHandler` for serving static resources\n\n```\n\nThe log statements above are excellent examples of **Spring Boot Auto Configuration** in action.\n\nSpring Boot auto-detects that **Spring MVC** is on the classpath when you include **Spring Boot Starter Web** as a dependency. It automatically configures:\n- `dispatcherServlet`\n- A default error page\n- WebJars for serving static resources\n\nSimilarly, when you add **Spring Boot Data JPA Starter**, Spring Boot Auto Configuration automatically sets up a **DataSource** and an **EntityManager**.\n\n## Where is Spring Boot Auto Configuration Implemented?\n\nThe JAR `spring-boot-autoconfigure.jar` contains all the autoconfiguration logic.  \nIt provides configuration for **MVC, Data, JMS**, and other Spring frameworks in a single place.\n\n![Image](/images/spring-boot-autoconfigure-jar.png \"Spring Boot Auto Configure Jar\")\n\n/META-INF/spring.factories is another crucial file contained within spring-boot-autoconfigure.jar. This file contains a list of all the auto configuration classes that should be imported using the AutoConfigurationImportFilter and AutoConfigurationImportFilter keys, depending on the dependencies found on the classpath.\n\n```properties\n# Auto Configuration Import Listeners\norg.springframework.boot.autoconfigure.AutoConfigurationImportListener=\\\norg.springframework.boot.autoconfigure.condition.ConditionEvaluationReportAutoConfigurationImportListener\n\n# Auto Configuration Import Filters\norg.springframework.boot.autoconfigure.AutoConfigurationImportFilter=\\\norg.springframework.boot.autoconfigure.condition.OnBeanCondition,\\\norg.springframework.boot.autoconfigure.condition.OnClassCondition,\\\norg.springframework.boot.autoconfigure.condition.OnWebApplicationCondition\n```   \n\n### Example of Auto Configuration\n\nLet's take a look at **`DataSourceAutoConfiguration`**.\n\nTypically, all autoconfiguration classes check which classes are available on the classpath. If certain classes are present, Spring Boot enables the corresponding configuration automatically.\n\nAnnotations such as:\n- `@ConditionalOnClass`\n- `@ConditionalOnMissingBean`\n\nhelp provide this conditional autoconfiguration behavior.\n\n`@ConditionalOnClass({ DataSource.class, EmbeddedDatabaseType.class })` : This configuration is enabled only when these classes are available in the classpath.\n\n```\n@AutoConfiguration(\n    before = {SqlInitializationAutoConfiguration.class}\n)\n@ConditionalOnClass({DataSource.class, EmbeddedDatabaseType.class})\n@ConditionalOnMissingBean(\n    type = {\"io.r2dbc.spi.ConnectionFactory\"}\n)\n@EnableConfigurationProperties({DataSourceProperties.class})\n@Import({DataSourcePoolMetadataProvidersConfiguration.class})\npublic class DataSourceAutoConfiguration {\n```\n\n`@ConditionalOnMissingBean` : This bean is configured only if there is no other bean configured with the same name.\n\n```java\n@Bean\n@ConditionalOnMissingBean\npublic DataSourceInitializer dataSourceInitializer() {\n\treturn new DataSourceInitializer();\n}\n```\n\nAn **embedded database** is configured only if no beans of type `DataSource.class` or `XADataSource.class` are already defined in the application context.\n\n```java\n@Configuration(proxyBeanMethods = false)\n@Conditional({EmbeddedDatabaseCondition.class})\n@ConditionalOnMissingBean({DataSource.class, XADataSource.class})\n@Import({EmbeddedDataSourceConfiguration.class})\nprotected static class EmbeddedDatabaseConfiguration {\n    protected EmbeddedDatabaseConfiguration() {\n    }\n}\n\n```\n\n## Debugging Auto Configuration\n\nThere are two main ways to debug and get more information about Spring Boot auto-configuration:\n\n- **Enable debug logging**\n- **Use Spring Boot Actuator**\n\n### Debug Logging\n\nYou can enable debug logging by adding a property to `application.properties`.  \nFor example, the configuration below turns on **DEBUG** level logging for all classes in the `org.springframework` package and its subpackages:\n```properties\nlogging.level.org.springframework=DEBUG\n```\n\nWhen you restart the application, an **autoconfiguration report** will be printed in the logs.\n\nThe report lists all autoconfiguration classes, separating **positive matches** from **negative matches**.  \nIt shows:\n- Why a particular bean was autoconfigured\n- Why certain beans were **not** autoconfigured\n\n```log\n=========================\nCONDITIONS EVALUATION REPORT\n=========================\n\nPositive matches:\n-----------------\nDispatcherServletAutoConfiguration.DispatcherServletConfiguration matched:\n - @ConditionalOnClass found required class 'jakarta.servlet.ServletRegistration' (OnClassCondition)\n - Default DispatcherServlet did not find dispatcher servlet beans (DispatcherServletAutoConfiguration.DefaultDispatcherServletCondition)\n\n\nNegative matches:\n-----------------\nArtemisAutoConfiguration:\n   Did not match:\n      - @ConditionalOnClass did not find required class 'jakarta.jms.ConnectionFactory' (OnClassCondition)\n\nAopAutoConfiguration.ClassProxyingConfiguration:\n   Did not match:\n      - @ConditionalOnMissingClass found unwanted class 'org.aspectj.weaver.Advice' (OnClassCondition)\n\n\n```\n\n### Spring Boot Actuator\n\nAnother way to debug autoconfiguration is by adding **Spring Boot Actuator** to your project.\n\nWe can also include **HAL Explorer** to simplify browsing and exploring actuator endpoints.\n\n\n```xml\n<dependency>\n\t<groupId>org.springframework.boot</groupId>\n\t<artifactId>spring-boot-starter-actuator</artifactId>\n</dependency>\n\n<dependency>\n\t<groupId>org.springframework.data</groupId>\n\t<artifactId>spring-data-rest-hal-explorer</artifactId>\n</dependency>\n\n```\n\nHAL Explorer autoconfiguration [http://localhost:8080/actuator/conditions](http://localhost:8080/actuator/conditions) would show the details of all the beans which are autoconfigured and those which are not.\n\n![Image](/images/spring-boot-auto-configuration-actuator-negative-matches.png \"Negative Matches Spring Boot Auto Configuration\")\n\n![Image](/images/spring-boot-auto-configuration-actuator-positive-matches.png \"Positive Matches Spring Boot Auto Configuration\")\n\n"
  },
  {
    "path": "_blog/articles/2017-01-30-spring-boot-integration-testing.md",
    "content": "---\nlayout:     post\ntitle:      Writing Integration Tests for Rest Services with Spring Boot\ndate:       2025-09-06 12:31:19\nsummary:    Setting up a basic REST Service with Spring Boot is a cake walk. We will go one step further and add great integration tests! \ncategories:  SpringBootUnitTesting\npermalink:  /integration-testing-for-spring-boot-rest-services\nimage: /images/unit-test-category.png\n---\n\n![Image](/images/Spring-Initializr-Web.png \"Web, Actuator and Developer Tools\")   \n\nThis post will assist you in creating excellent integration tests for your Spring Boot Rest Service. We will create a few of basic rest services using a simple code sample.\n \n## You will learn\n- What is Integration Testing?\n- How to create a Get REST Service for retrieving the courses that a student registered for?\n- How to write a integration test for Get REST Service?\n- How to create a Post REST Service for registering a course for student?\n- How to write a integration test for the POST Service?\n\n\n\n## Tools you will need\n- Maven 3.0+ is your build tool\n- Your favorite IDE. We use Eclipse.\n- JDK 17\n\n## Complete Maven Project With Code Examples\n> Our Github repository has all the code examples - [https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-rest-services-with-unit-and-integration-tests](https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-rest-services-with-unit-and-integration-tests)\n\n## Integration Testing\n\nFollowing screenshot shows eclipse project with all the files we will create.\n\n![Image](/images/SpringBootRestService-ProjectStructure.png \"Spring Boot Rest Services - Project Structure\")\n\nWe want to write an integration test for the 'StudentController' Rest Controller. The 'StudentController' class offers two service methods: Get and Post. Both of these service methods will be subjected to integration testing. \n\nIn the integration test\n\n- `@SpringBootTest` will be used to launch the whole Spring Boot application.\n- `TestRestTemplate` will be used to call the service methods.\n- The results will be asserted using a fantastic JSON assert framework - `org.skyscreamer.jsonassert.JSONAssert`.\n\nTesting all of the application's levels is an important aspect of integration testing.\n\n## Overview\n\nIn this guide, we perform everything in the following order:\n\n- Spring Initializr may be used to bootstrap a project.\n- Build a Business Service - StudentService - for our API.\n- Use StudentController to implement the API. The GET methods are implemented first, followed by the POST methods. \n- Create API integration tests.\n\n\n## Using Spring Initializr to Create a REST Services Application\n\n> Spring Initializr [http://start.spring.io/](http://start.spring.io/){:target=\"_blank\"} is great tool to bootstrap your Spring Boot projects.\n\n![Image](/images/Spring-Initializr-Web.png \"Web, Actuator and Developer Tools\")   \n\nAs shown in the image above, following steps have to be done\n\n- Launch Spring Initializr and choose the following\n  - Choose `com.in28minutes.springboot` as Group\n  - Choose `student-services` as Artifact\n  - Choose following dependencies\n    - Web\n    - Actuator\n    - DevTools\n- Click Generate Project.\n- Import the project into Eclipse.\n- If you want to understand all the files that are part of this project, you can go here.\n\n## Adding Business Services to Your Application\n\nAll applications need data. Instead of talking to a real database, we will use an `ArrayList` - kind of an in-memory data store.\n\nA student may enrol in many courses. A course contains an id, a name, a description, and a set of actions that must be completed in order to complete the course. A student has an id, a name, a description, and a list of courses for which he or she is presently registered. StudentService is exposing methods to us. \n\n- `public List<Student> retrieveAllStudents()` - Retrieve details for all students\n- `public Student retrieveStudent(String studentId)` - Retrieve a specific student details\n- `public List<Course> retrieveCourses(String studentId)` - Retrieve all courses a student is registered for\n- `public Course retrieveCourse(String studentId, String courseId)` - Retrieve details of a specific course a student is registered for\n- `public Course addCourse(String studentId, Course course)` - Add a course to an existing student\n\n The precise implementation of the Service `StudentService` and the model classes `Course` and 'Student' may be seen at the bottom of this article.\n\n- src/main/java/com/in28minutes/springboot/model/Course.java\n- src/main/java/com/in28minutes/springboot/model/Student.java\n- src/main/java/com/in28minutes/springboot/service/StudentService.java\n\n\n## Adding Couple of Http GET Operations\n\nThe Rest Service `StudentController` exposes couple of get services.\n\n- `@Autowired private StudentService studentService` : Spring Autowiring is being used to connect the student service to the StudentController.\n- `@GetMapping(\"/students/{studentId}/courses\")`: Making a Get Service with studentId available as a route variable \n- `@GetMapping(\"/students/{studentId}/courses/{courseId}\")`: Introducing a Get Service for fetching a student's individual course. \n- `@PathVariable String studentId`: This argument will be mapped to the value of studentId from the uri.\n\n```java\npackage com.in28minutes.springboot.controller;\n\nimport java.net.URI;\nimport java.util.List;\n\nimport com.in28minutes.springboot.model.Course;\nimport com.in28minutes.springboot.service.StudentService;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.PostMapping;\nimport org.springframework.web.bind.annotation.RequestBody;\nimport org.springframework.web.bind.annotation.RestController;\nimport org.springframework.web.servlet.support.ServletUriComponentsBuilder;\n\n@RestController\npublic class StudentController {\n\n    @Autowired\n    private StudentService studentService;\n\n    @GetMapping(\"/students/{studentId}/courses\")\n    public List<Course> retrieveCoursesForStudent(@PathVariable String studentId) {\n        return studentService.retrieveCourses(studentId);\n    }\n\n\t@GetMapping(\"/students/{studentId}/courses/{courseId}\")\n\tpublic Course retrieveDetailsForCourse(@PathVariable String studentId, @PathVariable String courseId) {\n\t\treturn studentService.retrieveCourse(studentId, courseId);\n\t}\n\n    @PostMapping(\"/students/{studentId}/courses\")\n    public ResponseEntity<Void> registerStudentForCourse(@PathVariable String studentId, @RequestBody Course newCourse) {\n\n        Course course = studentService.addCourse(studentId, newCourse);\n\n        if (course == null)\n            return ResponseEntity.noContent().build();\n\n        URI location = ServletUriComponentsBuilder.fromCurrentRequest().path(\"/{id}\").buildAndExpand(course.getId()).toUri();\n\n        return ResponseEntity.created(location).build();\n    }\n\n}\n\n\n```\n\n## Executing the Http Get Operation Using Postman\nWe will fire a request to http://localhost:8080/students/Student1/courses/Course1 to test the service. Response is as shown below.\n\n```json\n{\n  \"id\": \"Course1\",\n  \"name\": \"Spring\",\n  \"description\": \"10Steps\",\n  \"steps\": [\n    \"Learn Maven\",\n    \"Import Project\",\n    \"First Example\",\n    \"Second Example\"\n  ]\n}\n```\n\nBelow picture shows how we can execute this Get Service from Postman - my favorite tool to run rest services.\n\n![Image](/images/ExecutingGetRestServiceUsingPostman.png \"Executing Rest Service From Postman\")   \n\n## Integration Testing with the Http Get Operation\n\n> When we are writing an integration test for a rest service, we would want to launch the entire spring context. \n\n- `@SpringBootTest(classes = StudentServicesApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)` : Launch the entire Spring Boot Application on a Random Port\n- `@LocalServerPort private int port;`: Autowire the random port into the variable so that we can use it create the url.\n- `createURLWithPort(String uri)` : Utility method to create the url given an uri. It appends the port.\n- `HttpEntity<String> entity = new HttpEntity<String>(null, headers);`: We use entity so that we have the flexibility of adding in request headers in future.\n- `restTemplate.exchange(createURLWithPort(\"/students/Student1/courses/Course1\"),HttpMethod.GET, entity, String.class)`: Fire a GET request to the specify uri and get the response as a String.\n- `JSONAssert.assertEquals(expected, response.getBody(), false)` : Assert that the response contains expected fields.\n            \n```java\npackage com.in28minutes.springboot.controller;\n\nimport org.json.JSONException;\nimport org.junit.jupiter.api.Test;\nimport org.junit.jupiter.api.extension.ExtendWith;\nimport org.skyscreamer.jsonassert.JSONAssert;\nimport org.springframework.boot.test.context.SpringBootTest;\nimport org.springframework.boot.test.web.client.TestRestTemplate;\nimport org.springframework.boot.test.web.server.LocalServerPort;\nimport org.springframework.http.HttpEntity;\nimport org.springframework.http.HttpHeaders;\nimport org.springframework.http.HttpMethod;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.test.context.junit.jupiter.SpringExtension;\n\nimport com.in28minutes.springboot.StudentServicesApplication;\n\n@ExtendWith(SpringExtension.class)\n@SpringBootTest(classes = StudentServicesApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)\npublic class StudentControllerIT {\n    @LocalServerPort\n    private int port;\n\n    TestRestTemplate restTemplate = new TestRestTemplate();\n\n    HttpHeaders headers = new HttpHeaders();\n\n    @Test\n    public void testRetrieveStudentCourse() throws JSONException {\n\n        HttpEntity<String> entity = new HttpEntity<>(null, headers);\n\n        ResponseEntity<String> response = restTemplate.exchange(\n                createURLWithPort(\"/students/Student1/courses/Course1\"),\n                HttpMethod.GET, entity, String.class);\n\n        String expected = \"{\\\"id\\\":\\\"Course1\\\",\\\"name\\\":\\\"Spring\\\",\\\"description\\\":\\\"10 Steps\\\"}\";\n\n        JSONAssert.assertEquals(expected, response.getBody(), false);\n    }\n\n    private String createURLWithPort(String uri) {\n        return \"http://localhost:\" + port + uri;\n    }\n}\n```\n\n## Adding Http POST Operation\n\n> A POST Service should return a status of created (201) when the resource creation is successful. \n\n`@PostMapping(\"/students/{studentId}/courses\")`: Mapping a url for the POST Request\n`@RequestBody Course newCourse`: Using Binding to bind the body of the request to Course object.\n`ResponseEntity.created(location).build()`: Return a status of created. Also return the location of created resource as a Response Header.\n\n```java\n\t@PostMapping(\"/students/{studentId}/courses\")\n\tpublic ResponseEntity<Void> registerStudentForCourse(@PathVariable String studentId, @RequestBody Course newCourse) {\n\n\t\tCourse course = studentService.addCourse(studentId, newCourse);\n\n\t\tif (course == null)\n\t\t\treturn ResponseEntity.noContent().build();\n\n\t\tURI location = ServletUriComponentsBuilder.fromCurrentRequest().path(\"/{id}\").buildAndExpand(course.getId()).toUri();\n\n\t\treturn ResponseEntity.created(location).build();\n\t}\n```\n\n## Executing Http POST Operation\n\nExample Request is shown below. It contains all the details to register a course to a student. \n```json\n{\n  \"name\": \"Microservices\",\n  \"description\": \"10Steps\",\n  \"steps\": [\n    \"Learn How to Break Things Up\",\n    \"Automate the hell out of everything\",\n    \"Have fun\"\n  ]\n}\n```\n\nBelow picture shows how we can execute this Http Post Operation from Postman - my favorite tool to run rest services. Make sure you go to the Body tab and select raw. Select JSON from the dropdown. Copy above request into body.\n\nThe URL we use is http://localhost:8080/students/Student1/courses.\n\n![Image](/images/ExecutingPostRestServiceUsingPostman.png \"Executing Post Rest Service From Postman\")   \n\n## Writing Integration Test for the Http POST Operation \n\n> When writing an integration test for a POST service we would want to check if the location header contains the uri of the created resource.\n\n- `String actual = response.getHeaders().get(HttpHeaders.LOCATION).get(0);` : Get the Location header from the response.\n- `assertTrue(actual.contains(\"/students/Student1/courses/\"))` : Assert that the header contains the uri of the newly created resource.\n\n```java\n\t@Test\n\tpublic void addCourse() {\n\n\t\tCourse course = new Course(\"Course1\", \"Spring\", \"10 Steps\",\n\t\t\t\tList.of(\"Learn Maven\", \"Import Project\", \"First Example\", \"Second Example\"));\n\n\t\tHttpEntity<Course> entity = new HttpEntity<Course>(course, headers);\n\n\t\tResponseEntity<String> response = restTemplate.exchange(\n\t\t\t\tcreateURLWithPort(\"/students/Student1/courses\"),\n\t\t\t\tHttpMethod.POST, entity, String.class);\n\n\t\tString actual = response.getHeaders()\n\t\t.get(HttpHeaders.LOCATION)\n\t\t.get(0);\n\n\t\tassertTrue(actual.contains(\"/students/Student1/courses/\"));\n\n\t}\n```\n\n\n## Complete Code Example\n\n\n### pom.xml\n\n```xml\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\n\t<groupId>com.in28minutes.springboot</groupId>\n\t<artifactId>student-services</artifactId>\n\t<version>0.0.1-SNAPSHOT</version>\n\t<packaging>jar</packaging>\n\n\t<name>student-services</name>\n\t<description>Demo project for Spring Boot</description>\n\n\t<parent>\n\t\t<groupId>org.springframework.boot</groupId>\n\t\t<artifactId>spring-boot-starter-parent</artifactId>\n\t\t<version>3.0.2</version>\n\t\t<relativePath /> <!-- lookup parent from repository -->\n\t</parent>\n\n\t<properties>\n\t\t<java.version>17</java.version>\n\t</properties>\n\n\t<dependencies>\n\t\t<dependency>\n\t\t\t<groupId>org.springframework.boot</groupId>\n\t\t\t<artifactId>spring-boot-starter-actuator</artifactId>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.springframework.boot</groupId>\n\t\t\t<artifactId>spring-boot-starter-web</artifactId>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>org.springframework.boot</groupId>\n\t\t\t<artifactId>spring-boot-devtools</artifactId>\n\t\t\t<scope>runtime</scope>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.springframework.boot</groupId>\n\t\t\t<artifactId>spring-boot-starter-test</artifactId>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t\t<dependency>\n\t\t    <groupId>org.springframework.security</groupId>\n\t\t    <artifactId>spring-security-test</artifactId>\n\t\t    <scope>test</scope>\n\t\t</dependency>\n\t</dependencies>\n\n\t<build>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.springframework.boot</groupId>\n\t\t\t\t<artifactId>spring-boot-maven-plugin</artifactId>\n\t\t\t</plugin>\n\t\t</plugins>\n\t</build>\n\n\t<repositories>\n\t\t<repository>\n\t\t\t<id>spring-milestones</id>\n\t\t\t<name>Spring Milestones</name>\n\t\t\t<url>https://repo.spring.io/milestone</url>\n\t\t\t<snapshots>\n\t\t\t\t<enabled>false</enabled>\n\t\t\t</snapshots>\n\t\t</repository>\n\t</repositories>\n\n\t<pluginRepositories>\n\t\t<pluginRepository>\n\t\t\t<id>spring-milestones</id>\n\t\t\t<name>Spring Milestones</name>\n\t\t\t<url>https://repo.spring.io/milestone</url>\n\t\t\t<snapshots>\n\t\t\t\t<enabled>false</enabled>\n\t\t\t</snapshots>\n\t\t</pluginRepository>\n\t</pluginRepositories>\n\n</project>\n```\n---\n\n### src/main/java/com/in28minutes/springboot/controller/StudentController.java\n\n```java\npackage com.in28minutes.springboot.controller;\n\nimport java.net.URI;\nimport java.util.List;\n\nimport com.in28minutes.springboot.model.Course;\nimport com.in28minutes.springboot.service.StudentService;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.PostMapping;\nimport org.springframework.web.bind.annotation.RequestBody;\nimport org.springframework.web.bind.annotation.RestController;\nimport org.springframework.web.servlet.support.ServletUriComponentsBuilder;\n\n@RestController\npublic class StudentController {\n\n    @Autowired\n    private StudentService studentService;\n\n    @GetMapping(\"/students/{studentId}/courses\")\n    public List<Course> retrieveCoursesForStudent(\n\t\t@PathVariable String studentId) {\n        return studentService.retrieveCourses(studentId);\n    }\n\n\t@GetMapping(\"/students/{studentId}/courses/{courseId}\")\n\tpublic Course retrieveDetailsForCourse(\n\t\t@PathVariable String studentId,\n\t    @PathVariable String courseId) {\n\t\treturn studentService.retrieveCourse(studentId, courseId);\n\t}\n\n    @PostMapping(\"/students/{studentId}/courses\")\n    public ResponseEntity<Void> registerStudentForCourse(\n\t\t@PathVariable String studentId,\n\t\t@RequestBody Course newCourse) {\n\n        Course course = studentService.addCourse(studentId, newCourse);\n\n        if (course == null)\n            return ResponseEntity.noContent().build();\n\n        URI location = ServletUriComponentsBuilder.fromCurrentRequest()\n                .path(\"/{id}\")\n                .buildAndExpand(course.getId())\n                .toUri();\n\n        return ResponseEntity.created(location).build();\n    }\n\n}\n```\n---\n\n### src/main/java/com/in28minutes/springboot/model/Course.java\n\n```java\npackage com.in28minutes.springboot.model;\n\nimport java.util.List;\n\npublic class Course {\n\tprivate String id;\n\tprivate String name;\n\tprivate String description;\n\tprivate List<String> steps;\n\n\t// Needed by Caused by: com.fasterxml.jackson.databind.JsonMappingException:\n\t// Can not construct instance of com.in28minutes.springboot.model.Course:\n\t// no suitable constructor found, can not deserialize from Object value\n\t// (missing default constructor or creator, or perhaps need to add/enable\n\t// type information?)\n\tpublic Course() {\n\n\t}\n\n\tpublic Course(String id, String name, String description, List<String> steps) {\n\t\tsuper();\n\t\tthis.id = id;\n\t\tthis.name = name;\n\t\tthis.description = description;\n\t\tthis.steps = steps;\n\t}\n\n\tpublic String getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(String id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getDescription() {\n\t\treturn description;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic List<String> getSteps() {\n\t\treturn steps;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn String.format(\n\t\t\t\t\"Course [id=%s, name=%s, description=%s, steps=%s]\", id, name,\n\t\t\t\tdescription, steps);\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + ((id == null) ? 0 : id.hashCode());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tCourse other = (Course) obj;\n\t\tif (id == null) {\n\t\t\tif (other.id != null)\n\t\t\t\treturn false;\n\t\t} else if (!id.equals(other.id))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n}\n```\n---\n\n### src/main/java/com/in28minutes/springboot/model/Student.java\n\n```java\npackage com.in28minutes.springboot.model;\n\nimport java.util.List;\n\npublic class Student {\n\tprivate String id;\n\tprivate String name;\n\tprivate String description;\n\tprivate List<Course> courses;\n\n\tpublic Student(String id, String name, String description,\n\t\t\tList<Course> courses) {\n\t\tsuper();\n\t\tthis.id = id;\n\t\tthis.name = name;\n\t\tthis.description = description;\n\t\tthis.courses = courses;\n\t}\n\n\tpublic String getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(String id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic String getDescription() {\n\t\treturn description;\n\t}\n\n\tpublic void setDescription(String description) {\n\t\tthis.description = description;\n\t}\n\n\tpublic List<Course> getCourses() {\n\t\treturn courses;\n\t}\n\n\tpublic void setCourses(List<Course> courses) {\n\t\tthis.courses = courses;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn String.format(\n\t\t\t\t\"Student [id=%s, name=%s, description=%s, courses=%s]\", id,\n\t\t\t\tname, description, courses);\n\t}\n}\n```\n---\n\n### src/main/java/com/in28minutes/springboot/service/StudentService.java\n\n```java\npackage com.in28minutes.springboot.service;\n\nimport java.math.BigInteger;\nimport java.security.SecureRandom;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport com.in28minutes.springboot.model.Course;\nimport com.in28minutes.springboot.model.Student;\nimport org.springframework.stereotype.Service;\n\n@Service\npublic class StudentService {\n\n\tprivate static final List<Student> students = new ArrayList<>();\n\n\tprivate final SecureRandom random = new SecureRandom();\n\n\tstatic {\n\t\t//Initialize Data\n\t\tCourse courseOne = new Course(\"Course1\", \"Spring\", \"10 Steps\",\n\t\t\t\tList.of(\"Learn Maven\", \"Import Project\", \"First Example\", \"Second Example\"));\n\n\t\tCourse courseTwo = new Course(\"Course2\", \"Spring MVC\", \"10 Examples\", \n\t\t        List.of(\"Learn Maven\", \"Import Project\", \"First Example\", \"Second Example\"));\n\n\t\tCourse courseThree = new Course(\"Course3\", \"Spring Boot\", \"6K Students\",\n\t\t\t\tList.of(\"Learn Maven\", \"Learn Spring\", \"Learn Spring MVC\", \"First Example\", \"Second Example\"));\n\n\t\tCourse courseFour = new Course(\"Course4\", \"Maven\", \"Most popular maven course on internet!\", List.of(\"Pom.xml\", \"Build Life Cycle\", \"Parent POM\", \"Importing into Eclipse\"));\n\n\t\tStudent ranga = new Student(\"Student1\", \"Ranga Karanam\", \"Hiker, Programmer and Architect\", new ArrayList<>(List.of(courseOne, courseTwo, courseThree, courseFour)));\n\n\t\tStudent satish = new Student(\"Student2\", \"Satish T\", \"Hiker, Programmer and Architect\", new ArrayList<>(List.of(courseOne, courseTwo, courseThree, courseFour)));\n\n\t\tstudents.add(ranga);\n\t\tstudents.add(satish);\n\t}\n\n\tpublic List<Student> retrieveAllStudents() {\n\t\treturn students;\n\t}\n\n\tpublic Student retrieveStudent(String studentId) {\n\t\tfor (Student student : students) {\n\t\t\tif (student.getId().equals(studentId)) {\n\t\t\t\treturn student;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic List<Course> retrieveCourses(String studentId) {\n\t\tStudent student = retrieveStudent(studentId);\n\n\t\treturn student == null ? null : student.getCourses();\n\t}\n\n\tpublic Course retrieveCourse(String studentId, String courseId) {\n\t\tStudent student = retrieveStudent(studentId);\n\n\t\tif (student == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\tfor (Course course : student.getCourses()) {\n\t\t\tif (course.getId().equals(courseId)) {\n\t\t\t\treturn course;\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}\n\n\tpublic Course addCourse(String studentId, Course course) {\n\t\tStudent student = retrieveStudent(studentId);\n\n\t\tif (student == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\tString randomId = new BigInteger(130, random).toString(32);\n\t\tcourse.setId(randomId);\n\n\t\tstudent.getCourses().add(course);\n\n\t\treturn course;\n\t}\n}\n```\n---\n\n### src/main/java/com/in28minutes/springboot/StudentServicesApplication.java\n\n```java\npackage com.in28minutes.springboot;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\n@SpringBootApplication\npublic class StudentServicesApplication {\n\n\tpublic static void main(String[] args) {\n\t\tSpringApplication.run(StudentServicesApplication.class, args);\n\t}\n}\n```\n---\n\n### src/main/resources/application.properties\n\n```\n```\n---\n\n### src/test/java/com/in28minutes/springboot/controller/StudentControllerIT.java\n\n```java\npackage com.in28minutes.springboot.controller;\n\nimport static org.junit.jupiter.api.Assertions.assertTrue;\n\nimport java.util.List;\n\nimport com.in28minutes.springboot.StudentServicesApplication;\nimport com.in28minutes.springboot.model.Course;\nimport org.json.JSONException;\nimport org.junit.jupiter.api.Test;\nimport org.junit.jupiter.api.extension.ExtendWith;\nimport org.skyscreamer.jsonassert.JSONAssert;\nimport org.springframework.boot.test.context.SpringBootTest;\nimport org.springframework.boot.test.web.client.TestRestTemplate;\nimport org.springframework.boot.test.web.server.LocalServerPort;\nimport org.springframework.http.HttpEntity;\nimport org.springframework.http.HttpHeaders;\nimport org.springframework.http.HttpMethod;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.test.context.junit.jupiter.SpringExtension;\n\n@ExtendWith(SpringExtension.class)\n@SpringBootTest(classes = StudentServicesApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)\npublic class StudentControllerIT {\n    @LocalServerPort\n    private int port;\n\n    TestRestTemplate restTemplate = new TestRestTemplate();\n\n    HttpHeaders headers = new HttpHeaders();\n\n    @Test\n    public void testRetrieveStudentCourse() throws JSONException {\n\n        HttpEntity<String> entity = new HttpEntity<>(null, headers);\n\n        ResponseEntity<String> response = restTemplate.exchange(\n                createURLWithPort(\"/students/Student1/courses/Course1\"),\n                HttpMethod.GET, entity, String.class);\n\n        String expected = \"{\\\"id\\\":\\\"Course1\\\",\\\"name\\\":\\\"Spring\\\",\\\"description\\\":\\\"10 Steps\\\"}\";\n\n        JSONAssert.assertEquals(expected, response.getBody(), false);\n    }\n\n    @Test\n    public void addCourse() {\n\n        Course course = new Course(\"Course1\", \"Spring\", \"10Steps\",\n                List.of(\"Learn Maven\", \"Import Project\", \"First Example\",\n                        \"Second Example\"));\n\n        HttpEntity<Course> entity = new HttpEntity<>(course, headers);\n\n        ResponseEntity<String> response = restTemplate.exchange(\n                createURLWithPort(\"/students/Student1/courses\"),\n                HttpMethod.POST, entity, String.class);\n\n        String actual = response.getHeaders().get(HttpHeaders.LOCATION).get(0);\n\n        assertTrue(actual.contains(\"/students/Student1/courses/\"));\n\n    }\n\n    private String createURLWithPort(String uri) {\n        return \"http://localhost:\" + port + uri;\n    }\n}\n```\n---\n"
  },
  {
    "path": "_blog/articles/2017-01-30-spring-boot-starter-parent.md",
    "content": "---\nlayout: post\ntitle: Introduction to Spring Boot Starter Parent\ndate: 2025-09-07 02:31:19\nsummary: Key goal of Spring Boot is to enable a quick start to developing production ready applications. Spring Boot Starter Parent plays a key role in managing dependency versions and having the right plug-ins configured.\ncategories: SpringBoot\npermalink: /spring-boot-starter-parent\nimage: /images/spring-boot-feature.png\n---\n\n![Image](/images/Spring-Initializr-Web.png \"Web, Actuator and Developer Tools\")\n\nThis guide will help you understand how the Spring Boot Starter Parent simplifies project setup by managing dependency\nversions, defining the Java version, and providing default configurations for commonly used plugins.\n\n![Image](/images/SpringBootStarterWeb-Dependencies.png \"Spring Boot Starter Web - Dependencies\")\n\n## You will learn\n\n- What is the Spring Boot Starter Parent?\n- What are its key features?\n- When should you use it?\n\n## Tools you will need\n\n- Maven 3.1+ as your build tool\n- Your favorite IDE (Eclipse or IntelliJ IDEA)\n- JDK 17+\n\n## What is Spring Boot Starter Parent?\n\nIn a typical **pom.xml**, most Spring Boot projects use **spring-boot-starter-parent** as the parent POM.  \nIt provides sensible defaults for dependency versions, plugin management, and build configuration,  \nso you don’t have to configure them manually.\n\n```xml\n\n<parent>\n    <groupId>org.springframework.boot</groupId>\n    <artifactId>spring-boot-starter-parent</artifactId>\n    <version>4.0.0-M2</version>\n</parent>\n```\n\nParent POMs let you handle the following for several child projects and modules:\n\n- **Configuration** – Java version and other project-wide properties\n- **Dependency Management** – Centralized version management for dependencies\n- **Default Plugin Configuration** – Predefined settings for common Maven plugins\n\n## What is inside Spring Boot Starter Parent?\n\n- The **Spring Boot Starter Parent POM** defines `spring-boot-dependencies`.\n- It inherits the dependency management from `spring-boot-dependencies`.\n- This ensures consistent and compatible versions for all Spring Boot modules and third-party libraries.\n- More details are covered in the next section.\n\n```xml\n\n<parent>\n    <groupId>org.springframework.boot</groupId>\n    <artifactId>spring-boot-dependencies</artifactId>\n    <version>4.0.0-M2</version>\n    <relativePath>../../spring-boot-dependencies</relativePath>\n</parent>\n\n```\n\nDefault java version is 1.6. A project can override this by specifying a property `<java.version>17</java.version>\n<maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>` in the project pom. A few other settings related to encoding\nand source, target version are also set in the parent pom.\n\n```xml\n\n<properties>\n    <java.version>17</java.version>\n    <resource.delimiter>@</resource.delimiter>\n    <maven.compiler.release>${java.version}</maven.compiler.release>\n    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>\n    <spring-boot.run.main-class>${start-class}</spring-boot.run.main-class>\n</properties>\n\n```\n\nSpring Boot Starter Parent specifies the default configuration for a host of plugins, including:\n\n- `maven-compiler-plugin`\n- `maven-failsafe-plugin`\n- `maven-jar-plugin`\n- `maven-war-plugin`\n- and many more...\n\n```xml\n\n<plugin>\n    <groupId>org.apache.maven.plugins</groupId>\n    <artifactId>maven-compiler-plugin</artifactId>\n    <configuration>\n        <parameters>true</parameters>\n    </configuration>\n</plugin>\n<plugin>\n<groupId>org.apache.maven.plugins</groupId>\n<artifactId>maven-failsafe-plugin</artifactId>\n<executions>\n    <execution>\n        <goals>\n            <goal>integration-test</goal>\n            <goal>verify</goal>\n        </goals>\n    </execution>\n</executions>\n<configuration>\n    <classesDirectory>${project.build.outputDirectory}</classesDirectory>\n</configuration>\n</plugin>\n<plugin>\n<groupId>org.apache.maven.plugins</groupId>\n<artifactId>maven-jar-plugin</artifactId>\n<configuration>\n    <archive>\n        <manifest>\n            <mainClass>${start-class}</mainClass>\n            <addDefaultImplementationEntries>true</addDefaultImplementationEntries>\n        </manifest>\n    </archive>\n</configuration>\n</plugin>\n<plugin>\n<groupId>org.apache.maven.plugins</groupId>\n<artifactId>maven-war-plugin</artifactId>\n<configuration>\n    <archive>\n        <manifest>\n            <mainClass>${start-class}</mainClass>\n            <addDefaultImplementationEntries>true</addDefaultImplementationEntries>\n        </manifest>\n    </archive>\n</configuration>\n</plugin>\n```\n\n## What does Spring Boot Starter Parent inherit from spring-boot-dependencies?\n\nSpring Boot Dependencies defines the Spring Boot project's default **dependency management**.\n\nIf we want to use a different version of a specific dependency, we can override it by adding a new property in the\nproject `pom.xml`.\n\nThe following extract demonstrates some of the key dependencies managed by the Spring Boot Dependencies parent POM.  \nSpring Boot Starter Parent inherits all of these properties from `spring-boot-dependencies`.\n\n```xml\n\n<properties>\n    <activemq.version>6.1.7</activemq.version>\n    <angus-mail.version>2.0.3</angus-mail.version>\n    <artemis.version>2.42.0</artemis.version>\n    <aspectj.version>1.9.24</aspectj.version>\n    <assertj.version>3.27.3</assertj.version>\n    <awaitility.version>4.3.0</awaitility.version>\n    <zipkin-reporter.version>3.5.1</zipkin-reporter.version>\n    <brave.version>6.3.0</brave.version>\n    <build-helper-maven-plugin.version>3.6.1</build-helper-maven-plugin.version>\n    <byte-buddy.version>1.17.6</byte-buddy.version>\n    <cache2k.version>2.6.1.Final</cache2k.version>\n    <caffeine.version>3.2.2</caffeine.version>\n    <cassandra-driver.version>4.19.0</cassandra-driver.version>\n    <classmate.version>1.7.0</classmate.version>\n    <commons-codec.version>1.19.0</commons-codec.version>\n    <commons-dbcp2.version>2.13.0</commons-dbcp2.version>\n    <commons-lang3.version>3.18.0</commons-lang3.version>\n    <commons-logging.version>1.3.5</commons-logging.version>\n    <commons-pool.version>1.6</commons-pool.version>\n    <commons-pool2.version>2.12.1</commons-pool2.version>\n    <couchbase-client.version>3.8.2</couchbase-client.version>\n    <crac.version>1.5.0</crac.version>\n    <cyclonedx-maven-plugin.version>2.9.1</cyclonedx-maven-plugin.version>\n    <db2-jdbc.version>12.1.2.0</db2-jdbc.version>\n    <dependency-management-plugin.version>1.1.7</dependency-management-plugin.version>\n    <derby.version>10.16.1.1</derby.version>\n    <ehcache3.version>3.10.8</ehcache3.version>\n    <elasticsearch-client.version>9.0.3</elasticsearch-client.version>\n    <flyway.version>11.10.3</flyway.version>\n    <freemarker.version>2.3.34</freemarker.version>\n    <git-commit-id-maven-plugin.version>9.0.2</git-commit-id-maven-plugin.version>\n    <glassfish-jaxb.version>4.0.5</glassfish-jaxb.version>\n    <glassfish-jstl.version>3.0.1</glassfish-jstl.version>\n    <graphql-java.version>24.1</graphql-java.version>\n    <groovy.version>4.0.28</groovy.version>\n    <gson.version>2.13.1</gson.version>\n    <h2.version>2.3.232</h2.version>\n    <hamcrest.version>3.0</hamcrest.version>\n    <hazelcast.version>5.5.0</hazelcast.version>\n    <hibernate.version>7.0.7.Final</hibernate.version>\n    <hibernate-validator.version>9.0.1.Final</hibernate-validator.version>\n    <hikaricp.version>6.3.1</hikaricp.version>\n    <hsqldb.version>2.7.3</hsqldb.version>\n    <htmlunit.version>4.13.0</htmlunit.version>\n    <httpasyncclient.version>4.1.5</httpasyncclient.version>\n    <httpclient5.version>5.5</httpclient5.version>\n    <httpcore.version>4.4.16</httpcore.version>\n    <httpcore5.version>5.3.4</httpcore5.version>\n    <infinispan.version>15.2.5.Final</infinispan.version>\n    <influxdb-java.version>2.25</influxdb-java.version>\n    <jackson-bom.version>2.19.2</jackson-bom.version>\n    <jakarta-activation.version>2.1.3</jakarta-activation.version>\n    <jakarta-annotation.version>3.0.0</jakarta-annotation.version>\n    <jakarta-inject.version>2.0.1</jakarta-inject.version>\n    <jakarta-jms.version>3.1.0</jakarta-jms.version>\n    <jakarta-json.version>2.1.3</jakarta-json.version>\n    <jakarta-json-bind.version>3.0.1</jakarta-json-bind.version>\n    <jakarta-mail.version>2.1.3</jakarta-mail.version>\n    <jakarta-management.version>1.1.4</jakarta-management.version>\n    <jakarta-persistence.version>3.2.0</jakarta-persistence.version>\n    <jakarta-servlet.version>6.1.0</jakarta-servlet.version>\n    <jakarta-servlet-jsp-jstl.version>3.0.2</jakarta-servlet-jsp-jstl.version>\n    <jakarta-transaction.version>2.0.1</jakarta-transaction.version>\n    <jakarta-validation.version>3.1.1</jakarta-validation.version>\n    <jakarta-websocket.version>2.2.0</jakarta-websocket.version>\n    <jakarta-ws-rs.version>4.0.0</jakarta-ws-rs.version>\n    <jakarta-xml-bind.version>4.0.2</jakarta-xml-bind.version>\n    <jakarta-xml-soap.version>3.0.2</jakarta-xml-soap.version>\n    <jakarta-xml-ws.version>4.0.2</jakarta-xml-ws.version>\n    <janino.version>3.1.12</janino.version>\n    <javax-cache.version>1.1.1</javax-cache.version>\n    <javax-money.version>1.1</javax-money.version>\n    <jaxen.version>2.0.0</jaxen.version>\n    <jaybird.version>6.0.2</jaybird.version>\n    <jboss-logging.version>3.6.1.Final</jboss-logging.version>\n    <jdom2.version>2.0.6.1</jdom2.version>\n    <jedis.version>6.0.0</jedis.version>\n    <jersey.version>4.0.0-M2</jersey.version>\n    <jetty-reactive-httpclient.version>4.0.10</jetty-reactive-httpclient.version>\n    <jetty.version>12.0.23</jetty.version>\n    <jmustache.version>1.16</jmustache.version>\n    <jooq.version>3.19.24</jooq.version>\n    <json-path.version>2.9.0</json-path.version>\n    <json-smart.version>2.5.2</json-smart.version>\n    <jsonassert.version>1.5.3</jsonassert.version>\n    <jtds.version>1.3.1</jtds.version>\n    <junit.version>4.13.2</junit.version>\n    <junit-jupiter.version>5.13.4</junit-jupiter.version>\n    <kafka.version>4.0.0</kafka.version>\n    <kotlin.version>2.2.0</kotlin.version>\n    <kotlin-coroutines.version>1.10.2</kotlin-coroutines.version>\n    <kotlin-serialization.version>1.9.0</kotlin-serialization.version>\n    <lettuce.version>6.7.1.RELEASE</lettuce.version>\n    <liquibase.version>4.33.0</liquibase.version>\n    <log4j2.version>2.24.3</log4j2.version>\n    <logback.version>1.5.18</logback.version>\n    <lombok.version>1.18.38</lombok.version>\n    <mariadb.version>3.5.4</mariadb.version>\n    <maven-antrun-plugin.version>3.1.0</maven-antrun-plugin.version>\n    <maven-assembly-plugin.version>3.7.1</maven-assembly-plugin.version>\n    <maven-clean-plugin.version>3.5.0</maven-clean-plugin.version>\n    <maven-compiler-plugin.version>3.14.0</maven-compiler-plugin.version>\n    <maven-dependency-plugin.version>3.8.1</maven-dependency-plugin.version>\n    <maven-deploy-plugin.version>3.1.4</maven-deploy-plugin.version>\n    <maven-enforcer-plugin.version>3.6.1</maven-enforcer-plugin.version>\n    <maven-failsafe-plugin.version>3.5.3</maven-failsafe-plugin.version>\n    <maven-help-plugin.version>3.5.1</maven-help-plugin.version>\n    <maven-install-plugin.version>3.1.4</maven-install-plugin.version>\n    <maven-invoker-plugin.version>3.9.1</maven-invoker-plugin.version>\n    <maven-jar-plugin.version>3.4.2</maven-jar-plugin.version>\n    <maven-javadoc-plugin.version>3.11.2</maven-javadoc-plugin.version>\n    <maven-resources-plugin.version>3.3.1</maven-resources-plugin.version>\n    <maven-shade-plugin.version>3.6.0</maven-shade-plugin.version>\n    <maven-source-plugin.version>3.3.1</maven-source-plugin.version>\n    <maven-surefire-plugin.version>3.5.3</maven-surefire-plugin.version>\n    <maven-war-plugin.version>3.4.0</maven-war-plugin.version>\n    <micrometer.version>1.16.0-M1</micrometer.version>\n    <micrometer-tracing.version>1.6.0-M1</micrometer-tracing.version>\n    <mockito.version>5.18.0</mockito.version>\n    <mongodb.version>5.5.1</mongodb.version>\n    <mssql-jdbc.version>12.10.1.jre11</mssql-jdbc.version>\n    <mysql.version>9.3.0</mysql.version>\n    <native-build-tools-plugin.version>0.10.6</native-build-tools-plugin.version>\n    <nekohtml.version>1.9.22</nekohtml.version>\n    <neo4j-java-driver.version>5.28.9</neo4j-java-driver.version>\n    <netty.version>4.2.3.Final</netty.version>\n    <opentelemetry.version>1.52.0</opentelemetry.version>\n    <oracle-database.version>23.8.0.25.04</oracle-database.version>\n    <oracle-r2dbc.version>1.3.0</oracle-r2dbc.version>\n    <pooled-jms.version>3.1.7</pooled-jms.version>\n    <postgresql.version>42.7.7</postgresql.version>\n    <prometheus-client.version>1.3.10</prometheus-client.version>\n    <prometheus-simpleclient.version>0.16.0</prometheus-simpleclient.version>\n    <pulsar.version>4.0.5</pulsar.version>\n    <pulsar-reactive.version>0.7.0</pulsar-reactive.version>\n    <quartz.version>2.5.0</quartz.version>\n    <querydsl.version>5.1.0</querydsl.version>\n    <r2dbc-h2.version>1.0.0.RELEASE</r2dbc-h2.version>\n    <r2dbc-mariadb.version>1.3.0</r2dbc-mariadb.version>\n    <r2dbc-mssql.version>1.0.2.RELEASE</r2dbc-mssql.version>\n    <r2dbc-mysql.version>1.4.1</r2dbc-mysql.version>\n    <r2dbc-pool.version>1.0.2.RELEASE</r2dbc-pool.version>\n    <r2dbc-postgresql.version>1.0.7.RELEASE</r2dbc-postgresql.version>\n    <r2dbc-proxy.version>1.1.6.RELEASE</r2dbc-proxy.version>\n    <r2dbc-spi.version>1.0.0.RELEASE</r2dbc-spi.version>\n    <rabbit-amqp-client.version>5.26.0</rabbit-amqp-client.version>\n    <rabbit-stream-client.version>0.23.0</rabbit-stream-client.version>\n    <reactive-streams.version>1.0.4</reactive-streams.version>\n    <reactor-bom.version>2025.0.0-M5</reactor-bom.version>\n    <rest-assured.version>5.5.5</rest-assured.version>\n    <rsocket.version>1.1.5</rsocket.version>\n    <rxjava3.version>3.1.11</rxjava3.version>\n    <saaj-impl.version>3.0.4</saaj-impl.version>\n    <selenium.version>4.34.0</selenium.version>\n    <selenium-htmlunit.version>4.33.0</selenium-htmlunit.version>\n    <sendgrid.version>4.10.3</sendgrid.version>\n    <slf4j.version>2.0.17</slf4j.version>\n    <snakeyaml.version>2.4</snakeyaml.version>\n    <spring-amqp.version>4.0.0-M3</spring-amqp.version>\n    <spring-authorization-server.version>2.0.0-M1</spring-authorization-server.version>\n    <spring-batch.version>6.0.0-M1</spring-batch.version>\n    <spring-data-bom.version>2025.1.0-M4</spring-data-bom.version>\n    <spring-framework.version>7.0.0-M7</spring-framework.version>\n    <spring-graphql.version>2.0.0-M1</spring-graphql.version>\n    <spring-hateoas.version>3.0.0-M3</spring-hateoas.version>\n    <spring-integration.version>7.0.0-M1</spring-integration.version>\n    <spring-kafka.version>4.0.0-M3</spring-kafka.version>\n    <spring-ldap.version>4.0.0-M1</spring-ldap.version>\n    <spring-pulsar.version>2.0.0-M1</spring-pulsar.version>\n    <spring-restdocs.version>4.0.0-M1</spring-restdocs.version>\n    <spring-retry.version>2.0.12</spring-retry.version>\n    <spring-security.version>7.0.0-M1</spring-security.version>\n    <spring-session.version>4.0.0-M1</spring-session.version>\n    <spring-ws.version>5.0.0-M1</spring-ws.version>\n    <sqlite-jdbc.version>3.50.3.0</sqlite-jdbc.version>\n    <testcontainers.version>1.21.3</testcontainers.version>\n    <testcontainers-redis-module.version>2.2.4</testcontainers-redis-module.version>\n    <thymeleaf.version>3.1.3.RELEASE</thymeleaf.version>\n    <thymeleaf-extras-data-attribute.version>2.0.1</thymeleaf-extras-data-attribute.version>\n    <thymeleaf-extras-springsecurity.version>3.1.3.RELEASE</thymeleaf-extras-springsecurity.version>\n    <thymeleaf-layout-dialect.version>3.4.0</thymeleaf-layout-dialect.version>\n    <tomcat.version>11.0.9</tomcat.version>\n    <unboundid-ldapsdk.version>7.0.3</unboundid-ldapsdk.version>\n    <undertow.version>2.3.18.Final</undertow.version>\n    <versions-maven-plugin.version>2.18.0</versions-maven-plugin.version>\n    <vibur.version>26.0</vibur.version>\n    <webjars-locator-core.version>0.59</webjars-locator-core.version>\n    <webjars-locator-lite.version>1.1.0</webjars-locator-lite.version>\n    <wsdl4j.version>1.6.3</wsdl4j.version>\n    <xml-maven-plugin.version>1.1.0</xml-maven-plugin.version>\n    <xmlunit2.version>2.10.3</xmlunit2.version>\n    <yasson.version>3.0.4</yasson.version>\n</properties>\n```\n\nDefines Maven 3.14.0 as the minimum version needed.\n\n```xml\n\n<prerequisites>\n    <maven>3.14.0</maven>\n</prerequisites>\n```\n"
  },
  {
    "path": "_blog/articles/2017-01-30-spring-boot-starter-projects.md",
    "content": "---\nlayout:     post\ntitle:      Initializing Projects with Spring Boot Starters - Web and JPA\ndate:       2025-09-07 12:31:19\nsummary:    Key goal of Spring Boot is to enable a quick start to developing production ready applications. Most important components behind the features of Spring Boot are the Spring Boot Starter Projects. \ncategories:  SpringBoot\npermalink:  /spring-boot-starter-projects\nimage: /images/spring-boot-feature.png\n---\n\n![Image](/images/Spring-Initializr-Web.png \"Web, Actuator and Developer Tools\")   \n\n# Spring Boot Starter Projects\n\nThis guide will help you understand how **Spring Boot Starter Projects** enable the key goal of Spring Boot — *a quick start to developing production-ready applications*.\n\n![Image](/images/SpringBootStarterWeb-Dependencies.png \"Spring Boot Starter Web - Dependencies\")\n\n## You will learn\n- What features are provided by Spring Boot Starter Projects?\n- Example of a Starter Project\n- Introduction to Spring Boot Starter Web\n- Overview of different Starter Projects provided by Spring Boot\n\n## Tools you will need\n- Maven 3.0+ as your build tool\n- Your favorite IDE (Eclipse or IntelliJ IDEA recommended)\n- JDK 17+\n\n## Why do we need Spring Boot Starter Projects?\n\nTo understand the value of starter projects, let’s first imagine a project **without them**.\n\n### What if we do not have starter projects?\n\nSuppose we want to build a **Spring MVC web application**.\n\n- First, we need to decide **which frameworks** to use.\n- Then, we need to figure out **compatible versions** of those frameworks.\n- Finally, we have to manage linking and configuration manually.\n\nSome of the dependencies we typically use in a Spring MVC project are:\n\n- **Spring MVC** – Core web framework\n- **Jackson Databind** – For JSON data binding\n- **Hibernate Validator** – For server-side validation using Java Validation API\n- **Log4j** – For logging\n\n👉 The challenge: We must carefully select versions that are compatible with each other, which adds complexity and slows down development.\n\n\n```xml\n<dependency>\n   <groupId>org.springframework</groupId>\n   <artifactId>spring-webmvc</artifactId>\n   <version>7.0.0-M7</version>\n</dependency>\n\n<dependency>\n    <groupId>com.fasterxml.jackson.core</groupId>\n    <artifactId>jackson-databind</artifactId>\n    <version>2.19.2</version>\n    <scope>compile</scope>\n</dependency>\n\n<dependency>\n    <groupId>org.hibernate.validator</groupId>\n    <artifactId>hibernate-validator</artifactId>\n    <version>9.0.1.Final</version>\n</dependency>\n\n<dependency>\n    <groupId>org.apache.logging.log4j</groupId>\n    <artifactId>log4j-bom</artifactId>\n    <version>2.25.1</version>\n    <type>pom</type>\n    <scope>import</scope>\n</dependency>\n    \n```\n\nTo get everything working together, we also had to add **manual configurations**, such as:\n\n- Dispatcher Servlet\n- View Resolver\n- Error Page\n- Web Jars (for serving static content)\n- And other supporting settings\n\n👉 As you can see, without starter projects, setting up even a simple Spring MVC application involves a lot of **boilerplate configuration**.\n\n```xml\n<bean\n    class=\"org.springframework.web.servlet.view.InternalResourceViewResolver\">\n    <property name=\"prefix\">\n        <value>/WEB-INF/views/</value>\n    </property>\n    <property name=\"suffix\">\n        <value>.jsp</value>\n    </property>\n</bean>\n\n<bean id=\"messageSource\"\n    class=\"org.springframework.context.support.ReloadableResourceBundleMessageSource\">\n    <property name=\"basename\" value=\"classpath:messages\" />\n    <property name=\"defaultEncoding\" value=\"UTF-8\" />\n</bean>\n\n<mvc:resources mapping=\"/webjars/**\" location=\"/webjars/\" />\n\n<servlet>\n    <servlet-name>dispatcher</servlet-name>\n    <servlet-class>\n        org.springframework.web.servlet.DispatcherServlet\n    </servlet-class>\n    <init-param>\n        <param-name>contextConfigLocation</param-name>\n        <param-value>/WEB-INF/todo-servlet.xml</param-value>\n    </init-param>\n    <load-on-startup>1</load-on-startup>\n</servlet>\n\n<servlet-mapping>\n    <servlet-name>dispatcher</servlet-name>\n    <url-pattern>/</url-pattern>\n</servlet-mapping>\n```\n\nWe would need to do **similar setup tasks when using JPA**.\n\n- Provide the required JPA and Hibernate jars\n- Configure the **DataSource**\n- Configure the **EntityManagerFactory**\n- Configure the **TransactionManager**\n- Add other related settings manually\n\n👉 As with Spring MVC, this becomes **time-consuming and error-prone**.\n\n```xml\n<bean id=\"dataSource\" class=\"com.mchange.v2.c3p0.ComboPooledDataSource\"\n    destroy-method=\"close\">\n    <property name=\"driverClass\" value=\"${db.driver}\" />\n    <property name=\"jdbcUrl\" value=\"${db.url}\" />\n    <property name=\"user\" value=\"${db.username}\" />\n    <property name=\"password\" value=\"${db.password}\" />\n</bean>\n\n<jdbc:initialize-database data-source=\"dataSource\">\n    <jdbc:script location=\"classpath:config/schema.sql\" />\n    <jdbc:script location=\"classpath:config/data.sql\" />\n</jdbc:initialize-database>\n\n<bean\n    class=\"org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean\"\n    id=\"entityManagerFactory\">\n    <property name=\"persistenceUnitName\" value=\"hsql_pu\" />\n    <property name=\"dataSource\" ref=\"dataSource\" />\n</bean>\n\n<bean id=\"transactionManager\" class=\"org.springframework.orm.jpa.JpaTransactionManager\">\n    <property name=\"entityManagerFactory\" ref=\"entityManagerFactory\" />\n    <property name=\"dataSource\" ref=\"dataSource\" />\n</bean>\n\n<tx:annotation-driven transaction-manager=\"transactionManager\"/>\n\n``` \n\n## Spring Boot Starter Projects\n\nHere’s how the official Spring Boot documentation defines starters:\n\n> **Starters are a set of convenient dependency descriptors that you can include in your application.**  \n> You get a one-stop shop for all the Spring and related technologies you need, without having to hunt through sample code or copy-paste loads of dependency descriptors.  \n> For example, if you want to get started using Spring and JPA for database access, just include the `spring-boot-starter-data-jpa` dependency in your project, and you are good to go.\n\n### Example: Spring Boot Starter Web\n\nIf you want to:\n- Build a **web application**\n- Or expose **RESTful services**\n\n👉 `spring-boot-starter-web` is the starter you should pick.\n\nLet’s create a simple project with **Spring Boot Starter Web** using **Spring Initializr**.\n\n---\n\n# Creating REST Services Applications with Spring Initializr\n\n## What is Spring Initializr?\n\n[Spring Initializr](https://start.spring.io/) is an invaluable web-based tool designed to **bootstrap your Spring Boot projects quickly and efficiently**. It eliminates the complexity of manual project setup by providing an intuitive interface for generating production-ready Spring Boot applications.\n\n## Key Configuration Options\n\nWhen creating your REST services project, you can customize several essential parameters:\n\n### Project Configuration\n- **Project Type**: Choose your preferred build automation tool\n    - **Maven** - XML-based configuration, widely adopted\n    - **Gradle** - Groovy/Kotlin DSL, modern build system\n\n- **Programming Language**: Select the language that fits your team's expertise\n    - **Java** - Industry standard, extensive ecosystem\n    - **Kotlin** - Concise syntax, 100% Java interoperability\n    - **Groovy** - Dynamic language with Java compatibility\n\n- **Spring Boot Version**: Pick the appropriate framework version\n    - Latest stable release (recommended for new projects)\n    - LTS versions for enterprise applications\n    - Snapshot versions for bleeding-edge features\n\nThis saves a lot of time by generating a ready-to-use project structure.\n\n\n![Image](/images/Spring-Initializr-Web.png \"Web, Actuator and Developer Tools\")   \n\n### Steps to Create a Spring Boot Starter Web Project\n\nAs shown in the image above, follow these steps:\n\n1. **Launch Spring Initializr** and choose the following options:\n    - **Group:** `com.in28minutes.springboot`\n    - **Artifact:** `student-services`\n    - **Dependencies:**\n        - Web\n        - Actuator\n        - DevTools\n\n2. **Click \"Generate Project\"** to download the project as a `.zip` file.\n\n3. **Import the project into Eclipse** (or your preferred IDE).\n    - In Eclipse, use:  \n      `File > Import > Existing Maven Projects`\n\n4. If you want to **understand all the files** that are part of this generated project, you can check the detailed explanation [here](#) _(link to explanation or documentation)_.\n\n\n## Spring Boot Starter Web\n\nSpring Boot Starter Web has two crucial features:\n\n- **Compatible Dependencies** that are needed to develop web applications\n- **Auto Configuration** to automatically set up common configurations (DispatcherServlet, Jackson, Validation, Embedded Tomcat, etc.)\n\n### Dependency for Spring Boot Starter Web\n\nIf you are using **Maven**, add this to your `pom.xml`:\n\n```xml\n<dependency>\n    <groupId>org.springframework.boot</groupId>\n    <artifactId>spring-boot-starter-web</artifactId>\n</dependency>\n```\nIf you are using Gradle, add this to your `build.gradle`:\n```gradle\nimplementation 'org.springframework.boot:spring-boot-starter-web'\n```\n\n### Dependencies\nFollowing screenshot shows the different dependencies that are added in to our application \n\n![Image](/images/SpringBootStarterWeb-Dependencies.png \"Spring Boot Starter Web - Dependencies\")\n\nDependencies can be classified into:\n\n- Spring - core, beans, context, aop\n- Web MVC - (Spring MVC)\n- Jackson - for JSON Binding \n- Validation - Hibernate Validator, Validation API\n- Embedded Servlet Container - Tomcat\n- Logging - logback, slf4j\n\nAll of these requirements would be used by any regular web application. Spring Boot Starter Site already has them. As a developer, I would not have to be concerned about their dependencies or their compatible version \n\n### Auto Configuration\nSpring Boot Starter Web automatically configures the essentials. To explore the functionality added by Spring Boot Starter Web, run StudentServicesApplication.java as a Java Application and examine the log.\n\n```\nMapping servlet: 'dispatcherServlet' to [/]\n\nMapped \"{[/error]}\" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)\n\nMapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]\n\n```\nSpring Boot Starter Web auto-configures \n\n- Dispatcher Servlet\n- Error Page\n- Web Jars to manage your static dependencies\n- Embedded Servlet Container - Tomcat is the default\n\nThe image below shows the different things that might be auto configured by Spring Boot Starter Web\n\n![Image](/images/SpringBootStarterWeb-AutoConfiguration.png \"Spring Boot Starter Web - Auto Configuration\")\n\n## Spring Boot Starter Project Options\n\nAs we can see from **Spring Boot Starter Web**, starter projects allow us to get started quickly with designing various types of applications.\n\n### Application Starters\n- `spring-boot-starter-web-services` - SOAP Web Services\n- `spring-boot-starter-web` - Web & RESTful applications\n- `spring-boot-starter-test` - Unit testing and Integration Testing\n- `spring-boot-starter-jdbc` - Traditional JDBC\n- `spring-boot-starter-hateoas` - Add HATEOAS features to your services\n- `spring-boot-starter-security` - Authentication and Authorization using Spring Security\n- `spring-boot-starter-data-jpa` - Spring Data JPA with Hibernate\n- `spring-boot-starter-cache` - Enabling Spring Framework’s caching support\n- `spring-boot-starter-data-rest` - Expose Simple REST Services using Spring Data REST\n\n### Technical Starters\n- `spring-boot-starter-actuator` - Advanced features like monitoring & tracing out of the box\n- `spring-boot-starter-undertow`, `spring-boot-starter-jetty`, `spring-boot-starter-tomcat` - Choose your specific Embedded Servlet Container\n- `spring-boot-starter-logging` - Logging using Logback\n- `spring-boot-starter-log4j2` - Logging using Log4j2  \n\n"
  },
  {
    "path": "_blog/articles/2017-01-30-spring-boot-starter-security.md",
    "content": "---\nlayout: post\ntitle: Secure Rest Services and Web Applications with Spring Boot Security Starter\ndate: 2025-09-13 12:31:19\nsummary: Spring Boot Starter Security is the recommended starter for enabling security on web application - including REST services.\ncategories: SpringBoot\npermalink: /securing-rest-services-with-spring-boot-starter-security\nimage: /images/spring-boot-feature.png\n---\n\n![Image](/images/Spring-Initializr-Web.png \"Web, Actuator and Developer Tools\")\n\n# Spring Boot Starter Security\n\nThis guide will help you understand the different features that **Spring Boot Starter Security** brings in, using two\nexamples:\n\n- **A REST Service**\n- **A Simple Web Application Page**\n\nSpring Boot Starter Security makes it very easy to secure your applications by providing:\n\n- Default authentication and authorization\n- Integration with common security standards (basic auth, form login, OAuth2, JWT, etc.)\n- Auto-configuration that works out-of-the-box, but can be customized as needed.\n\n![Image](/images/SpringBootSecuritySecurity-WebApplication.png \"Spring Security - Web Application\")\n\n## You will learn\n\n- What is **Spring Boot Starter Security**?\n- What features are provided by **Spring Boot Starter Security**?\n- How do you enable Spring Security on a **web application**?\n- How do you enable Spring Security on a **REST Web Service**?\n- How do you invoke a REST Service using **Basic Authentication**?\n- Example: securing a simple **Web Application**\n- Example: securing a **REST Service** with Basic Authentication\n\n## Tools you will need\n\n- **Maven 3.0+** as your build tool\n- Your favorite **IDE** (Eclipse or IntelliJ IDEA recommended)\n- **JDK 17+**\n\n## Complete Maven Project With Code Examples\n\n> Our GitHub repository has all the code\n> examples - [https://github.com/in28minutes/in28minutes.github.io/tree/master/code-zip-files](https://github.com/in28minutes/in28minutes.github.io/tree/master/code-zip-files)\n\n- **Spring Security Example**\n    - `Website-SpringSecurityStarterWebApplication_Final.zip`\n\n---\n\n## Bootstrapping Web Application with Spring Initializr\n\nUsing **Spring Initializr** to create a Web application is very simple.  \nFor both the **web page** and the **REST service**, we will use **Spring Web MVC** as our web framework.\n\n> Spring Initializr: [http://start.spring.io/](http://start.spring.io/) is a great tool to bootstrap your Spring Boot\n> projects.\n\n\n![Image](/images/Spring-Initializr-Web.png \"Web, Actuator and Developer Tools\")\n\nAs shown in the image above, following steps have to be done\n\n### Steps to Launch Spring Initializr\n\n- Launch **Spring Initializr** and choose the following:\n    - Group: `com.in28minutes.springboot`\n    - Artifact: `student-services`\n    - Dependencies:\n        - Web\n- Click **Generate Project**.\n- Import the project into **Eclipse** or **IntelliJ IDEA** (or your favorite IDE).\n- If you want to understand all the files that are part of this project, you can\n  go [here](https://github.com/in28minutes/in28minutes.github.io/tree/master/code-zip-files){:target=\"_blank\"}.\n\n## Setting up a Simple Web Application\n\nLet's rapidly secure a basic web application with **Spring Security**.  \nWe’ll create a simple Controller that redirects to the welcome view – just a basic JSP.\n\n### JSP Support\n\nAs the view, we intend to use **JSP**.\n\nSince **Tomcat** is the default embedded servlet container for **Spring Boot Starter Web**,  \nwe need to add a dependency on `tomcat-embed-jasper` to enable JSP support.\n\n```xml\n\n<dependency>\n    <groupId>org.apache.tomcat.embed</groupId>\n    <artifactId>tomcat-embed-jasper</artifactId>\n    <scope>provided</scope>\n    // default for IntelliJ IDE\n</dependency>\n```\n\n### Adding Login Controller\n\nWe will create a **LoginController** to handle the root URL `/`.\n\n- The `showLoginPage()` function will be mapped to `/`.\n- The `Model` will be pre-populated with a hardcoded name.\n- It will return a view with the name `\"welcome\"`, which maps to `welcome.jsp`.\n\n```java\npackage com.in28minutes.springboot.web.controller;\n\nimport org.springframework.stereotype.Controller;\nimport org.springframework.ui.ModelMap;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\n\n@Controller\npublic class LoginController {\n\n    @RequestMapping(value = \"/\", method = RequestMethod.GET)\n    public String showLoginPage(ModelMap model) {\n        model.put(\"name\", \"in28Minutes\");\n        return \"welcome\";\n    }\n\n}\n```\n\n### Adding welcome.jsp\n\n`welcome.jsp` is a simple JSP page that displays a welcome message to the user.\n\n```html\n\n<div class=\"container\">\n    Welcome ${name}!!\n</div>\n```\n\n### Configure a View Resolver\n\n`welcome.jsp` is placed under `src/main/webapp/WEB-INF/jsp/`.  \nTo map the view name (like `\"welcome\"`) returned from the controller to the actual JSP file, we configure a **view\nresolver** in `application.properties`.\n\n```properties\nspring.mvc.view.prefix=/WEB-INF/jsp/\nspring.mvc.view.suffix=.jsp\n```\n\n### Run the Web Application\n\nStart the `StudentServicesApplication.java` program as a **Spring Boot Application**.\n\nOnce started, the application will run on the default port `8080`.  \nYou can access it at:\n\n[http://localhost:8080](http://localhost:8080)\n\nAt this point, the `LoginController` will redirect you to the `welcome.jsp` page, displaying the welcome message.\n\n![Image](/images/SpringBootSecuritySecurity-WebApplication.png \"Spring Security - Web Application\")\n\n## Add a Simple REST Service\n\nLet's also provide a basic REST Service. We will include:\n\n- **Model Objects**: `Course` and `Student`.\n    - A student may enroll in many courses.\n- **Business Service**: `StudentService`\n    - Handles the business logic.\n    - Uses hardcoded data stored in a static `ArrayList`.\n- **REST Controller**: `StudentController`\n    - Exposes one REST endpoint to fetch the list of courses for which a student is registered.\n\n### REST Endpoint Example\n\n- `@GetMapping(\"/students/{studentId}/courses\")`  \n  Retrieves all courses a given student is enrolled in.\n\n## Model and Business Logic\n\nThe following excerpts are taken from the model objects **Course** and **Student**.\n\n- A **Course** represents a subject with details such as `id`, `name`, and `description`.\n- A **Student** represents a learner and includes information along with the list of courses they are enrolled in.\n\nThe **business logic** is handled by the `StudentService` class.\n\n- It uses a static `ArrayList` to store student data.\n- The data is hardcoded for simplicity.\n- Its primary function is to retrieve the list of courses for a specific student.\n\n```java\npublic class Course {\n    private String id;\n    private String name;\n    private String description;\n    private List<String> steps;\n}\n```\n\n```java\npublic class Student {\n    private String id;\n    private String name;\n    private String description;\n    private List<Course> courses;\n}\n```\n\nStudentService provides a method `public List<Course> retrieveCourses(String studentId)` to retrieve the courses a\nstudent registered for.\n\n```java\n\n@Component\npublic class StudentService {\n\n    private static List<Student> students = new ArrayList<>();\n\n    static {\n        // Initialize Data\n        Course course1 = new Course(\"Course1\", \"Spring\", \"10 Steps\",\n                List.of(\"Learn Maven\", \"Import Project\", \"First Example\",\n                        \"Second Example\"));\n        Course course2 = new Course(\"Course2\", \"Spring MVC\", \"10 Examples\",\n                List.of(\"Learn Maven\", \"Import Project\", \"First Example\",\n                        \"Second Example\"));\n\n        Student ranga = new Student(\"Student1\", \"Ranga Karanam\",\n                \"Hiker, Programmer and Architect\", new ArrayList<>(\n                List.of(course1, course2)));\n\n        students.add(ranga);\n    }\n\n    public Student retrieveStudent(String studentId) {\n        for (Student student : students) {\n            if (student.getId().equals(studentId)) {\n                return student;\n            }\n        }\n        return null;\n    }\n\n    public List<Course> retrieveCourses(String studentId) {\n        Student student = retrieveStudent(studentId);\n\n        return student == null > null :student.getCourses();\n\n    }\n}\n```\n\n### Creating REST Service\n\nRest Service `StudentController` exposes a simple Get service at URI mapping \"/students/{studentId}/courses\". The\n`StudentService` is auto-wired in.\n\n```java\npackage com.in28minutes.springboot.controller;\n\nimport java.util.List;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.RestController;\n\nimport com.in28minutes.springboot.model.Course;\nimport com.in28minutes.springboot.service.StudentService;\n\n@RestController\npublic class StudentController {\n\n    @Autowired\n    private StudentService studentService;\n\n    @GetMapping(\"/students/{studentId}/courses\")\n    public List<Course> retrieveCoursesForStudent(@PathVariable String studentId) {\n        return studentService.retrieveCourses(studentId);\n    }\n}\n\n```\n\n### Executing REST Service\n\nRunning the REST Service is simple.  \nOpen the URL `http://localhost:8080/students/Student1/courses` in your browser or use your favorite REST client (e.g.,\nPostman).\n\n![Image](/images/SpringBootSecuritySecurity-RestService.png \"Spring Security - Rest Service\")\n\n## Add Spring Boot Starter Security\n\nNext, let’s add the **Spring Boot Starter Security** dependency to our project.  \nThis will enable authentication and authorization features for both our web application and REST services.\n\n```xml\n\n<dependency>\n    <groupId>org.springframework.boot</groupId>\n    <artifactId>spring-boot-starter-security</artifactId>\n</dependency>\n\n```\n\n### New Dependencies\n\nThe screenshot below shows the additional dependencies that are included when we add **spring-boot-starter-security**.  \nThese libraries provide the core functionality required for securing web applications and REST services.\n\n![Image](/images/SpringBootSecuritySecurity-Depedencies.png \"Dependencies of Spring Boot Security Starter\")\n\n### Auto Configuration\n\nAfter restarting the application, you will notice the following statements printed in the logs.  \nThese messages indicate that Spring Boot has automatically configured Spring Security for your application.\n\n```logs\nMapping filter: 'springSecurityFilterChain' to: [/*]\n\nUsing default security password: 25e07e82-720d-4109-ba8d-25177c6347e6\n\nCreating filter chain:\n...\n...\n\n```\n\nAll this magic happens because of **Spring Boot Auto-Configuration**:\n\n- `Mapping filter: 'springSecurityFilterChain' to: [/*]`\n    - Spring Security is automatically enabled for **all URLs** in the application.\n- **Basic Authentication** is applied by default.\n- `Using default security password: 25e07e82-720d-4109-ba8d-25177c6347e6`\n    - The default username is **user**.\n    - The default password is randomly generated and printed in the startup log.\n    - In this example, the password is `25e07e82-720d-4109-ba8d-25177c6347e6`.\n- Several **filter chains** are auto-configured to enforce security.\n\n### Executing the REST Service\n\nWhen we execute the REST service at `http://localhost:8080/students/Student1/courses`, it now returns an *\n*authentication failure**.\n\n- The **HTTP status** is `401 Unauthorized`.\n- The response message is `\"Bad credentials\"`.\n- This happens because the service is now **protected by Spring Security**.\n\n```json\n{\n  \"timestamp\": 1485768623632,\n  \"status\": 401,\n  \"error\": \"Unauthorized\",\n  \"message\": \"Bad credentials\",\n  \"path\": \"/students/Student1/courses\"\n}\n```\n\n- Make sure to provide the correct username and password, as the service is now secured with Spring Security.\n\n![Image](/images/SpringBootSecuritySecurity-RestService-WithoutAuthentication.png \"Spring Boot Security Starter - Executing Protected Rest Service without Authentication\")\n\n### Executing REST Service with Basic Authentication\n\nRetrieve the password from the application log by looking for `Using default security password:`.  \nThe default username is `user`.\n\nUse this username and password combination to access the service using Basic Authentication, as illustrated in the\nscreenshot below.\n\n![Image](/images/SpringBootSecuritySecurity-RestService-Authentication.png \"Spring Boot Security Starter - Executing Rest Service with Basic Authentication\")\n\n### Running the Web Application\n\nWhen you open the URL `http://localhost:8080` in your browser, a popup will appear requesting a username and password.\n\nEnter the same credentials that you used for the REST Service.\n\n![Image](/images/SpringBootSecuritySecurity-WebApplication-Authentication.png \"Spring Boot Security Starter - Providing authentication details for Web application\")\n\nThat's quite a bit of functionality we enabled just by adding the simple dependency `Spring Boot Starter Security`.\n\n## Configuring Custom Users and Roles\n\nNow let's configure custom users and roles:\n\n- We will define two roles: **Admin** and **User**.\n    - The **Admin** role will have access to the web application.\n    - The **User** role will have access to execute REST services.\n- We will create one user for the **Admin** role with credentials: `admin1 / secret1`.\n- We will create one user for the **User** role with credentials: `user1 / secret1`.\n\n```java\npackage com.in28minutes.springboot.security;\n\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;\nimport org.springframework.security.config.annotation.web.builders.HttpSecurity;\nimport org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;\n\n@Configuration\npublic class SecurityConfig {\n\n    @Bean\n    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {\n\n        http.authorizeHttpRequests(\n                auth -> auth.requestMatchers(\"/students/**\")\n                        .permitAll().anyRequest().authenticated());\n\n        http.httpBasic(withDefaults());\n\n        http.csrf().disable();\n\n        return http.build();\n\n    }\n\n    @Bean\n    public AuthenticationManager authenticationManager(UserDetailsService userDetailsService) {\n        var authenticationProvider = new DaoAuthenticationProvider();\n        authenticationProvider.setUserDetailsService(userDetailsService);\n\n        return new ProviderManager(authenticationProvider);\n    }\n\n    @Bean\n    public UserDetailsService userDetailsService() {\n        UserDetails user = User.withUsername(\"user1\")\n                .password(\"{noop}secret1\")\n                .authorities(\"read\")\n                .roles(\"USER\")\n                .build();\n        UserDetails userOne = User.withUsername(\"admin1\")\n                .password(\"{noop}secret1\")\n                .authorities(\"read\")\n                .roles(\"ADMIN\")\n                .build();\n\n        return new InMemoryUserDetailsManager(user, userOne);\n    }\n\n}\n```\n\n### Executing REST Services\n\nNow you can use the `user1 / secret1` credentials to access the REST service.\n\n### Launching the Web Application\n\nUse the `admin1 / secret1` credentials in the authentication popup to access the web application.\n"
  },
  {
    "path": "_blog/articles/2017-01-30-spring-boot-web-application-top20.md",
    "content": "---\nlayout:     post\ntitle:      Creating a Web Application with Spring Boot with JSP\ndate:       2025-09-13 12:31:19\nsummary:    Setting up a basic web application with Spring Boot is a cake walk. We will create a simple web application using Spring Initializr and add JSP features to it. \ncategories:  SpringBoot\npermalink:  /creating-web-application-with-spring-boot\nimage: /images/spring-boot-application.png\n---\n\nThis guide will help you create a simple web application with Spring Boot. We will develop an application that includes login functionality and the ability to display a list of todos. The application will follow the MVC pattern, using JSP as the view.\n\n![Image](/images/SpringBootWebApplication-AllFiles.png \"Spring Boot Web Application - All Files\")\n\n\n## You will learn\n- How to bootstrap a simple Spring Boot project using Spring Initializr.\n- How to initialize a basic web application with Spring Boot.\n- How to add JSP pages to your web application.\n- How to implement basic login functionality.\n- How to display a list of todos.\n- How to auto-wire components using the Spring Framework.\n- Next steps if you want to explore further.\n\n## Tools You Will Need\n- Maven 3.0+ as your build tool\n- Your preferred IDE (Eclipse or IntelliJ IDEA recommended)\n- JDK 17 or higher\n\n\n## Overview of the Web Application\n\nWe will build a simple **To-Do list page** (unformatted) with a basic **login feature**.\n\n### Project Files\n\nThe screenshot below shows the Eclipse project with all the files we will create.\n\n\n![Image](/images/SpringBootWebApplication-AllFiles.png \"Spring Boot Web Application - All Files\") \n\n## Brief Overview of All Files\n\n- `LoginService` and `TodoService`  \n  Contain the business logic. `LoginService` provides simple hardcoded validation for user ID and password. `TodoService` contains a method to retrieve a list of todos.\n\n- `login.jsp`, `welcome.jsp`, `list-todos.jsp`  \n  The names clearly indicate the content of each view.\n\n- `LoginController` and `TodoController`  \n  Act as controllers in the MVC pattern. `LoginController` handles login flow: if the user enters a valid ID and password, they are redirected to the welcome page; otherwise, the login page is shown with an error message.\n\n- `pom.xml`  \n  Contains important dependencies such as Spring Boot Starter Web and `tomcat-embed-jasper`.\n\n- `application.properties`  \n  Typically used to configure frameworks in Spring Boot. In this example, it is used to configure the view resolver.\n\n\n### Screenshots of the application\n\nLogin Page\n\n![Image](/images/SpringBootWebApplication-LoginPage.png \"Spring Boot Web Application - Login Page\")\n\nLogin Page if user enters invalid userid and password\n\n![Image](/images/SpringBootWebApplication-LoginPage-InvalidCredentials.png \"Spring Boot Web Application - Login Page with Invalid Credentials\")\n\nWelcome Page \n\n![Image](/images/SpringBootWebApplication-WelcomePage.png \"Spring Boot Web Application - Welcome Page\")\n\nList Todos Page\n\n![Image](/images/SpringBootWebApplication-TodoPage.png \"Spring Boot Web Application - Todo Page\")\n\n\n## Bootstrapping a Web Application with Spring Initializr\n\nCreating a web application with Spring Initializr is a cakewalk. We will use Spring Web MVC as our web framework.\n\n> Spring Initializr [http://start.spring.io/](http://start.spring.io/) is a great tool to bootstrap your Spring Boot projects.\n\n\n![Image](/images/Spring-Initializr-Web.png \"Web, Actuator and Developer Tools\")   \n\nAs shown in the image above, follow these steps:\n\n- Launch Spring Initializr and choose the following:\n    - **Group**: `com.in28minutes.springboot`\n    - **Artifact**: `student-services`\n    - **Dependencies**:\n        - Web\n        - Actuator\n        - DevTools\n- Click **Generate Project**.\n- Import the project into **Eclipse** or **IntelliJ IDEA**.\n- To understand all the files included in this project, you can refer [here](#).\n\n\n## Project Dependencies\n\nSpring Boot Starter Web provides all the necessary dependencies and auto-configuration required to develop web applications. This is the first dependency we will use in our project.\n\n```xml\n<dependency>\n    <groupId>org.springframework.boot</groupId>\n    <artifactId>spring-boot-starter-web</artifactId>\n</dependency>\n```\n\nWe want to use JSP as the view. The default embedded servlet container for Spring Boot Starter Web is Tomcat. To enable JSP support, we need to add a dependency on `tomcat-embed-jasper`.\n\n```xml\n<dependency>\n    <groupId>org.apache.tomcat.embed</groupId>\n    <artifactId>tomcat-embed-jasper</artifactId>\n    <scope>provided</scope> // default for IntelliJ IDE\n</dependency>\n```\n\n### Spring Boot Starter Web Dependencies\n\nThe following screenshot shows the dependencies that are automatically added to our application by including Spring Boot Starter Web.\n\n\n![Image](/images/SpringBootStarterWeb-Dependencies.png \"Spring Boot Starter Web - Dependencies\")\n\nDependencies can be categorized as follows:\n\n- **Spring** – core, beans, context, AOP\n- **Web MVC** – Spring MVC\n- **Jackson** – for JSON binding\n- **Validation** – Hibernate Validator, Validation API\n- **Embedded Servlet Container** – Tomcat\n- **Logging** – Logback, SLF4J\n\n\nAny typical web application would use all these dependencies. Spring Boot Starter Web comes pre-packaged with them. As a developer, you don’t need to worry about these dependencies or their compatible versions.\n\n### Auto Configuration\nSpring Boot Starter Web also auto-configures the basic components required for a web application. To see the features it provides, run `StudentServicesApplication.java` as a Java application and review the log.\n\n\n```logs\nMapping servlet: 'dispatcherServlet' to [/]\n\nMapped \"{[/error]}\" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)\n\nMapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]\n\n```\nSpring Boot Starter Web auto-configures the following components:\n\n- **Dispatcher Servlet**\n- **Error Page**\n- **Web Jars** to manage static dependencies\n- **Embedded Servlet Container** – Tomcat is used by default\n\n\n## Configuring a View Resolver\n\nOur JSP files will be located in `/WEB-INF/jsp/`. We need to configure a view resolver with the appropriate **prefix** and **suffix** to map view names to these JSP files.\n\n\n```properties\nspring.mvc.view.prefix=/WEB-INF/jsp/\nspring.mvc.view.suffix=.jsp\n```\n\n## Login Controller\n\n- `public String showLoginPage(ModelMap model)`: Mapped to the `\\login` GET method; displays the login page.\n- `@Autowired LoginService service`: Injects `LoginService`, which contains the validation logic.\n- `showWelcomePage(ModelMap model, @RequestParam String name, @RequestParam String password)`: Mapped to the `\\login` POST method; validates the user ID and password, and redirects to the welcome page if login is successful.\n\n```java\npackage com.in28minutes.springboot.web.controller;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.ui.ModelMap;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\nimport org.springframework.web.bind.annotation.RequestParam;\nimport org.springframework.web.bind.annotation.SessionAttributes;\n\nimport com.in28minutes.springboot.web.service.LoginService;\n\n@Controller\n@SessionAttributes(\"name\")\npublic class LoginController {\n\n    @Autowired\n    LoginService service;\n\n    @RequestMapping(value=\"/login\", method = RequestMethod.GET)\n    public String showLoginPage(ModelMap model){\n        return \"login\";\n    }\n\n    @RequestMapping(value=\"/login\", method = RequestMethod.POST)\n    public String showWelcomePage(ModelMap model, @RequestParam String name, @RequestParam String password){\n\n        boolean isValidUser = service.validateUser(name, password);\n\n        if (!isValidUser) {\n            model.put(\"errorMessage\", \"Invalid Credentials\");\n            return \"login\";\n        }\n\n        model.put(\"name\", name);\n        model.put(\"password\", password);\n\n        return \"welcome\";\n    }\n\n}\n```\n\n## Login Service\n\nContains the basic authentication logic. Uses hardcoded credentials for simplicity.\n\n```java\npackage com.in28minutes.springboot.web.service;\n\nimport org.springframework.stereotype.Component;\nimport org.springframework.stereotype.Service;\n\n@Service\npublic class LoginService {\n\n    public boolean validateUser(String userid, String password) {\n        // in28minutes, dummy\n        return userid.equalsIgnoreCase(\"in28minutes\")\n                && password.equalsIgnoreCase(\"dummy\");\n    }\n\n}\n```\n\n## Login View - JSP\n\nA simple login page with fields for `userid` and `password`.  \nIf an error message is set in the model, `${errorMessage}` will display the authentication failure message.\n\n\n```html\n<html lang=\"en\">\n\n<head>\n<title>First Web Application</title>\n</head>\n\n<body>\n    <font color=\"red\">${errorMessage}</font>\n    <form method=\"post\">\n        Name : <input type=\"text\" name=\"name\" />\n        Password : <input type=\"password\" name=\"password\" /> \n        <input type=\"submit\" />\n    </form>\n</body>\n\n</html>\n```\n\n## Welcome-View - JSP\n\nThis page is displayed upon successful authentication.  \nIt shows the name of the logged-in user and provides a link to manage the todo list.\n\n\n```html\n<html lang=\"en\">\n\n<head>\n<title>First Web Application</title>\n</head>\n\n<body>\n    Welcome ${name}!! <a href=\"/list-todos\">Click here</a> to manage your todo's.\n</body>\n\n</html>\n```\n\n## Todo Model and Business Service\n\nThe `Todo` model contains the following fields: `id`, `user`, `description`, and `targetDate`.  \nThe `TodoService` provides basic business logic to manage and retrieve todo items.\n\n\n```java\npackage com.in28minutes.springboot.web.model;\n\nimport java.util.Date;\n\npublic class Todo {\n    private int id;\n    private String user;\n    private String desc;\n    private Date targetDate;\n    private boolean isDone;\n\n\t//Getters, Setters, Constructors, toString, equals and hash code\n} \n```\n\n`TodoService` uses a simple `ArrayList` to store todos in memory. It provides a method to retrieve the list of todos.\n\n```java\npackage com.in28minutes.springboot.web.service;\n\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.Iterator;\nimport java.util.List;\n\nimport org.springframework.stereotype.Service;\n\nimport com.in28minutes.springboot.web.model.Todo;\n\n@Service\npublic class TodoService {\n    private static List<Todo> todos = new ArrayList<>();\n    private static int todoCount = 3;\n\n    static {\n        todos.add(new Todo(1, \"in28Minutes\", \"Learn Spring MVC\", new Date(),\n                false));\n        todos.add(new Todo(2, \"in28Minutes\", \"Learn Struts\", new Date(), false));\n        todos.add(new Todo(3, \"in28Minutes\", \"Learn Hibernate\", new Date(),\n                false));\n    }\n\n    public List<Todo> retrieveTodos(String user) {\n        List<Todo> filteredTodos = new ArrayList<>();\n        for (Todo todo : todos) {\n            if (todo.getUser().equals(user)) {\n                filteredTodos.add(todo);\n            }\n        }\n        return filteredTodos;\n    }\n}\n```\n\n## List Todos JSP\n\nThe List Todos page displays all the todos. This page is currently unformatted. In subsequent steps of the course, we will enhance this page by styling it and adding functionality to add, delete, and update todos.\n\n```jsp\n<html>\n\n<head>\n<title>First Web Application</title>\n</head>\n\n<body>\n    Here are the list of your todos:\n    ${todos} \n    <BR/>\n    Your Name is : ${name}\n</body>\n\n</html>\n```\n\n## Todo Controller\n\nThe TodoController has a simple method that retrieves the list of todos and adds them to the model. It then redirects to the `list-todos` view.\n\n```java\npackage com.in28minutes.springboot.web.controller;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.ui.ModelMap;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\nimport org.springframework.web.bind.annotation.RequestParam;\nimport org.springframework.web.bind.annotation.SessionAttributes;\n\nimport com.in28minutes.springboot.web.service.LoginService;\nimport com.in28minutes.springboot.web.service.TodoService;\n\n@Controller\n@SessionAttributes(\"name\")\npublic class TodoController {\n\n    @Autowired\n    TodoService service;\n\n    @RequestMapping(value=\"/list-todos\", method = RequestMethod.GET)\n    public String showTodos(ModelMap model){\n        String name = (String) model.get(\"name\");\n        model.put(\"todos\", service.retrieveTodos(name));\n        return \"list-todos\";\n    }\n}\n```\n\n## Running the Application\n\nWe use a Spring Boot application class to launch our web application.\n\n\n```java\npackage com.in28minutes.springboot.web;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.context.annotation.ComponentScan;\n\n@SpringBootApplication\n@ComponentScan(\"com.in28minutes.springboot.web\")\npublic class SpringBootFirstWebApplication {\n\n    static void main(String[] args) {\n        SpringApplication.run(SpringBootFirstWebApplication.class, args);\n    }\n}\n```\n\nComplete code is available on the GitHub repository: [https://github.com/in28minutes/SpringBootWebApplicationStepByStep](https://github.com/in28minutes/SpringBootWebApplicationStepByStep). You can download `Step12.zip` and import it as a Maven project to run it.\n\nRun the application as a simple Java application. Upon startup, you will see the application initializing in the logs. All request mappings will be properly configured.\n\nYou can access the application at [http://localhost:8080/login](http://localhost:8080/login) and log in using the credentials:\n\n- **UserID**: in28Minutes\n- **Password**: dummy\n\n\n```\n\n  .   ____          _            __ _ _\n /\\\\ / ___'_ __ _ _(_)_ __  __ _ \\ \\ \\ \\\n( ( )\\___ | '_ | '_| | '_ \\/ _` | \\ \\ \\ \\\n \\\\/  ___)| |_)| | | | | || (_| |  ) ) ) )\n  '  |____| .__|_| |_|_| |_\\__, | / / / /\n =========|_|==============|___/=/_/_/_/\n :: Spring Boot ::        (v4.0.0-M2)\n\n2017-01-30 10:02:01.775  INFO 6070 --- [  restartedMain] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)\n2017-01-30 10:02:01.798  INFO 6070 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service Tomcat\n2017-01-30 10:02:01.800  INFO 6070 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.6\n2017-01-30 10:02:02.498  INFO 6070 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext\n2017-01-30 10:02:02.498  INFO 6070 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 3747 ms\n2017-01-30 10:02:02.803  INFO 6070 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]\n2017-01-30 10:02:03.557  INFO 6070 --- [  restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped \"{[/login],methods=[GET]}\" onto public java.lang.String com.in28minutes.springboot.web.controller.LoginController.showLoginPage(org.springframework.ui.ModelMap)\n2017-01-30 10:02:03.559  INFO 6070 --- [  restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped \"{[/login],methods=[POST]}\" onto public java.lang.String com.in28minutes.springboot.web.controller.LoginController.showWelcomePage(org.springframework.ui.ModelMap,java.lang.String,java.lang.String)\n2017-01-30 10:02:03.559  INFO 6070 --- [  restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped \"{[/list-todos],methods=[GET]}\" onto public java.lang.String com.in28minutes.springboot.web.controller.TodoController.showTodos(org.springframework.ui.ModelMap)\n2017-01-30 10:02:03.564  INFO 6070 --- [  restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped \"{[/error]}\" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)\n2017-01-30 10:02:03.565  INFO 6070 --- [  restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped \"{[/error],produces=[text/html]}\" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)\n2017-01-30 10:02:03.615  INFO 6070 --- [  restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]\n2017-01-30 10:02:03.616  INFO 6070 --- [  restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]\n2017-01-30 10:02:03.682  INFO 6070 --- [  restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]\n2017-01-30 10:02:04.108  INFO 6070 --- [  restartedMain] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup\n2017-01-30 10:02:04.288  INFO 6070 --- [  restartedMain] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)\n2017-01-30 10:02:04.307  INFO 6070 --- [  restartedMain] c.i.s.web.SpringBootFirstWebApplication  : Started SpringBootFirstWebApplication in 7.204 seconds (JVM running for 9.191)\n\n```\n\nComplete code is available on the GitHub repository: [https://github.com/in28minutes/SpringBootWebApplicationStepByStep](https://github.com/in28minutes/SpringBootWebApplicationStepByStep). You can download `Step12.zip` and import it as a Maven project to run the application.\n"
  },
  {
    "path": "_blog/articles/2017-02-02-spring-boot-vs-spring-mvc-vs-spring.md",
    "content": "---\nlayout:     post\ntitle:      Spring Boot vs Spring MVC vs Spring - How do they compare?\ndate:       2025-09-13 12:31:19\nsummary:    How does Spring Boot compare with Spring MVC and Spring? What is Spring Boot? What is Spring MVC? What is Spring Framework? What are their goals? How do they compare?\ncategories:  SpringBoot\npermalink:  /spring-boot-vs-spring-mvc-vs-spring\nimage: /images/spring-boot-category.png\n---\n\nWhat is Spring Boot, Spring MVC, and the Spring Framework? What are their respective goals, and how do they compare to one another?\n\n![Image](/images/SpringBootStarterWeb-Dependencies.png \"Spring Boot Starter Web - Dependencies\")\n\n\n## You Will Learn\n- An overview of the **Spring Framework**\n- The key problems the **Spring Framework** addresses\n- An overview of the **Spring MVC Framework**\n- The key problems the **Spring MVC Framework** addresses\n- An overview of the **Spring Boot Framework**\n- The key problems that **Spring Boot** solves\n- A comparison: **Spring vs. Spring MVC vs. Spring Boot**\n- Most importantly: **Spring, Spring MVC, and Spring Boot are not competitors.**  \n  They each solve different problems—and they solve them very well.\n\n# A Complete Maven Project With Code Examples\n\n> Our GitHub repository contains all the code examples:  \n> https://github.com/in28minutes/in28minutes.github.io/tree/master/code-zip-files\n\n- `Website-springbootrestservices-simplerestserviceswithunitandintegrationtests.zip` — Rest services with unit & integration tests\n- `Website-SpringSecurityStarterWebApplication_Final.zip` — Spring Security example\n- `Website-springbootrestservices-all-examples.zip` — Other RESTful web services examples\n\n# What is the core problem that the Spring Framework solves?\n\nThink about the core problem: **how objects get their dependencies**. Spring's answer is **Dependency Injection (DI)**, also known as **Inversion of Control (IoC)**.\n\n> The most important feature of the Spring Framework is **Dependency Injection**. At the core of all Spring modules is DI / IoC.\n\n**Why this matters**\n- Enables **loose coupling** between components.\n- Makes code **easy to unit test** (you can inject mocks).\n- Simplifies **swapping implementations** and managing object lifecycles.\n\n# Example — without Dependency Injection\n```java\n@RestController\npublic class WelcomeController {\n\n    private WelcomeService service = new WelcomeService();\n\n\t@RequestMapping(\"/welcome\")\n\tpublic String welcome() {\n\t\treturn service.retrieveWelcomeMessage();\n\t}\n}\n\n```\n\n### Same Example with Dependency Injection\n\nWith **Dependency Injection (DI)**, life becomes much easier. Instead of manually wiring dependencies, you let the **Spring Framework** handle the heavy lifting. This is achieved using two simple annotations:\n\n- `@Service` — Tells Spring: *\"This is a bean. Please create and manage its lifecycle.\"*\n- `@Autowired` — Tells Spring: *\"Find a matching bean of this type and inject it here.\"*\n\nIn the example below, Spring automatically creates a bean for `WelcomeService` and injects it into `WelcomeController`.\n\n```java\n\n@Service\npublic class WelcomeService {\n    //Bla Bla Bla\n}\n\n@RestController\npublic class WelcomeController {\n\n    @Autowired\n    private WelcomeService service;\n\n\t@RequestMapping(\"/welcome\")\n\tpublic String welcome() {\n\t\treturn service.retrieveWelcomeMessage();\n\t}\n}\n\n```\n\n## What else does the Spring Framework solve?\n\n### Problem 1: Boilerplate and Plumbing Code\nDoes the Spring Framework stop with Dependency Injection? **No.**  \nIt builds on DI with a number of modules, such as:\n\n- Spring JDBC\n- Spring MVC\n- Spring AOP\n- Spring ORM\n- Spring JMS\n- Spring Test\n\nTake **Spring JDBC** and **Spring JMS** as examples.  \nDo these modules provide brand-new functionality? **Not really.** Everything can already be done with J2EE/JEE.\n\nSo, what do they add? They provide **simplified abstractions** that:\n- Reduce boilerplate and duplication\n- Promote decoupling and improve unit testability\n\nFor instance, using Spring’s templates (like `JdbcTemplate` or `JmsTemplate`) requires far less code compared to traditional JDBC or JMS approaches.\n\n---\n\n### Problem 2: Seamless Integration with Other Frameworks\nAnother strength of Spring is that it doesn’t reinvent the wheel.  \nInstead, it integrates smoothly with popular, proven frameworks, such as:\n\n- **Hibernate** for ORM\n- **iBatis** for object mapping\n- **JUnit & Mockito** for testing\n\n---\n\n## What is the core problem that the Spring MVC Framework solves?\n\nThe **Spring MVC Framework** offers a **decoupled way to build web applications**.  \nBy introducing simple yet powerful concepts like the **Dispatcher Servlet**, **ModelAndView**, and **View Resolver**, it makes web application development cleaner, more modular, and easier to manage.\n\n---\n\n## Why do we need Spring Boot?\n\nWhile Spring is powerful, **Spring-based applications traditionally require a lot of configuration**.\n\nFor example, when using Spring MVC, you typically need to configure:\n- Component scanning\n- The Dispatcher Servlet\n- A View Resolver\n- WebJars (for serving static content)\n- And more...\n\nSpring Boot was created to **remove this heavy setup burden** by providing sensible defaults, auto-configuration, and embedded servers — making it much faster to build and run Spring applications.\n\n\n```xml\n  <bean\n        class=\"org.springframework.web.servlet.view.InternalResourceViewResolver\">\n        <property name=\"prefix\">\n            <value>/WEB-INF/views/</value>\n        </property>\n        <property name=\"suffix\">\n            <value>.jsp</value>\n        </property>\n  </bean>\n  \n  <mvc:resources mapping=\"/webjars/**\" location=\"/webjars/\"/>\n    \n```\n\nThe below code snippet shows the typical configuration of a dispatcher servlet in a web application.\n\n```xml\n    <servlet>\n        <servlet-name>dispatcher</servlet-name>\n        <servlet-class>\n            org.springframework.web.servlet.DispatcherServlet\n        </servlet-class>\n        <init-param>\n            <param-name>contextConfigLocation</param-name>\n            <param-value>/WEB-INF/todo-servlet.xml</param-value>\n        </init-param>\n        <load-on-startup>1</load-on-startup>\n    </servlet>\n\n    <servlet-mapping>\n        <servlet-name>dispatcher</servlet-name>\n        <url-pattern>/</url-pattern>\n    </servlet-mapping>\n```\n  \nWhen we use Hibernate/JPA, we would need to configure a datasource, an entity manager factory, and a transaction manager, among a host of other things. \n\n```xml\n    <bean id=\"dataSource\" class=\"com.mchange.v2.c3p0.ComboPooledDataSource\"\n        destroy-method=\"close\">\n        <property name=\"driverClass\" value=\"${db.driver}\" />\n        <property name=\"jdbcUrl\" value=\"${db.url}\" />\n        <property name=\"user\" value=\"${db.username}\" />\n        <property name=\"password\" value=\"${db.password}\" />\n    </bean>\n\n    <jdbc:initialize-database data-source=\"dataSource\">\n        <jdbc:script location=\"classpath:config/schema.sql\" />\n        <jdbc:script location=\"classpath:config/data.sql\" />\n    </jdbc:initialize-database>\n\n    <bean\n        class=\"org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean\"\n        id=\"entityManagerFactory\">\n        <property name=\"persistenceUnitName\" value=\"hsql_pu\" />\n        <property name=\"dataSource\" ref=\"dataSource\" />\n    </bean>\n\n    <bean id=\"transactionManager\" class=\"org.springframework.orm.jpa.JpaTransactionManager\">\n        <property name=\"entityManagerFactory\" ref=\"entityManagerFactory\" />\n        <property name=\"dataSource\" ref=\"dataSource\" />\n    </bean>\n\n    <tx:annotation-driven transaction-manager=\"transactionManager\"/>\n\n``` \n\n## Problem #1: Spring Boot Auto-Configuration — A New Way of Thinking\n\nSpring Boot introduced a fresh perspective:  \n**Can configuration be made smarter and more automatic?**\n\n> For example:\n> - If a **Hibernate** JAR is on the classpath, can Spring Boot auto-configure a **DataSource**?\n> - If a **Spring MVC** JAR is on the classpath, can it auto-configure a **DispatcherServlet**?\n\nThe answer is **yes**. Spring Boot automatically provides sensible defaults by analyzing:\n1. The **frameworks available on the classpath**\n2. The **existing configuration** in the application\n\nBased on this, it sets up the basic configuration required to run the application.  \nThis intelligent setup is known as **Auto-Configuration**.\n\nAnd of course, developers can **override** the defaults when needed.\n\n---\n\n## Problem #2: Spring Boot Starter Projects — Simplifying Dependencies\n\nWhen developing a web application, we usually need to:\n- Identify which frameworks to use\n- Choose the correct versions of those frameworks\n- Ensure all dependencies are compatible and work together\n\nThis can be tedious and error-prone.\n\nMost web applications share common dependencies. For example, in our Spring MVC course we used:\n- **Spring MVC**\n- **Jackson Databind** (for JSON data binding)\n- **Hibernate Validator** (for server-side validation with JSR-303/380)\n- **Log4j** (for logging)\n\nManually selecting and managing versions of all these libraries was a challenge.\n\nSpring Boot solved this with **Starter Projects** — curated dependency descriptors that bring in a set of compatible libraries for common application needs (like `spring-boot-starter-web` for web apps). This removes guesswork and ensures consistent, stable builds.\n\n```xml\n<dependency>\n   <groupId>org.springframework</groupId>\n   <artifactId>spring-webmvc</artifactId>\n   <version>6.0.0-M4</version>\n</dependency>\n\n<dependency>\n    <groupId>com.fasterxml.jackson.core</groupId>\n    <artifactId>jackson-databind</artifactId>\n    <version>2.13.3</version>\n</dependency>\n\n<dependency>\n    <groupId>org.hibernate</groupId>\n    <artifactId>hibernate-validator</artifactId>\n    <version>7.0.4.Final</version>\n</dependency>\n\n<dependency>\n    <groupId>log4j</groupId>\n    <artifactId>log4j</artifactId>\n    <version>1.2.17</version>\n</dependency>\n    \n```\nHere’s how the official Spring Boot documentation describes **Starters**:\n\n> **Starters** are a convenient set of dependency descriptors that you can include in your application. They act as a one-stop shop for all the Spring and related technologies you need—without having to search through sample code or copy-paste multiple dependency entries.  \n> For example, if you want to start using **Spring + JPA** for database access, simply include the `spring-boot-starter-data-jpa` dependency in your project, and you’re good to go.\n\n---\n\n### Example: Spring Boot Starter Web\n\nIf you want to:\n- Develop a **web application**, or\n- Expose **RESTful services**,\n\nthen **`spring-boot-starter-web`** is the right starter to use.\n\nLet’s create a simple project with **Spring Boot Starter Web** using **Spring Initializr**.\n\n---\n\n### Dependency for Spring Boot Starter Web\n\n```xml\n<dependency>\n\t<groupId>org.springframework.boot</groupId>\n\t<artifactId>spring-boot-starter-web</artifactId>\n</dependency>\n```\n\nThe screenshot below shows the dependencies added to our application by the `spring-boot-starter-web` starter.\n\n\n![Image](/images/SpringBootStarterWeb-Dependencies.png \"Spring Boot Starter Web - Dependencies\")\n\n## Dependencies in Spring Boot Starter Web\n\nDependencies in a typical web application can be grouped as follows:\n\n- **Spring** – core, beans, context, aop\n- **Web MVC** – Spring MVC\n- **Jackson** – for JSON binding\n- **Validation** – Hibernate Validator, Validation API\n- **Embedded Servlet Container** – Tomcat\n- **Logging** – Logback, SLF4J\n\nAny typical web application would use all of these.  \nThe **Spring Boot Starter Web** bundles them together, so as a developer you don’t need to worry about choosing or managing compatible versions.\n\n---\n\n## Spring Boot Starter Project Options\n\nStarter projects make it easy to get started with specific types of applications. Examples include:\n\n- **spring-boot-starter-web-services** – SOAP Web Services\n- **spring-boot-starter-web** – Web & RESTful applications\n- **spring-boot-starter-test** – Unit and integration testing\n- **spring-boot-starter-jdbc** – Traditional JDBC access\n- **spring-boot-starter-hateoas** – Add HATEOAS features to services\n- **spring-boot-starter-security** – Authentication & authorization with Spring Security\n- **spring-boot-starter-data-jpa** – Spring Data JPA with Hibernate\n- **spring-boot-starter-cache** – Enable Spring Framework’s caching support\n- **spring-boot-starter-data-rest** – Expose REST services using Spring Data REST\n\n---\n\n## Other Goals of Spring Boot\n\nIn addition to application-specific starters, there are also starters for technical concerns:\n\n- **spring-boot-starter-actuator** – Advanced monitoring and tracing out of the box\n- **spring-boot-starter-undertow**, **spring-boot-starter-jetty**, **spring-boot-starter-tomcat** – Choose your embedded servlet container\n- **spring-boot-starter-logging** – Logging with Logback\n- **spring-boot-starter-log4j2** – Logging with Log4j2\n\nSpring Boot’s broader goals include enabling **production-ready applications quickly** by providing:\n- **Actuator** – Built-in monitoring, health checks, and tracing\n- **Embedded server integration** – No need for an external application server; everything runs inside the application\n- **Default error handling** – Sensible defaults for error responses  \n"
  },
  {
    "path": "_blog/articles/2017-07-05-introduction-to-jpa-with-spring-boot.md",
    "content": "---\nlayout: post\ntitle: JPA and Hibernate Tutorial using Spring Boot Data JPA\ndate: 2025-09-13 12:31:19\nsummary: Complete journey starting from JDBC to JPA to Spring Data JPA using an example with Spring Boot Data JPA starter project. We use Hibernate as the JPA Implementation.\ncategories: SpringBootJPA\npermalink: /introduction-to-jpa-with-spring-boot-data-jpa\nimage: /images/spring-data-category.png\n---\n\n![Image](/images/JPA_02_Architecture.png \"JPA Architecuture\")\n\nThis guide introduces **JPA** and walks you through setting up a simple example in **Spring Boot**.\n\n![Image](/images/JPA_01_Introduction.png \"JPA Introduction\")\n\n## You Will Learn\n\n- **What is JPA?**\n- **The problem JPA solves** – Object-Relational Impedance Mismatch\n- **Alternatives to JPA**\n- **What is Hibernate, and how does it relate to JPA?**\n- **What is Spring Data JPA?**\n- **How to create a simple JPA project** using the Spring Boot Data JPA Starter\n\n## You Will Need the Following Tools\n\n- **Maven 3.0+** – Build and dependency management tool\n- **An IDE of your choice** – for example, Eclipse or IntelliJ IDEA\n- **JDK 17+** – Java Development Kit\n- **H2 Database** – In-memory database for quick setup and testing\n\n## What is Object Relational Impedance Mismatch?\n\n![Image](/images/JPA_01_Introduction.png \"JPA Introduction\")\n\nJava is an object-oriented programming language, where all data is represented and managed through objects.\n\nIn most applications, data is stored in relational databases (although NoSQL databases are also gaining popularity, we\nwill not focus on them here). Relational databases store data in tables.\n\nHowever, the way we design objects in Java is very different from how relational databases are structured, leading to\nwhat is known as an *impedance mismatch*.\n\n- **Object-oriented programming** uses concepts like encapsulation, inheritance, interfaces, and polymorphism.\n- **Relational databases** organize data into tables and follow principles such as normalization.\n\n### Examples of Object-Relational Impedance Mismatch\n\nLet’s take a simple example involving **Employees** and **Tasks**.\n\n- Each `Employee` can be assigned multiple tasks.\n- Each `Task` can be shared by multiple employees.\n\nThis creates a **many-to-many relationship** between `Employee` and `Task`.  \nNow, let’s look at some examples of impedance mismatch.\n\n#### Example 1: Column Naming Differences\n\nSuppose the `Task` class in Java has fields like `taskId` and `taskDescription`.  \nIn the database, the corresponding table might use column names such as `id` and `description`.\n\nEven though they represent the same data, the mismatch in naming conventions between objects and database tables creates\nfriction in mapping.\n\n```java\npublic class Task {\n    private int id;\n\n    private String desc;\n\n    private Date targetDate;\n\n    private boolean isDone;\n\n    private List<Employee> employees;\n}\n```\n\n```sql\n CREATE TABLE task\n (\n     id          INTEGER GENERATED BY DEFAULT AS IDENTITY,\n     description VARCHAR(255),\n     is_done     BOOLEAN,\n     target_date TIMESTAMP,\n     PRIMARY KEY (id)\n ) \n```\n\n#### Example 2: Differences in Representing Relationships\n\nIn Java, relationships between objects are expressed differently than relationships between tables in a database.\n\nFor example:\n\n- Each `Employee` object can have multiple `Task` objects.\n- Each `Task` object can be associated with multiple `Employee` objects.\n\nThis creates a **many-to-many relationship**.  \nIn a relational database, representing this relationship typically requires a **join table**, which adds an extra layer\nof complexity when mapping objects to tables.\n\n```java\npublic class Employee {\n\n    //Some other code\n\n    private List<Task> tasks;\n}\n\npublic class Task {\n\n    //Some other code\n\n    private List<Employee> employees;\n}\n```\n\n```sql\nCREATE TABLE employee\n(\n    id BIGINT NOT NULL,\n    OTHER_COLUMNS\n)\n\n\nCREATE TABLE employee_tasks\n(\n    employees_id BIGINT  NOT NULL,\n    tasks_id     INTEGER NOT NULL\n)\n\nCREATE TABLE task\n(\n    id INTEGER GENERATED BY DEFAULT AS IDENTITY,\n    OTHER_COLUMNS\n)\n\n```\n\n#### Example 3: Sometimes multiple classes are mapped to a single table and vice versa.\n\nObjects\n\n```java\npublic class Employee {\n    //Other Employee Attributes\n}\n\npublic class FullTimeEmployee extends Employee {\n    protected Integer salary;\n}\n\npublic class PartTimeEmployee extends Employee {\n    protected Float hourlyWage;\n}\n```\n\nTables\n\n```sql\nCREATE TABLE employee\n(\n    employee_type VARCHAR(31) NOT NULL,\n    id            BIGINT      NOT NULL,\n    city          VARCHAR(255),\n    state         VARCHAR(255),\n    street        VARCHAR(255),\n    zip           VARCHAR(255),\n\n    hourly_wage   FLOAT,   --PartTimeEmployee\n\n    salary        INTEGER, --FullTimeEmployee\n\n    PRIMARY KEY (id)\n)\n\n```\n\n## Other Approaches Before JPA — JDBC, Spring JDBC & MyBatis\n\nBefore JPA, most approaches focused on **writing queries** and **mapping query results to objects**.\n\nTypically, any query-based approach involves two main tasks:\n\n- **Setting query parameters** – reading values from objects and assigning them as parameters to the query.\n- **Mapping query results** – converting the results returned by the query into Java objects (beans).\n\n\n### JDBC\n\n- JDBC stands for Java Database Connectivity.\n- It used concepts like Statement, PreparedStatement, and ResultSet.\n- In the example below, the query used is ```Update todo set user=?, desc=?, target_date=?, is_done=? where id=?```\n- The values required to execute the query are set using various `set` methods on the **PreparedStatement**.\n- The results returned by the query are stored in a **ResultSet**, and we must manually map these results into Java objects.\n\n\n#### Update Todo\n\n```java\nConnection connection = datasource.getConnection();\n\nPreparedStatement st = connection.prepareStatement(\"Update todo set user=?, desc=?, target_date=?, is_done=? where id=?\");\n\nst.setString(1,todo.getUser());\nst.setString(2,todo.getDesc());\nst.setTimestamp(3,new Timestamp(todo.getTargetDate().getTime()));\nst.setBoolean(4,todo.isDone());\nst.setInt(5,todo.getId());\nst.execute();\nst.close();\nconnection.close();\n```\n\n#### Retrieved by Todo\n\n```java\nConnection connection = datasource.getConnection();\n\nPreparedStatement st = connection.prepareStatement(\n        \"SELECT * FROM TODO where id=?\");\n\nst.setInt(1,id);\n\nResultSet resultSet = st.executeQuery();\n\nif(resultSet.next()) {\n\n    Todo todo = new Todo();\n    todo.setId(resultSet.getInt(\"id\"));\n    todo.setUser(resultSet.getString(\"user\"));\n    todo.setDesc(resultSet.getString(\"desc\"));\n    todo.setTargetDate(resultSet.getTimestamp(\"target_date\"));\n\n    return todo;\n}\n\nst.close();\n\nconnection.close();\n\nreturn null;\n```\n\n### Spring JDBC\n\n- **Spring JDBC** provides a higher-level abstraction over standard JDBC.\n- It introduces concepts like **JdbcTemplate**.\n- Typically, requires fewer lines of code compared to plain JDBC, because it simplifies:\n    - Mapping parameters to queries\n    - Converting (mapping) result sets into Java objects (beans)\n\n\n#### Update Todo\n\n```java\njdbcTemplate.update(\"Update todo set user=?, desc=?, target_date=?, is_done=? where id=?\", todo.getUser(), \ntodo.getDesc(), new Timestamp(todo.getTargetDate().getTime()),\ntodo.isDone(), \ntodo.getId());\n```\n\n#### Retrieve a Todo\n\n```java\n\n@Override\npublic Todo retrieveTodo(int id) {\n\n    return jdbcTemplate.queryForObject(\n            \"SELECT * FROM TODO where id=?\",\n            new Object[]{id}, new TodoMapper());\n\n}\n```\n\nReusable Row Mapper\n\n```java\n// new BeanPropertyRowMapper(TodoMapper.class)\nclass TodoMapper implements RowMapper<Todo> {\n    @Override\n    public Todo mapRow(ResultSet rs, int rowNum)\n            throws SQLException {\n        Todo todo = new Todo();\n\n        todo.setId(rs.getInt(\"id\"));\n        todo.setUser(rs.getString(\"user\"));\n        todo.setDesc(rs.getString(\"desc\"));\n        todo.setTargetDate(rs.getTimestamp(\"target_date\"));\n        todo.setDone(rs.getBoolean(\"is_done\"));\n        return todo;\n    }\n}    \n```\n\n### MyBatis\n\n**MyBatis** eliminates the need to manually write code for setting query parameters and mapping results.  \nIt provides a simple **XML- or annotation-based configuration** to map Java POJOs to database tables.\n\nBelow, we compare the approaches used to write queries in different frameworks.\n\n- **JDBC or Spring JDBC**\n  ```sql\n  UPDATE todo \n  SET user=?, desc=?, target_date=?, is_done=? \n  WHERE id=?\n  ```\n- **MyBatis**\n  ```sql\n  UPDATE todo \n  SET user=#{user}, desc=#{desc}, target_date=#{targetDate}, is_done=#{isDone}\n  WHERE id=#{id}\n  ```\n\n#### Todo Update and Todo Retrieve\n\n```java\n\n@Mapper\npublic interface TodoMybatisService\n        extends TodoDataService {\n\n    @Override\n    @Update(\"Update todo set user=#{user}, desc=#{desc}, target_date=#{targetDate}, is_done=#{isDone} where id=#{id}\")\n    void updateTodo(Todo todo) throws SQLException;\n\n    @Override\n    @Select(\"SELECT * FROM TODO WHERE id = #{id}\")\n    Todo retrieveTodo(int id) throws SQLException;\n}\n\npublic class Todo {\n\n    private int id;\n\n    private String user;\n\n    private String desc;\n\n    private Date targetDate;\n\n    private boolean isDone;\n}\n\n```\n\n### Common Features of JDBC, Spring JDBC, and MyBatis\n\n- All three approaches—**JDBC**, **Spring JDBC**, and **MyBatis**—require writing SQL queries.\n- In large applications, queries can become complex, especially when retrieving data from multiple tables.\n- This complexity creates problems whenever the **database structure changes**, requiring updates to all affected queries.\n\n---\n\n## How Does JPA Work?\n\n**JPA** was designed with a different approach: instead of focusing on queries, it maps **Java objects directly to database tables**.\n\nKey concepts include:\n- **Entities** – Java classes that represent database tables\n- **Attributes** – Fields in the class that correspond to table columns\n- **Relationships** – Associations between entities, such as one-to-many or many-to-many\n\nThis process is known as **Object-Relational Mapping (ORM)**.  \nBefore JPA, the term ORM was commonly used to describe frameworks like **Hibernate**, which is why Hibernate is often referred to as an ORM framework.\n\n\n## Important Concepts in JPA\n\n![Image](/images/JPA_02_Architecture.png \"JPA Architecuture\")\n\n**JPA** allows you to map application classes directly to database tables.\n\n- **Entity Manager** – Once mappings are defined, the Entity Manager manages your entities and handles all interactions with the database.\n- **JPQL (Java Persistence Query Language)** – Provides a way to write queries against entities. Unlike SQL, JPQL understands the mappings between entities and tables, allowing you to add conditions as needed.\n- **Criteria API** – Offers a Java-based API to build and execute queries programmatically against the database.\n\n## JPA vs Hibernate\n\n**Hibernate** is one of the most popular **ORM frameworks**.\n\n**JPA** defines the **specification** and provides an **API**, answering key questions like:\n- How do you define entities?\n- How do you map attributes?\n- How do you map relationships between entities?\n- Who manages the entities?\n\n**Hibernate** is a widely used implementation of JPA:\n- It understands the mappings defined between objects and database tables, ensuring that data is stored and retrieved correctly.\n- Hibernate also offers additional features beyond JPA. However, relying on these features creates a **vendor lock-in**, making it difficult to switch to other JPA implementations such as TopLink.\n\n\n## Examples of JPA Mappings\n\nLet’s look at a few examples to understand how **JPA** can be used to map objects to database tables.\n\n#### Example 1\n\nSuppose we have a `Task` class that we want to map to a `Task` table. There may be differences in column names between the class and the table. JPA provides annotations to handle this mapping:\n\n- `@Table(name = \"Task\")` – Maps the class to the database table.\n- `@Id` – Marks the primary key of the entity.\n- `@GeneratedValue` – Specifies that the primary key value will be generated automatically.\n- `@Column(name = \"description\")` – Maps the class attribute to a specific column in the table.\n\n\n```java\nimport jakarta.persistence.Column;\nimport jakarta.persistence.Entity;\nimport jakarta.persistence.GeneratedValue;\nimport jakarta.persistence.GenerationType;\nimport jakarta.persistence.Id;\nimport jakarta.persistence.ManyToMany;\nimport jakarta.persistence.Table;\n\n@Entity\n@Table(name = \"Task\")\npublic class Task {\n    @Id\n    @GeneratedValue\n    private int id;\n\n    @Column(name = \"description\")\n    private String desc;\n\n    @Column(name = \"target_date\")\n    private Date targetDate;\n\n    @Column(name = \"is_done\")\n    private boolean isDone;\n\n}\n```\n\n```sql\n CREATE TABLE task\n (\n     id          INTEGER GENERATED BY DEFAULT AS IDENTITY,\n     description VARCHAR(255),\n     is_done     BOOLEAN,\n     target_date TIMESTAMP,\n     PRIMARY KEY (id)\n ) \n```\n\n#### Example 2\n\nRelationships between objects are expressed differently than relationships between database tables.\n\nFor example:\n- Each `Employee` can have multiple `Tasks`.\n- Each `Task` can be associated with multiple `Employees`.\n\nThis creates a **many-to-many relationship**, which can be mapped in JPA using the `@ManyToMany` annotation.\n\n\n```java\npublic class Employee {\n\n    //Some other code\n\n    @ManyToMany\n    private List<Task> tasks;\n}\n\npublic class Task {\n\n    //Some other code\n\n    @ManyToMany(mappedBy = \"tasks\")\n    private List<Employee> employees;\n}\n```\n\n```sql\nCREATE TABLE employee\n(\n    id BIGINT NOT NULL,\n    OTHER_COLUMNS\n)\n\n\nCREATE TABLE employee_tasks\n(\n    employees_id BIGINT  NOT NULL,\n    tasks_id     INTEGER NOT NULL\n)\n\nCREATE TABLE task\n(\n    id INTEGER GENERATED BY DEFAULT AS IDENTITY,\n    OTHER_COLUMNS\n)\n\n```\n\n#### Example 3\n\nSometimes, multiple classes need to be mapped to a single table, or a single class needs to be mapped across multiple tables.  \nIn such cases, we define an **inheritance strategy**.\n\nFor example, the strategy `InheritanceType.SINGLE_TABLE` maps an entire class hierarchy to a **single database table**.\n\n```java\n\n@Entity\n@Inheritance(strategy = InheritanceType.SINGLE_TABLE)\n@DiscriminatorColumn(name = \"EMPLOYEE_TYPE\")\npublic class Employee {\n    //Other Employee Attributes\n}\n\npublic class FullTimeEmployee extends Employee {\n    protected Integer salary;\n}\n\npublic class PartTimeEmployee extends Employee {\n    protected Float hourlyWage;\n}\n```\n\nTables\n\n```sql\nCREATE TABLE employee\n(\n    employee_type VARCHAR(31) NOT NULL,\n    id            BIGINT      NOT NULL,\n    city          VARCHAR(255),\n    state         VARCHAR(255),\n    street        VARCHAR(255),\n    zip           VARCHAR(255),\n\n    hourly_wage   FLOAT,   --PartTimeEmployee\n\n    salary        INTEGER, --FullTimeEmployee\n\n    PRIMARY KEY (id)\n)\n\n```\n\n## Step-by-Step Code Example\n\n### Bootstrapping a Web application with Spring Initializr\n\nCreating a JPA application with Spring Initializr is very simple.\n\n![Image](/images/Spring-Initializr-Web.png \"Web, Actuator and Developer Tools\")\n\nAs shown in the image above, follow these steps to create your Spring Boot project:\n\n- Launch **Spring Initializr**: [http://start.spring.io/](http://start.spring.io/){:target=\"_blank\"}\n    - Set **Group** to `com.in28minutes.springboot`\n    - Set **Artifact** to `H2InMemoryDbDemo`\n    - Add the following **dependencies**:\n        - **Web**\n        - **JPA**\n        - **H2** – an in-memory database used for this example\n- Click the **Generate** button at the bottom of the page.\n- Import the generated project into **Eclipse**.\n\n#### Project Structure\n\n- **H2InMemoryDbDemoApplication.java** – Spring Boot launcher that initializes Auto Configuration and the Application Context.\n- **application.properties** – Application configuration file.\n- **H2InMemoryDbDemoApplicationTests.java** – Simple launcher for unit testing.\n- **pom.xml** – Includes dependencies for Spring Boot Starter Web and Data JPA, and uses Spring Boot Starter Parent as the parent POM.\n\nImportant dependencies are listed below.\n\n\n```xml\n\n<dependency>\n    <groupId>org.springframework.boot</groupId>\n    <artifactId>spring-boot-starter-web</artifactId>\n</dependency>\n\n<dependency>\n    <groupId>org.springframework.boot</groupId>\n    <artifactId>spring-boot-starter-data-jpa</artifactId>\n</dependency>\n\n<dependency>\n    <groupId>com.h2database</groupId>\n    <artifactId>h2</artifactId>\n    <scope>runtime</scope>\n</dependency>\n\n<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-h2console -->\n<dependency>\n    <groupId>org.springframework.boot</groupId>\n    <artifactId>spring-boot-h2console</artifactId>\n    <version>4.0.0-M1</version> // you can it in if you're creating a Spring Boot application\n</dependency>\n```\n\n### User Entity\n\nLet's define a bean user and add the appropriate JPA annotations.\n\n```java\npackage com.example.h2.user;\n\nimport jakarta.persistence.Entity;\nimport jakarta.persistence.GeneratedValue;\nimport jakarta.persistence.GenerationType;\nimport jakarta.persistence.Id;\nimport jakarta.persistence.NamedQuery;\n\n@Entity\n@NamedQuery(query = \"select u from User u\", name = \"query_find_all_users\")\npublic class User {\n\n    @Id\n    @GeneratedValue(strategy = GenerationType.AUTO)\n    private Long id;\n\n    private String name;// Not perfect!! Should be a proper object!\n\n    private String role;// Not perfect!! An enum should be a better choice!\n\n    protected User() {\n    }\n\n    public User(String name, String role) {\n        super();\n        this.name = name;\n        this.role = role;\n    }\n\n}\n```\n\n### Important Annotations and Concepts\n\n- `@Entity` – Specifies that the class is a JPA entity. Apply this annotation to the entity class.\n- `@NamedQuery` – Defines a static, named query in **Java Persistence Query Language (JPQL)**.\n- `@Id` – Marks the primary key of an entity.\n- `@GeneratedValue` – Specifies how the primary key value should be automatically generated.\n- `protected User()` – Default constructor required by JPA to instantiate the entity.\n\n\n## User Service to Interact with the Entity Manager\n\nWith JPA, it is common to create a **service layer** to interact with the **Entity Manager**.  \nIn this example, we create a `UserService` to manage the persistence operations for the `User` entity.\n\n\n```java\n\n@Repository\n@Transactional\npublic class UserService {\n\n    @PersistenceContext\n    private EntityManager entityManager;\n\n    public long insert(User user) {\n        entityManager.persist(user);\n        return user.getId();\n    }\n\n    public User find(long id) {\n        return entityManager.find(User.class, id);\n    }\n\n    public List<User> findAll() {\n        Query query = entityManager.createNamedQuery(\n                \"query_find_all_users\", User.class);\n        return query.getResultList();\n    }\n}\n```\n\n### Important Annotations and Concepts\n\n- `@Repository` – A Spring annotation indicating that this component is responsible for **data access** and interacting with a data store.\n- `@Transactional` – A Spring annotation that simplifies **transaction management**.\n- `@PersistenceContext` – Injects a **persistence context**, which manages a set of entities and tracks their states (e.g., managed, detached) in relation to the underlying database.\n- `EntityManager` – The interface used to interact with the **persistence context**.\n- `entityManager.persist(user)` – Makes the `user` entity **managed and persistent**, i.e., saves it to the database.\n- `entityManager.createNamedQuery` – Creates a **TypedQuery** to execute a JPQL **named query**. The second parameter specifies the expected result type.\n\n> An **EntityManager** instance is associated with a **persistence context**.  \n> A persistence context is a set of entity instances in which each persistent entity identity corresponds to a unique entity instance.  \n> Within this context, the lifecycle of entities is managed. The **EntityManager API** is used to create and remove persistent entities, find entities by their primary key, and execute queries over entities.\n\n> The set of entities managed by an EntityManager is defined by a **persistence unit**.  \n> A persistence unit specifies all classes related or grouped by the application that must be mapped to a single database.\n\n---\n\n## CommandLineRunner for User Entity Manager\n\nThe **CommandLineRunner** interface is used to indicate that a Spring bean should run **as soon as the application context is initialized**.\n\nIn this example, we execute a few simple methods on the `UserService` to demonstrate entity persistence and queries.\n\n```java\n\n@Component\npublic class UserEntityManagerCommandLineRunner implements CommandLineRunner {\n\n    private static final Logger log = LoggerFactory.getLogger(UserEntityManagerCommandLineRunner.class);\n\n    @Autowired\n    private UserService userService;\n\n    @Override\n    public void run(String... args) {\n\n        log.info(\"-------------------------------\");\n        log.info(\"Adding Tom as Admin\");\n        log.info(\"-------------------------------\");\n        User tom = new User(\"Tom\", \"Admin\");\n        userService.insert(tom);\n        log.info(\"Inserted Tom\" + tom);\n\n        log.info(\"-------------------------------\");\n        log.info(\"Finding user with id 1\");\n        log.info(\"-------------------------------\");\n        User user = userService.find(1L);\n        log.info(user.toString());\n\n        log.info(\"-------------------------------\");\n        log.info(\"Finding all users\");\n        log.info(\"-------------------------------\");\n        log.info(userService.findAll().toString());\n    }\n}\n```\n\n### Important Things to Note\n\n- `@Autowired private UserService userService` – The `UserService` is automatically injected by Spring.\n- The remaining setup and configuration are straightforward.\n\n---\n\n## Spring Data JPA\n\n**Spring Data JPA** provides a consistent and simplified model for accessing data from different types of data stores.\n\nThe `UserService` we created earlier contains some redundant code that can be generalized. **Spring Data JPA** helps reduce boilerplate code and simplifies data access.\n\n\n```java\n\n@Repository\n@Transactional\npublic class UserService {\n\n    @PersistenceContext\n    private EntityManager entityManager;\n\n    public long insert(User user) {\n        entityManager.persist(user);\n        return user.getId();\n    }\n\n    public User find(long id) {\n        return entityManager.find(User.class, id);\n    }\n\n    public List<User> findAll() {\n        Query query = entityManager.createNamedQuery(\n                \"query_find_all_users\", User.class);\n        return query.getResultList();\n    }\n}\n```\n\nAs far as **JPA** is concerned, there are two key **Spring Data** modules to know:\n\n- **Spring Data Commons** – Defines concepts that are shared across all Spring Data modules.\n- **Spring Data JPA** – Provides easy integration with **JPA repositories**.\n\n---\n\n### CrudRepository\n\n**CrudRepository** is a core repository interface provided by **Spring Data Commons**.  \nIt enables basic CRUD operations on a repository. Some important methods include:\n\n\n```java\npublic interface CrudRepository<T, ID extends Serializable> extends Repository<T, ID> {\n\n    <S extends T> S save(S entity);\n\n    T findOne(ID primaryKey);\n\n    Iterable<T> findAll();\n\n    Long count();\n\n    void delete(T entity);\n\n    boolean exists(ID primaryKey);\n\n    // … more functionality omitted.\n}\n```\n\n### JpaRepository\n\n**JpaRepository**, provided by **Spring Data JPA**, is a JPA-specific repository interface that extends `CrudRepository`.  \nIt offers additional JPA-related methods, such as flushing changes to the database and batch operations, while retaining all CRUD functionalities.\n\n\n```java\npublic interface JpaRepository<T, ID extends Serializable>\n        extends PagingAndSortingRepository<T, ID>, QueryByExampleExecutor<T> {\n```\n\nWe will now use **JpaRepository** to manage the `User` entity.\n\nThe key idea is to create a **UserRepository** that manages `User` entities, where the primary key is of type `Long`.  \nThe snippet below highlights the important details for defining this repository.\n\n\n```java\npackage com.example.h2.user;\n\nimport org.springframework.data.jpa.repository.JpaRepository;\n\npublic interface UserRepository extends JpaRepository<User, Long> {\n}\n```\n\n### User Repository: CommandLineRunner\n\nThe following code is straightforward. The **CommandLineRunner** interface indicates that this bean should run **as soon as the Spring application context is initialized**.\n\nIn this example, we execute a few simple methods on the **UserRepository** to demonstrate basic CRUD operations.\n\n\n```java\npackage com.example.h2;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.CommandLineRunner;\nimport org.springframework.stereotype.Component;\n\nimport com.example.h2.user.User;\nimport com.example.h2.user.UserRepository;\n\n@Component\npublic class UserRepositoryCommandLineRunner implements CommandLineRunner {\n\n    private static final Logger log = LoggerFactory.getLogger(UserRepositoryCommandLineRunner.class);\n\n    @Autowired\n    private UserRepository userRepository;\n\n    @Override\n    public void run(String... args) {\n        User harry = new User(\"Harry\", \"Admin\");\n        userRepository.save(harry);\n        log.info(\"-------------------------------\");\n        log.info(\"Finding all users\");\n        log.info(\"-------------------------------\");\n        for (User user : userRepository.findAll()) {\n            log.info(user.toString());\n        }\n    }\n\n}\n```\n\n### Important Things to Note\n\n- `@Autowired private UserRepository userRepository` – The `UserRepository` is automatically injected by Spring.\n- The rest of the setup is straightforward.\n\n---\n\n### H2 Console\n\nEnable the H2 console in `/src/main/resources/application.properties`:\n\n```properties\nspring.h2.console.enabled=true\n```\n\nStart the application by running H2InMemoryDbDemoApplication as a Java application.\n\nThe H2-Console can also be accessed via the web browser.\n\n- http://localhost:8080/h2-console\n- Use db url jdbc:h2:mem:testdb\n\n### Questions\n\n- **Where was the database created?**\n    - In memory, using H2.\n\n- **What schema is used to create the tables?**\n    - Tables are created automatically based on the entity definitions.\n\n- **Where are the tables created?**\n    - In memory, using H2, based on the entity definitions.\n\n- **Can I see the data in the database?**\n    - http://localhost:8080/h2-console\n    - Use db url jdbc:h2:mem:testdb\n- **Where is Hibernate coming from?**\n    - Provided by the **Spring Data JPA Starter**.\n\n- **How is a data source created?**\n    - Automatically configured through **Spring Boot Auto Configuration**.\n\n\n### Spring Boot's Magic with In-Memory Databases\n\n- No project setup or additional infrastructure required.\n- Zero configuration.\n- Minimal maintenance.\n- Easy to use for learning and unit testing.\n- Simple to switch to a real database with minimal configuration.\n\n---\n\n### Restrictions of Using In-Memory Databases\n\n- Data is **not persisted** between application restarts.\n\n\n## Complete Code Example\n\n### /pom.xml\n\n```xml\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n         xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n    <modelVersion>4.0.0</modelVersion>\n\n    <groupId>com.example</groupId>\n    <artifactId>jpa-in-10-steps</artifactId>\n    <version>0.0.1-SNAPSHOT</version>\n    <packaging>jar</packaging>\n\n    <name>jpa-with-in-memory-db-in-10-steps</name>\n    <description>Demo project for in memory database H2</description>\n\n    <parent>\n        <groupId>org.springframework.boot</groupId>\n        <artifactId>spring-boot-starter-parent</artifactId>\n        <version>4.0.0-M2</version>\n        <relativePath/> <!-- lookup parent from repository -->\n    </parent>\n\n    <properties>\n        <java.version>21</java.version>\n    </properties>\n\n    <dependencies>\n        <dependency>\n            <groupId>org.springframework.boot</groupId>\n            <artifactId>spring-boot-starter-web</artifactId>\n        </dependency>\n\n        <dependency>\n            <groupId>org.springframework.boot</groupId>\n            <artifactId>spring-boot-starter-data-jpa</artifactId>\n        </dependency>\n\n        <dependency>\n            <groupId>com.h2database</groupId>\n            <artifactId>h2</artifactId>\n            <scope>runtime</scope>\n        </dependency>\n\n        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-h2console -->\n        <dependency>\n            <groupId>org.springframework.boot</groupId>\n            <artifactId>spring-boot-h2console</artifactId>\n        </dependency>\n\n        <dependency>\n            <groupId>org.springframework.boot</groupId>\n            <artifactId>spring-boot-starter-test</artifactId>\n            <scope>test</scope>\n        </dependency>\n\n    </dependencies>\n\n    <build>\n        <plugins>\n            <plugin>\n                <groupId>org.springframework.boot</groupId>\n                <artifactId>spring-boot-maven-plugin</artifactId>\n            </plugin>\n        </plugins>\n    </build>\n    \n</project>\n```\n\n---\n\n### /src/main/java/com/example/h2/H2InMemoryDbDemoApplication.java\n\n```java\npackage com.example.h2;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\n@SpringBootApplication\npublic class H2InMemoryDbDemoApplication {\n\n    static void main(String[] args) {\n        SpringApplication.run(H2InMemoryDbDemoApplication.class, args);\n    }\n}\n```\n\n---\n\n### /src/main/java/com/example/h2/user/User.java\n\n```java\npackage com.example.h2.user;\n\nimport jakarta.persistence.Entity;\nimport jakarta.persistence.GeneratedValue;\nimport jakarta.persistence.GenerationType;\nimport jakarta.persistence.Id;\nimport jakarta.persistence.NamedQuery;\n\n@Entity\n@NamedQuery(query = \"select u from User u\", name = \"query_find_all_users\")\npublic class User {\n\n    @Id\n    @GeneratedValue(strategy = GenerationType.AUTO)\n    private Long id;\n\n    private String name;// Not perfect!! Should be a proper object!\n    private String role;// Not perfect!! An enum should be a better choice!\n\n    protected User() {\n    }\n\n    public User(String name, String role) {\n        super();\n        this.name = name;\n        this.role = role;\n    }\n\n    public Long getId() {\n        return id;\n    }\n\n    public String getName() {\n        return name;\n    }\n\n    public String getRole() {\n        return role;\n    }\n\n    @Override\n    public String toString() {\n        return String.format(\"User [id=%s, name=%s, role=%s]\", id, name, role);\n    }\n\n}\n```\n\n---\n\n### /src/main/java/com/example/h2/user/UserRepository.java\n\n```java\npackage com.example.h2.user;\n\nimport org.springframework.data.jpa.repository.JpaRepository;\n\npublic interface UserRepository extends JpaRepository<User, Long> {\n}\n```\n\n---\n\n### /src/main/java/com/example/h2/user/UserService.java\n\n```java\npackage com.example.h2.user;\n\nimport java.util.List;\n\nimport jakarta.persistence.EntityManager;\nimport jakarta.persistence.PersistenceContext;\nimport jakarta.persistence.Query;\nimport jakarta.transaction.Transactional;\n\nimport org.springframework.stereotype.Repository;\n\n@Repository\n@Transactional\npublic class UserService {\n\n    @PersistenceContext\n    private EntityManager entityManager;\n\n    public long insert(User user) {\n        entityManager.persist(user);\n        return user.getId();\n    }\n\n    public User find(long id) {\n        return entityManager.find(User.class, id);\n    }\n\n    public List<User> findAll() {\n        Query query = entityManager.createNamedQuery(\n                \"query_find_all_users\", User.class);\n        return query.getResultList();\n    }\n}\n```\n\n---\n\n### /src/main/java/com/example/h2/UserEntityManagerCommandLineRunner.java\n\n```java\npackage com.example.h2;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.CommandLineRunner;\nimport org.springframework.stereotype.Component;\n\nimport com.example.h2.user.User;\nimport com.example.h2.user.UserService;\n\n@Component\npublic class UserEntityManagerCommandLineRunner implements CommandLineRunner {\n\n    private static final Logger log = LoggerFactory.getLogger(UserEntityManagerCommandLineRunner.class);\n\n    @Autowired\n    private UserService userService;\n\n    @Override\n    public void run(String... args) {\n\n        log.info(\"-------------------------------\");\n        log.info(\"Adding Tom as Admin\");\n        log.info(\"-------------------------------\");\n        User tom = new User(\"Tom\", \"Admin\");\n        userService.insert(tom);\n        log.info(\"Inserted Tom\" + tom);\n\n        log.info(\"-------------------------------\");\n        log.info(\"Finding user with id 1\");\n        log.info(\"-------------------------------\");\n        User user = userService.find(1L);\n        log.info(user.toString());\n\n        log.info(\"-------------------------------\");\n        log.info(\"Finding all users\");\n        log.info(\"-------------------------------\");\n        log.info(userService.findAll().toString());\n    }\n}\n```\n\n---\n\n### /src/main/java/com/example/h2/UserRepositoryCommandLineRunner.java\n\n```java\npackage com.example.h2;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.CommandLineRunner;\nimport org.springframework.stereotype.Component;\n\nimport com.example.h2.user.User;\nimport com.example.h2.user.UserRepository;\n\n@Component\npublic class UserRepositoryCommandLineRunner implements CommandLineRunner {\n\n    private static final Logger log = LoggerFactory.getLogger(UserRepositoryCommandLineRunner.class);\n\n    @Autowired\n    private UserRepository userRepository;\n\n    @Override\n    public void run(String... args) {\n        User harry = new User(\"Harry\", \"Admin\");\n        userRepository.save(harry);\n        log.info(\"-------------------------------\");\n        log.info(\"Finding all users\");\n        log.info(\"-------------------------------\");\n        for (User user : userRepository.findAll()) {\n            log.info(user.toString());\n        }\n    }\n\n}\n```\n\n---\n\n### /src/main/resources/application.properties\n\n```properties\nspring.h2.console.enabled=true\n#logging.level.org.hibernate=debug\nspring.jpa.show-sql=true\nspring.datasource.url=jdbc:h2:mem:testdb;NON_KEYWORDS=USER\nspring.data.jpa.repositories.bootstrap-mode=default\nspring.jpa.defer-datasource-initialization=true\n```\n\n---\n\n### /src/main/resources/data.sql\n\n```sql\ninsert into user (id, name, role) values (101, 'Ranga', 'Admin');\ninsert into user (id, name, role) values (102, 'Ravi', 'User');\ninsert into user (id, name, role) values (103, 'Satish', 'Admin');\n```\n\n---\n\n### /src/test/java/com/example/h2/H2InMemoryDbDemoApplicationTests.java\n\n```java\npackage com.example.h2;\n\nimport org.junit.jupiter.api.Test;\nimport org.junit.jupiter.api.extension.ExtendWith;\nimport org.springframework.boot.test.context.SpringBootTest;\nimport org.springframework.test.context.junit.jupiter.SpringExtension;\n\n@ExtendWith(SpringExtension.class)\n@SpringBootTest\npublic class H2InMemoryDbDemoApplicationTests {\n\n    @Test\n    public void contextLoads() {\n    }\n\n}\n```\n\n---\n\n### /src/test/java/com/example/h2/user/UserRepositoryTest.java\n\n```java\npackage com.example.h2.user;\n\nimport static org.junit.Assert.assertEquals;\n\nimport org.junit.jupiter.api.Test;\nimport org.junit.jupiter.api.extension.ExtendWith;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;\nimport org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;\nimport org.springframework.test.context.junit.jupiter.SpringExtension;\n\nimport com.example.h2.user.UserRepository;\n\n@DataJpaTest\n@ExtendWith(SpringExtension.class)\npublic class UserRepositoryTest {\n\n    @Autowired\n    UserRepository userRepository;\n\n    @Autowired\n    TestEntityManager entityManager;\n\n    @Test\n    public void check_todo_count() {\n        assertEquals(3, userRepository.count());\n    }\n}\n```\n\n---\n"
  },
  {
    "path": "_blog/articles/2017-07-06-introduction-to-web-services-restful-and-soap.md",
    "content": "---\nlayout: post\ntitle: Introduction to Web Services - Restful and SOAP\ndate: 2025-09-16 12:31:19\nsummary: Introduction to Web Services - Restful and SOAP, This tutorial will help you understand the basics of web services and the different kinds of web services - REST and SOAP.\ncategories: SwArchitecture\npermalink: /introduction-to-web-services-with-soap-and-rest\nimage: /images/spring-boot-application.png\n---\n\nIn this tutorial, you’ll learn the fundamentals of web services and explore the two primary types—REST and SOAP.\n\n## You will learn\n\n- What web services are\n- The advantages of using web services\n- The main types of web services\n- An introduction to RESTful web services\n- An introduction to SOAP web services\n\n## You will require the following tools:\n\n- **Maven 3.0+** as the build tool\n- **JDK 17+** for running Java applications\n- **An IDE of your choice** (e.g., Eclipse or IntelliJ IDEA)\n\n# What is a Web Service?\n\n> **Service delivered over the web**\n\nIs this really a complete definition?  \nDoes everything delivered over the web qualify as a *web service*?\n\nFor example, consider a web application we developed in our Spring MVC course to manage to-dos.\n\n![Image](/images/Web_Services_Web_Application_To_Manage_Todos.png)\n\n## Is this application a web service?\n\n> Nope. The answer is no. This is a **web application**, not a web service.\n\nSo, we are back to square one:\n\n- What is a web service?\n- How is it different from a web application?\n\n---\n\n## Understanding the difference\n\nLet’s consider an example:\n\nMark Zuckerberg likes the **To-Do application** we developed in our Spring MVC course. He believes it’s a perfect fit to\nintegrate into Facebook so users can manage their tasks directly inside Facebook.\n\nCan we use the existing application for this integration? **No.**\n\n### Why not?\n\nBecause the current application is designed for **humans**.\n\n- Its output is **HTML**, which is rendered by the browser.\n- It is not designed for other **applications** to consume.\n\n---\n\n## Thinking differently\n\nWhat if I wanted to design the To-Do application so that **other applications** could interact with it?\n\n> I would need to produce the output in a format that other systems could understand. Then, Facebook could call my web\n> service and integrate with it.\n\n---\n\n## W3C Definition of a Web Service\n\n> **A software system designed to support interoperable machine-to-machine interaction over a network.**\n\n---\n\n## Key Takeaways\n\n- Web services are designed for **machine-to-machine (or application-to-application)** interaction.\n- They are **interoperable**, meaning not tied to a single platform or technology.\n- They enable **communication over a network**.\n\n---\n\n## Web Service Data Exchange Formats\n\nNow, let’s revisit our example:\n\nFacebook wants to talk to the To-Do application.\n\n- Facebook uses multiple technologies: PHP (frontend), Erlang (chat), Java and C++ (backend).\n- The To-Do application is built with **Java (Spring MVC)**.\n\nEven though these systems use **different technologies**, we still want them to communicate. That’s where **standard\ndata exchange formats** come in—allowing seamless interaction between diverse platforms.\n\n![Image](/images/Web_Service_Basic_Interaction.png)\n\n## Requests and Responses\n\nBoth applications must be able to understand the **request** and the **response**.\n\nSo, what formats should we use?\n\n> They should be **standard formats** so that they can work across different platforms.  \n> JSON and XML are the most popular data exchange formats.\n\n---\n\n## Types of Web Services\n\nThis is more of a **broad classification** rather than strict types:\n\n- **SOAP**\n- **REST**\n\nThese are not always mutually exclusive. Some SOAP services can also be RESTful.\n\nSo the key question is:\n\n> When does a web service become a SOAP web service or a RESTful web service?\n\n---\n\n### SOAP\n\nSOAP originally stood for **Simple Object Access Protocol**.\n\n- SOAP requests and responses are always in **XML format**.\n- But not every XML is valid SOAP. SOAP defines its own standard XML structure.\n- WSDL (Web Service Definition Language) is used to describe the format of the request and response.\n\nIf Facebook wanted to call the **To-Do service**, what would we give their developers?\n\nWe would provide the **WSDL file**, which explains:\n\n- The different operations (services) exposed by the server\n- The endpoint (URL) to use for each operation\n- The structure of the request XML\n- The structure of the response XML\n\n#### SOAP Message Structure\n\nA SOAP message is wrapped inside a **SOAP-Envelope**:\n\n- **SOAP-Header** (optional): Metadata such as authentication, authorization, or encryption info\n- **SOAP-Body**: The actual request/response content\n- **SOAP-Fault**: Error messages returned in case of failure\n\n---\n\n### REST\n\nUnlike SOAP, **REST does not define a standard message format**.\n\n- REST services can use **XML** or **JSON** (JSON is more popular).\n\nSo, what exactly is REST?\n\n> REST is an **architectural style** for distributed systems, based on the idea of **resources**.\n\n#### Key Concepts\n\n- **Resource**: Anything that can be identified—e.g., a todo item, a Facebook user\n- **Resource URI**: Identifies a resource\n    - `/user/Ranga/todos/1`\n    - `/person/Ranga`\n- **Resource Representation**: Describes the resource’s current state (XML, JSON, HTML)\n\nWhen a resource is requested, its **representation** is returned.\n\n---\n\n#### REST and HTTP\n\nREST is built on top of **HTTP (the language of the web)**.\n\n**HTTP Methods (Verbs):**\n\n- **POST** – Create a new resource\n- **GET** – Read a resource\n- **PUT** – Update an existing resource\n- **DELETE** – Delete a resource\n\n**HTTP Response Codes:**\n\n- `200` – SUCCESS\n- `201` – CREATED\n- `400` – BAD REQUEST\n- `401` – UNAUTHORIZED\n- `404` – RESOURCE NOT FOUND\n- `415` – UNSUPPORTED TYPE\n- `500` – SERVER ERROR\n\n---\n\n#### REST Constraints\n\n- **Client-Server**: Clear separation of consumer and provider\n- **Uniform Interface**: Resources exposed through consistent URIs (nouns, not actions)\n- **Stateless**: Each request is independent, no session data stored on the server\n- **Cacheable**: Responses can be cached (e.g., HTTP cache)\n- **Layered System**: Clients should not assume a direct connection to the server; intermediaries may exist\n\n---\n\n### Richardson Maturity Model\n\nThe **Richardson Maturity Model** defines the maturity of REST services:\n\n- **Level 0**: Use REST endpoints but keep action-based URIs (e.g., `/getPosts`, `/deletePosts`)\n- **Level 1**: Use resources with proper URIs (`/accounts`, `/accounts/10`) but ignore HTTP methods\n- **Level 2**: Use proper URIs **and** HTTP methods (`PUT /accounts/1`, `POST /accounts`)\n- **Level 3**: HATEOAS (Hypermedia as the Engine of Application State) – responses include links to possible next\n  actions\n\n---\n\n### Designing RESTful APIs\n\nWhen designing REST APIs, keep these points in mind:\n\n- Focus on the **API consumer**: Does the request/response format make sense for them?\n- Use **nouns (resources)** in URIs, not verbs. Prefer plurals.\n- Use **hierarchical and self-descriptive URIs**.\n- Always use the correct **HTTP methods**:\n    - **GET** – Read (idempotent, multiple calls = same result)\n    - **POST** – Create (returns `201 Created`, often with link to new resource)\n    - **PUT** – Update (returns `200 OK`)\n    - **DELETE** – Remove (returns `200 OK` or `204 No Content`)\n\n---\n\n## REST vs SOAP\n\n- **REST** is an **architectural style**.\n- **SOAP** is a **protocol/message format**.\n\n**Typical implementations:**\n\n- RESTful services: JSON over HTTP\n- SOAP services: XML over SOAP over HTTP\n\n**Key Comparisons:**\n\n- REST is **simpler** to implement and consume.\n- REST offers better **performance and scalability** (caching supported).\n- REST supports multiple formats (JSON, XML, etc.); SOAP only uses XML.\n- SOAP has **strict standards** (WSDL, WS-Security, WS-ReliableMessaging). REST documentation is evolving (\n  Swagger/OpenAPI).\n\n---\n\n## Advantages of Web Services\n\n- **Reuse**: Facebook doesn’t need to build its own To-Do app—just reuse ours.\n- **Modularity**: Applications can be broken into smaller, independent services.\n- **Language Neutrality**: Services can be consumed across different languages and platforms.\n\nWeb services are the foundation of **SOA (Service-Oriented Architecture)** and **Microservices architectures**.\n\n## SOAP Service Examples\n\n### Request\n\n```xml\n\n<Envelope xmlns=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <Body>\n        <getCourseDetailsRequest xmlns=\"http://in28minutes.com/courses\">\n            <id>Course1</id>\n        </getCourseDetailsRequest>\n    </Body>\n</Envelope>\n```\n\n### Response\n\n```xml\n\n<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <SOAP-ENV:Header/>\n    <SOAP-ENV:Body>\n        <ns2:getCourseDetailsResponse xmlns:ns2=\"http://in28minutes.com/courses\">\n            <ns2:course>\n                <ns2:id>Course1</ns2:id>\n                <ns2:name>Spring</ns2:name>\n                <ns2:description>10 Steps</ns2:description>\n            </ns2:course>\n        </ns2:getCourseDetailsResponse>\n    </SOAP-ENV:Body>\n</SOAP-ENV:Envelope>\n```\n\n### Fault\n\n```xml\n\n<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <SOAP-ENV:Header/>\n    <SOAP-ENV:Body>\n        <SOAP-ENV:Fault>\n            <faultcode>SOAP-ENV:Server</faultcode>\n            <faultstring xml:lang=\"en\">java.lang.NullPointerException</faultstring>\n        </SOAP-ENV:Fault>\n    </SOAP-ENV:Body>\n</SOAP-ENV:Envelope>\n```\n\n### WSDL\n\n- view-source:http://localhost:8080/ws/courses.wsdl\n\n```xml\n<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n<wsdl:definitions xmlns:wsdl=\"http://schemas.xmlsoap.org/wsdl/\" xmlns:sch=\"http://in28minutes.com/courses\"\n                  xmlns:soap=\"http://schemas.xmlsoap.org/wsdl/soap/\" xmlns:tns=\"http://in28minutes.com/courses\"\n                  targetNamespace=\"http://in28minutes.com/courses\">\n    <wsdl:types>\n        <xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" elementFormDefault=\"qualified\"\n                   targetNamespace=\"http://in28minutes.com/courses\">\n\n            <xs:element name=\"getCourseDetailsRequest\">\n                <xs:complexType>\n                    <xs:sequence>\n                        <xs:element name=\"id\" type=\"xs:string\"/>\n                    </xs:sequence>\n                </xs:complexType>\n            </xs:element>\n\n            <xs:element name=\"getCourseDetailsResponse\">\n                <xs:complexType>\n                    <xs:sequence>\n                        <xs:element name=\"course\" type=\"tns:course\"/>\n                    </xs:sequence>\n                </xs:complexType>\n            </xs:element>\n\n            <xs:complexType name=\"course\">\n                <xs:sequence>\n                    <xs:element name=\"id\" type=\"xs:string\"/>\n                    <xs:element name=\"name\" type=\"xs:string\"/>\n                    <xs:element name=\"description\" type=\"xs:string\"/>\n                </xs:sequence>\n            </xs:complexType>\n        </xs:schema>\n    </wsdl:types>\n    <wsdl:message name=\"getCourseDetailsRequest\">\n        <wsdl:part element=\"tns:getCourseDetailsRequest\" name=\"getCourseDetailsRequest\">\n        </wsdl:part>\n    </wsdl:message>\n    <wsdl:message name=\"getCourseDetailsResponse\">\n        <wsdl:part element=\"tns:getCourseDetailsResponse\" name=\"getCourseDetailsResponse\">\n        </wsdl:part>\n    </wsdl:message>\n    <wsdl:portType name=\"CoursesPort\">\n        <wsdl:operation name=\"getCourseDetails\">\n            <wsdl:input message=\"tns:getCourseDetailsRequest\" name=\"getCourseDetailsRequest\">\n            </wsdl:input>\n            <wsdl:output message=\"tns:getCourseDetailsResponse\" name=\"getCourseDetailsResponse\">\n            </wsdl:output>\n        </wsdl:operation>\n    </wsdl:portType>\n    <wsdl:binding name=\"CoursesPortSoap11\" type=\"tns:CoursesPort\">\n        <soap:binding style=\"document\" transport=\"http://schemas.xmlsoap.org/soap/http\"/>\n        <wsdl:operation name=\"getCourseDetails\">\n            <soap:operation soapAction=\"\"/>\n            <wsdl:input name=\"getCourseDetailsRequest\">\n                <soap:body use=\"literal\"/>\n            </wsdl:input>\n            <wsdl:output name=\"getCourseDetailsResponse\">\n                <soap:body use=\"literal\"/>\n            </wsdl:output>\n        </wsdl:operation>\n    </wsdl:binding>\n    <wsdl:service name=\"CoursesPortService\">\n        <wsdl:port binding=\"tns:CoursesPortSoap11\" name=\"CoursesPortSoap11\">\n            <soap:address location=\"http://localhost:8080/ws\"/>\n        </wsdl:port>\n    </wsdl:service>\n</wsdl:definitions>\n```\n"
  },
  {
    "path": "_blog/articles/2017-10-11-spring-boot-master-class.md",
    "content": "---\nlayout: post\ntitle: Spring Boot For Beginners in 100 Steps\ndate: 2025-09-18 12:31:19\nsummary: Understand and love the power of Spring Boot - All its features are illustrated developing a web application managing todos and a basic API for survey questionnaire. Also covers unit testing, mocking and integration testing.\ncategories: SpringBoot\npermalink: /spring-boot-for-beginners-and-experts\nimage: /images/generic-category.png\n---\n\nSpring Boot has a lot of **magic** going for it.\n\nDeveloping applications with Spring Boot is both **cool** and **fun**.\n\nIt makes it easy to create **stand-alone, production-grade Spring applications** that you can *just run*.  \nMost Spring Boot applications require **minimal configuration**, letting you focus on business logic rather than\nboilerplate setup.\n\n> You will explore the key concepts of Spring Boot and discover how Starter projects simplify application development.\n\n[![Image](/images/Course-Learn-Spring-Boot-in-100-Steps---Beginner-to-Expert.png \"Learn Spring Boot in 100 Steps - Beginner to Expert\")](https://links.in28minutes.com/MISC-SPRING-BOOT)\n\n## What you will learn\n\nYou will build:\n\n- A web application to manage your to-dos\n- A basic REST service to manage survey questions\n\nThis course is a perfect first step into Spring Boot.\n\n> You will learn Spring Boot step by step — in more than **90** hands-on steps.\n\nYou will work with:\n\n- REST services\n- Spring (dependency management)\n- Spring MVC\n- Spring Boot and Spring Boot Starter projects\n- Spring Security (authentication & authorization)\n- Bootstrap (UI styling)\n- Maven (dependency management)\n- Eclipse (IDE) and embedded Tomcat (web server)\n\nWe’ll help you set up each of these.\n\n### Topics covered\n\n- Basics of Spring Boot\n- Auto-configuration and Spring Boot \"magic\"\n- Spring Boot Starter projects and Spring Initializr\n- DispatcherServlet and request flow\n- Todo management application with login/logout\n- Models, Controllers, ViewResolver, and Filters\n- Forms: data binding and validation\n- Annotation-based handling: `@RequestParam`, `@ModelAttribute`, `@SessionAttributes`, etc.\n- Using Bootstrap to style pages\n- Building REST APIs with Spring Boot Starter Web\n- Content negotiation (JSON and XML)\n- Embedded servlet containers: Tomcat, Jetty, Undertow\n- Unit and integration testing with Spring Boot Starter Test\n- Profiles and dynamic configuration\n- Spring Data JPA\n- Spring Boot Actuator\n- Spring Security essentials and configuration\n- Developer tools and LiveReload\n\n## Getting Started\n\n### Installing Tools\n\n- **Installation Resources**\n    - 🎥 [Video Playlist](https://www.youtube.com/playlist?list=PLBBog2r6uMCSmMVTW_QmDLyASBvovyAO3)\n    -\n  📄 [PDF Guide](https://github.com/in28minutes/SpringIn28Minutes/blob/master/InstallationGuide-JavaEclipseAndMaven_v2.pdf)\n    - 📚 [More Details](https://github.com/in28minutes/getting-started-in-5-steps)\n\n- **Troubleshooting**\n  -\n  🛠️ [Troubleshooting Guide (50 pages, 200+ errors and FAQs answered)](https://github.com/in28minutes/in28minutes-initiatives/blob/master/The-in28Minutes-TroubleshootingGuide-And-FAQ)\n\n### Running Examples\n\n1. Download the ZIP file or clone the Git repository.\n2. Unzip the ZIP file (if you downloaded one).\n3. Open **Command Prompt/Terminal** and navigate (`cd`) to the folder containing `pom.xml`.\n4. Open **Eclipse**:\n    - Go to **File → Import → Existing Maven Project**\n    - Navigate to the folder where you unzipped the project\n    - Select the correct project\n5. Locate the Spring Boot Application file (look for the class annotated with `@SpringBootApplication`).\n6. Right-click the file → **Run As → Java Application**.\n7. ✅ You’re all set!\n8. For\n   help: [Installation Guide (Video Playlist)](https://www.youtube.com/playlist?list=PLBBog2r6uMCSmMVTW_QmDLyASBvovyAO3)\n\n---\n\n## Spring Level 1 to Level 6 — Section Overview\n\nHere’s a quick overview of the different sections of the course:\n\n- **Level 1**: Introduction to Spring in 10 Steps\n- **Level 2**: Develop a Todo Management Web Application in 30 Steps\n- **Level 3**: Introduction to Unit Testing with JUnit in 5 Steps\n- **Level 4**: Introduction to Mocking with Mockito in 5 Steps\n- **Level 5**: Advanced Features of Spring Boot in 25 Steps\n    - Build a simple API for managing a survey questionnaire\n- **Level 6**: Introduction to JPA in 10 Steps\n- **Level 7**: Connect the Todo Management Web Application to JPA\n\n| Title                              |     Category     | Github                                                                                                                                                             |\n|------------------------------------|:----------------:|--------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| Spring Framework in 10 Steps       | Spring - Level 1 | [Project Folder on Github](https://github.com/in28minutes/spring-master-class/tree/master/01-spring-in-depth)                                                      |\n| Spring in Depth                    | Spring - Level 2 | [Project Folder on Github](https://github.com/in28minutes/spring-master-class/tree/master/01-spring-in-depth)                                                      |\n| Unit Testing with Spring Framework | Spring - Level 3 | [Project Folder on Github](https://github.com/in28minutes/spring-master-class/tree/master/01-spring-in-depth)                                                      |\n| Spring Boot in 10 Steps            | Spring - Level 4 | [Project Folder on Github](https://github.com/in28minutes/spring-master-class/tree/master/00-framework-tool-introductions/05.Spring-Boot-Introduction-In-10-Steps) |\n| Spring AOP                         | Spring - Level 5 | [Project Folder on Github](https://github.com/in28minutes/spring-master-class/tree/master/03-spring-aop)                                                           |\n| Spring JDBC and JPA                | Spring - Level 6 | [Project Folder on Github](https://github.com/in28minutes/spring-master-class/tree/master/04-spring-jdbc-to-jpa)                                                   |\n\n## 5 Bonus Sections - Introduction to Tools and Frameworks\n\n| Title                                 |   Category   | Github                                                                                                                                                        |\n|---------------------------------------|:------------:|---------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| Eclipse in 5 Steps                    | Introduction | [Project Folder on Github](https://github.com/in28minutes/spring-master-class/tree/master/00-framework-tool-introductions/01.Eclipse-Introduction-in-5-steps) |\n| Maven in 5 Steps                      | Introduction | [Project Folder on Github](https://github.com/in28minutes/spring-master-class/tree/master/00-framework-tool-introductions/02.Maven-Introduction-In-5-Steps)   |\n| JUnit in 5 Steps                      | Introduction | [Project Folder on Github](https://github.com/in28minutes/spring-master-class/tree/master/00-framework-tool-introductions/03.JUnit-Introduction-In-5-Steps)   |\n| Mockito in 5 Steps                    | Introduction | [Project Folder on Github](https://github.com/in28minutes/spring-master-class/tree/master/00-framework-tool-introductions/04.Mockito-Introduction-In-5-Steps) |\n| Basic Web Application with Spring MVC | Introduction | [Project Folder on Github]()                                                                                                                                  |\n\n# Step-by-Step Details\n\n### Introductory Modules\n\n> **Note:** These introductory modules are organized across the course to enable JIT (Just-In-Time) learning. If you are\n> new to Spring, don't forget to check the *Introduction to Spring* module in the appendix.\n\n- Introduction to JUnit — 5 steps\n- Introduction to Mockito — 5 steps\n- Introduction to JPA — 10 steps\n- Introduction to Spring — 10 steps\n\n---\n\n### Web Application with Spring Boot\n\n- **Step 01 — Part 1:** Basic Spring Boot web application setup\n- **Step 01 — Part 2:** `pom.xml`, Spring Boot application, and `application.properties`\n- **Step 02 — Part 1:** First Spring MVC controller — `@ResponseBody` vs `@Controller`\n- **Step 02 — Part 2:** Understanding HTTP request flow\n- **Step 03:** Demystifying some of the Spring Boot \"magic\"\n- **Step 04:** Redirect to Login JSP — `@ResponseBody` and view resolver\n- **Step 05:** Show user id and password on welcome page — `ModelMap` and `@RequestParam`\n- **Step 06:** `DispatcherServlet` and Spring MVC flow\n- **Step 07:** Your first HTML form\n- **Step 08:** Add hard-coded validation of user id and password\n- **Step 09:** More Spring \"magic\"\n- **Step 10:** Create `TodoController` and `list-todos` view. Make `TodoService` a `@Service`\n- **Step 11:** Architecture of web applications\n- **Step 12:** Session vs Model vs Request — `@SessionAttributes`\n- **Step 13:** Add new to-do\n- **Step 14:** Display to-dos in a table using JSTL tags\n- **Step 15:** Bootstrap for page formatting using webjars\n- **Step 16:** Delete a to-do\n- **Step 17:** Format \"Add Todo\" page and add basic HTML5 form validation\n- **Step 18 — Part 1:** Validations with Hibernate Validator — using command bean\n- **Step 18 — Part 2:** Using JSR 349 (Bean Validation)\n- **Step 19:** Updating a to-do\n- **Step 20:** Add a target date for to-do — use `initBinder` to handle date fields\n- **Step 21:** JSP fragments and navigation bar\n- **Step 22:** Preparing for Spring Security\n- **Step 23:** Initial Spring Security setup\n- **Step 24:** Refactor and add logout functionality using Spring Security\n- **Step 25:** Exception handling\n\n---\n\n### Connecting Web Application with JPA\n\n> **Note:** Ensure you complete the *Introduction to JPA* module before starting this section.\n\n- **Step 26:** Add dependencies for JPA and H2\n- **Step 27:** Configure H2 console\n- **Step 28:** Create `Todo` entity and JPA repository\n- **Step 29:** Insert `Todo` using JPA repository\n- **Step 30:** Update, delete, and retrieve to-dos using JPA repository\n- **Step 31:** Data initialization with `data.sql`\n- **Step 32:** Connecting JPA to other databases\n- **Step 33:** Upgrading to Spring Boot 2 and Spring 5\n\n---\n\n### Spring Boot Deep Dive — Simple API\n\n- **Step 01:** Setup and launch Spring Boot application with Maven and Eclipse\n- **Step 02:** Create your first `@RestController`\n- **Step 03:** Understanding Spring Boot magic: `spring-boot-starter-web`\n- **Step 04:** Understanding Spring Boot magic: `spring-boot-starter-parent`\n- **Step 05:** Spring Boot vs Spring framework\n- **Step 06:** Create services for survey and questions\n- **Step 07:** What is REST? Create REST service with `@GetMapping` and `@PathVariable`\n- **Step 08:** Second REST service to retrieve a specific question\n- **Step 09:** Spring Boot Developer Tools and LiveReload — develop faster!\n- **Step 10:** Create a REST service to add a new question: `@PostMapping`, Postman\n- **Step 11:** Content negotiation — deliver XML responses from REST services\n- **Step 12:** Spring Initializr — create Spring Boot projects on the fly\n- **Step 13:** Spring Boot Actuator — monitor your application\n- **Step 14:** Embedded servlet containers — switch to Jetty or Undertow\n- **Step 15:** Add dynamic configuration: YAML & more\n- **Step 16:** Basics of profiles\n- **Step 17:** Advanced configuration with type-safe `@ConfigurationProperties`\n- **Step 18:** Spring Data JPA with `CommandLineRunner`\n- **Step 19:** H2 console and add a custom JPA repository method\n- **Step 20:** Introduction to Spring Data REST\n- **Step 21:** Spring Boot integration tests\n- **Step 22:** Add integration test for POST requests\n- **Step 23:** Small refactor to organize code\n- **Step 24:** Unit tests with Spring Boot and Mockito\n- **Step 25:** Unit test for `createTodo`\n- **Step 26:** Secure services with Basic Authentication using Spring Security\n- **Step 27:** Configure Spring Security roles for survey and other services\n- **Step 28:** Deep dive into Spring Boot auto-configuration\n\n---\n\n## Step-by-Step Notes and Code Examples\n\n### 02. Spring-Boot-Web-Application\n\n#### Step01.md\n\n##### What you will learn in this step\n\n- Let's create a simple web application using Spring Boot.\n- How to run the Spring Boot application.\n- An overview of the \"magic\" that Spring Boot provides (deep dive in Step 03).\n\n##### Files list\n\n- *(Add list of files for this step —\n  e.g., `pom.xml`, `src/main/java/...`, `src/main/resources/application.properties`, `src/main/resources/templates/*`)*\n\npom.xml\n\n```xml\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n         xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n    <modelVersion>4.0.0</modelVersion>\n\n    <groupId>com.in28minutes.springboot.web</groupId>\n    <artifactId>spring-boot-first-web-application</artifactId>\n    <version>0.0.1-SNAPSHOT</version>\n    <packaging>jar</packaging>\n\n    <name>spring-boot-first-web-application</name>\n    <description>Demo project for Spring Boot</description>\n\n    <parent>\n        <groupId>org.springframework.boot</groupId>\n        <artifactId>spring-boot-starter-parent</artifactId>\n        <version>4.0.0-M2</version>\n        <relativePath/> <!-- lookup parent from repository -->\n    </parent>\n\n    <properties>\n        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>\n        <java.version>21</java.version>\n        <maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>\n    </properties>\n\n    <dependencies>\n        <dependency>\n            <groupId>org.springframework.boot</groupId>\n            <artifactId>spring-boot-starter-web</artifactId>\n        </dependency>\n        <dependency>\n            <groupId>org.springframework.boot</groupId>\n            <artifactId>spring-boot-devtools</artifactId>\n            <scope>runtime</scope>\n        </dependency>\n        <dependency>\n            <groupId>org.springframework.boot</groupId>\n            <artifactId>spring-boot-starter-test</artifactId>\n            <scope>test</scope>\n        </dependency>\n    </dependencies>\n\n    <build>\n        <plugins>\n            <plugin>\n                <groupId>org.springframework.boot</groupId>\n                <artifactId>spring-boot-maven-plugin</artifactId>\n            </plugin>\n        </plugins>\n    </build>\n\n</project>\n```\n\n---\nsrc/main/java/com/in28minutes/springboot/web/SpringBootFirstWebApplication.java\n\n```java\npackage com.in28minutes.springboot.web;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\n@SpringBootApplication\npublic class SpringBootFirstWebApplication {\n\n    public static void main(String[] args) {\n        SpringApplication.run(SpringBootFirstWebApplication.class, args);\n    }\n}\n```\n\n---\nsrc/main/resources/application.properties\n\n```\n```\n\n---\nsrc/test/java/com/in28minutes/springboot/web/SpringBootFirstWebApplicationTests.java\n\n```java\npackage com.in28minutes.springboot.web;\n\nimport org.junit.jupiter.api.Test;\nimport org.springframework.boot.test.context.SpringBootTest;\n\n@SpringBootTest\npublic class SpringBootFirstWebApplicationTests {\n\n    @Test\n    public void contextLoads() {\n    }\n\n}\n```\n\n---\n\n## Step02.md\n\n#### What You Will Learn during this Step:\n\n- Using `@RequestMapping(value = \"/login\", method = RequestMethod.GET)`\n- Accessing endpoint: `http://localhost:8080/login`\n- Why use `@ResponseBody`?\n- Importance of the `@RequestMapping` method\n- How web applications work — Request and Response cycle:\n    - Browser sends **HTTP Request** to the web server\n    - Code in the web server executes\n        - **Input:** `HttpRequest`\n        - **Output:** `HttpResponse`\n    - Web server responds with an **HTTP Response**\n\nsrc/main/java/com/in28minutes/springboot/web/controller/LoginController.java New\n\n```java\npackage com.in28minutes.springboot.web.controller;\n\nimport org.springframework.stereotype.Controller;\nimport org.springframework.web.bind.annotation.RequestMapping;\n\n@Controller\npublic class LoginController {\n\n    @RequestMapping(\"/login\")\n    public String loginMessage() {\n        return \"Hello World\";\n    }\n}\n```\n\n---\nsrc/main/resources/application.properties Modified\nNew Lines\n\n```\nlogging.level.org.springframework.web: DEBUG\n```\n\n## Step03.md\n\n#### What You Will Learn during this Step:\n\n- Demystifying some of the Spring Boot magic:\n    - **Spring Boot Starter Parent**\n    - **Spring Boot Starter Web**\n    - **Embedded Tomcat**\n    - **Spring Boot DevTools**\n\n---\n\n## Step04.md\n\n#### What You Will Learn during this Step:\n\n- Creating your **first JSP**\n    - (Note: A bit of setup is required before this step!)\n- Introduction to **ViewResolver**\n\n#### Useful Snippets and References\n\n- First Snippet: `/src/main/webapp/WEB-INF/jsp/login.jsp`\n\n```html\n\n<html>\n<head>\n    <title>Yahoo!!</title>\n</head>\n<body>\nMy First JSP!!!\n</body>\n</html>\n```\n\nSecond Snippet - /src/main/resources/application.properties\n\n```\nspring.mvc.view.prefix: /WEB-INF/jsp/\nspring.mvc.view.suffix: .jsp\nlogging.level.: DEBUG\n```\n\nThird Snippet : To enable jsp support in embedded tomcat server!\n\n```xml\n\n<dependency>\n    <groupId>org.apache.tomcat.embed</groupId>\n    <artifactId>tomcat-embed-jasper</artifactId>\n    <scope>provided</scope>//default for IntelliJ IDEA\n</dependency>\n\n```\n\n#### Exercises\n\n- Create a new jsp and a new controller method to redirect to it!\n- Play around!\n\n#### Files List\n\npom.xml Modified\nNew Lines\n\n```xml\n\n<dependency>\n    <groupId>org.apache.tomcat.embed</groupId>\n    <artifactId>tomcat-embed-jasper</artifactId>\n    <scope>provided</scope>\n    //default for IntelliJ IDEA\n</dependency>        \n```\n\nsrc/main/java/com/in28minutes/springboot/web/controller/LoginController.java Modified\n\n```java\npackage com.in28minutes.springboot.web.controller;\n\nimport org.springframework.stereotype.Controller;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.ResponseBody;\n\n@Controller\npublic class LoginController {\n\n    @RequestMapping(\"/login\")\n    public String loginMessage() {\n        return \"login\";\n    }\n}\n```\n\n---\nsrc/main/resources/application.properties Modified\nNew Lines\n\n```\nspring.mvc.view.prefix=/WEB-INF/jsp/\nspring.mvc.view.suffix=.jsp\nlogging.level.org.springframework.web=DEBUG\n```\n\nsrc/main/webapp/WEB-INF/jsp/login.jsp New\n\n```html\n\n<html>\n\n<head>\n    <title>First Web Application</title>\n</head>\n\n<body>\nMy First JSP!!\n</body>\n\n</html>\n```\n\n## Step05.md\n\n#### What You Will Learn during this Step:\n\n- You first GET Parameter\n- Problem with using GET\n\nsrc/main/java/com/in28minutes/springboot/web/controller/LoginController.java Modified\n\n```java\n\n@Controller\npublic class LoginController {\n    @RequestMapping(\"/login\")\n    public String loginMessage(@RequestParam String name, ModelMap model) {\n        model.put(\"name\", name);\n        return \"login\";\n    }\n}\n```\n\n---\nsrc/main/webapp/WEB-INF/jsp/login.jsp Modified\nNew Lines\n\n```\nMy First JSP!! Welcome ${name}!\n```\n\n## Step06.md\n\n#### What You Will Learn during this Step:\n\n- Importance of the **DispatcherServlet** in Spring MVC.\n\n---\n\n#### Spring MVC Request Flow\n\n1. **DispatcherServlet** receives the HTTP Request.\n2. **DispatcherServlet** identifies the correct Controller based on the URL.\n    - The Controller executes business logic.\n    - The Controller returns:  \n      a) **Model**  \n      b) **View Name** back to DispatcherServlet.\n3. **DispatcherServlet** uses a **ViewResolver** to identify the correct view.\n4. **DispatcherServlet** makes the Model available to the View and executes it.\n5. **DispatcherServlet** sends the final HTTP Response back to the client.\n\n📌 Reference Flow Diagram:  \n[Spring MVC Request Flow](http://docs.spring.io/spring-framework/docs/2.0.8/reference/images/mvc.png)\n\n## Step07.md\n\n#### What You Will Learn during this Step:\n\n- Lets get the name from the user in a form\n\n#### Useful Snippets and References\n\nFirst Snippet\n\n```java\n\n@RequestMapping(value = \"/login\", method = RequestMethod.GET)\npublic String showLoginPage(ModelMap model, @RequestParam String name) {\n    return \"login\";\n}\n\n@RequestMapping(value = \"/login\", method = RequestMethod.POST)\npublic String handleLogin(ModelMap model, @RequestParam String name) {\n    model.put(\"name\", name);\n    return \"welcome\";\n}\n\n```\n\nSecond Snippet\n\n```html\n\n<form method=\"POST\">\n    Name : <input name=\"name\" type=\"text\"/> <input type=\"submit\"/>\n</form>\n\n```\n\n#### Files List\n\nsrc/main/java/com/in28minutes/springboot/web/controller/LoginController.java Modified\n\n```java\npackage com.in28minutes.springboot.web.controller;\n\nimport org.springframework.stereotype.Controller;\nimport org.springframework.ui.ModelMap;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\nimport org.springframework.web.bind.annotation.RequestParam;\n\n@Controller\npublic class LoginController {\n\n    @RequestMapping(value = \"/login\", method = RequestMethod.GET)\n    public String showLoginPage(ModelMap model) {\n        return \"login\";\n    }\n\n    @RequestMapping(value = \"/login\", method = RequestMethod.POST)\n    public String showWelcomePage(ModelMap model, @RequestParam String name) {\n        model.put(\"name\", name);\n        return \"welcome\";\n    }\n\n}\n```\n\n---\nsrc/main/webapp/WEB-INF/jsp/login.jsp Modified\nNew Lines\n\n```\n\t<form method=\"post\">\n\t\tName : <input type=\"text\" name=\"name\" />\n\t\tPassword : <input type=\"password\" name=\"password\" /> \n\t\t<input type=\"submit\" />\n\t</form>\n```\n\nsrc/main/webapp/WEB-INF/jsp/welcome.jsp New\n\n```html\n\n<html>\n\n<head>\n    <title>First Web Application</title>\n</head>\n\n<body>\nWelcome ${name}!!\n</body>\n\n</html>\n```\n\n---\n\n## Step08.md\n\n#### What You Will Learn during this Step:\n\n- Add validation for **userid** and **password**.\n- Understand the concept of **hard-coded validation** (checking credentials against fixed values).\n- Show appropriate **error messages** when invalid credentials are entered.\n- Learn the flow of form submission:\n    - User submits login form.\n    - Application checks credentials against hard-coded values.\n    - On success → Redirect to welcome page.\n    - On failure → Stay on login page and display error message.\n\n---\n\n✅ This step introduces **basic login validation**, preparing the ground for more flexible and secure authentication\napproaches later in the course.\n\n#### Files List\n\nsrc/main/java/com/in28minutes/springboot/web/controller/LoginController.java Modified\n\n```java\n\n@Controller\npublic class LoginController {\n\n    @Autowired\n    LoginService service;\n\n    @RequestMapping(value = \"/login\", method = RequestMethod.GET)\n    public String showLoginPage(ModelMap model) {\n        return \"login\";\n    }\n\n    @RequestMapping(value = \"/login\", method = RequestMethod.POST)\n    public String showWelcomePage(ModelMap model, @RequestParam String name, @RequestParam String password) {\n        boolean isValidUser = service.validateUser(name, password);\n\n        if (!isValidUser) {\n            model.put(\"errorMessage\", \"Invalid Credentials\");\n            return \"login\";\n        }\n\n        model.put(\"name\", name);\n        model.put(\"password\", password);\n\n        return \"welcome\";\n    }\n\n}\n```\n\n---\nsrc/main/java/com/in28minutes/springboot/web/service/LoginService.java New\n\n```java\npackage com.in28minutes.springboot.web.service;\n\nimport org.springframework.stereotype.Component;\n\n@Component\npublic class LoginService {\n\n    public boolean validateUser(String userid, String password) {\n        // in28minutes, dummy\n        return userid.equalsIgnoreCase(\"in28minutes\")\n                && password.equalsIgnoreCase(\"dummy\");\n    }\n\n}\n```\n\n---\nsrc/main/webapp/WEB-INF/jsp/login.jsp Modified\nNew Lines\n\n```\n\t<font color=\"red\">${errorMessage}</font>\n```\n\n## Step09.md\n\n#### What You Will Learn during this Step:\n\n- Understand the **magic of Spring**.\n- Learn about **Spring Auto-wiring** and **Dependency Injection**.\n- Key concepts: `@Autowired`, `@Component`.\n- How Spring manages dependencies automatically to reduce boilerplate code.\n\n---\n\n## Step10.md\n\n#### What You Will Do:\n\n- Create `TodoController` and the `list-todos.jsp` page.\n- Implement `TodoService` as a Spring `@Service` and inject it into the controller.\n\n#### Pending for Next Step:\n\n- The variable `${name}` is not yet available in `list-todos.jsp`.\n- The username \"in28Minutes\" is still hardcoded in `TodoController`.\n\n#### Notes:\n\n- In this step, you will see **controller-service interaction** in action.\n- Prepare for dynamic data handling and model binding in the next step.\n\n```java\npackage com.in28minutes.springboot.web.model;\n\nimport java.util.Date;\n\npublic class Todo {\n    private int id;\n    private String user;\n    private String desc;\n    private Date targetDate;\n    private boolean isDone;\n\n    public Todo(int id, String user, String desc, Date targetDate,\n                boolean isDone) {\n        super();\n        this.id = id;\n        this.user = user;\n        this.desc = desc;\n        this.targetDate = targetDate;\n        this.isDone = isDone;\n    }\n\n    public int getId() {\n        return id;\n    }\n\n    public void setId(int id) {\n        this.id = id;\n    }\n\n    public String getUser() {\n        return user;\n    }\n\n    public void setUser(String user) {\n        this.user = user;\n    }\n\n    public String getDesc() {\n        return desc;\n    }\n\n    public void setDesc(String desc) {\n        this.desc = desc;\n    }\n\n    public Date getTargetDate() {\n        return targetDate;\n    }\n\n    public void setTargetDate(Date targetDate) {\n        this.targetDate = targetDate;\n    }\n\n    public boolean isDone() {\n        return isDone;\n    }\n\n    public void setDone(boolean isDone) {\n        this.isDone = isDone;\n    }\n\n    @Override\n    public int hashCode() {\n        final int prime = 31;\n        int result = 1;\n        result = prime * result + id;\n        return result;\n    }\n\n    @Override\n    public boolean equals(Object obj) {\n        if (this == obj) {\n            return true;\n        }\n        if (obj == null) {\n            return false;\n        }\n        if (getClass() != obj.getClass()) {\n            return false;\n        }\n        Todo other = (Todo) obj;\n        if (id != other.id) {\n            return false;\n        }\n        return true;\n    }\n\n    @Override\n    public String toString() {\n        return String.format(\n                \"Todo [id=%s, user=%s, desc=%s, targetDate=%s, isDone=%s]\", id,\n                user, desc, targetDate, isDone);\n    }\n\n}\n```\n\nSnippet - /src/main/java/com/in28minutes/springboot/web/service/TodoService.java\n\n```java\npackage com.in28minutes.springboot.web.service;\n\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.Iterator;\nimport java.util.List;\n\nimport org.springframework.stereotype.Service;\n\nimport com.in28minutes.springboot.web.model.Todo;\n\n@Service\npublic class TodoService {\n    private static List<Todo> todos = new ArrayList<>();\n    private static int todoCount = 3;\n\n    static {\n        todos.add(new Todo(1, \"in28Minutes\", \"Learn Spring MVC\", new Date(),\n                false));\n        todos.add(new Todo(2, \"in28Minutes\", \"Learn Struts\", new Date(), false));\n        todos.add(new Todo(3, \"in28Minutes\", \"Learn Hibernate\", new Date(),\n                false));\n    }\n\n    public List<Todo> retrieveTodos(String user) {\n        List<Todo> filteredTodos = new ArrayList<>();\n        for (Todo todo : todos) {\n            if (todo.getUser().equals(user)) {\n                filteredTodos.add(todo);\n            }\n        }\n        return filteredTodos;\n    }\n\n    public void addTodo(String name, String desc, Date targetDate,\n                        boolean isDone) {\n        todos.add(new Todo(++todoCount, name, desc, targetDate, isDone));\n    }\n\n    public void deleteTodo(int id) {\n        todos.removeIf(todo -> todo.getId() == id);\n    }\n}\n```\n\n## Step11.md\n\n#### What You Will Do:\n\n- Discuss the **architecture of web applications**.\n- Understand how different layers (Controller, Service, View) interact.\n- Learn about the responsibilities of each layer and how they contribute to **separation of concerns**.\n\n---\n\n## Step12.md\n\n#### What You Will Learn during this Step:\n\n- Differences between **Session**, **Model**, and **Request** scopes.\n- Best practices for using **Session** data — avoid storing unnecessary information.\n- How `@SessionAttributes(\"name\")` works to store model attributes in the session.\n- Why **Model** is preferred over adding elements directly to `HttpServletRequest`:\n    - Ensures **view-agnostic design**.\n    - Allows the use of different view technologies not tied to `HttpServletRequest`.\n- Understanding Spring documentation on `@SessionAttributes`:\n    - Lists model attribute names to be **transparently stored** in session or conversational storage.\n\n#### Notes:\n\n- This step is crucial for handling user-specific data across multiple requests.\n- Helps prepare for form handling, login sessions, and dynamic content rendering.\n\nFirst Snippet\n\n```java\n@SessionAttributes(\"name\")\n```\n\n#### Files List\n\nsrc/main/java/com/in28minutes/springboot/web/SpringBootFirstWebApplication.java Modified\nNew Lines\n\n```java\nimport org.springframework.context.annotation.ComponentScan;\n\n@ComponentScan(\"com.in28minutes.springboot.web\")\n```\n\n---\nsrc/main/java/com/in28minutes/springboot/web/controller/LoginController.java Modified\n\n```java\n\n@Controller\n@SessionAttributes(\"name\")\npublic class LoginController {\n```\n\n---\nsrc/main/java/com/in28minutes/springboot/web/controller/TodoController.java New\n\n```java\npackage com.in28minutes.springboot.web.controller;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.ui.ModelMap;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\nimport org.springframework.web.bind.annotation.RequestParam;\nimport org.springframework.web.bind.annotation.SessionAttributes;\n\nimport com.in28minutes.springboot.web.service.LoginService;\nimport com.in28minutes.springboot.web.service.TodoService;\n\n@Controller\n@SessionAttributes(\"name\")\npublic class TodoController {\n\n    @Autowired\n    TodoService service;\n\n    @RequestMapping(value = \"/list-todos\", method = RequestMethod.GET)\n    public String showTodos(ModelMap model) {\n        String name = (String) model.get(\"name\");\n        model.put(\"todos\", service.retrieveTodos(name));\n        return \"list-todos\";\n    }\n}\n```\n\n---\nsrc/main/java/com/in28minutes/springboot/web/model/Todo.java New\n\n```java\npackage com.in28minutes.springboot.web.model;\n\nimport java.util.Date;\n\npublic class Todo {\n    private int id;\n    private String user;\n    private String desc;\n    private Date targetDate;\n    private boolean isDone;\n\n    public Todo(int id, String user, String desc, Date targetDate,\n                boolean isDone) {\n        super();\n        this.id = id;\n        this.user = user;\n        this.desc = desc;\n        this.targetDate = targetDate;\n        this.isDone = isDone;\n    }\n\n    public int getId() {\n        return id;\n    }\n\n    public void setId(int id) {\n        this.id = id;\n    }\n\n    public String getUser() {\n        return user;\n    }\n\n    public void setUser(String user) {\n        this.user = user;\n    }\n\n    public String getDesc() {\n        return desc;\n    }\n\n    public void setDesc(String desc) {\n        this.desc = desc;\n    }\n\n    public Date getTargetDate() {\n        return targetDate;\n    }\n\n    public void setTargetDate(Date targetDate) {\n        this.targetDate = targetDate;\n    }\n\n    public boolean isDone() {\n        return isDone;\n    }\n\n    public void setDone(boolean isDone) {\n        this.isDone = isDone;\n    }\n\n    @Override\n    public int hashCode() {\n        final int prime = 31;\n        int result = 1;\n        result = prime * result + id;\n        return result;\n    }\n\n    @Override\n    public boolean equals(Object obj) {\n        if (this == obj) {\n            return true;\n        }\n        if (obj == null) {\n            return false;\n        }\n        if (getClass() != obj.getClass()) {\n            return false;\n        }\n        Todo other = (Todo) obj;\n        return id == other.id;\n    }\n\n    @Override\n    public String toString() {\n        return String.format(\n                \"Todo [id=%s, user=%s, desc=%s, targetDate=%s, isDone=%s]\", id,\n                user, desc, targetDate, isDone);\n    }\n\n}\n```\n\n---\nsrc/main/java/com/in28minutes/springboot/web/service/LoginService.java Modified\n\n```java\n\n@Service\npublic class LoginService {\n\n```\n\n---\nsrc/main/java/com/in28minutes/springboot/web/service/TodoService.java New\n\n```java\npackage com.in28minutes.springboot.web.service;\n\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.Iterator;\nimport java.util.List;\n\nimport org.springframework.stereotype.Service;\n\nimport com.in28minutes.springboot.web.model.Todo;\n\n@Service\npublic class TodoService {\n    private static List<Todo> todos = new ArrayList<>();\n    private static int todoCount = 3;\n\n    static {\n        todos.add(new Todo(1, \"in28Minutes\", \"Learn Spring MVC\", new Date(),\n                false));\n        todos.add(new Todo(2, \"in28Minutes\", \"Learn Struts\", new Date(), false));\n        todos.add(new Todo(3, \"in28Minutes\", \"Learn Hibernate\", new Date(),\n                false));\n    }\n\n    public List<Todo> retrieveTodos(String user) {\n        List<Todo> filteredTodos = new ArrayList<>();\n        for (Todo todo : todos) {\n            if (todo.getUser().equals(user)) {\n                filteredTodos.add(todo);\n            }\n        }\n        return filteredTodos;\n    }\n\n    public void addTodo(String name, String desc, Date targetDate,\n                        boolean isDone) {\n        todos.add(new Todo(++todoCount, name, desc, targetDate, isDone));\n    }\n\n    public void deleteTodo(int id) {\n        todos.removeIf(todo -> todo.getId() == id);\n    }\n}\n```\n\n---\nsrc/main/webapp/WEB-INF/jsp/list-todos.jsp New\n\n```html\n\n<html>\n\n<head>\n    <title>First Web Application</title>\n</head>\n\n<body>\nHere are the list of your todos:\n${todos}\n<BR/>\nYour Name is : ${name}\n</body>\n\n</html>\n```\n\n---\nsrc/main/webapp/WEB-INF/jsp/welcome.jsp Modified\nNew Lines\n\n```\n\tWelcome ${name}!! <a href=\"/list-todos\">Click here</a> to manage your todo's.\n```\n\n## Step13.md\n\n#### What You Will Do:\n\n- Add functionality to **create a new Todo**.\n- Work with the **todo.jsp** page for adding todos.\n- Learn the importance of using **redirect:/list-todos** after form submission:\n    - Prevents duplicate form submissions on page refresh.\n    - Updates the list view to show the newly added todo.\n\n#### Notes:\n\n- Controller handles the form submission and redirects to the list view.\n- Model and view interaction ensures the new todo is displayed correctly.\n\n#### Files Modified:\n\n- `src/main/java/com/in28minutes/springboot/web/controller/TodoController.java`\n\n```java\n\n@RequestMapping(value = \"/add-todo\", method = RequestMethod.GET)\npublic String showAddTodoPage(ModelMap model) {\n    return \"todo\";\n}\n\n@RequestMapping(value = \"/add-todo\", method = RequestMethod.POST)\npublic String addTodo(ModelMap model, @RequestParam String desc) {\n    service.addTodo((String) model.get(\"name\"), desc, new Date(), false);\n    return \"redirect:/list-todos\";\n}\n```\n\n---\n\nsrc/main/webapp/WEB-INF/jsp/list-todos.jsp Modified\nNew Lines\n\n```html\n    Here are the list of ${name}'s todos:\n${todos}.\n<a href=\"/add-todo\">Add a Todo</a> \n```\n\nsrc/main/webapp/WEB-INF/jsp/todo.jsp New\n\n```html\n\n<html>\n\n<head>\n    <title>First Web Application</title>\n</head>\n\n<body>\nADD Todo Page for ${name}\n\n<form method=\"post\">\n    Description : <input name=\"desc\" type=\"text\"/>\n    <input type=\"submit\"/>\n</form>\n\n</body>\n\n</html>\n```\n\n## Step14.md\n\n#### What You Will Do:\n\n- Display the list of **Todos in a table** using **JSTL tags**.\n- Use the JSTL core tag library:\n    - `<%@ taglib uri=\"http://java.sun.com/jsp/jstl/core\" prefix=\"c\"%>`\n- Add the necessary **JSTL dependency** to your project.\n\n#### Notes:\n\n- JSTL tags make it easier to **iterate over collections**, conditionally display content, and reduce scriptlets in JSP.\n- This step focuses on **dynamic content rendering** using standard JSP techniques.\n\n#### Files Modified:\n\n- `list-todos.jsp` (to use JSTL tags for displaying todos)\n\n```xml       \n\n<dependency>\n    <groupId>jakarta.servlet.jsp.jstl</groupId>\n    <artifactId>jakarta.servlet.jsp.jstl-api</artifactId>\n</dependency>\n```\n\n## Step15.md\n\n#### What You Will Do:\n\n- Add **Bootstrap** to give basic styling and formatting to pages.\n    - Use Bootstrap classes like `container`, `table`, and `table-striped`.\n- Use **WebJars** to manage Bootstrap dependencies.\n- Leverage **Spring Boot auto-configuration** for WebJars:\n    - `SimpleUrlHandlerMapping` automatically maps `/webjars/**` URLs to the appropriate resource handler.\n\n#### Notes:\n\n- WebJars allow you to include client-side libraries (like Bootstrap) via Maven.\n- This step improves **UI presentation** without manual setup of static resources.\n\n#### Useful Snippets\n\n```     \n        <dependency>\n            <groupId>org.webjars</groupId>\n            <artifactId>bootstrap</artifactId>\n            <version>3.3.6</version>\n        </dependency>\n        <dependency>\n            <groupId>org.webjars</groupId>\n            <artifactId>jquery</artifactId>\n            <version>1.9.1</version>\n        </dependency>\n        \n  \t\t\n  \n\t\t<script src=\"webjars/jquery/1.9.1/jquery.min.js\"></script>\n\t    <script src=\"webjars/bootstrap/3.3.6/js/bootstrap.min.js\"></script>\n\t\t<link href=\"webjars/bootstrap/3.3.6/css/bootstrap.min.css\"\n\t    \t\trel=\"stylesheet\">\n\n```\n\n#### Files List\n\npom.xml Modified\nNew Lines\n\n```xml\n\n<dependency>\n    <groupId>org.webjars</groupId>\n    <artifactId>bootstrap</artifactId>\n    <version>5.1.3</version>\n</dependency>\n\n<dependency>\n<groupId>org.webjars</groupId>\n<artifactId>jquery</artifactId>\n<version>3.6.0</version>\n</dependency>\n<dependency>\n<groupId>org.apache.tomcat.embed</groupId>\n<artifactId>tomcat-embed-jasper</artifactId>\n<scope>provided</scope> <!--default for IntelliJ -->\n</dependency>\n<dependency>\n<groupId>jakarta.servlet.jsp.jstl</groupId>\n<artifactId>jakarta.servlet.jsp.jstl-api</artifactId>\n</dependency>\n```\n\nsrc/main/resources/application.properties Modified\nNew Lines\n\n```\nlogging.level.org.springframework.web=INFO\n```\n\nsrc/main/webapp/WEB-INF/jsp/list-todos.jsp Modified\nNew Lines\n\n```html\n<%@ taglib prefix=\"c\" uri=\"jakarta.tags.core\" %>\n<title>Todo's for ${name}</title>\n<link href=\"webjars/bootstrap/3.3.6/css/bootstrap.min.css\"\n      rel=\"stylesheet\">\n<div class=\"container\">\n    <table class=\"table table-striped\">\n        <caption>Your todos are</caption>\n        <thead>\n        <tr>\n            <th>Description</th>\n            <th>Target Date</th>\n            <th>Is it Done?</th>\n        </tr>\n        </thead>\n        <tbody>\n        <c:forEach items=\"${todos}\" var=\"todo\">\n            <tr>\n                <td>${todo.desc}</td>\n                <td>${todo.targetDate}</td>\n                <td>${todo.done}</td>\n            </tr>\n        </c:forEach>\n        </tbody>\n    </table>\n    <div><a class=\"button\" href=\"/add-todo\">Add a Todo</a></div>\n    <script src=\"webjars/jquery/1.9.1/jquery.min.js\"></script>\n    <script src=\"webjars/bootstrap/3.3.6/js/bootstrap.min.js\"></script>\n</div>\n```\n\n## Step16.md\n\n#### What we will do:\n\n- Add functionality to delete a todo\n\n#### Useful Snippets\n\n```html    \n    <a type=\"button\" class=\"btn btn-warning\" href=\"/delete-todo?id=${todo.id}\">Delete</a>\n```\n\n#### Files List\n\nsrc/main/java/com/in28minutes/springboot/web/controller/TodoController.java Modified\nNew Lines\n\n```java\n\n@RequestMapping(value = \"/delete-todo\", method = RequestMethod.GET)\npublic String deleteTodo(@RequestParam int id) {\n    service.deleteTodo(id);\n}\n```\n\n---\nsrc/main/webapp/WEB-INF/jsp/list-todos.jsp Modified\nNew Lines\n\n```\n   <td><a type=\"button\" class=\"btn btn-warning\" href=\"/delete-todo?id=${todo.id}\">Delete</a></td>\n```\n\n## Step17.md\n\n## Step17.md\n\n#### What You Will Do:\n\n- Format the **Add Todo** page for better presentation.\n- Add **HTML5 form validations** to ensure proper input from the user.\n    - Examples: required fields, date format checks, and text length constraints.\n\n#### Notes:\n\n- HTML5 validations provide **basic client-side checks** before the form is submitted.\n- Improves user experience by preventing invalid data entry.\n\n#### Useful Snippets:\n\n- Form fields with HTML5 validation attributes (`required`, `type=\"date\"`, etc.).\n\n```html     \n\n<fieldset class=\"form-group\">\n    <label>Description</label>\n    <input name=\"desc\" type=\"text\" class=\"form-control\" required=\"required\"/>\n</fieldset>\n\n```\n\n#### Files List\n\nsrc/main/webapp/WEB-INF/jsp/list-todos.jsp Modified\nSnippets\n\n```html\n\n<td><a type=\"button\" class=\"btn btn-warning\"\n       href=\"/delete-todo?id=${todo.id}\">Delete</a></td>\n\n<div>\n    <a class=\"button\" href=\"/add-todo\">Add a Todo</a>\n</div>\n\n<script src=\"webjars/bootstrap/5.1.3/js/bootstrap.min.js\"></script>\n<script src=\"webjars/jquery/3.6.0/jquery.min.js\"></script>\n```\n\nsrc/main/webapp/WEB-INF/jsp/todo.jsp Modified\nNew Lines\n\n```html\n\n<link href=\"webjars/bootstrap/5.1.3/css/bootstrap.min.css\"\n      rel=\"stylesheet\">\n<div class=\"container\">\n    <form method=\"post\">\n        <fieldset class=\"form-group\">\n            <label>Description</label>\n            <input name=\"desc\" type=\"text\"\n                   class=\"form-control\" required=\"required\"/>\n        </fieldset>\n        <button type=\"submit\" class=\"btn btn-success\">Add</button>\n    </form>\n</div>\n<script src=\"webjars/bootstrap/5.1.3/js/bootstrap.min.js\"></script>\n<script src=\"webjars/jquery/3.6.0/jquery.min.js\"></script>\n```\n\n## Step18.md\n\n#### What we will do:\n\n- Lets use a command bean for Todo\n- Add Validations\n- The JSR 303 and JSR 349 defines specification for the Bean Validation API (version 1.0 and 1.1, respectively), and\n  Hibernate Validator is the reference implementation.\n- org.hibernate:hibernate-validator\n\n#### Useful Snippets\n\n```html   \n    <%@ taglib prefix=\"form\" uri=\"http://www.springframework.org/tags/form\" %>\n\n<form:form method=\"post\" commandName=\"todo\">\n    <!-- use modelAttribute instead of commandName for Spring Boot Versions > 2.*\n    <form:form method=\"post\" modelAttribute=\"todo\"> -->\n    <fieldset class=\"form-group\">\n        <form:label path=\"desc\">Description</form:label>\n        <form:input path=\"desc\" type=\"text\" class=\"form-control\" required=\"required\"/>\n    </fieldset>\n</form:form>\n\n@Size(min = 10, message = \"Enter atleast 10 Characters.\")\n\n@Valid Todo todo, BindingResult result\n\nif (result.hasErrors())\nreturn \"todo\";\n\n<form:errors path=\"desc\" cssClass=\"text-warning\"/>\n\n```\n\n#### Files List\n\nsrc/main/java/com/in28minutes/springboot/web/controller/TodoController.java Modified\n\n```java\n\n@Controller\n@SessionAttributes(\"name\")\npublic class TodoController {\n\n    @Autowired\n    TodoService service;\n\n    @RequestMapping(value = \"/list-todos\", method = RequestMethod.GET)\n    public String showTodos(ModelMap model) {\n        String name = (String) model.get(\"name\");\n        model.put(\"todos\", service.retrieveTodos(name));\n        return \"list-todos\";\n    }\n\n    @RequestMapping(value = \"/add-todo\", method = RequestMethod.GET)\n    public String showAddTodoPage(ModelMap model) {\n        model.addAttribute(\"todo\", new Todo(0, (String) model.get(\"name\"), \"Default Desc\",\n                new Date(), false));\n        return \"todo\";\n    }\n\n    @RequestMapping(value = \"/delete-todo\", method = RequestMethod.GET)\n    public String deleteTodo(@RequestParam int id) {\n        service.deleteTodo(id);\n        return \"redirect:/list-todos\";\n    }\n\n    @RequestMapping(value = \"/add-todo\", method = RequestMethod.POST)\n    public String addTodo(ModelMap model, @Valid Todo todo, BindingResult result) {\n\n        if (result.hasErrors()) {\n            return \"todo\";\n        }\n\n        service.addTodo((String) model.get(\"name\"), todo.getDesc(), new Date(),\n                false);\n        return \"redirect:/list-todos\";\n    }\n}\n```\n\n---\nsrc/main/java/com/in28minutes/springboot/web/model/Todo.java Modified\nNew Lines\n\n```java\n    public Todo() {\n    super();\n}\n\n@Size(min = 10, message = \"Enter at least 10 Characters...\")\nprivate String desc;\n\n```\n\n---\nsrc/main/webapp/WEB-INF/jsp/todo.jsp Modified\nNew Lines\n\n```html\n<%@ taglib prefix=\"form\" uri=\"http://www.springframework.org/tags/form\" %>\n<form:form method=\"post\" commandName=\"todo\">\n\n    <!-- use modelAttribute instead of commandName for Spring Boot Versions > 2.*\n<form:form method=\"post\" modelAttribute=\"todo\"> -->\n\n    <form:label path=\"desc\">Description</form:label>\n    <form:input path=\"desc\" type=\"text\"\n    <form:errors path=\"desc\" cssClass=\"text-warning\"/>\n</form:form>\n```\n\n## Step19.md\n\n#### What You Will Do:\n\n- Add **update functionality** for existing todos.\n- Reuse the **same JSP page** used for adding todos to handle updates.\n\n#### Notes:\n\n- Updating a todo involves **pre-populating the form** with existing data.\n- This step demonstrates **reusing views** and keeping the UI consistent.\n- Controller logic will differentiate between **add** and **update** operations based on the presence of an existing\n  todo.\n\n#### Useful Snippets\n\n```java\n    public Todo retrieveTodo(int id) {\n    for (Todo todo : todos) {\n        if (todo.getId() == id)\n            return todo;\n    }\n    return null;\n}\n\npublic void updateTodo(Todo todo) {\n    todos.remove(todo);\n    todos.add(todo);\n}\n   \n   todo.\n\nsetUser(\"in28Minutes\"); //TODO:Remove Hardcoding Later\n   service.\n\nupdateTodo(todo);\n   \n   <form:\nhidden path = \"id\" / >  \n```\n\n#### Files List\n\nsrc/main/java/com/in28minutes/springboot/web/controller/TodoController.java Modified\n\n```java\n\n@RequestMapping(value = \"/update-todo\", method = RequestMethod.GET)\npublic String showUpdateTodoPage(@RequestParam int id, ModelMap model) {\n    Todo todo = service.retrieveTodo(id);\n    model.put(\"todo\", todo);\n    return \"todo\";\n}\n\n@RequestMapping(value = \"/update-todo\", method = RequestMethod.POST)\npublic String updateTodo(ModelMap model, @Valid Todo todo, BindingResult result) {\n\n    if (result.hasErrors()) {\n        return \"todo\";\n    }\n\n    todo.setUser((String) model.get(\"name\"));\n\n    service.updateTodo(todo);\n\n    return \"redirect:/list-todos\";\n}\n\n```\n\n---\nsrc/main/java/com/in28minutes/springboot/web/service/TodoService.java Modified\n\n```java\n    public List<Todo> retrieveTodos(String user) {\n    List<Todo> filteredTodos = new ArrayList<>();\n    for (Todo todo : todos) {\n        if (todo.getUser().equalsIgnoreCase(user)) {\n            filteredTodos.add(todo);\n        }\n    }\n    return filteredTodos;\n}\n\npublic Todo retrieveTodo(int id) {\n    for (Todo todo : todos) {\n        if (todo.getId() == id) {\n            return todo;\n        }\n    }\n    return null;\n}\n\npublic void updateTodo(Todo todo) {\n    todos.remove(todo);\n    todos.add(todo);\n}\n```\n\n---\nsrc/main/webapp/WEB-INF/jsp/list-todos.jsp Modified\nNew Lines\n\n```html\n\n<td><a type=\"button\" class=\"btn btn-success\" href=\"/update-todo?id=${todo.id}\">Update</a></td>\n```\n\nsrc/main/webapp/WEB-INF/jsp/todo.jsp Modified\nNew Lines\n\n```html\n\n<form:hidden path=\"id\"/>\n```\n\n## Step20.md\n\n#### What You Will Do:\n\n- Utilize the **Target Date** field in the Todo form.\n- Learn about the **`initBinder` method** to handle date formatting and binding.\n\n#### Notes:\n\n- `initBinder` allows customization of how **form input is converted** to Java objects.\n- Ensures that date fields are properly parsed and bound to the command bean.\n- Prepares the application for handling other complex data types in forms.\n\n#### Useful Snippets\n\n```html\n    <%@ taglib uri=\"http://java.sun.com/jsp/jstl/fmt\" prefix=\"fmt\"%>\n<fmt:formatDate pattern=\"dd/MM/yyyy\" value=\"${todo.targetDate}\"/>\n\n\n@InitBinder\nprotected void initBinder(WebDataBinder binder) {\nSimpleDateFormat dateFormat = new SimpleDateFormat(\"dd/MM/yyyy\");\nbinder.registerCustomEditor(Date.class, new CustomDateEditor(\ndateFormat, false));\n}\n\n<dependency>\n    <groupId>org.webjars</groupId>\n    <artifactId>bootstrap-datepicker</artifactId>\n    <version>1.9.0</version>\n</dependency>\n\n<script\n        src=\"webjars/bootstrap-datepicker/1.0.1/js/bootstrap-datepicker.js\"></script>\n\n<script>\n    $('#targetDate').datepicker({\n        format: 'dd/mm/yyyy'\n    });\n</script>\n\n```\n\n#### Files List\n\npom.xml Modified\nNew Lines\n\n```xml\n\n<dependency>\n    <groupId>org.webjars</groupId>\n    <artifactId>bootstrap-datepicker</artifactId>\n    <version>1.9.0</version>\n</dependency>\n<dependency>\n<groupId>org.webjars</groupId>\n<artifactId>bootstrap</artifactId>\n<version>5.1.3</version>\n</dependency>\n<dependency>\n<groupId>org.webjars</groupId>\n<artifactId>jquery</artifactId>\n<version>3.6.0</version>\n</dependency>\n\n\n```\n\nsrc/main/java/com/in28minutes/springboot/web/controller/TodoController.java Modified\n\n```java\n\n@RequestMapping(value = \"update-todo\", method = RequestMethod.POST)\npublic String updateTodo(ModelMap model, @Valid Todo todo, BindingResult result) {\n\n    if (result.hasErrors()) {\n        return \"todo\";\n    }\n\n    String username = getLoggedInUsername(model);\n    todo.setUsername(username);\n    todoService.updateTodo(todo);\n    return \"redirect:list-todos\";\n}\n\n@RequestMapping(value = \"add-todo\", method = RequestMethod.POST)\npublic String addNewTodo(ModelMap model, @Valid Todo todo, BindingResult result) {\n\n    if (result.hasErrors()) {\n        return \"todo\";\n    }\n\n    String username = getLoggedInUsername(model);\n    todoService.addTodo(username, todo.getDescription(),\n            LocalDate.now().plusYears(1), false);\n    return \"redirect:list-todos\";\n}\n```\n\n---\nsrc/main/webapp/WEB-INF/jsp/todo.jsp Modified\nNew Snippets\n\n```\n<form:input type=\"hidden\" path=\"id\"/>\n<form:input type=\"hidden\" path=\"done\"/>\n<form:label path=\"desc\">Description</form:label>\n<form:input path=\"desc\" type=\"text\" class=\"form-control\"\n\trequired=\"required\" />\n<form:errors path=\"desc\" cssClass=\"text-warning\" />\n<form:label path=\"targetDate\">Target Date</form:label>\n<form:input path=\"targetDate\" type=\"text\" class=\"form-control\"\n\trequired=\"required\" />\n<form:errors path=\"targetDate\" cssClass=\"text-warning\" />\n\n\n<script src=\"webjars/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.js\"></script>\n\n<script type=\"text/javascript\">\n\t$('#targetDate').datepicker({\n\t    format: 'yyyy-mm-dd'\n\t});\n</script>\n```\n\n## Step21.md\n\n#### What we will do:\n\n- Add a navigation bar\n- Use JSP Fragments\n- Exercise : Align the login & welcome pages.\n- Exercise : Highlight the correct menu item.\n\n#### Useful Snippets\n\n```\n<nav class=\"navbar navbar-expand-md navbar-light bg-light mb-3 p-1\">\n\t<a class=\"navbar-brand m-1\" href=\"https://courses.in28minutes.com\">in28minutes</a>\n\t<div class=\"collapse navbar-collapse\">\n\t\t<ul class=\"navbar-nav\">\n\t\t\t<li class=\"nav-item\"><a class=\"nav-link\" href=\"/\">Home</a></li>\n\t\t\t<li class=\"nav-item\"><a class=\"nav-link\" href=\"/list-todos\">Todos</a></li>\n\t\t</ul>\n\t</div>\n\t<ul class=\"navbar-nav\">\n\t\t<li class=\"nav-item\"><a class=\"nav-link\" href=\"/logout\">Logout</a></li>\n\t</ul>\t\n</nav>\n```\n\n#### Files List\n\nsrc/main/webapp/WEB-INF/jsp/common/footer.jspf New\n\n```\n<script src=\"webjars/bootstrap/5.1.3/js/bootstrap.min.js\"></script>\n\t\t<script src=\"webjars/jquery/3.6.0/jquery.min.js\"></script>\n\t\t<script src=\"webjars/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js\"></script>\n\t\t\t\t\t\t\n\t</body>\n</html>\n```\n\n---\n\nsrc/main/webapp/WEB-INF/jsp/common/header.jspf New\n\n```\n<%@ taglib prefix=\"c\" uri=\"jakarta.tags.core\" %>\n<%@ taglib prefix=\"form\" uri=\"http://www.springframework.org/tags/form\" %>\n\n\n<html>\n\t<head>\n\t\t<link href=\"webjars/bootstrap/5.1.3/css/bootstrap.min.css\" rel=\"stylesheet\" >\n\t\t<link href=\"webjars/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.standalone.min.css\" rel=\"stylesheet\" >\n\t\t\n\t\t<title>Manage Your Todos</title>\t\t\n\t</head>\n\t<body>\n```\n\n---\nsrc/main/webapp/WEB-INF/jsp/common/navigation.jspf New\n\n```\n<nav class=\"navbar navbar-expand-md navbar-light bg-light mb-3 p-1\">\n\t<a class=\"navbar-brand m-1\" href=\"https://courses.in28minutes.com\">in28minutes</a>\n\t<div class=\"collapse navbar-collapse\">\n\t\t<ul class=\"navbar-nav\">\n\t\t\t<li class=\"nav-item\"><a class=\"nav-link\" href=\"/\">Home</a></li>\n\t\t\t<li class=\"nav-item\"><a class=\"nav-link\" href=\"/list-todos\">Todos</a></li>\n\t\t</ul>\n\t</div>\n\t<ul class=\"navbar-nav\">\n\t\t<li class=\"nav-item\"><a class=\"nav-link\" href=\"/logout\">Logout</a></li>\n\t</ul>\t\n</nav>\n```\n\n---\nsrc/main/webapp/WEB-INF/jsp/list-todos.jsp Modified\nNew Lines\n\n```\n<%@ include file=\"common/header.jspf\" %>\n<%@ include file=\"common/navigation.jspf\" %>\n<%@ include file=\"common/footer.jspf\" %>\n```\n\nsrc/main/webapp/WEB-INF/jsp/login.jsp Modified\nNew Lines\n\n```\n<%@ include file=\"common/header.jspf\" %>\n<%@ include file=\"common/navigation.jspf\" %>\n<div class=\"container\">\n\n<!--OLD CODE-->\n\n</div>\n<%@ include file=\"common/footer.jspf\" %>\n```\n\nsrc/main/webapp/WEB-INF/jsp/todo.jsp Modified\nNew Lines\n\n```\n<%@ include file=\"common/header.jspf\" %>\n<%@ include file=\"common/navigation.jspf\" %>\n<div class=\"container\">\n\t<form:form method=\"post\" commandName=\"todo\">\n\t\t\t<!-- use modelAttribute instead of commandName for Spring Boot Versions > 2.*\n\t\t<form:form method=\"post\" modelAttribute=\"todo\"> -->\n\t\t<form:hidden path=\"id\" />\n\t\t<fieldset class=\"form-group\">\n\t\t\t<form:label path=\"desc\">Description</form:label>\n\t\t\t<form:input path=\"desc\" type=\"text\" class=\"form-control\"\n\t\t\t\trequired=\"required\" />\n\t\t\t<form:errors path=\"desc\" cssClass=\"text-warning\" />\n\t\t</fieldset>\n\t\t<fieldset class=\"form-group\">\n\t\t\t<form:label path=\"targetDate\">Target Date</form:label>\n\t\t\t<form:input path=\"targetDate\" type=\"text\" class=\"form-control\"\n\t\t\t\trequired=\"required\" />\n\t\t\t<form:errors path=\"targetDate\" cssClass=\"text-warning\" />\n\t\t</fieldset>\n\t\t<button type=\"submit\" class=\"btn btn-success\">Add</button>\n\t</form:form>\n</div>\n<%@ include file=\"common/footer.jspf\" %>\n```\n\nsrc/main/webapp/WEB-INF/jsp/welcome.jsp Modified\nNew Lines\n\n```\n<%@ include file=\"common/header.jspf\"%>\n<%@ include file=\"common/navigation.jspf\"%>\n<div class=\"container\">\n\tWelcome ${name}!! <a href=\"/list-todos\">Click here</a> to manage your\n\ttodo's.\n</div>\n<%@ include file=\"common/footer.jspf\"%>\n```\n\n## Step22.md\n\n#### What we will do:\n\n- Set up the application for Spring Security\n- Remove all custom login-related functionality\n- Make the Welcome page the default (with initial hardcoding)\n- Refactor the `getLoggedInUserName` method\n- Update the Home Page link in the navigation\n\n#### Files List\n\nsrc/main/java/com/in28minutes/springboot/web/controller/LoginController.java Modified\nNew Lines\n\n```java\n\n@RequestMapping(value = \"/\", method = RequestMethod.GET)\npublic String showLoginPage(ModelMap model) {\n    model.put(\"name\", \"in28Minutes\");\n}\n```\n\n---\nsrc/main/java/com/in28minutes/springboot/web/controller/TodoController.java Modified\n\n```java\n\n@RequestMapping(value = \"/list-todos\", method = RequestMethod.GET)\npublic String showTodos(ModelMap model) {\n    String name = getLoggedInUserName(model);\n    model.put(\"todos\", service.retrieveTodos(name));\n    return \"list-todos\";\n}\n\nprivate String getLoggedInUserName(ModelMap model) {\n    return (String) model.get(\"name\");\n}\n\n```\n\n---\nsrc/main/webapp/WEB-INF/jsp/common/navigation.jspf Modified\nNew Lines\n\n```html\n\n<li class=\"active\"><a href=\"/\">Home</a></li>\n```\n\nsrc/main/webapp/WEB-INF/jsp/login.jsp Deleted\n\n## Step23.md\n\n#### What we will do:\n\n- Get Setup for Spring Security\n\n#### Useful Snippets\n\n```xml\n\n<dependency>\n    <groupId>org.springframework.boot</groupId>\n    <artifactId>spring-boot-starter-security</artifactId>\n</dependency>\n```\n\n```java\npackage com.in28minutes.springboot.myfirstwebapp.security;\n\nimport static org.springframework.security.config.Customizer.withDefaults;\n\nimport java.util.function.Function;\n\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.security.config.annotation.web.builders.HttpSecurity;\nimport org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;\nimport org.springframework.security.config.annotation.web.configurers.HeadersConfigurer;\nimport org.springframework.security.core.userdetails.User;\nimport org.springframework.security.core.userdetails.UserDetails;\nimport org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;\nimport org.springframework.security.crypto.password.PasswordEncoder;\nimport org.springframework.security.provisioning.InMemoryUserDetailsManager;\nimport org.springframework.security.web.SecurityFilterChain;\n\n@Configuration\npublic class SpringSecurityConfiguration {\n    //LDAP or Database\n    //In Memory \n\n    //InMemoryUserDetailsManager\n    //InMemoryUserDetailsManager(UserDetails... users)\n\n    @Bean\n    public InMemoryUserDetailsManager createUserDetailsManager() {\n\n        UserDetails userDetails1 = createNewUser(\"in28minutes\", \"dummy\");\n        UserDetails userDetails2 = createNewUser(\"ranga\", \"dummydummy\");\n\n        return new InMemoryUserDetailsManager(userDetails1, userDetails2);\n    }\n\n    private UserDetails createNewUser(String username, String password) {\n        Function<String, String> passwordEncoder\n                = input -> passwordEncoder().encode(input);\n\n        UserDetails userDetails = User.builder()\n                .passwordEncoder(passwordEncoder)\n                .username(username)\n                .password(password)\n                .roles(\"USER\", \"ADMIN\")\n                .build();\n        return userDetails;\n    }\n\n    @Bean\n    public PasswordEncoder passwordEncoder() {\n        return new BCryptPasswordEncoder();\n    }\n\n    //All URLs are protected\n    //A login form is shown for unauthorized requests\n    //CSRF disable\n    //Frames\n\n    @Bean\n    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {\n\n        http.authorizeHttpRequests(\n                auth -> auth.anyRequest().authenticated());\n        http.formLogin(withDefaults());\n\n        http.csrf(AbstractHttpConfigurer::disable);\n        // OR\n        // http.csrf(AbstractHttpConfigurer::disable);\n\n        http.headers(headers -> headers.frameOptions(HeadersConfigurer.FrameOptionsConfig::disable)); // Starting from SB 3.1.x\n\n        return http.build();\n    }\n\n}\n\n```\n\nNot Needed anymore with Spring Boot Auto Configuration\n\n```xml\n\n<filter>\n    <filter-name>springSecurityFilterChain</filter-name>\n    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>\n</filter>\n\n<filter-mapping>\n<filter-name>springSecurityFilterChain</filter-name>\n<url-pattern>/*</url-pattern>\n</filter-mapping> \n```\n\n#### Files List\n\npom.xml Modified\nNew Lines\n\n```xml\n\n<dependency>\n    <groupId>org.springframework.boot</groupId>\n    <artifactId>spring-boot-starter-security</artifactId>\n</dependency>\n```\n\nsrc/main/java/com/in28minutes/springboot/web/security/SecurityConfiguration.java New\n\n```java\npackage com.in28minutes.springboot.myfirstwebapp.security;\n\nimport static org.springframework.security.config.Customizer.withDefaults;\n\nimport java.util.function.Function;\n\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.security.config.annotation.web.builders.HttpSecurity;\nimport org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;\nimport org.springframework.security.config.annotation.web.configurers.HeadersConfigurer;\nimport org.springframework.security.core.userdetails.User;\nimport org.springframework.security.core.userdetails.UserDetails;\nimport org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;\nimport org.springframework.security.crypto.password.PasswordEncoder;\nimport org.springframework.security.provisioning.InMemoryUserDetailsManager;\nimport org.springframework.security.web.SecurityFilterChain;\n\n@Configuration\npublic class SpringSecurityConfiguration {\n    //LDAP or Database\n    //In Memory \n\n    //InMemoryUserDetailsManager\n    //InMemoryUserDetailsManager(UserDetails... users)\n\n    @Bean\n    public InMemoryUserDetailsManager createUserDetailsManager() {\n\n        UserDetails userDetails1 = createNewUser(\"in28minutes\", \"dummy\");\n        UserDetails userDetails2 = createNewUser(\"ranga\", \"dummydummy\");\n\n        return new InMemoryUserDetailsManager(userDetails1, userDetails2);\n    }\n\n    private UserDetails createNewUser(String username, String password) {\n        Function<String, String> passwordEncoder\n                = input -> passwordEncoder().encode(input);\n\n        UserDetails userDetails = User.builder()\n                .passwordEncoder(passwordEncoder)\n                .username(username)\n                .password(password)\n                .roles(\"USER\", \"ADMIN\")\n                .build();\n        return userDetails;\n    }\n\n    @Bean\n    public PasswordEncoder passwordEncoder() {\n        return new BCryptPasswordEncoder();\n    }\n\n    //All URLs are protected\n    //A login form is shown for unauthorized requests\n    //CSRF disable\n    //Frames\n\n    @Bean\n    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {\n\n        http.authorizeHttpRequests(\n                auth -> auth.anyRequest().authenticated());\n        http.formLogin(withDefaults());\n\n        http.csrf(AbstractHttpConfigurer::disable);\n        // OR\n        // http.csrf(AbstractHttpConfigurer::disable);\n\n        http.headers(headers -> headers.frameOptions(HeadersConfigurer.FrameOptionsConfig::disable)); // Starting from SB 3.1.x\n\n        return http.build();\n    }\n\n}\n```\n\n---\n\n## Step24.md\n\n#### What we will do:\n\n- Remove hardcoded user name\n- Delete the `LoginService`\n- Rename `LoginController` to `WelcomeController`\n- Implement logout functionality\n\n#### Useful Snippets\n\n```java\n    private String getLoggedInUserName(ModelMap model) {\n    Object principal = SecurityContextHolder.getContext()\n            .getAuthentication().getPrincipal();\n\n    if (principal instanceof UserDetails)\n        return ((UserDetails) principal).getUsername();\n\n    return principal.toString();\n}\n```\n\n```html\n\n<ul class=\"nav navbar-nav navbar-right\">\n    <li><a href=\"/logout\">Logout</a></li>\n</ul>\n```\n\n```java\n\n@RequestMapping(value = \"/logout\", method = RequestMethod.GET)\npublic String logout(HttpServletRequest request,\n                     HttpServletResponse response) {\n    Authentication auth = SecurityContextHolder.getContext()\n            .getAuthentication();\n    if (auth != null) {\n        new SecurityContextLogoutHandler().logout(request, response, auth);\n    }\n    return \"redirect:/\";\n}\n\n```\n\n## Step25.md\n\n#### What we will do:\n\n- Introduce basic exception handling\n- Understand that exception handling is a cross-cutting concern\n- Avoid handling exceptions in Controllers or Services unless additional value is added\n- Refactor controllers for cleaner error management\n- Explore the default Spring Boot Whitelabel Error Page\n- Review the details shown on error pages\n- Learn how to customize error pages if needed\n- Use `@ControllerAdvice` for global and controller-specific exception handling\n- Handle errors thrown from views\n\n\n#### Useful Snippets\n\n```\n@Controller(\"error\")\npublic class ExceptionController {\n\n    private Log logger = LogFactory.getLog(ExceptionController.class);\n\n    @ExceptionHandler(Exception.class)\n    public ModelAndView handleError(HttpServletRequest req, Exception ex) {\n        logger.error(\"Request: \" + req.getRequestURL() + \" raised \" + ex);\n\n        ModelAndView mav = new ModelAndView();\n        mav.addObject(\"exception\", ex);\n        mav.addObject(\"url\", req.getRequestURL());\n        mav.setViewName(\"error\");\n        return mav;\n    }\n}\n\n```\n\n#### Files List\n\nsrc/main/java/com/in28minutes/springboot/web/controller/ErrorController.java New\n\n```java\npackage com.in28minutes.springboot.web.controller;\n\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\n\nimport org.springframework.stereotype.Controller;\nimport org.springframework.web.bind.annotation.ExceptionHandler;\nimport org.springframework.web.servlet.ModelAndView;\n\n@Controller(\"error\")\npublic class ErrorController {\n\n    @ExceptionHandler(Exception.class)\n    public ModelAndView handleException\n            (HttpServletRequest request, Exception ex) {\n        ModelAndView mv = new ModelAndView();\n\n        mv.addObject(\"exception\", ex.getLocalizedMessage());\n        mv.addObject(\"url\", request.getRequestURL());\n\n        mv.setViewName(\"error\");\n        return mv;\n    }\n\n}\n```\n\n---\nsrc/main/java/com/in28minutes/springboot/web/controller/LoginController.java Deleted\n\nsrc/main/java/com/in28minutes/springboot/web/controller/LogoutController.java New\n\n```java\npackage com.in28minutes.springboot.web.controller;\n\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\n\nimport org.springframework.security.core.Authentication;\nimport org.springframework.security.core.context.SecurityContextHolder;\nimport org.springframework.security.core.userdetails.UserDetails;\nimport org.springframework.security.web.authentication.logout.LogoutHandler;\nimport org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.ui.ModelMap;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\n\n@Controller\npublic class LogoutController {\n\n    @RequestMapping(value = \"/logout\", method = RequestMethod.GET)\n    public String logout(HttpServletRequest request,\n                         HttpServletResponse response) {\n\n        Authentication authentication = SecurityContextHolder.getContext()\n                .getAuthentication();\n\n        if (authentication != null) {\n            new SecurityContextLogoutHandler().logout(request, response,\n                    authentication);\n        }\n\n        return \"redirect:/\";\n    }\n}\n```\n\n---\nsrc/main/java/com/in28minutes/springboot/web/controller/TodoController.java Modified\n\n```java\n\nprivate String getLoggedInUserName(ModelMap model) {\n    Object principal = SecurityContextHolder.getContext()\n            .getAuthentication().getPrincipal();\n\n    if (principal instanceof UserDetails) {\n        return ((UserDetails) principal).getUsername();\n    }\n\n    return principal.toString();\n}\n\n```\n\n---\nsrc/main/java/com/in28minutes/springboot/web/controller/WelcomeController.java New\n\n```java\npackage com.in28minutes.springboot.web.controller;\n\nimport org.springframework.security.core.context.SecurityContextHolder;\nimport org.springframework.security.core.userdetails.UserDetails;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.ui.ModelMap;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\n\n@Controller\npublic class WelcomeController {\n\n    @RequestMapping(value = \"/\", method = RequestMethod.GET)\n    public String showWelcomePage(ModelMap model) {\n        model.put(\"name\", getLoggedinUserName());\n        return \"welcome\";\n    }\n\n    private String getLoggedinUserName() {\n        Object principal = SecurityContextHolder.getContext()\n                .getAuthentication().getPrincipal();\n\n        if (principal instanceof UserDetails) {\n            return ((UserDetails) principal).getUsername();\n        }\n\n        return principal.toString();\n    }\n\n}\n```\n\n---\nsrc/main/java/com/in28minutes/springboot/web/service/LoginService.java Deleted\n\nsrc/main/webapp/WEB-INF/jsp/common/navigation.jspf Modified\nNew Lines\n\n```html\n<nav role=\"navigation\" class=\"navbar navbar-default\">\n\t<div class=\"\">\n\t\t<a href=\"http://www.in28minutes.com\" class=\"navbar-brand\">in28Minutes</a>\n\t</div>\n\t<div class=\"navbar-collapse\">\n\t\t<ul class=\"nav navbar-nav\">\n\t\t\t<li class=\"active\"><a href=\"/\">Home</a></li>\n\t\t\t<li><a href=\"/list-todos\">Todos</a></li>\n\t\t</ul>\n\t\t<ul class=\"nav navbar-nav navbar-right\">\n\t\t\t<li><a href=\"/logout\">Logout</a></li>\n\t\t</ul>\n\t</div>\n</nav>\n```\n\nsrc/main/webapp/WEB-INF/jsp/error.jsp New\n\n```\n<%@ include file=\"common/header.jspf\"%>\n<%@ include file=\"common/navigation.jspf\"%>\n<div class=\"container\">\nAn exception occurred! Please contact Support!\n</div>\n<%@ include file=\"common/footer.jspf\"%>\n```\n\n---\n\n## Connecting Web Application with JPA\n\n> Note: Complete the \"Introduction to JPA\" module before starting this section.\n\n- Step 26: Add dependencies for JPA and H2\n- Step 27: Configure the H2 Console\n- Step 28: Create the `Todo` entity and JPA repository\n- Step 29: Insert a `Todo` using the JPA repository\n- Step 30: Update, delete, and retrieve `Todos` using the JPA repository\n- Step 31: Initialize data with `data.sql`\n- Step 32: Connect JPA to other databases\n- Step 33: Upgrade to Spring Boot 2 and Spring 5\n\n\n## Step 26 to 32\n\n### /pom.xml New\n\n```xml\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n         xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n    <modelVersion>4.0.0</modelVersion>\n\n    <groupId>com.in28minutes.springboot.web</groupId>\n    <artifactId>spring-boot-first-web-application-git</artifactId>\n    <version>0.0.1-SNAPSHOT</version>\n    <packaging>jar</packaging>\n\n    <name>spring-boot-first-web-application</name>\n    <description>Demo project for Spring Boot</description>\n\n    <parent>\n        <groupId>org.springframework.boot</groupId>\n        <artifactId>spring-boot-starter-parent</artifactId>\n        <version>3.5.5</version>\n        <relativePath/> <!-- lookup parent from repository -->\n    </parent>\n\n    <properties>\n        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>\n        <java.version>21</java.version>\n        <maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>\n    </properties>\n\n    <dependencies>\n        <dependency>\n            <groupId>org.springframework.boot</groupId>\n            <artifactId>spring-boot-starter-web</artifactId>\n        </dependency>\n\n        <dependency>\n            <groupId>org.springframework.boot</groupId>\n            <artifactId>spring-boot-starter-data-jpa</artifactId>\n        </dependency>\n\n        <dependency>\n            <groupId>com.h2database</groupId>\n            <artifactId>h2</artifactId>\n            <scope>runtime</scope>\n        </dependency>\n\n        <dependency>\n            <groupId>org.springframework.boot</groupId>\n            <artifactId>spring-boot-starter-security</artifactId>\n        </dependency>\n\n        <dependency>\n            <groupId>org.apache.tomcat.embed</groupId>\n            <artifactId>tomcat-embed-jasper</artifactId>\n            <scope>provided</scope> <!--default for IntelliJ -->\n        </dependency>\n\n        <dependency>\n            <groupId>jakarta.servlet.jsp.jstl</groupId>\n            <artifactId>jakarta.servlet.jsp.jstl-api</artifactId>\n        </dependency>\n\n        <dependency>\n            <groupId>org.glassfish.web</groupId>\n            <artifactId>jakarta.servlet.jsp.jstl</artifactId>\n        </dependency>\n\n        <dependency>\n            <groupId>org.webjars</groupId>\n            <artifactId>bootstrap</artifactId>\n            <version>5.1.3</version>\n        </dependency>\n\n        <dependency>\n            <groupId>org.webjars</groupId>\n            <artifactId>jquery</artifactId>\n            <version>3.6.0</version>\n        </dependency>\n\n        <dependency>\n            <groupId>org.webjars</groupId>\n            <artifactId>bootstrap-datepicker</artifactId>\n            <version>1.9.0</version>\n        </dependency>\n\n        <dependency>\n            <groupId>org.springframework.boot</groupId>\n            <artifactId>spring-boot-devtools</artifactId>\n            <scope>runtime</scope>\n        </dependency>\n\n        <dependency>\n            <groupId>org.springframework.boot</groupId>\n            <artifactId>spring-boot-starter-test</artifactId>\n            <scope>test</scope>\n        </dependency>\n    </dependencies>\n\n    <build>\n        <plugins>\n            <plugin>\n                <groupId>org.springframework.boot</groupId>\n                <artifactId>spring-boot-maven-plugin</artifactId>\n            </plugin>\n        </plugins>\n    </build>\n\n</project>\n```\n\n---\n\n### /src/main/java/com/in28minutes/springboot/web/SpringBootFirstWebApplication.java New\n\n```java\npackage com.in28minutes.springboot.web;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.context.annotation.ComponentScan;\n\n@SpringBootApplication\n@ComponentScan(\"com.in28minutes.springboot.web\")\npublic class SpringBootFirstWebApplication {\n\n    public static void main(String[] args) {\n        SpringApplication.run(SpringBootFirstWebApplication.class, args);\n    }\n}\n```\n\n---\n\n### /src/main/java/com/in28minutes/springboot/web/controller/ErrorController.java New\n\n```java\npackage com.in28minutes.springboot.web.controller;\n\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\n\nimport org.springframework.stereotype.Controller;\nimport org.springframework.web.bind.annotation.ExceptionHandler;\nimport org.springframework.web.servlet.ModelAndView;\n\n@Controller(\"error\")\npublic class ErrorController {\n\n    @ExceptionHandler(Exception.class)\n    public ModelAndView handleException\n            (HttpServletRequest request, Exception ex) {\n        ModelAndView mv = new ModelAndView();\n\n        mv.addObject(\"exception\", ex.getLocalizedMessage());\n        mv.addObject(\"url\", request.getRequestURL());\n\n        mv.setViewName(\"error\");\n        return mv;\n    }\n\n}\n```\n\n---\n\n### /src/main/java/com/in28minutes/springboot/web/controller/LogoutController.java New\n\n```java\npackage com.in28minutes.springboot.web.controller;\n\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\n\nimport org.springframework.security.core.Authentication;\nimport org.springframework.security.core.context.SecurityContextHolder;\nimport org.springframework.security.core.userdetails.UserDetails;\nimport org.springframework.security.web.authentication.logout.LogoutHandler;\nimport org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.ui.ModelMap;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\n\n@Controller\npublic class LogoutController {\n\n    @RequestMapping(value = \"/logout\", method = RequestMethod.GET)\n    public String logout(HttpServletRequest request,\n                         HttpServletResponse response) {\n\n        Authentication authentication = SecurityContextHolder.getContext()\n                .getAuthentication();\n\n        if (authentication != null) {\n            new SecurityContextLogoutHandler().logout(request, response,\n                    authentication);\n        }\n\n        return \"redirect:/\";\n    }\n}\n```\n\n---\n\n### /src/main/java/com/in28minutes/springboot/web/controller/TodoController.java New\n\n```java\npackage com.in28minutes.springboot.web.controller;\n\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\n\nimport javax.validation.Valid;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.beans.propertyeditors.CustomDateEditor;\nimport org.springframework.security.core.context.SecurityContextHolder;\nimport org.springframework.security.core.userdetails.UserDetails;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.ui.ModelMap;\nimport org.springframework.validation.BindingResult;\nimport org.springframework.web.bind.WebDataBinder;\nimport org.springframework.web.bind.annotation.InitBinder;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\nimport org.springframework.web.bind.annotation.RequestParam;\n\nimport com.in28minutes.springboot.web.model.Todo;\nimport com.in28minutes.springboot.web.service.TodoRepository;\n\n@Controller\npublic class TodoController {\n\n    @Autowired\n    TodoRepository repository;\n\n    @InitBinder\n    public void initBinder(WebDataBinder binder) {\n        // Date - dd/MM/yyyy\n        SimpleDateFormat dateFormat = new SimpleDateFormat(\"dd/MM/yyyy\");\n        binder.registerCustomEditor(Date.class, new CustomDateEditor(\n                dateFormat, false));\n    }\n\n    @RequestMapping(value = \"/list-todos\", method = RequestMethod.GET)\n    public String showTodos(ModelMap model) {\n        String name = getLoggedInUserName(model);\n        model.put(\"todos\", repository.findByUser(name));\n        //model.put(\"todos\", service.retrieveTodos(name));\n        return \"list-todos\";\n    }\n\n    private String getLoggedInUserName(ModelMap model) {\n        Object principal = SecurityContextHolder.getContext()\n                .getAuthentication().getPrincipal();\n\n        if (principal instanceof UserDetails) {\n            return ((UserDetails) principal).getUsername();\n        }\n\n        return principal.toString();\n    }\n\n    @RequestMapping(value = \"/add-todo\", method = RequestMethod.GET)\n    public String showAddTodoPage(ModelMap model) {\n        model.addAttribute(\"todo\", new Todo(0, getLoggedInUserName(model),\n                \"Default Desc\", new Date(), false));\n        return \"todo\";\n    }\n\n    @RequestMapping(value = \"/delete-todo\", method = RequestMethod.GET)\n    public String deleteTodo(@RequestParam int id) {\n\n        //if(id==1)\n        //throw new RuntimeException(\"Something went wrong\");\n        repository.delete(id);\n        //service.deleteTodo(id);\n        return \"redirect:/list-todos\";\n    }\n\n    @RequestMapping(value = \"/update-todo\", method = RequestMethod.GET)\n    public String showUpdateTodoPage(@RequestParam int id, ModelMap model) {\n        Todo todo = repository.findOne(id);\n        //Todo todo = service.retrieveTodo(id);\n        model.put(\"todo\", todo);\n        return \"todo\";\n    }\n\n    @RequestMapping(value = \"/update-todo\", method = RequestMethod.POST)\n    public String updateTodo(ModelMap model, @Valid Todo todo,\n                             BindingResult result) {\n\n        if (result.hasErrors()) {\n            return \"todo\";\n        }\n\n        todo.setUser(getLoggedInUserName(model));\n\n        repository.save(todo);\n        //service.updateTodo(todo);\n\n        return \"redirect:/list-todos\";\n    }\n\n    @RequestMapping(value = \"/add-todo\", method = RequestMethod.POST)\n    public String addTodo(ModelMap model, @Valid Todo todo, BindingResult result) {\n\n        if (result.hasErrors()) {\n            return \"todo\";\n        }\n\n        todo.setUser(getLoggedInUserName(model));\n        repository.save(todo);\n\t\t/*service.addTodo(getLoggedInUserName(model), todo.getDesc(), todo.getTargetDate(),\n\t\t\t\tfalse);*/\n        return \"redirect:/list-todos\";\n    }\n}\n```\n\n---\n\n### /src/main/java/com/in28minutes/springboot/web/controller/WelcomeController.java New\n\n```java\npackage com.in28minutes.springboot.web.controller;\n\nimport org.springframework.security.core.context.SecurityContextHolder;\nimport org.springframework.security.core.userdetails.UserDetails;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.ui.ModelMap;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\n\n@Controller\npublic class WelcomeController {\n\n    @RequestMapping(value = \"/\", method = RequestMethod.GET)\n    public String showWelcomePage(ModelMap model) {\n        model.put(\"name\", getLoggedinUserName());\n        return \"welcome\";\n    }\n\n    private String getLoggedinUserName() {\n        Object principal = SecurityContextHolder.getContext()\n                .getAuthentication().getPrincipal();\n\n        if (principal instanceof UserDetails) {\n            return ((UserDetails) principal).getUsername();\n        }\n\n        return principal.toString();\n    }\n\n}\n```\n\n---\n\n### /src/main/java/com/in28minutes/springboot/web/model/Todo.java New\n\n```java\npackage com.in28minutes.springboot.web.model;\n\nimport java.util.Date;\n\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.Id;\nimport javax.validation.constraints.Size;\n\n@Entity\npublic class Todo {\n\n    @Id\n    @GeneratedValue\n    private int id;\n\n    private String user;\n\n    @Size(min = 10, message = \"Enter at least 10 Characters...\")\n    private String desc;\n\n    private Date targetDate;\n    private boolean isDone;\n\n    public Todo() {\n        super();\n    }\n\n    public Todo(int id, String user, String desc, Date targetDate,\n                boolean isDone) {\n        super();\n        this.id = id;\n        this.user = user;\n        this.desc = desc;\n        this.targetDate = targetDate;\n        this.isDone = isDone;\n    }\n\n    public int getId() {\n        return id;\n    }\n\n    public void setId(int id) {\n        this.id = id;\n    }\n\n    public String getUser() {\n        return user;\n    }\n\n    public void setUser(String user) {\n        this.user = user;\n    }\n\n    public String getDesc() {\n        return desc;\n    }\n\n    public void setDesc(String desc) {\n        this.desc = desc;\n    }\n\n    public Date getTargetDate() {\n        return targetDate;\n    }\n\n    public void setTargetDate(Date targetDate) {\n        this.targetDate = targetDate;\n    }\n\n    public boolean isDone() {\n        return isDone;\n    }\n\n    public void setDone(boolean isDone) {\n        this.isDone = isDone;\n    }\n\n    @Override\n    public int hashCode() {\n        final int prime = 31;\n        int result = 1;\n        result = prime * result + id;\n        return result;\n    }\n\n    @Override\n    public boolean equals(Object obj) {\n        if (this == obj) {\n            return true;\n        }\n        if (obj == null) {\n            return false;\n        }\n        if (getClass() != obj.getClass()) {\n            return false;\n        }\n        Todo other = (Todo) obj;\n        if (id != other.id) {\n            return false;\n        }\n        return true;\n    }\n\n    @Override\n    public String toString() {\n        return String.format(\n                \"Todo [id=%s, user=%s, desc=%s, targetDate=%s, isDone=%s]\", id,\n                user, desc, targetDate, isDone);\n    }\n\n}\n```\n\n---\n\n### /src/main/java/com/in28minutes/springboot/web/security/SecurityConfiguration.java New\n\n```java\npackage com.in28minutes.springboot.web.security;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;\nimport org.springframework.security.config.annotation.web.builders.HttpSecurity;\nimport org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;\n\n@Configuration\npublic class SecurityConfiguration extends WebSecurityConfigurerAdapter {\n    //Create User - in28Minutes/dummy\n    @Autowired\n    public void configureGlobalSecurity(AuthenticationManagerBuilder auth)\n            throws Exception {\n        auth.inMemoryAuthentication().passwordEncoder(org.springframework.security.crypto.password.NoOpPasswordEncoder.getInstance()).withUser(\"in28Minutes\").password(\"dummy\")\n                .roles(\"USER\", \"ADMIN\");\n    }\n\n    @Override\n    protected void configure(HttpSecurity http) throws Exception {\n        http.authorizeRequests().antMatchers(\"/login\", \"/h2-console/**\").permitAll()\n                .antMatchers(\"/\", \"/*todo*/**\").access(\"hasRole('USER')\").and()\n                .formLogin();\n\n        http.csrf().disable();\n        http.headers().frameOptions().disable();\n    }\n}\n```\n\n---\n\n### /src/main/java/com/in28minutes/springboot/web/service/TodoRepository.java New\n\n```java\npackage com.in28minutes.springboot.web.service;\n\nimport java.util.List;\n\nimport org.springframework.data.jpa.repository.JpaRepository;\n\nimport com.in28minutes.springboot.web.model.Todo;\n\npublic interface TodoRepository extends JpaRepository<Todo, Integer> {\n    List<Todo> findByUser(String user);\n\n    //service.retrieveTodos(name)\n\n    //service.deleteTodo(id);\n    //service.retrieveTodo(id)\n    //service.updateTodo(todo)\n    //service.addTodo(getLoggedInUserName(model), todo.getDesc(), todo.getTargetDate(),false);\n}\n```\n\n---\n\n### /src/main/java/com/in28minutes/springboot/web/service/TodoService.java New\n\n```java\npackage com.in28minutes.springboot.web.service;\n\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.Iterator;\nimport java.util.List;\n\nimport org.springframework.stereotype.Service;\n\nimport com.in28minutes.springboot.web.model.Todo;\n\n@Service\npublic class TodoService {\n    private static List<Todo> todos = new ArrayList<Todo>();\n    private static int todoCount = 3;\n\n    static {\n        todos.add(new Todo(1, \"in28Minutes\", \"Learn Spring MVC\", new Date(),\n                false));\n        todos.add(new Todo(2, \"in28Minutes\", \"Learn Struts\", new Date(), false));\n        todos.add(new Todo(3, \"in28Minutes\", \"Learn Hibernate\", new Date(),\n                false));\n    }\n\n    public List<Todo> retrieveTodos(String user) {\n        List<Todo> filteredTodos = new ArrayList<Todo>();\n        for (Todo todo : todos) {\n            if (todo.getUser().equalsIgnoreCase(user)) {\n                filteredTodos.add(todo);\n            }\n        }\n        return filteredTodos;\n    }\n\n    public Todo retrieveTodo(int id) {\n        for (Todo todo : todos) {\n            if (todo.getId() == id) {\n                return todo;\n            }\n        }\n        return null;\n    }\n\n    public void updateTodo(Todo todo) {\n        todos.remove(todo);\n        todos.add(todo);\n    }\n\n    public void addTodo(String name, String desc, Date targetDate,\n                        boolean isDone) {\n        todos.add(new Todo(++todoCount, name, desc, targetDate, isDone));\n    }\n\n    public void deleteTodo(int id) {\n        Iterator<Todo> iterator = todos.iterator();\n        while (iterator.hasNext()) {\n            Todo todo = iterator.next();\n            if (todo.getId() == id) {\n                iterator.remove();\n            }\n        }\n    }\n}\n```\n\n---\n\n### /src/main/resources/application.properties New\n\n```properties\nspring.mvc.view.prefix=/WEB-INF/jsp/\nspring.mvc.view.suffix=.jsp\nlogging.level.org.springframework.web=INFO\nspring.jpa.show-sql=true\nspring.datasource.url=jdbc:h2:mem:testdb\nspring.data.jpa.repositories.bootstrap-mode=default\nspring.h2.console.enabled=true\n```\n\n---\n\n### /src/main/resources/data.sql New\n\n```\ninsert into TODO\nvalues(10001, 'Learn Spring Boot', false, sysdate(), 'in28Minutes');\ninsert into TODO\nvalues(10002, 'Learn Angular JS', false, sysdate(), 'in28Minutes');\ninsert into TODO\nvalues(10003, 'Learn to Dance', false, sysdate(), 'in28Minutes');\n```\n\n---\n\n### /src/main/webapp/WEB-INF/jsp/common/footer.jspf New\n\n```\n<script src=\"webjars/jquery/1.9.1/jquery.min.js\"></script>\n<script src=\"webjars/bootstrap/3.3.6/js/bootstrap.min.js\"></script>\n<script\n\tsrc=\"webjars/bootstrap-datepicker/1.0.1/js/bootstrap-datepicker.js\"></script>\n<script>\n\t$('#targetDate').datepicker({\n\t\tformat : 'dd/mm/yyyy'\n\t});\n</script>\n\n</body>\n</html>\n```\n\n---\n\n### /src/main/webapp/WEB-INF/jsp/common/header.jspf New\n\n```\n<%@ taglib uri=\"http://java.sun.com/jsp/jstl/core\" prefix=\"c\"%>\n<%@ taglib uri=\"http://java.sun.com/jsp/jstl/fmt\" prefix=\"fmt\"%>\n<%@taglib uri=\"http://www.springframework.org/tags/form\" prefix=\"form\"%>\n\n<html>\n\n<head>\n<title>First Web Application</title>\n<link href=\"webjars/bootstrap/3.3.6/css/bootstrap.min.css\"\n\trel=\"stylesheet\">\n\n</head>\n\n<body>\n```\n\n---\n\n### /src/main/webapp/WEB-INF/jsp/common/navigation.jspf New\n\n```\n\n<nav role=\"navigation\" class=\"navbar navbar-default\">\n\t<div class=\"\">\n\t\t<a href=\"http://www.in28minutes.com\" class=\"navbar-brand\">in28Minutes</a>\n\t</div>\n\t<div class=\"navbar-collapse\">\n\t\t<ul class=\"nav navbar-nav\">\n\t\t\t<li class=\"active\"><a href=\"/\">Home</a></li>\n\t\t\t<li><a href=\"/list-todos\">Todos</a></li>\n\t\t</ul>\n\t\t<ul class=\"nav navbar-nav navbar-right\">\n\t\t\t<li><a href=\"/logout\">Logout</a></li>\n\t\t</ul>\n\t</div>\n</nav>\n```\n\n---\n\n### /src/main/webapp/WEB-INF/jsp/error.jsp New\n\n```\n<%@ include file=\"common/header.jspf\"%>\n<%@ include file=\"common/navigation.jspf\"%>\n<div class=\"container\">\nAn exception occurred! Please contact Support!\n</div>\n<%@ include file=\"common/footer.jspf\"%>\n```\n\n---\n\n### /src/main/webapp/WEB-INF/jsp/list-todos.jsp New\n\n```\n<%@ include file=\"common/header.jspf\" %>\n<%@ include file=\"common/navigation.jspf\" %>\n\t\n\t<div class=\"container\">\n\t\t<table class=\"table table-striped\">\n\t\t\t<caption>Your todos are</caption>\n\t\t\t<thead>\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Description</th>\n\t\t\t\t\t<th>Target Date</th>\n\t\t\t\t\t<th>Is it Done?</th>\n\t\t\t\t\t<th></th>\n\t\t\t\t\t<th></th>\n\t\t\t\t</tr>\n\t\t\t</thead>\n\t\t\t<tbody>\n\t\t\t\t<c:forEach items=\"${todos}\" var=\"todo\">\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td>${todo.desc}</td>\n\t\t\t\t\t\t<td><fmt:formatDate value=\"${todo.targetDate}\" pattern=\"dd/MM/yyyy\"/></td>\n\t\t\t\t\t\t<td>${todo.done}</td>\n\t\t\t\t\t\t<td><a type=\"button\" class=\"btn btn-success\"\n\t\t\t\t\t\t\thref=\"/update-todo?id=${todo.id}\">Update</a></td>\n\t\t\t\t\t\t<td><a type=\"button\" class=\"btn btn-warning\"\n\t\t\t\t\t\t\thref=\"/delete-todo?id=${todo.id}\">Delete</a></td>\n\t\t\t\t\t</tr>\n\t\t\t\t</c:forEach>\n\t\t\t</tbody>\n\t\t</table>\n\t\t<div>\n\t\t\t<a class=\"button\" href=\"/add-todo\">Add a Todo</a>\n\t\t</div>\n\t</div>\n<%@ include file=\"common/footer.jspf\" %>\n```\n\n---\n\n### /src/main/webapp/WEB-INF/jsp/todo.jsp New\n\n```\n<%@ include file=\"common/header.jspf\" %>\n<%@ include file=\"common/navigation.jspf\" %>\n<div class=\"container\">\n\t<form:form method=\"post\" commandName=\"todo\">\n\t\t\t<!-- use modelAttribute instead of commandName for Spring Boot Versions > 2.*\n\t\t<form:form method=\"post\" modelAttribute=\"todo\"> -->\n\t\t<form:hidden path=\"id\" />\n\t\t<fieldset class=\"form-group\">\n\t\t\t<form:label path=\"desc\">Description</form:label>\n\t\t\t<form:input path=\"desc\" type=\"text\" class=\"form-control\"\n\t\t\t\trequired=\"required\" />\n\t\t\t<form:errors path=\"desc\" cssClass=\"text-warning\" />\n\t\t</fieldset>\n\n\t\t<fieldset class=\"form-group\">\n\t\t\t<form:label path=\"targetDate\">Target Date</form:label>\n\t\t\t<form:input path=\"targetDate\" type=\"text\" class=\"form-control\"\n\t\t\t\trequired=\"required\" />\n\t\t\t<form:errors path=\"targetDate\" cssClass=\"text-warning\" />\n\t\t</fieldset>\n\n\t\t<button type=\"submit\" class=\"btn btn-success\">Add</button>\n\t</form:form>\n</div>\n<%@ include file=\"common/footer.jspf\" %>\n```\n\n---\n\n### /src/main/webapp/WEB-INF/jsp/welcome.jsp New\n\n```\n<%@ include file=\"common/header.jspf\"%>\n<%@ include file=\"common/navigation.jspf\"%>\n<div class=\"container\">\n\tWelcome ${name}!! <a href=\"/list-todos\">Click here</a> to manage your\n\ttodo's.\n</div>\n<%@ include file=\"common/footer.jspf\"%>\n```\n\n---\n\n### /src/test/java/com/in28minutes/springboot/web/SpringBootFirstWebApplicationTests.java New\n\n```java\npackage com.in28minutes.springboot.web;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.springframework.boot.test.context.SpringBootTest;\nimport org.springframework.test.context.junit4.SpringRunner;\n\n@RunWith(SpringRunner.class)\n@SpringBootTest\npublic class SpringBootFirstWebApplicationTests {\n\n    @Test\n    public void contextLoads() {\n    }\n\n}\n```\n\n## step33-Upgrade-To-Sprint-Boot-2-M3.md\n\n### /pom.xml Modified\n\nNew Lines\n\n```\n\t\t<version>2.3.1.RELEASE</version>\n```\n\n### /src/main/java/com/in28minutes/springboot/web/controller/TodoController.java Modified\n\nNew Lines\n\n```\n\trepository.deleteById(id);\n\tTodo todo = repository.findById(id).get();\n```\n\n---\n\n### /src/main/webapp/WEB-INF/jsp/todo.jsp Modified\n\nNew Lines\n\n```\n\t<form:form method=\"post\" modelAttribute=\"todo\">\n```\n\n## Files List\n\n### 02.Spring-Boot-Web-Application/notes.md\n\n## Schema\n\n```sql\ncreate table todo\n(\n    id          integer not null,\n    desc        varchar(255),\n    is_done     boolean not null,\n    target_date timestamp,\n    user        varchar(255),\n    primary key (id)\n)\n```\n\n### Data\n\n```sql\nINSERT INTO TODO\nVALUES (10001, 'Learn Spring Boot', false, sysdate(), 'in28Minutes')\n    INSERT\nINTO TODO\nVALUES (10002, 'Learn RESTful Web Services', false, sysdate(), 'in28Minutes')\n\nINSERT INTO TODO\nVALUES (10003, 'Learn SOAP Web Services', false, sysdate(), 'in28Minutes')\n```\n\n### 02.Spring-Boot-Web-Application/README.md\n\nDeveloping your first Spring Boot Web Application is fun.\n\n## Installing and Setting Up MySQL\n\n- Install MySQL https://dev.mysql.com/doc/en/installing.html\n    - More details : http://www.mysqltutorial.org/install-mysql/\n    - Trouble Shooting - https://dev.mysql.com/doc/refman/en/problems.html\n- Startup the Server (as a service)\n- Go to command prompt (or terminal)\n    - Execute following commands to create a database and a user\n\n```\nmysql --user=user_name --password db_name\ncreate database todo_example;\ncreate user 'todouser'@'localhost' identified by 'YOUR_PASSWORD';\ngrant all on todo_example.* to 'todouser'@'localhost';\n```\n\n- Execute following sql queries to create the table and insert the data\n\nTable\n\n```sql\ncreate table todo\n(\n    id          integer not null,\n    desc        varchar(255),\n    is_done     boolean not null,\n    target_date timestamp,\n    user        varchar(255),\n    primary key (id)\n);\n```\n\nData\n\n```sql\nINSERT INTO TODO\nVALUES (10001, 'Learn Spring Boot', false, sysdate(), 'in28Minutes');\n\nINSERT INTO TODO\nVALUES (10002, 'Learn RESTful Web Services', false, sysdate(), 'in28Minutes');\n\nINSERT INTO TODO\nVALUES (10003, 'Learn SOAP Web Services', false, sysdate(), 'in28Minutes');\n```\n\n## Code changes to connect to MySQL\n\n- Add dependency to pom.xml (and remove H2 dependency)\n\n```xml\n\n<dependency>\n    <groupId>mysql</groupId>\n    <artifactId>mysql-connector-java</artifactId>\n</dependency>\n```\n\n- Configure application.properties\n\n```properties\nspring.jpa.hibernate.ddl-auto=none\nspring.datasource.url=jdbc:mysql://localhost:3306/todo_example\nspring.datasource.username=todouser\nspring.datasource.password=YOUR_PASSWORD\n```\n\n- Restart and You are ready!\n\n# 05.Spring-Boot-Advanced\n\nYou will be using Spring Boot and get introduced to REST Services.\n\nYou will learn about\n\n- Basics of Auto Configuration and Spring Boot Magic\n- Spring Boot Starter Projects\n- Spring Initializr\n- REST Service Content Negotiation with JSON and XML\n- Embedded servlet containers : Tomcat, Jetty and Undertow\n- Writing Unit and Integration tests using Spring Boot Starter Test\n- Profiles and Dynamic Configuration with Spring Boot\n- Spring Boot Data JPA\n- Spring Boot Actuator\n- Spring Boot Developer Tools and LiveReload\n\n## Step01.md\n\n#### What You Will Learn during this Step:\n\n- Set up an Maven Project with Eclipse.\n- Intellij Link : https://www.jetbrains.com/help/idea/2016.2/getting-started-with-maven.html#create_maven_project\n- Copy Two Files pom.xml and Application.java\n- Launch Your First Spring Boot Application.\n- You will be introduced to Maven\n    - Dependency Management\n\n#### Cool thing to note!\n\n- Without a lot of configuration, we are up and running with a web application\n- Refer https://github.com/in28minutes/SpringMvcStepByStep/blob/master/Step15.md to understand the sort of stuff -\n  web.xml, dispatcher servlet configuration, maven dependency management and plugins - that are need to launch a typical\n  web application without Spring Boot!\n\n#### What You Will NOT Learn during this Step:\n\n- Spring Boot does a lot of magic. This magic is called Auto Configuration. We will discuss about different terms\n  related to Spring Boot - Starter Parent, Starter projects, Auto configuration - in depth during our first 10 steps.\n- As far as this step is concerned, we will focus on getting up and running with Spring Boot. We will understand all the\n  magic a little later.\n- We will copy a lot of code in this step - just to avoid typos\n\n#### Exercises\n\n- If you are comfortable with Spring, try to create a few dependencies and see if are automatically auto-wired!\n\n#### Files List\n\npom.xml\n\n```\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\t<groupId>com.in28minutes.springboot</groupId>\n\t<artifactId>first-springboot-project</artifactId>\n\t<version>0.0.1-SNAPSHOT</version>\n\t<parent>\n\t\t<groupId>org.springframework.boot</groupId>\n\t\t<artifactId>spring-boot-starter-parent</artifactId>\n\t\t<version>1.4.0.RELEASE</version>\n\t</parent>\n\n\t<properties>\n\t\t<java.version>1.8</java.version>\n<maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>\n\t</properties>\n\n\t<dependencies>\n\t\t<dependency>\n\t\t\t<groupId>org.springframework.boot</groupId>\n\t\t\t<artifactId>spring-boot-starter-web</artifactId>\n\t\t</dependency>\n\t</dependencies>\n\n\t<build>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.springframework.boot</groupId>\n\t\t\t\t<artifactId>spring-boot-maven-plugin</artifactId>\n\t\t\t</plugin>\n\t\t</plugins>\n\t</build>\n</project>\n```\n\nsrc/main/java/com/in28minutes/springboot/Application.java\n\n```\npackage com.in28minutes.springboot;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.context.ApplicationContext;\n\n@SpringBootApplication\npublic class Application {\n\n\tpublic static void main(String[] args) {\n\t\tApplicationContext ctx = SpringApplication.run(Application.class, args);\n\n\t}\n\n}\n```\n\n## Step02.md\n\n#### What You Will Learn during this Step:\n\n- Lets add a RestController with a dependency and see Spring Boot Magic live\n\n#### Theory Break : Quick Spring and Spring MVC Primer\n\n- What is dependency?\n- @Component\n- @Autowired\n- @RestController\n\n#### Useful Snippets and References\n\n```\npackage com.in28minutes.springboot;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Component;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RestController;\n\n@RestController\npublic class WelcomeController {\n\n\t//Auto wiring\n\t@Autowired\n\tprivate WelcomeService service;\n\n\t@RequestMapping(\"/welcome\")\n\tpublic String welcome() {\n\t\treturn service.retrieveWelcomeMessage();\n\t}\n}\n\n@Component\nclass WelcomeService {\n\n\tpublic String retrieveWelcomeMessage() {\n\t\t//Complex Method\n\t\treturn \"Good Morning updated\";\n\t}\n}\n```\n\n#### Files List\n\nsrc/main/java/com/in28minutes/service/WelcomeService.java New\n\n```\npackage com.in28minutes.service;\n\nimport org.springframework.stereotype.Component;\n\n@Component\npublic class WelcomeService {\n\n\tpublic String retrieveWelcomeMessage() {\n\t\t//Complex Method\n\t\treturn \"Good Morning updated\";\n\t}\n}\n```\n\nsrc/main/java/com/in28minutes/springboot/Application.java Modified\nNew Lines\n\n```\nimport org.springframework.context.annotation.ComponentScan;\n@ComponentScan(\"com.in28minutes\")\n```\n\n```\npackage com.in28minutes.springboot;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.annotation.ComponentScan;\n\n@SpringBootApplication\n@ComponentScan(\"com.in28minutes\")\npublic class Application {\n\n\tpublic static void main(String[] args) {\n\t\tApplicationContext ctx = SpringApplication.run(Application.class, args);\n\n\t}\n\n}\n```\n\nsrc/main/java/com/in28minutes/springboot/WelcomeController.java New\n\n```\npackage com.in28minutes.springboot;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RestController;\n\nimport com.in28minutes.service.WelcomeService;\n\n@RestController\npublic class WelcomeController {\n\n\t//Auto wiring\n\t@Autowired\n\tprivate WelcomeService service;\n\n\t@RequestMapping(\"/welcome\")\n\tpublic String welcome() {\n\t\treturn service.retrieveWelcomeMessage();\n\t}\n}\n```\n\n## Step03.md\n\n#### What You Will Learn during this Step:\n\n- First installment of revealing how magic happens with Spring Boot. As a Spring Boot developer, you need to understand\n  what's happening beneath the hood of Spring Boot!\n- spring-boot-starter-web : starter for building applications with Spring MVC. Tomcat is default embedded container.\n- We already added this starter in the first step! Now we will explore the features it provides\n- We will enable logging in DEBUG mode to understand further\n\n## spring-boot-starter-web\n\n- Spring Boot Starter Web brings all dependencies needed to build normal and RESTful web applications. Look at the\n  dependency tree.\n- All the dependencies are added in because of spring-boot-starter-web\n- Also look at /META-INF/spring.provides inside the spring-boot-starter-web.jar\n- Spring Boot Starter Web auto configures things needed to startup a web application. Look at the log\n- Mapping servlet: 'dispatcherServlet' to [/]\n- Mapped \"{[/error]}\" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String,\n  java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(\n  javax.servlet.http.HttpServletRequest)\n- Mapped URL path [/webjars/**] onto handler of\n  type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]\n- Look at package org.springframework.boot.autoconfigure.web in spring-boot-autoconfigure-*.jar\n- Go to url http://localhost:8080/some-non-existing-url\n\n#### Useful Snippets\n\n/src/main/resources/application.properties\n\n```\nlogging.level.org.springframework: DEBUG\n```\n\n#### Files List\n\nsrc/main/java/com/in28minutes/service/WelcomeService.java Deleted\nsrc/main/java/com/in28minutes/springboot/Application.java Modified\nNew Lines\n\n```\n```\n\n```\npackage com.in28minutes.springboot;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.context.ApplicationContext;\n\n@SpringBootApplication\npublic class Application {\n\n\tpublic static void main(String[] args) {\n\t\tApplicationContext ctx = SpringApplication.run(Application.class, args);\n\n\t}\n\n}\n```\n\nsrc/main/java/com/in28minutes/springboot/WelcomeController.java Modified\nNew Lines\n\n```\n```\n\n```\npackage com.in28minutes.springboot;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RestController;\n\n@RestController\npublic class WelcomeController {\n\n\t//Auto wiring\n\t@Autowired\n\tprivate WelcomeService service;\n\n\t@RequestMapping(\"/welcome\")\n\tpublic String welcome() {\n\t\treturn service.retrieveWelcomeMessage();\n\t}\n}\n```\n\nsrc/main/java/com/in28minutes/springboot/WelcomeService.java New\n\n```\npackage com.in28minutes.springboot;\n\nimport org.springframework.stereotype.Component;\n\n@Component\npublic class WelcomeService {\n\n\tpublic String retrieveWelcomeMessage() {\n\t\t//Complex Method\n\t\treturn \"Good Morning updated\";\n\t}\n}\n```\n\nsrc/main/resources/application.properties New\n\n```\nlogging.level.org.springframework: DEBUG\n```\n\n## Step04.md\n\n#### What You Will Learn during this Step:\n\n- Understand Starter Parent\n- How to override things defined in Starter Parent\n- Other starter projects\n\n#### Starter Parent\n\n- Dependency Versions\n- Java Versions\n- Default Plugins\n\n#### Other Starter Projects\n\n- spring-boot-starter-web-services\n- spring-boot-starter-test\n- spring-boot-starter-jdbc\n- spring-boot-starter-security\n- spring-boot-starter-data-jpa\n- spring-boot-starter-data-rest\n- More at https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#using-boot-starter\n\n#### Useful Snippets and References\n\nFirst Snippet\n\n```\n    <parent>\n        <groupId>org.springframework.boot</groupId>\n        <artifactId>spring-boot-starter-parent</artifactId>\n        <version>1.4.0.RELEASE</version>\n    </parent>\n```\n\n## Step05.md\n\n#### What You Will Learn during this Step:\n\n- Spring Boot vs Spring\n- What Spring Boot is Not!\n\n#### Spring Boot vs Spring\n\n### Applications with Spring Framework New\n\n- Over the next few years, a number of applications were developed with Spring Framework\n- Testable but\n- Lot of configuration (XML and Java)\n- Developing Spring Based application need configuration of a lot of beans!\n- Integration with other frameworks need configuration as well!\n- In the last few years, focus is moving from monolith applications to microservices. We need to be able to start\n  project quickly. Minimum or Zero start up time\n- Framework Setup\n- Deployment - Configurability\n- Logging, Transaction Management\n- Monitoring\n- Web Server Configuration\n\n### Spring New\n\n- Spring is just a dependency injection framework. Spring focuses on the \"plumbing\" of enterprise applications so that\n  teams can focus on application-level business logic, without unnecessary ties to specific deployment environments.\n- First half of the 2000 decade! EJBs\n- EJBs were NOT easy to develop.\n- Write a lot of xml and plumbing code to get EJBs running\n- Impossible to Unit Test\n- Alternative - Writing simple JDBC Code involved a lot of plumbing\n- Spring framework started with aim of making Java EE development simpler.\n- Goals\n- Make applications testable. i.e. easier to write unit tests\n- Reduce plumbing code of JDBC and JMS\n- Simple architecture. Minus EJB.\n- Integrates well with other popular frameworks.\n\n### Spring Boot New\n\n- Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can “just run”.\n- We take an opinionated view of the Spring platform and third-party libraries so you can get started with minimum fuss.\n- Example Problem Statements\n- You want to add Hibernate to your project. You dont worry about configuring a data source and a session factory. I\n  will do if for you!\n- Goals\n    - Provide quick start for projects with Spring.\n    - Be opinionated but provide options.\n    - Provide a range of non-functional features that are common to large classes of projects (e.g. embedded servers,\n      security, metrics, health checks, externalized configuration).\n\n###### What Spring Boot is NOT?\n\n- It’s not an app or a web server\n- Does not implement any specific framework - for example, JPA or JMS\n- Does not generate code\n\npom.xml Deleted\nsrc/main/java/com/in28minutes/springboot/Application.java Deleted\nsrc/main/java/com/in28minutes/springboot/WelcomeController.java Deleted\nsrc/main/java/com/in28minutes/springboot/WelcomeService.java Deleted\nsrc/main/resources/application.properties Deleted\n\n## Step06.md\n\n#### What You Will Learn during this Step:\n\n- We want to prepare for creating a Rest Service\n- Survey\n- Question\n- SurveyService\n- We use hard-coded data to get started\n\n#### Files List\n\n### Applications with Spring Framework Deleted\n\n### Spring Deleted\n\n### Spring Boot Deleted\n\npom.xml New\n\n```\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\t<groupId>com.in28minutes.springboot</groupId>\n\t<artifactId>first-springboot-project</artifactId>\n\t<version>0.0.1-SNAPSHOT</version>\n\t<parent>\n\t\t<groupId>org.springframework.boot</groupId>\n\t\t<artifactId>spring-boot-starter-parent</artifactId>\n\t\t<version>1.4.0.RELEASE</version>\n\t</parent>\n\n\t<properties>\n\t\t<java.version>1.8</java.version>\n<maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>\n\t</properties>\n\n\t<dependencies>\n\t\t<dependency>\n\t\t\t<groupId>org.springframework.boot</groupId>\n\t\t\t<artifactId>spring-boot-starter-web</artifactId>\n\t\t</dependency>\n\t</dependencies>\n\n\t<build>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.springframework.boot</groupId>\n\t\t\t\t<artifactId>spring-boot-maven-plugin</artifactId>\n\t\t\t</plugin>\n\t\t</plugins>\n\t</build>\n</project>\n```\n\nsrc/main/java/com/in28minutes/springboot/Application.java New\n\n```\npackage com.in28minutes.springboot;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.context.ApplicationContext;\n\n@SpringBootApplication\npublic class Application {\n\n\tpublic static void main(String[] args) {\n\t\tApplicationContext ctx = SpringApplication.run(Application.class, args);\n\n\t}\n\n}\n```\n\nsrc/main/java/com/in28minutes/springboot/WelcomeController.java New\n\n```\npackage com.in28minutes.springboot;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RestController;\n\n@RestController\npublic class WelcomeController {\n\n\t//Auto wiring\n\t@Autowired\n\tprivate WelcomeService service;\n\n\t@RequestMapping(\"/welcome\")\n\tpublic String welcome() {\n\t\treturn service.retrieveWelcomeMessage();\n\t}\n}\n```\n\nsrc/main/java/com/in28minutes/springboot/WelcomeService.java New\n\n```\npackage com.in28minutes.springboot;\n\nimport org.springframework.stereotype.Component;\n\n@Component\npublic class WelcomeService {\n\n\tpublic String retrieveWelcomeMessage() {\n\t\t//Complex Method\n\t\treturn \"Good Morning updated\";\n\t}\n}\n```\n\nsrc/main/java/com/in28minutes/springboot/model/Question.java New\n\n```\npackage com.in28minutes.springboot.model;\n\nimport java.util.List;\n\npublic class Question {\n\tprivate String id;\n\tprivate String description;\n\tprivate String correctAnswer;\n\tprivate List<String> options;\n\n\t// Needed by Caused by: com.fasterxml.jackson.databind.JsonMappingException:\n\t// Can not construct instance of com.in28minutes.springboot.model.Question:\n\t// no suitable constructor found, can not deserialize from Object value\n\t// (missing default constructor or creator, or perhaps need to add/enable\n\t// type information?)\n\tpublic Question() {\n\n\t}\n\n\tpublic Question(String id, String description, String correctAnswer,\n\t\t\tList<String> options) {\n\t\tsuper();\n\t\tthis.id = id;\n\t\tthis.description = description;\n\t\tthis.correctAnswer = correctAnswer;\n\t\tthis.options = options;\n\t}\n\n\tpublic String getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(String id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getDescription() {\n\t\treturn description;\n\t}\n\n\tpublic String getCorrectAnswer() {\n\t\treturn correctAnswer;\n\t}\n\n\tpublic List<String> getOptions() {\n\t\treturn options;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn String\n\t\t\t\t.format(\"Question [id=%s, description=%s, correctAnswer=%s, options=%s]\",\n\t\t\t\t\t\tid, description, correctAnswer, options);\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + ((id == null) ? 0 : id.hashCode());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tQuestion other = (Question) obj;\n\t\tif (id == null) {\n\t\t\tif (other.id != null)\n\t\t\t\treturn false;\n\t\t} else if (!id.equals(other.id))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n}\n```\n\nsrc/main/java/com/in28minutes/springboot/model/Survey.java New\n\n```\npackage com.in28minutes.springboot.model;\n\nimport java.util.List;\n\npublic class Survey {\n\tprivate String id;\n\tprivate String title;\n\tprivate String description;\n\tprivate List<Question> questions;\n\n\tpublic Survey(String id, String title, String description,\n\t\t\tList<Question> questions) {\n\t\tsuper();\n\t\tthis.id = id;\n\t\tthis.title = title;\n\t\tthis.description = description;\n\t\tthis.questions = questions;\n\t}\n\n\tpublic String getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(String id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getTitle() {\n\t\treturn title;\n\t}\n\n\tpublic void setTitle(String title) {\n\t\tthis.title = title;\n\t}\n\n\tpublic String getDescription() {\n\t\treturn description;\n\t}\n\n\tpublic void setDescription(String description) {\n\t\tthis.description = description;\n\t}\n\n\tpublic List<Question> getQuestions() {\n\t\treturn questions;\n\t}\n\n\tpublic void setQuestions(List<Question> questions) {\n\t\tthis.questions = questions;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Survey [id=\" + id + \", title=\" + title + \", description=\"\n\t\t\t\t+ description + \", questions=\" + questions + \"]\";\n\t}\n\n}\n```\n\nsrc/main/java/com/in28minutes/springboot/service/SurveyService.java New\n\n```\npackage com.in28minutes.springboot.service;\n\nimport java.math.BigInteger;\nimport java.security.SecureRandom;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\nimport org.springframework.stereotype.Component;\n\nimport com.in28minutes.springboot.model.Question;\nimport com.in28minutes.springboot.model.Survey;\n\n@Component\npublic class SurveyService {\n\tprivate static List<Survey> surveys = new ArrayList<>();\n\tstatic {\n\t\tQuestion question1 = new Question(\"Question1\",\n\t\t\t\t\"Largest Country in the World\", \"Russia\", Arrays.asList(\n\t\t\t\t\t\t\"India\", \"Russia\", \"United States\", \"China\"));\n\t\tQuestion question2 = new Question(\"Question2\",\n\t\t\t\t\"Most Populus Country in the World\", \"China\", Arrays.asList(\n\t\t\t\t\t\t\"India\", \"Russia\", \"United States\", \"China\"));\n\t\tQuestion question3 = new Question(\"Question3\",\n\t\t\t\t\"Highest GDP in the World\", \"United States\", Arrays.asList(\n\t\t\t\t\t\t\"India\", \"Russia\", \"United States\", \"China\"));\n\t\tQuestion question4 = new Question(\"Question4\",\n\t\t\t\t\"Second largest english speaking country\", \"India\", Arrays\n\t\t\t\t\t\t.asList(\"India\", \"Russia\", \"United States\", \"China\"));\n\n\t\tList<Question> questions = new ArrayList<>(Arrays.asList(question1,\n\t\t\t\tquestion2, question3, question4));\n\n\t\tSurvey survey = new Survey(\"Survey1\", \"My Favorite Survey\",\n\t\t\t\t\"Description of the Survey\", questions);\n\n\t\tsurveys.add(survey);\n\t}\n\n\tpublic List<Survey> retrieveAllSurveys() {\n\t\treturn surveys;\n\t}\n\n\tpublic Survey retrieveSurvey(String surveyId) {\n\t\tfor (Survey survey : surveys) {\n\t\t\tif (survey.getId().equals(surveyId)) {\n\t\t\t\treturn survey;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic List<Question> retrieveQuestions(String surveyId) {\n\t\tSurvey survey = retrieveSurvey(surveyId);\n\n\t\tif (survey == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\treturn survey.getQuestions();\n\t}\n\n\tpublic Question retrieveQuestion(String surveyId, String questionId) {\n\t\tSurvey survey = retrieveSurvey(surveyId);\n\n\t\tif (survey == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\tfor (Question question : survey.getQuestions()) {\n\t\t\tif (question.getId().equals(questionId)) {\n\t\t\t\treturn question;\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}\n\n\tprivate SecureRandom random = new SecureRandom();\n\n\tpublic Question addQuestion(String surveyId, Question question) {\n\t\tSurvey survey = retrieveSurvey(surveyId);\n\n\t\tif (survey == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\tString randomId = new BigInteger(130, random).toString(32);\n\t\tquestion.setId(randomId);\n\n\t\tsurvey.getQuestions().add(question);\n\n\t\treturn question;\n\t}\n}\n```\n\nsrc/main/resources/application.properties New\n\n```\nlogging.level.org.springframework: DEBUG\n```\n\n## Step07.md\n\n#### What You Will Learn during this Step:\n\n- Create a REST Service for Retrieving all questions for a survey\n- Autowire SurveyService\n- Create @GetMapping(\"/surveys/{surveyId}/questions\")\n- Use @PathVariable String surveyId\n- http://localhost:8080/surveys/Survey1/questions/\n- How does the Bean get converted to a JSON?\n- Auto Configuration : If Jackson jar is on the class path, message converters are auto created! (Search in log :\n  Creating shared instance of singleton bean 'mappingJackson2HttpMessageConverter')\n\n#### Some Theory\n\n- What is REST?\n- Architectural style for the web. REST specifies a set of constraints.\n    - Client - Server : Server (service provider) should be different from a client (service consumer).\n        - Enables loose coupling and independent evolution of server and client as new technologies emerge.\n    - Each service should be stateless.\n    - Each Resource has a resource identifier.\n    - It should be possible to cache response.\n    - Consumer of the service may not have a direct connection to the Service Provider. Response might be sent from a\n      middle layer cache.\n    - A resource can have multiple representations. Resource can modified through a message in any of the these\n      representations.\n\n#### Useful Snippets and References\n\n- JSON View : https://jsonview.com/\n  First Snippet\n\n```\n@RestController\nclass SurveyController {\n    @Autowired\n    private SurveyService surveyService;\n\n    @GetMapping(\"/surveys/{surveyId}/questions\")\n    public List<Question> retrieveQuestions(@PathVariable String surveyId) {\n        return surveyService.retrieveQuestions(surveyId);\n    }\n}\n```\n\n#### Exercise\n\n- Try to think about how the URI for retrieving the details of a specific question should be!\n\n#### Files List\n\npom.xml Modified\nNew Lines\n\n```\n\t\t\n            <groupId>org.springframework.boot</groupId>\n            <artifactId>spring-boot-devtools</artifactId>\n            <optional>true</optional>\n        </dependency>\n```\n\nsrc/main/java/com/in28minutes/springboot/controller/SurveyController.java New\n\n```\npackage com.in28minutes.springboot.controller;\n\nimport java.util.List;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.RestController;\n\nimport com.in28minutes.springboot.model.Question;\nimport com.in28minutes.springboot.service.SurveyService;\n\n@RestController\nclass SurveyController {\n\t@Autowired\n\tprivate SurveyService surveyService;\n\n\t@GetMapping(\"/surveys/{surveyId}/questions\")\n\tpublic List<Question> retrieveQuestions(@PathVariable String surveyId) {\n\t\treturn surveyService.retrieveQuestions(surveyId);\n\t}\n}\n```\n\n## Step08.md\n\n#### What You Will Learn during this Step:\n\n- Adding the second method to rest service to retrieve a specific question\n- This will be a very short step\n- http://localhost:8080/surveys/Survey1/questions/Question1\n- Different Request Methods\n    - GET - Retrieve details of a resource\n    - POST - Create a new resource\n    - PUT - Update an existing resource\n    - PATCH - Update part of a resource\n    - DELETE - Delete a resource\n\n#### Useful Snippets and References\n\nFirst Snippet\n\n```\n    @GetMapping(path = \"/surveys/{surveyId}/questions/{questionId}\")\n    public Question retrieveQuestion(@PathVariable String surveyId,\n            @PathVariable String questionId) {\n        return surveyService.retrieveQuestion(surveyId, questionId);\n    }\n\n```\n\n#### Exercises\n\n- Write the method to retrieve all surveys!\n\n#### Files List\n\nsrc/main/java/com/in28minutes/springboot/controller/SurveyController.java Modified\nNew Lines\n\n```\n\t// GET \"/surveys/{surveyId}/questions/{questionId}\"\n\t@GetMapping(\"/surveys/{surveyId}/questions/{questionId}\")\n\tpublic Question retrieveDetailsForQuestion(@PathVariable String surveyId,\n\t\t\t@PathVariable String questionId) {\n\t\treturn surveyService.retrieveQuestion(surveyId, questionId);\n```\n\n```\npackage com.in28minutes.springboot.controller;\n\nimport java.util.List;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.RestController;\n\nimport com.in28minutes.springboot.model.Question;\nimport com.in28minutes.springboot.service.SurveyService;\n\n@RestController\nclass SurveyController {\n\t@Autowired\n\tprivate SurveyService surveyService;\n\n\t@GetMapping(\"/surveys/{surveyId}/questions\")\n\tpublic List<Question> retrieveQuestions(@PathVariable String surveyId) {\n\t\treturn surveyService.retrieveQuestions(surveyId);\n\t}\n\n\t// GET \"/surveys/{surveyId}/questions/{questionId}\"\n\t@GetMapping(\"/surveys/{surveyId}/questions/{questionId}\")\n\tpublic Question retrieveDetailsForQuestion(@PathVariable String surveyId,\n\t\t\t@PathVariable String questionId) {\n\t\treturn surveyService.retrieveQuestion(surveyId, questionId);\n\t}\n\n}\n```\n\n## Step09.md\n\n#### What You Will Learn during this Step:\n\n- I hate the fact that I've to stop and start the server each time. Can somebody save me?\n- Yeah. Spring Boot Developer Tools\n- By default, any entry on the classpath that points to a folder will be monitored for changes.\n- These will not trigger restart - /META-INF/maven, /META-INF/resources ,/resources ,/static ,/public or /templates\n- Folders can be configured : spring.devtools.restart.exclude=static/**,public/**\n- Additional Paths : spring.devtools.restart.additional-paths\n- LiveReload http://livereload.com/extensions/\n- Technology in progress!! So, expect a few problems!\n- Programming Tip\n- Become an expert at your IDE - https://www.youtube.com/watch?v=dN9GYsG1v_c\n\n#### Useful Snippets and References\n\nFirst Snippet\n\n```\n        <dependency>\n            <groupId>org.springframework.boot</groupId>\n            <artifactId>spring-boot-devtools</artifactId>\n            <optional>true</optional>\n        </dependency>\n```\n\n#### Exercises\n\n- Make changes and see if they reflect immediately\n\n## Step10.md\n\n#### What You Will Learn during this Step:\n\n- Create a REST Service to add a new question to survey\n- @PostMapping(\"/surveys/{surveyId}/questions\")\n- @RequestBody Question question\n- What should be Response Status for create?\n- ResponseEntity.created(location).build()\n- ResponseEntity.noContent().build()\n- Using Postman : https://www.getpostman.com\n- URL to POST to - http://localhost:8080/surveys/Survey1/questions\n\n#### Useful Snippets and References\n\nSample Body for POST Request\n\n```\n{\"description\":\"Second Most Populous Country in the World\",\"correctAnswer\":\"India\",\"options\":[\"India\",\"Russia\",\"United States\",\"China\"]}\n```\n\nFirst Snippet\n\n```\n    @PostMapping(\"/surveys/{surveyId}/questions\")\n    ResponseEntity<?> add(@PathVariable String surveyId,\n            @RequestBody Question question) {\n\n        Question createdTodo = surveyService.addQuestion(surveyId, question);\n\n        if (createdTodo == null) {\n            return ResponseEntity.noContent().build();\n        }\n\n        URI location = ServletUriComponentsBuilder.fromCurrentRequest()\n                .path(\"/{id}\").buildAndExpand(createdTodo.getId()).toUri();\n\n        return ResponseEntity.created(location).build();\n\n    }\n```\n\n#### Exercises\n\n- Create more REST services of your choice\n\n#### Files List\n\nsrc/main/java/com/in28minutes/springboot/controller/SurveyController.java Modified\nNew Lines\n\n```\nimport java.net.URI;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.web.bind.annotation.PostMapping;\nimport org.springframework.web.bind.annotation.RequestBody;\nimport org.springframework.web.servlet.support.ServletUriComponentsBuilder;\n\t// /surveys/{surveyId}/questions\n\t@PostMapping(\"/surveys/{surveyId}/questions\")\n\tpublic ResponseEntity<Void> addQuestionToSurvey(\n\t\t\t@PathVariable String surveyId, @RequestBody Question newQuestion) {\n\t\tQuestion question = surveyService.addQuestion(surveyId, newQuestion);\n\t\tif (question == null)\n\t\t\treturn ResponseEntity.noContent().build();\n\t\t// Success - URI of the new resource in Response Header\n\t\t// Status - created\n\t\t// URI -> /surveys/{surveyId}/questions/{questionId}\n\t\t// question.getQuestionId()\n\t\tURI location = ServletUriComponentsBuilder.fromCurrentRequest().path(\n\t\t\t\t\"/{id}\").buildAndExpand(question.getId()).toUri();\n\t\t// Status\n\t\treturn ResponseEntity.created(location).build();\n```\n\n```\npackage com.in28minutes.springboot.controller;\n\nimport java.net.URI;\nimport java.util.List;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.PostMapping;\nimport org.springframework.web.bind.annotation.RequestBody;\nimport org.springframework.web.bind.annotation.RestController;\nimport org.springframework.web.servlet.support.ServletUriComponentsBuilder;\n\nimport com.in28minutes.springboot.model.Question;\nimport com.in28minutes.springboot.service.SurveyService;\n\n@RestController\nclass SurveyController {\n\t@Autowired\n\tprivate SurveyService surveyService;\n\n\t@GetMapping(\"/surveys/{surveyId}/questions\")\n\tpublic List<Question> retrieveQuestions(@PathVariable String surveyId) {\n\t\treturn surveyService.retrieveQuestions(surveyId);\n\t}\n\n\t// GET \"/surveys/{surveyId}/questions/{questionId}\"\n\t@GetMapping(\"/surveys/{surveyId}/questions/{questionId}\")\n\tpublic Question retrieveDetailsForQuestion(@PathVariable String surveyId,\n\t\t\t@PathVariable String questionId) {\n\t\treturn surveyService.retrieveQuestion(surveyId, questionId);\n\t}\n\n\t// /surveys/{surveyId}/questions\n\t@PostMapping(\"/surveys/{surveyId}/questions\")\n\tpublic ResponseEntity<Void> addQuestionToSurvey(\n\t\t\t@PathVariable String surveyId, @RequestBody Question newQuestion) {\n\n\t\tQuestion question = surveyService.addQuestion(surveyId, newQuestion);\n\n\t\tif (question == null)\n\t\t\treturn ResponseEntity.noContent().build();\n\n\t\t// Success - URI of the new resource in Response Header\n\t\t// Status - created\n\t\t// URI -> /surveys/{surveyId}/questions/{questionId}\n\t\t// question.getQuestionId()\n\t\tURI location = ServletUriComponentsBuilder.fromCurrentRequest().path(\n\t\t\t\t\"/{id}\").buildAndExpand(question.getId()).toUri();\n\n\t\t// Status\n\t\treturn ResponseEntity.created(location).build();\n\t}\n\n}\n```\n\n## Step11.md\n\n#### What You Will Learn during this Step:\n\n- Understand Content Negotiation\n- Accept:application/xml\n- Deliver XML Responses from the REST Services\n- http://localhost:8080/surveys/Survey1/questions/\n\n#### Useful Snippets and References\n\nFirst Snippet\n\n```\n        <dependency>\n            <groupId>com.fasterxml.jackson.dataformat</groupId>\n            <artifactId>jackson-dataformat-xml</artifactId>\n        </dependency>\n\n```\n\nSecond Snippet\n\n```\n<List>\n    <item>\n        <id>Question1</id>\n        <description>Largest Country in the World</description>\n        <correctAnswer>Russia</correctAnswer>\n        <options>\n            <options>India</options>\n            <options>Russia</options>\n            <options>United States</options>\n            <options>China</options>\n        </options>\n    </item>\n    <item>\n        <id>Question2</id>\n        <description>Most Populus Country in the World</description>\n        <correctAnswer>China</correctAnswer>\n        <options>\n            <options>India</options>\n            <options>Russia</options>\n            <options>United States</options>\n            <options>China</options>\n        </options>\n    </item>\n    <item>\n        <id>Question3</id>\n        <description>Highest GDP in the World</description>\n        <correctAnswer>United States</correctAnswer>\n        <options>\n            <options>India</options>\n            <options>Russia</options>\n            <options>United States</options>\n            <options>China</options>\n        </options>\n    </item>\n    <item>\n        <id>Question4</id>\n        <description>Second largest english speaking country</description>\n        <correctAnswer>India</correctAnswer>\n        <options>\n            <options>India</options>\n            <options>Russia</options>\n            <options>United States</options>\n            <options>China</options>\n        </options>\n    </item>\n</List>\n```\n\n#### Exercises\n\n- Execute other services using xml and see what happens!\n\n## Step12.md\n\n#### What You Will Learn during this Step:\n\n- Spring Initializr\n- https://start.spring.io\n- Create a few projects!\n\n#### Exercises\n\n- Create more projects with Spring Initializr and play around with it!\n\n## Step13.md\n\n#### What You Will Learn during this Step:\n\n- Spring Boot Actuator\n- /env, /metrics, /trace, /dump, /shutdown, /beans, / autoconfig, /configprops, /mappings\n- HAL Browser\n- http://localhost:8080/actuator/\n- Execute individual REST Services for each of above\n- Programming Tip\n- Use static code analysis - https://www.youtube.com/watch?v=rB_BaftN3nE\n\n#### Useful Snippets and References\n\nFirst Snippet\n\n```\n        <dependency>\n            <groupId>org.springframework.boot</groupId>\n            <artifactId>spring-boot-starter-actuator</artifactId>\n        </dependency>\n        \n        <dependency>\n            <groupId>org.springframework.data</groupId>\n            <artifactId>spring-data-rest-hal-browser</artifactId>\n        </dependency>\n\n```\n\n#### Files List\n\npom.xml Modified\nNew Lines\n\n```\n\t\t\t<artifactId>spring-boot-devtools</artifactId>\n\t\t\t<optional>true</optional>\n\t\t\t<artifactId>spring-boot-starter-actuator</artifactId>\n\t\t\t<groupId>org.springframework.data</groupId>\n\t\t\t<artifactId>spring-data-rest-hal-browser</artifactId>\n```\n\n## Step14.md\n\n#### What You Will Learn during this Step:\n\n- Embedded servlet containers\n- Default Tomcat\n- We did not install Tomcat. Did we? Magic is done by Spring Boot!\n- Switching to Jetty or Undertow\n- Configuration\n- server.port\n- Programming Tip\n- Always review code : https://www.youtube.com/watch?v=hVJGu0xdXII\n\n#### Useful Snippets and References\n\nFirst Snippet\n\n```\n<dependency>\n    <groupId>org.springframework.boot</groupId>\n    <artifactId>spring-boot-starter-web</artifactId>\n    <exclusions>\n        <exclusion>\n            <groupId>org.springframework.boot</groupId>\n            <artifactId>spring-boot-starter-tomcat</artifactId>\n        </exclusion>\n    </exclusions>\n</dependency>\n<dependency>\n    <groupId>org.springframework.boot</groupId>\n    <artifactId>spring-boot-starter-jetty</artifactId>\n</dependency>\n```\n\n#### Exercises\n\n- Find out from\n  documentation (https://docs.spring.io/spring-boot/docs/current/reference/html/howto-embedded-servlet-containers.html)\n  how to switch to undertow!\n\n#### Files List\n\npom.xml Modified\nNew Lines\n\n```\n\t\t\t<exclusions>\n\t\t\t\t<exclusion>\n\t\t\t\t\t<groupId>org.springframework.boot</groupId>\n\t\t\t\t\t<artifactId>spring-boot-starter-tomcat</artifactId>\n\t\t\t\t</exclusion>\n\t\t\t</exclusions>\n\t\t\t<artifactId>spring-boot-starter-jetty</artifactId>\n```\n\n## Step15.md\n\n#### What You Will Learn during this Step:\n\n- Using Dynamic Configuration in your application\n- Customize Welcome Message\n- Different ways of configuration\n- --welcome.message=\"SomethingElse\" in Program Arguments\n- --spring.config.location=classpath:/default.properties\n- We will learn about profiles in next step\n- Using Placeholders\n- YAML\n\n#### Snippets\n\nFirst Snippet\n\n```\nlogging:\n  level:\n      org.springframework: DEBUG\napp:\n   name: In28Minutes\n   description: ${app.name} is your first Spring Boot application\nwelcome:\n    message: Welcome to your first Spring Boot app!\n```\n\nSecond Snippet\n\n```\n@Value(\"${welcome.message}\")\n```\n\n#### Files List\n\nsrc/main/java/com/in28minutes/springboot/WelcomeService.java Modified\nNew Lines\n\n```\nimport org.springframework.beans.factory.annotation.Value;\n//Spring to manage this bean and create an instance of this\n\t@Value(\"${welcome.message}\")\n\tprivate String welcomeMessage;\n\t\treturn welcomeMessage;\n```\n\n```\npackage com.in28minutes.springboot;\n\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.stereotype.Component;\n\n//Spring to manage this bean and create an instance of this\n@Component\npublic class WelcomeService {\n\n\t@Value(\"${welcome.message}\")\n\tprivate String welcomeMessage;\n\n\tpublic String retrieveWelcomeMessage() {\n\t\t//Complex Method\n\t\treturn welcomeMessage;\n\t}\n}\n```\n\nsrc/main/resources/application.properties Modified\nNew Lines\n\n```\nlogging.level.org.springframework.web.servlet: DEBUG\napp.name=in28Minutes\nwelcome.message=Welcome message from property file! Welcome to ${app.name}\n```\n\nsrc/main/resources/application.yaml New\n\n```\nlogging:\n level:\n   org.springframework: INFO\n   org.springframework.web.servlet: DEBUG\n```\n\n## Step16.md\n\n#### What You Will Learn during this Step:\n\n- Understand Basics of Profiles\n- Setting a profile\n- Using -Dspring.profiles.active=prod in VM Arguments\n- spring.profiles.active=prod\n- Using a profile\n- application-{profile-name}.properties\n- @Profile(\"dev\") on a bean\n- Usage\n- Configure Resources - Databases, Queues, External Services\n\n#### Files List\n\nsrc/main/java/com/in28minutes/springboot/Application.java Modified\nNew Lines\n\n```\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Profile;\n\t@Profile(\"prod\")\n\t@Bean\n\tpublic String dummy() {\n\t\treturn \"something\";\n```\n\n```\npackage com.in28minutes.springboot;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Profile;\n\n@SpringBootApplication\npublic class Application {\n\n\tpublic static void main(String[] args) {\n\t\tApplicationContext ctx = SpringApplication.run(Application.class, args);\n\n\t}\n\n\t@Profile(\"prod\")\n\t@Bean\n\tpublic String dummy() {\n\t\treturn \"something\";\n\t}\n}\n```\n\nsrc/main/resources/application-dev.properties New\n\n```\nlogging.level.org.springframework: TRACE\n```\n\nsrc/main/resources/application-prod.properties New\n\n```\nlogging.level.org.springframework: INFO\n```\n\nsrc/main/resources/application.properties Modified\nNew Lines\n\n```\nspring.profiles.active=prod\n\n \n```\n\nsrc/main/resources/application.yaml Deleted\n\n## Step17.md\n\n#### What You Will Learn during this Step:\n\n- Even better configuration management than @Value\n- Type-safe Configuration Properties\n- http://localhost:8080/dynamic-configuration\n- Also look at http://localhost:8080/actuator/#http://localhost:8080/configprops\n\n#### Useful Snippets and References\n\nFirst Snippet\n\n```\npackage com.in28minutes.springboot.configuration;\n\nimport org.springframework.boot.context.properties.ConfigurationProperties;\nimport org.springframework.stereotype.Component;\n\n@Component\n@ConfigurationProperties(\"basic\")\npublic class BasicConfiguration {\n    private boolean value;\n    private String message;\n    private int number;\n\n    public boolean isValue() {\n        return value;\n    }\n\n    public void setValue(boolean value) {\n        this.value = value;\n    }\n\n    public String getMessage() {\n        return message;\n    }\n\n    public void setMessage(String message) {\n        this.message = message;\n    }\n\n    public int getNumber() {\n        return number;\n    }\n\n    public void setNumber(int number) {\n        this.number = number;\n    }\n\n}\n\n```\n\nSecond Snippet\n\n```\n        @Autowired\n        private BasicConfiguration configuration;\n\n        @RequestMapping(\"/dynamic-configuration\")\n        public Map dynamicConfiguration() {\n            // Not the best practice to use a map to store differnt types!\n            Map map = new HashMap();\n            map.put(\"message\", configuration.getMessage());\n            map.put(\"number\", configuration.getNumber());\n            map.put(\"key\", configuration.isValue());\n            return map;\n        }\n\n```\n\nThird Snippet\n\n```\nbasic.value: true\nbasic.message: Dynamic Message\nbasic.number: 100\n```\n\nFourth Snippet\n\n```\nbasic: \n   value: true\n   message: Dynamic Message YAML\n   number: 100\n```\n\n#### Exercises\n\nUnderstand Type Safety\n\n```\n***************************\nAPPLICATION FAILED TO START\n***************************\n\nDescription:\n\nBinding to target com.in28minutes.springboot.configuration.BasicConfiguration@391b8545 failed:\n\n    Property: basic.number\n    Value: ABC\n    Reason: Failed to convert property value of type [java.lang.String] to required type [int] for property 'number'; nested exception is org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.String] to type [int]\n\n\nAction:\n\nUpdate your application's configuration\n\n```\n\n#### Files List\n\nsrc/main/java/com/in28minutes/springboot/WelcomeController.java Modified\nNew Lines\n\n```\nimport java.util.HashMap;\nimport java.util.Map;\nimport com.in28minutes.springboot.configuration.BasicConfiguration;\n\tprivate BasicConfiguration configuration;\n\t@RequestMapping(\"/dynamic-configuration\")\n\tpublic Map dynamicConfiguration() {\n\t\tMap map = new HashMap();\n\t\tmap.put(\"message\", configuration.getMessage());\n\t\tmap.put(\"number\", configuration.getNumber());\n\t\tmap.put(\"value\", configuration.isValue());\n\t\treturn map;\n```\n\n```\npackage com.in28minutes.springboot;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RestController;\n\nimport com.in28minutes.springboot.configuration.BasicConfiguration;\n\n@RestController\npublic class WelcomeController {\n\n\t//Auto wiring\n\t@Autowired\n\tprivate WelcomeService service;\n\n\t@Autowired\n\tprivate BasicConfiguration configuration;\n\n\t@RequestMapping(\"/welcome\")\n\tpublic String welcome() {\n\t\treturn service.retrieveWelcomeMessage();\n\t}\n\n\t@RequestMapping(\"/dynamic-configuration\")\n\tpublic Map dynamicConfiguration() {\n\t\tMap map = new HashMap();\n\t\tmap.put(\"message\", configuration.getMessage());\n\t\tmap.put(\"number\", configuration.getNumber());\n\t\tmap.put(\"value\", configuration.isValue());\n\n\t\treturn map;\n\t}\n\n}\n```\n\nsrc/main/java/com/in28minutes/springboot/configuration/BasicConfiguration.java New\n\n```\npackage com.in28minutes.springboot.configuration;\n\nimport org.springframework.boot.context.properties.ConfigurationProperties;\nimport org.springframework.stereotype.Component;\n\n@Component\n@ConfigurationProperties(\"basic\")\npublic class BasicConfiguration {\n\tprivate boolean value;\n\tprivate String message;\n\tprivate int number;\n\n\tpublic boolean isValue() {\n\t\treturn value;\n\t}\n\n\tpublic void setValue(boolean value) {\n\t\tthis.value = value;\n\t}\n\n\tpublic String getMessage() {\n\t\treturn message;\n\t}\n\n\tpublic void setMessage(String message) {\n\t\tthis.message = message;\n\t}\n\n\tpublic int getNumber() {\n\t\treturn number;\n\t}\n\n\tpublic void setNumber(int number) {\n\t\tthis.number = number;\n\t}\n}\n```\n\nsrc/main/resources/application.properties Modified\nNew Lines\n\n```\nbasic.value=true\nbasic.message=Welcome to in28minutes\nbasic.number=200\n```\n\n## Step18.md\n\n#### What You Will Learn during this Step:\n\n- Let's switch back to tomcat first!\n- Get introduced to Spring Data JPA\n- Create a very simple example with Spring Data JPA\n- Use CommandLineRunner!\n\n#### Some Notes\n\n- Useful Properties\n- spring.datasource.driver-class-name=com.mysql.jdbc.Driver\n- spring.datasource.url=jdbc:mysql://localhost:3306/test\n- spring.datasource.username=root\n- spring.datasource.password=admin\n- spring.datasource.initialize=true\n- spring.jpa.hibernate.ddl-auto=update\n- spring.jpa.show-sql=true\n  spring.datasource.url=jdbc:h2:mem:testdb\n  spring.data.jpa.repositories.bootstrap-mode=default\n\n#### Useful Snippets and References\n\nFirst Snippet - Add H2 Later after showing the error\n\n```\n        <dependency>\n            <groupId>org.springframework.boot</groupId>\n            <artifactId>spring-boot-starter-data-jpa</artifactId>\n        </dependency>\n\n        <dependency>\n            <groupId>com.h2database</groupId>\n            <artifactId>h2</artifactId>\n        </dependency>\n\n```\n\nSecond Snippet\n\n```\npackage com.in28minutes.springboot.jpa;\n\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\n\n@Entity\npublic class User {\n\n    @Id\n    @GeneratedValue(strategy = GenerationType.AUTO)\n    private Long id;\n\n    private String name;// Not perfect!! Should be a proper object!\n    private String role;// Not perfect!! An enum should be a better choice!\n\n    protected User() {\n    }\n\n    public User(String name, String role) {\n        super();\n        this.name = name;\n        this.role = role;\n    }\n\n    public Long getId() {\n        return id;\n    }\n\n    public String getName() {\n        return name;\n    }\n\n    public String getRole() {\n        return role;\n    }\n\n    @Override\n    public String toString() {\n        return String.format(\"User [id=%s, name=%s, role=%s]\", id, name, role);\n    }\n\n}\n\n```\n\nThird Snippet\n\n```\npackage com.in28minutes.springboot.jpa;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.CommandLineRunner;\nimport org.springframework.stereotype.Component;\n\n@Component\npublic class UserCommandLineRunner implements CommandLineRunner {\n\n    private static final Logger log = LoggerFactory\n            .getLogger(UserCommandLineRunner.class);\n\n    @Autowired\n    private UserRepository repository;\n\n    @Override\n    public void run(String... args) {\n        // save a couple of customers\n        repository.save(new User(\"Ranga\", \"Admin\"));\n        repository.save(new User(\"Ravi\", \"User\"));\n        repository.save(new User(\"Satish\", \"Admin\"));\n        repository.save(new User(\"Raghu\", \"User\"));\n\n        log.info(\"-------------------------------\");\n        log.info(\"Finding all users\");\n        log.info(\"-------------------------------\");\n        for (User user : repository.findAll()) {\n            log.info(user.toString());\n        }\n\n    }\n\n}\n\n```\n\nFourth Snippet\n\n```\npackage com.in28minutes.springboot.jpa;\n\nimport java.util.List;\n\nimport org.springframework.data.repository.CrudRepository;\n\npublic interface UserRepository extends CrudRepository<User, Long> {\n}\n```\n\n#### Exercises\n\n- Look at other methods provided by the UserRepository\n\n#### Files List\n\npom.xml Modified\nNew Lines\n\n```\n\t\t\t<artifactId>spring-boot-starter-data-jpa</artifactId>\n\t\t\t<groupId>com.h2database</groupId>\n\t\t\t<artifactId>h2</artifactId>\n```\n\nsrc/main/java/com/in28minutes/springboot/jpa/User.java New\n\n```\npackage com.in28minutes.springboot.jpa;\n\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\n\n@Entity\npublic class User {\n\n\t@Id\n\t@GeneratedValue(strategy = GenerationType.AUTO)\n\tprivate Long id;\n\n\tprivate String name;\n\tprivate String role;\n\n\tprotected User() {\n\t}\n\n\tpublic User(String name, String role) {\n\t\tsuper();\n\t\tthis.name = name;\n\t\tthis.role = role;\n\t}\n\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic String getRole() {\n\t\treturn role;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"User [id=\" + id + \", name=\" + name + \", role=\" + role + \"]\";\n\t}\n\n}\n```\n\nsrc/main/java/com/in28minutes/springboot/jpa/UserCommandLineRunner.java New\n\n```\npackage com.in28minutes.springboot.jpa;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.CommandLineRunner;\nimport org.springframework.stereotype.Component;\n\n@Component\npublic class UserCommandLineRunner implements CommandLineRunner {\n\n\tprivate static final Logger log = LoggerFactory\n\t\t\t.getLogger(UserCommandLineRunner.class);\n\n\t@Autowired\n\tprivate UserRepository repository;\n\n\t@Override\n\tpublic void run(String... args) throws Exception {\n\n\t\trepository.save(new User(\"Ranga\", \"Admin\"));\n\t\trepository.save(new User(\"Ravi\", \"User\"));\n\t\trepository.save(new User(\"Satish\", \"Admin\"));\n\t\trepository.save(new User(\"Raghu\", \"User\"));\n\n\t\tfor (User user : repository.findAll()) {\n\t\t\tlog.info(user.toString());\n\t\t}\n\n\t\tlog.info(\"Admin users are.....\");\n\t\tlog.info(\"____________________\");\n\t\tfor (User user : repository.findByRole(\"Admin\")) {\n\t\t\tlog.info(user.toString());\n\t\t}\n\n\t}\n\n}\n```\n\nsrc/main/java/com/in28minutes/springboot/jpa/UserRepository.java New\n\n```\npackage com.in28minutes.springboot.jpa;\n\nimport java.util.List;\n\nimport org.springframework.data.repository.CrudRepository;\n\npublic interface UserRepository extends CrudRepository<User, Long> {\n}\n```\n\n## Step19.md\n\n#### What You Will Learn during this Step:\n\n- Look at H2 Console : http://localhost:8080/h2-console\n- Use db url jdbc:h2:mem:testdb\n- Add findByRole method\n\n#### Some Notes\n\n- Useful Properties\n- spring.datasource.driver-class-name=com.mysql.jdbc.Driver\n- spring.datasource.url=jdbc:mysql://localhost:3306/test\n- spring.datasource.username=root\n- spring.datasource.password=admin\n- spring.datasource.initialize=true\n- spring.jpa.hibernate.ddl-auto=update\n- spring.jpa.show-sql=true\n  spring.datasource.url=jdbc:h2:mem:testdb\n  spring.data.jpa.repositories.bootstrap-mode=default\n\n#### Useful Snippets and References\n\nFirst Snippet\n\n```\n\n        log.info(\"-------------------------------\");\n        log.info(\"Finding user with id 1\");\n        log.info(\"-------------------------------\");\n        User user = repository.findOne(1L);\n        log.info(user.toString());\n\n        log.info(\"-------------------------------\");\n        log.info(\"Finding all Admins\");\n        log.info(\"-------------------------------\");\n        for (User admin : repository.findByRole(\"Admin\")) {\n            log.info(admin.toString());\n            // Do something...\n        }\n\n```\n\nSecond Snippet\n\n```\npackage com.in28minutes.springboot.jpa;\n\nimport java.util.List;\n\nimport org.springframework.data.repository.CrudRepository;\n\npublic interface UserRepository extends CrudRepository<User, Long> {\n    List<User> findByRole(String description);\n}\n```\n\n#### Files List\n\nsrc/main/java/com/in28minutes/springboot/jpa/UserRepository.java Modified\nNew Lines\n\n```\n\tList<User> findByRole(String role);\n```\n\n```\npackage com.in28minutes.springboot.jpa;\n\nimport java.util.List;\n\nimport org.springframework.data.repository.CrudRepository;\n\npublic interface UserRepository extends CrudRepository<User, Long> {\n\tList<User> findByRole(String role);\n}\n```\n\n## Step20.md\n\n#### What You Will Learn during this Step:\n\n- Introduction to Spring Data Rest\n- Hit http://localhost:8080/users in POSTMAN\n- http://localhost:8080/users/1\n- http://localhost:8080/users/?size=4\n- http://localhost:8080/users/?sort=name,desc\n- @Param(\"role\")\n- http://localhost:8080/users/search/findByRole?role=Admin\n- Good for quick prototype! Be cautious about using this in Big applications!\n\n#### Useful Snippets and References\n\nFirst Snippet\n\n```\n        <dependency>\n            <groupId>org.springframework.boot</groupId>\n            <artifactId>spring-boot-starter-data-rest</artifactId>\n        </dependency>\n\n```\n\nSecond Snippet\n\n```\npackage com.in28minutes.springboot.jpa;\n\nimport java.util.List;\n\nimport org.springframework.data.repository.PagingAndSortingRepository;\nimport org.springframework.data.repository.query.Param;\nimport org.springframework.data.rest.core.annotation.RepositoryRestResource;\n\n@RepositoryRestResource(collectionResourceRel = \"users\", path = \"users\")\npublic interface UserRestRepository extends\nPagingAndSortingRepository<User, Long> {\n    List<User> findByRole(@Param(\"role\") String role);\n}\n```\n\nThird Snippet : POST to http://localhost:8080/users\n\n```\nHEADER\nContent-Type:application/json\n\nBODY\n{\n  \"name\": \"Raja\",\n  \"role\": \"Admin\"\n}\n```\n\nFourth Snippet : POST to http://localhost:8080/users/5\n\n```\nHEADER\nContent-Type:application/json\n\nBODY\n{\n  \"name\": \"Raja-Updated\",\n  \"role\": \"Admin\"\n}\n```\n\n#### Files List\n\npom.xml Modified\nNew Lines\n\n```\n\t\t\t<artifactId>spring-boot-starter-data-rest</artifactId>\n```\n\nsrc/main/java/com/in28minutes/springboot/jpa/UserRestRepository.java New\n\n```\npackage com.in28minutes.springboot.jpa;\n\nimport java.util.List;\n\nimport org.springframework.data.repository.PagingAndSortingRepository;\nimport org.springframework.data.repository.query.Param;\nimport org.springframework.data.rest.core.annotation.RepositoryRestResource;\n\n@RepositoryRestResource(path = \"users\", collectionResourceRel = \"users\")\npublic interface UserRestRepository extends\n\t\tPagingAndSortingRepository<User, Long> {\n\tList<User> findByRole(@Param(\"role\") String role);\n}\n```\n\n## Step21.md\n\n### /pom.xml New\n\n```\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n    xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n    <modelVersion>4.0.0</modelVersion>\n    <groupId>com.in28minutes</groupId>\n    <artifactId>springboot-for-beginners-example</artifactId>\n    <version>0.0.1-SNAPSHOT</version>\n    <name>Your First Spring Boot Example</name>\n    <packaging>jar</packaging>\n\n    <parent>\n        <groupId>org.springframework.boot</groupId>\n        <artifactId>spring-boot-starter-parent</artifactId>\n        <version>1.4.0.RELEASE</version>\n    </parent>\n\n    <dependencies>\n\n        <dependency>\n            <groupId>org.springframework.boot</groupId>\n            <artifactId>spring-boot-starter-web</artifactId>\n        </dependency>\n\n        <dependency>\n            <groupId>org.springframework.boot</groupId>\n            <artifactId>spring-boot-starter-data-jpa</artifactId>\n        </dependency>\n\n        <dependency>\n            <groupId>com.h2database</groupId>\n            <artifactId>h2</artifactId>\n        </dependency>\n\n        <dependency>\n            <groupId>org.springframework.boot</groupId>\n            <artifactId>spring-boot-starter-data-rest</artifactId>\n        </dependency>\n\n        <dependency>\n            <groupId>com.fasterxml.jackson.dataformat</groupId>\n            <artifactId>jackson-dataformat-xml</artifactId>\n        </dependency>\n\n        <dependency>\n            <groupId>org.springframework.boot</groupId>\n            <artifactId>spring-boot-starter-actuator</artifactId>\n        </dependency>\n\n        <dependency>\n            <groupId>org.springframework.data</groupId>\n            <artifactId>spring-data-rest-hal-browser</artifactId>\n        </dependency>\n\n        <dependency>\n            <groupId>org.springframework.boot</groupId>\n            <artifactId>spring-boot-devtools</artifactId>\n            <optional>true</optional>\n        </dependency>\n\n        <dependency>\n            <groupId>org.springframework.boot</groupId>\n            <artifactId>spring-boot-starter-test</artifactId>\n            <scope>test</scope>\n        </dependency>\n\n    </dependencies>\n\n\n    <properties>\n        <java.version>1.8</java.version>\n<maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>\n    </properties>\n\n    <build>\n        <plugins>\n            <plugin>\n                <groupId>org.springframework.boot</groupId>\n                <artifactId>spring-boot-maven-plugin</artifactId>\n            </plugin>\n        </plugins>\n    </build>\n\n</project>\n```\n\n### /src/main/java/com/in28minutes/springboot/Application.java New\n\n```\npackage com.in28minutes.springboot;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.stereotype.Component;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RestController;\n\nimport com.in28minutes.springboot.configuration.BasicConfiguration;\n\n@SpringBootApplication\npublic class Application {\n\n    public static void main(String[] args) {\n\n        ApplicationContext ctx = SpringApplication.run(Application.class, args);\n    }\n\n    @RestController\n    class SomeBean {\n\n        @Autowired\n        private SomeDependency someDependency;\n\n        @Autowired\n        private BasicConfiguration configuration;\n\n        @RequestMapping(\"/\")\n        public String index() {\n            return someDependency.getSomething();\n        }\n\n        @RequestMapping(\"/dynamic-configuration\")\n        public Map dynamicConfiguration() {\n            // Not the best practice to use a map to store differnt types!\n            Map map = new HashMap();\n            map.put(\"message\", configuration.getMessage());\n            map.put(\"number\", configuration.getNumber());\n            map.put(\"key\", configuration.isValue());\n            return map;\n        }\n\n    }\n\n    @Component\n    class SomeDependency {\n\n        @Value(\"${welcome.message}\")\n        private String welcomeMessage;\n\n        public String getSomething() {\n            return welcomeMessage;\n        }\n\n    }\n\n}\n```\n\n### /src/main/java/com/in28minutes/springboot/configuration/BasicConfiguration.java New\n\n```\npackage com.in28minutes.springboot.configuration;\n\nimport org.springframework.boot.context.properties.ConfigurationProperties;\nimport org.springframework.stereotype.Component;\n\n@Component\n@ConfigurationProperties(\"basic\")\npublic class BasicConfiguration {\n    private boolean value;\n    private String message;\n    private int number;\n\n    public boolean isValue() {\n        return value;\n    }\n\n    public void setValue(boolean value) {\n        this.value = value;\n    }\n\n    public String getMessage() {\n        return message;\n    }\n\n    public void setMessage(String message) {\n        this.message = message;\n    }\n\n    public int getNumber() {\n        return number;\n    }\n\n    public void setNumber(int number) {\n        this.number = number;\n    }\n\n}\n```\n\n### /src/main/java/com/in28minutes/springboot/controller/SurveyController.java New\n\n```\npackage com.in28minutes.springboot.controller;\n\nimport java.net.URI;\nimport java.util.List;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.PostMapping;\nimport org.springframework.web.bind.annotation.RequestBody;\nimport org.springframework.web.bind.annotation.RestController;\nimport org.springframework.web.servlet.support.ServletUriComponentsBuilder;\n\nimport com.in28minutes.springboot.model.Question;\nimport com.in28minutes.springboot.service.SurveyService;\n\n@RestController\nclass SurveyController {\n    @Autowired\n    private SurveyService surveyService;\n\n    @GetMapping(\"/surveys/{surveyId}/questions\")\n    public List<Question> retrieveQuestions(@PathVariable String surveyId) {\n        return surveyService.retrieveQuestions(surveyId);\n    }\n\n    @GetMapping(path = \"/surveys/{surveyId}/questions/{questionId}\")\n    public Question retrieveQuestion(@PathVariable String surveyId,\n            @PathVariable String questionId) {\n        return surveyService.retrieveQuestion(surveyId, questionId);\n    }\n\n    @PostMapping(\"/surveys/{surveyId}/questions\")\n    ResponseEntity<?> add(@PathVariable String surveyId,\n            @RequestBody Question question) {\n\n        Question createdTodo = surveyService.addQuestion(surveyId, question);\n\n        if (createdTodo == null) {\n            return ResponseEntity.noContent().build();\n        }\n\n        URI location = ServletUriComponentsBuilder.fromCurrentRequest()\n                .path(\"/{id}\").buildAndExpand(createdTodo.getId()).toUri();\n\n        return ResponseEntity.created(location).build();\n\n    }\n\n}\n```\n\n### /src/main/java/com/in28minutes/springboot/jpa/User.java New\n\n```\npackage com.in28minutes.springboot.jpa;\n\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\n\n@Entity\npublic class User {\n\n    @Id\n    @GeneratedValue(strategy = GenerationType.AUTO)\n    private Long id;\n\n    private String name;// Not perfect!! Should be a proper object!\n    private String role;// Not perfect!! An enum should be a better choice!\n\n    protected User() {\n    }\n\n    public User(String name, String role) {\n        super();\n        this.name = name;\n        this.role = role;\n    }\n\n    public Long getId() {\n        return id;\n    }\n\n    public String getName() {\n        return name;\n    }\n\n    public String getRole() {\n        return role;\n    }\n\n    @Override\n    public String toString() {\n        return String.format(\"User [id=%s, name=%s, role=%s]\", id, name, role);\n    }\n\n}\n```\n\n### /src/main/java/com/in28minutes/springboot/jpa/UserCommandLineRunner.java New\n\n```\npackage com.in28minutes.springboot.jpa;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.CommandLineRunner;\nimport org.springframework.stereotype.Component;\n\n@Component\npublic class UserCommandLineRunner implements CommandLineRunner {\n\n    private static final Logger log = LoggerFactory\n            .getLogger(UserCommandLineRunner.class);\n\n    @Autowired\n    private UserRepository repository;\n\n    @Override\n    public void run(String... args) {\n        // save a couple of customers\n        repository.save(new User(\"Ranga\", \"Admin\"));\n        repository.save(new User(\"Ravi\", \"User\"));\n        repository.save(new User(\"Satish\", \"Admin\"));\n        repository.save(new User(\"Raghu\", \"User\"));\n\n        log.info(\"-------------------------------\");\n        log.info(\"Finding all users\");\n        log.info(\"-------------------------------\");\n        for (User user : repository.findAll()) {\n            log.info(user.toString());\n        }\n\n        log.info(\"-------------------------------\");\n        log.info(\"Finding user with id 1\");\n        log.info(\"-------------------------------\");\n        User user = repository.findOne(1L);\n        log.info(user.toString());\n\n        log.info(\"-------------------------------\");\n        log.info(\"Finding all Admins\");\n        log.info(\"-------------------------------\");\n        for (User admin : repository.findByRole(\"Admin\")) {\n            log.info(admin.toString());\n            // Do something...\n        }\n    }\n\n}\n```\n\n### /src/main/java/com/in28minutes/springboot/jpa/UserRepository.java New\n\n```\npackage com.in28minutes.springboot.jpa;\n\nimport java.util.List;\n\nimport org.springframework.data.repository.CrudRepository;\n\npublic interface UserRepository extends CrudRepository<User, Long> {\n    List<User> findByRole(String description);\n}\n```\n\n### /src/main/java/com/in28minutes/springboot/jpa/UserRestRepository.java New\n\n```\npackage com.in28minutes.springboot.jpa;\n\nimport java.util.List;\n\nimport org.springframework.data.repository.PagingAndSortingRepository;\nimport org.springframework.data.repository.query.Param;\nimport org.springframework.data.rest.core.annotation.RepositoryRestResource;\n\n@RepositoryRestResource(collectionResourceRel = \"users\", path = \"users\")\npublic interface UserRestRepository extends\nPagingAndSortingRepository<User, Long> {\n    List<User> findByRole(@Param(\"role\") String role);\n}\n```\n\n### /src/main/java/com/in28minutes/springboot/model/Question.java New\n\n```\npackage com.in28minutes.springboot.model;\n\nimport java.util.List;\n\npublic class Question {\n    private String id;\n    private String description;\n    private String correctAnswer;\n    private List<String> options;\n\n    // Needed by Caused by: com.fasterxml.jackson.databind.JsonMappingException:\n    // Can not construct instance of com.in28minutes.springboot.model.Question:\n    // no suitable constructor found, can not deserialize from Object value\n    // (missing default constructor or creator, or perhaps need to add/enable\n    // type information?)\n    public Question() {\n\n    }\n\n    public Question(String id, String description, String correctAnswer,\n            List<String> options) {\n        super();\n        this.id = id;\n        this.description = description;\n        this.correctAnswer = correctAnswer;\n        this.options = options;\n    }\n\n    public String getId() {\n        return id;\n    }\n\n    public void setId(String id) {\n        this.id = id;\n    }\n\n    public String getDescription() {\n        return description;\n    }\n\n    public String getCorrectAnswer() {\n        return correctAnswer;\n    }\n\n    public List<String> getOptions() {\n        return options;\n    }\n\n    @Override\n    public String toString() {\n        return String\n                .format(\"Question [id=%s, description=%s, correctAnswer=%s, options=%s]\",\n                        id, description, correctAnswer, options);\n    }\n\n    @Override\n    public int hashCode() {\n        final int prime = 31;\n        int result = 1;\n        result = prime * result + (id == null ? 0 : id.hashCode());\n        return result;\n    }\n\n    @Override\n    public boolean equals(Object obj) {\n        if (this == obj) {\n            return true;\n        }\n        if (obj == null) {\n            return false;\n        }\n        if (getClass() != obj.getClass()) {\n            return false;\n        }\n        Question other = (Question) obj;\n        if (id == null) {\n            if (other.id != null) {\n                return false;\n            }\n        } else if (!id.equals(other.id)) {\n            return false;\n        }\n        return true;\n    }\n\n}\n```\n\n### /src/main/java/com/in28minutes/springboot/model/Survey.java New\n\n```\npackage com.in28minutes.springboot.model;\n\nimport java.util.List;\n\npublic class Survey {\n    private String id;\n    private String title;\n    private String description;\n    private List<Question> questions;\n\n    public Survey(String id, String title, String description,\n            List<Question> questions) {\n        super();\n        this.id = id;\n        this.title = title;\n        this.description = description;\n        this.questions = questions;\n    }\n\n    public String getId() {\n        return id;\n    }\n\n    public String getTitle() {\n        return title;\n    }\n\n    public String getDescription() {\n        return description;\n    }\n\n    public List<Question> getQuestions() {\n        return questions;\n    }\n\n    @Override\n    public String toString() {\n        return String.format(\n                \"Survey [id=%s, title=%s, description=%s, questions=%s]\", id,\n                title, description, questions);\n    }\n\n}\n```\n\n### /src/main/java/com/in28minutes/springboot/service/SurveyService.java New\n\n```\npackage com.in28minutes.springboot.service;\n\nimport java.math.BigInteger;\nimport java.security.SecureRandom;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\nimport org.springframework.stereotype.Component;\n\nimport com.in28minutes.springboot.model.Question;\nimport com.in28minutes.springboot.model.Survey;\n\n@Component\npublic class SurveyService {\n    private static List<Survey> surveys = new ArrayList<>();\n    static {\n        Question question1 = new Question(\"Question1\",\n                \"Largest Country in the World\", \"Russia\", Arrays.asList(\n                        \"India\", \"Russia\", \"United States\", \"China\"));\n        Question question2 = new Question(\"Question2\",\n                \"Most Populus Country in the World\", \"China\", Arrays.asList(\n                        \"India\", \"Russia\", \"United States\", \"China\"));\n        Question question3 = new Question(\"Question3\",\n                \"Highest GDP in the World\", \"United States\", Arrays.asList(\n                        \"India\", \"Russia\", \"United States\", \"China\"));\n        Question question4 = new Question(\"Question4\",\n                \"Second largest english speaking country\", \"India\",\n                Arrays.asList(\"India\", \"Russia\", \"United States\", \"China\"));\n\n        List<Question> questions = new ArrayList<>(Arrays.asList(question1,\n                question2, question3, question4));\n\n        Survey survey = new Survey(\"Survey1\", \"My Favorite Survey\",\n                \"Description of the Survey\", questions);\n\n        surveys.add(survey);\n    }\n\n    public List<Survey> retrieveAllSurveys() {\n        return surveys;\n    }\n\n    public Survey retrieveSurvey(String surveyId) {\n        for (Survey survey : surveys) {\n            if (survey.getId().equals(surveyId)) {\n                return survey;\n            }\n        }\n        return null;\n    }\n\n    public List<Question> retrieveQuestions(String surveyId) {\n        Survey survey = retrieveSurvey(surveyId);\n\n        if (survey == null) {\n            return null;\n        }\n\n        return survey.getQuestions();\n    }\n\n    public Question retrieveQuestion(String surveyId, String questionId) {\n        Survey survey = retrieveSurvey(surveyId);\n\n        if (survey == null) {\n            return null;\n        }\n\n        for (Question question : survey.getQuestions()) {\n            if (question.getId().equals(questionId)) {\n                return question;\n            }\n        }\n\n        return null;\n    }\n\n    private SecureRandom random = new SecureRandom();\n\n    public Question addQuestion(String surveyId, Question question) {\n        Survey survey = retrieveSurvey(surveyId);\n\n        if (survey == null) {\n            return null;\n        }\n\n        String randomId = new BigInteger(130, random).toString(32);\n        question.setId(randomId);\n\n        survey.getQuestions().add(question);\n\n        return question;\n    }\n}\n```\n\n### /src/main/resources/application.properties New\n\n```\nlogging.level.org.springframework: INFO\napp.name: In28Minutes\napp.description: ${app.name} is your first Spring Boot application Properties\nwelcome.message: Welcome to your first Spring Boot application\nbasic.value: true\nbasic.message: Dynamic Message\nbasic.number: 123\n```\n\n### /src/main/resources/application.yaml New\n\n```\nlogging:\n  level:\n      org.springframework: DEBUG\n\napp:\n   name: In28Minutes\n   description: ${app.name} is your first Spring Boot application\n\nwelcome:\n    message: Welcome to your first Spring Boot app!\n    \nbasic: \n   value: true\n   message: Dynamic Message YAML\n   number: 100\n```\n\n### /src/test/java/com/in28minutes/springboot/controller/SurveyControllerIT.java New\n\n```\npackage com.in28minutes.springboot.controller;\n\nimport java.util.Arrays;\n\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.skyscreamer.jsonassert.JSONAssert;\nimport org.springframework.boot.context.embedded.LocalServerPort;\nimport org.springframework.boot.test.context.SpringBootTest;\nimport org.springframework.boot.test.web.client.TestRestTemplate;\nimport org.springframework.http.HttpEntity;\nimport org.springframework.http.HttpHeaders;\nimport org.springframework.http.HttpMethod;\nimport org.springframework.http.MediaType;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.test.context.junit4.SpringRunner;\n\nimport com.in28minutes.springboot.Application;\n\n@RunWith(SpringRunner.class)\n@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)\npublic class SurveyControllerIT {\n\n    @LocalServerPort\n    private int port;\n\n    private TestRestTemplate template = new TestRestTemplate();\n\n    HttpHeaders headers = new HttpHeaders();\n\n    @Before\n    public void setupJSONAcceptType() {\n        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));\n    }\n\n    @Test\n    public void retrieveSurveyQuestion() throws Exception {\n\n        String expected = \"{id:Question1,description:Largest Country in the World,correctAnswer:Russia,options:[India,Russia,United States,China]}\";\n\n        ResponseEntity<String> response = template.exchange(\n                createUrl(\"/surveys/Survey1/questions/Question1\"),\n                HttpMethod.GET, new HttpEntity<String>(\"DUMMY_DOESNT_MATTER\",\n                        headers), String.class);\n\n        JSONAssert.assertEquals(expected, response.getBody(), false);\n    }\n\n    private String createUrl(String uri) {\n        return \"http://localhost:\" + port + uri;\n    }\n\n}\n```\n\n#### What You Will Learn during this Step:\n\n- First thing first : I hate the fact that we did not write tests until Step 20 of this course\n- I love TDD and use it in all my projects. However, when learning something new, I think it is important to focus on\n  one thing at a time!\n- You can learn more about unit testing here - https://www.youtube.com/playlist?list=PL83C941BB0D27A6AF\n- Let's write a Integration Test for our service\n\n#### Useful Snippets and References\n\nFirst Snippet\n\n```\n        <dependency>\n            <groupId>org.springframework.boot</groupId>\n            <artifactId>spring-boot-starter-test</artifactId>\n            <scope>test</scope>\n        </dependency>\n\n```\n\nUnRefactored Snippet\n\n```\npackage com.in28minutes.springboot.controller;\n\nimport java.util.Arrays;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.skyscreamer.jsonassert.JSONAssert;\nimport org.springframework.boot.context.embedded.LocalServerPort;\nimport org.springframework.boot.test.context.SpringBootTest;\nimport org.springframework.boot.test.web.client.TestRestTemplate;\nimport org.springframework.http.HttpEntity;\nimport org.springframework.http.HttpHeaders;\nimport org.springframework.http.HttpMethod;\nimport org.springframework.http.MediaType;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.test.context.junit4.SpringRunner;\n\nimport com.in28minutes.springboot.Application;\n\n@RunWith(SpringRunner.class)\n@SpringBootTest(classes = Application.class,\n\t\twebEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)\npublic class SurveyControllerIT {\n\n\t@LocalServerPort\n\tprivate int port;\n\n\t@Test\n\tpublic void testRetrieveSurveyQuestion() {\n\n\t\tString url = \"http://localhost:\" + port\n\t\t\t\t+ \"/surveys/Survey1/questions/Question1\";\n\n\t\tTestRestTemplate restTemplate = new TestRestTemplate();\n\n\t\tHttpHeaders headers = new HttpHeaders();\n\n\t\theaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));\n\n\t\tHttpEntity<String> entity = new HttpEntity<String>(null, headers);\n\n\t\tResponseEntity<String> response = restTemplate.exchange(url,\n\t\t\t\tHttpMethod.GET, entity, String.class);\n\n\t\tString expected = \"{id:Question1,description:Largest Country in the World,correctAnswer:Russia}\";\n\n\t\tJSONAssert.assertEquals(expected, response.getBody(), false);\n\t}\n}\n\n\n```\n\nRefactored Snippet\n\n```\npackage com.in28minutes.springboot.controller;\n\nimport java.util.Arrays;\n\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.skyscreamer.jsonassert.JSONAssert;\nimport org.springframework.boot.context.embedded.LocalServerPort;\nimport org.springframework.boot.test.context.SpringBootTest;\nimport org.springframework.boot.test.web.client.TestRestTemplate;\nimport org.springframework.http.HttpEntity;\nimport org.springframework.http.HttpHeaders;\nimport org.springframework.http.HttpMethod;\nimport org.springframework.http.MediaType;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.test.context.junit4.SpringRunner;\n\nimport com.in28minutes.springboot.Application;\n\n@RunWith(SpringRunner.class)\n@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)\npublic class SurveyControllerIT {\n\n    @LocalServerPort\n    private int port;\n\n    private TestRestTemplate template = new TestRestTemplate();\n\n    HttpHeaders headers = new HttpHeaders();\n\n    @Before\n    public void setupJSONAcceptType() {\n        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));\n    }\n\n    @Test\n    public void retrieveSurveyQuestion() throws Exception {\n\n        String expected = \"{id:Question1,description:Largest Country in the World,correctAnswer:Russia,options:[India,Russia,United States,China]}\";\n\n        ResponseEntity<String> response = template.exchange(\n                createUrl(\"/surveys/Survey1/questions/Question1\"),\n                HttpMethod.GET, new HttpEntity<String>(\"DUMMY_DOESNT_MATTER\",\n                        headers), String.class);\n\n        JSONAssert.assertEquals(expected, response.getBody(), false);\n    }\n\n    private String createUrl(String uri) {\n        return \"http://localhost:\" + port + uri;\n    }\n\n}\n```\n\n#### Exercises\n\n- Try writing integration test for retrieveAllQuestions\n\n#### Files List\n\npom.xml Deleted\nsrc/main/java/com/in28minutes/springboot/Application.java Deleted\nsrc/main/java/com/in28minutes/springboot/WelcomeController.java Deleted\nsrc/main/java/com/in28minutes/springboot/WelcomeService.java Deleted\nsrc/main/java/com/in28minutes/springboot/configuration/BasicConfiguration.java Deleted\nsrc/main/java/com/in28minutes/springboot/controller/SurveyController.java Deleted\nsrc/main/java/com/in28minutes/springboot/jpa/User.java Deleted\nsrc/main/java/com/in28minutes/springboot/jpa/UserCommandLineRunner.java Deleted\nsrc/main/java/com/in28minutes/springboot/jpa/UserRepository.java Deleted\nsrc/main/java/com/in28minutes/springboot/jpa/UserRestRepository.java Deleted\nsrc/main/java/com/in28minutes/springboot/model/Question.java Deleted\nsrc/main/java/com/in28minutes/springboot/model/Survey.java Deleted\nsrc/main/java/com/in28minutes/springboot/service/SurveyService.java Deleted\nsrc/main/resources/application-dev.properties Deleted\nsrc/main/resources/application-prod.properties Deleted\nsrc/main/resources/application.properties Deleted\n\n## Step22.md\n\n### /pom.xml Deleted\n\n### /src/main/java/com/in28minutes/springboot/Application.java Deleted\n\n### /src/main/java/com/in28minutes/springboot/configuration/BasicConfiguration.java Deleted\n\n### /src/main/java/com/in28minutes/springboot/controller/SurveyController.java Deleted\n\n### /src/main/java/com/in28minutes/springboot/jpa/User.java Deleted\n\n### /src/main/java/com/in28minutes/springboot/jpa/UserCommandLineRunner.java Deleted\n\n### /src/main/java/com/in28minutes/springboot/jpa/UserRepository.java Deleted\n\n### /src/main/java/com/in28minutes/springboot/jpa/UserRestRepository.java Deleted\n\n### /src/main/java/com/in28minutes/springboot/model/Question.java Deleted\n\n### /src/main/java/com/in28minutes/springboot/model/Survey.java Deleted\n\n### /src/main/java/com/in28minutes/springboot/service/SurveyService.java Deleted\n\n### /src/main/resources/application.properties Deleted\n\n### /src/main/resources/application.yaml Deleted\n\n### /src/test/java/com/in28minutes/springboot/controller/SurveyControllerIT.java Deleted\n\n#### What You Will Learn during this Step:\n\n- Exercise from previous step\n- Integration Test for POST Request - Add To do\n\n#### Useful Snippets and References\n\nFirst Snippet\n\n```\n    @Test\n    public void retrieveSurveyQuestions() throws Exception {\n        ResponseEntity<List<Question>> response = template.exchange(\n                createUrl(\"/surveys/Survey1/questions/\"), HttpMethod.GET,\n                new HttpEntity<String>(\"DUMMY_DOESNT_MATTER\", headers),\n                new ParameterizedTypeReference<List<Question>>() {\n                });\n\n        Question sampleQuestion = new Question(\"Question1\",\n                \"Largest Country in the World\", \"Russia\", Arrays.asList(\n                        \"India\", \"Russia\", \"United States\", \"China\"));\n\n        assertTrue(response.getBody().contains(sampleQuestion));\n    }\n\n```\n\nBefore Refactoring Snippet\n\n```\n\t//NEEDS REFACTORING\n\t@Test\n\tpublic void retrieveAllSurveyQuestions() throws Exception {\n\n\t\tString url = \"http://localhost:\" + port + \"/surveys/Survey1/questions\";\n\n\t\tTestRestTemplate restTemplate = new TestRestTemplate();\n\n\t\tHttpHeaders headers = new HttpHeaders();\n\n\t\theaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));\n\n\t\tResponseEntity<List<Question>> response = restTemplate.exchange(url,\n\t\t\t\tHttpMethod.GET, new HttpEntity<String>(\"DUMMY_DOESNT_MATTER\",\n\t\t\t\t\t\theaders),\n\t\t\t\tnew ParameterizedTypeReference<List<Question>>() {\n\t\t\t\t});\n\n\t\tQuestion sampleQuestion = new Question(\"Question1\",\n\t\t\t\t\"Largest Country in the World\", \"Russia\", Arrays.asList(\n\t\t\t\t\t\t\"India\", \"Russia\", \"United States\", \"China\"));\n\n\t\tassertTrue(response.getBody().contains(sampleQuestion));\n\t}\n\n```\n\nAfter Refactoring Snippet - We will discuss this in Step 23\n\n```\n\n    @Test\n    public void createSurveyQuestion() throws Exception {\n        Question question = new Question(\"DOESN'T MATTER\", \"Smallest Number\",\n                \"1\", Arrays.asList(\"1\", \"2\", \"3\", \"4\"));\n\n        ResponseEntity<String> response = template.exchange(\n                createUrl(\"/surveys/Survey1/questions/\"), HttpMethod.POST,\n                new HttpEntity<Question>(question, headers), String.class);\n\n        assertThat(response.getHeaders().get(HttpHeaders.LOCATION).get(0),\n                containsString(\"/surveys/Survey1/questions/\"));\n    }\n\n```\n\n#### Files List\n\npom.xml New\n\n```\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\t<groupId>com.in28minutes.springboot</groupId>\n\t<artifactId>first-springboot-project</artifactId>\n\t<version>0.0.1-SNAPSHOT</version>\n\t<parent>\n\t\t<groupId>org.springframework.boot</groupId>\n\t\t<artifactId>spring-boot-starter-parent</artifactId>\n\t\t<version>1.4.0.RELEASE</version>\n\t</parent>\n\n\t<properties>\n\t\t<java.version>1.8</java.version>\n<maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>\n\t</properties>\n\n\t<dependencies>\n\t\t<dependency>\n\t\t\t<groupId>org.springframework.boot</groupId>\n\t\t\t<artifactId>spring-boot-starter-web</artifactId>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>org.springframework.boot</groupId>\n\t\t\t<artifactId>spring-boot-starter-data-jpa</artifactId>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>org.springframework.boot</groupId>\n\t\t\t<artifactId>spring-boot-starter-data-rest</artifactId>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.h2database</groupId>\n\t\t\t<artifactId>h2</artifactId>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>org.springframework.boot</groupId>\n\t\t\t<artifactId>spring-boot-devtools</artifactId>\n\t\t\t<optional>true</optional>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>org.springframework.boot</groupId>\n\t\t\t<artifactId>spring-boot-starter-actuator</artifactId>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>org.springframework.data</groupId>\n\t\t\t<artifactId>spring-data-rest-hal-browser</artifactId>\n\t\t</dependency>\n\n        <dependency>\n            <groupId>org.springframework.boot</groupId>\n            <artifactId>spring-boot-starter-test</artifactId>\n            <scope>test</scope>\n        </dependency>\n\t</dependencies>\n\n\t<build>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.springframework.boot</groupId>\n\t\t\t\t<artifactId>spring-boot-maven-plugin</artifactId>\n\t\t\t</plugin>\n\t\t</plugins>\n\t</build>\n</project>\n```\n\nsrc/main/java/com/in28minutes/springboot/Application.java New\n\n```\npackage com.in28minutes.springboot;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Profile;\n\n@SpringBootApplication\npublic class Application {\n\n\tpublic static void main(String[] args) {\n\t\tApplicationContext ctx = SpringApplication.run(Application.class, args);\n\n\t}\n\n\t@Profile(\"prod\")\n\t@Bean\n\tpublic String dummy() {\n\t\treturn \"something\";\n\t}\n}\n```\n\nsrc/main/java/com/in28minutes/springboot/WelcomeController.java New\n\n```\npackage com.in28minutes.springboot;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RestController;\n\nimport com.in28minutes.springboot.configuration.BasicConfiguration;\n\n@RestController\npublic class WelcomeController {\n\n\t//Auto wiring\n\t@Autowired\n\tprivate WelcomeService service;\n\n\t@Autowired\n\tprivate BasicConfiguration configuration;\n\n\t@RequestMapping(\"/welcome\")\n\tpublic String welcome() {\n\t\treturn service.retrieveWelcomeMessage();\n\t}\n\n\t@RequestMapping(\"/dynamic-configuration\")\n\tpublic Map dynamicConfiguration() {\n\t\tMap map = new HashMap();\n\t\tmap.put(\"message\", configuration.getMessage());\n\t\tmap.put(\"number\", configuration.getNumber());\n\t\tmap.put(\"value\", configuration.isValue());\n\n\t\treturn map;\n\t}\n\n}\n```\n\nsrc/main/java/com/in28minutes/springboot/WelcomeService.java New\n\n```\npackage com.in28minutes.springboot;\n\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.stereotype.Component;\n\n//Spring to manage this bean and create an instance of this\n@Component\npublic class WelcomeService {\n\n\t@Value(\"${welcome.message}\")\n\tprivate String welcomeMessage;\n\n\tpublic String retrieveWelcomeMessage() {\n\t\t//Complex Method\n\t\treturn welcomeMessage;\n\t}\n}\n```\n\nsrc/main/java/com/in28minutes/springboot/configuration/BasicConfiguration.java New\n\n```\npackage com.in28minutes.springboot.configuration;\n\nimport org.springframework.boot.context.properties.ConfigurationProperties;\nimport org.springframework.stereotype.Component;\n\n@Component\n@ConfigurationProperties(\"basic\")\npublic class BasicConfiguration {\n\tprivate boolean value;\n\tprivate String message;\n\tprivate int number;\n\n\tpublic boolean isValue() {\n\t\treturn value;\n\t}\n\n\tpublic void setValue(boolean value) {\n\t\tthis.value = value;\n\t}\n\n\tpublic String getMessage() {\n\t\treturn message;\n\t}\n\n\tpublic void setMessage(String message) {\n\t\tthis.message = message;\n\t}\n\n\tpublic int getNumber() {\n\t\treturn number;\n\t}\n\n\tpublic void setNumber(int number) {\n\t\tthis.number = number;\n\t}\n}\n```\n\nsrc/main/java/com/in28minutes/springboot/controller/SurveyController.java New\n\n```\npackage com.in28minutes.springboot.controller;\n\nimport java.net.URI;\nimport java.util.List;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.PostMapping;\nimport org.springframework.web.bind.annotation.RequestBody;\nimport org.springframework.web.bind.annotation.RestController;\nimport org.springframework.web.servlet.support.ServletUriComponentsBuilder;\n\nimport com.in28minutes.springboot.model.Question;\nimport com.in28minutes.springboot.service.SurveyService;\n\n@RestController\nclass SurveyController {\n\t@Autowired\n\tprivate SurveyService surveyService;\n\n\t@GetMapping(\"/surveys/{surveyId}/questions\")\n\tpublic List<Question> retrieveQuestions(@PathVariable String surveyId) {\n\t\treturn surveyService.retrieveQuestions(surveyId);\n\t}\n\n\t// GET \"/surveys/{surveyId}/questions/{questionId}\"\n\t@GetMapping(\"/surveys/{surveyId}/questions/{questionId}\")\n\tpublic Question retrieveDetailsForQuestion(@PathVariable String surveyId,\n\t\t\t@PathVariable String questionId) {\n\t\treturn surveyService.retrieveQuestion(surveyId, questionId);\n\t}\n\n\t// /surveys/{surveyId}/questions\n\t@PostMapping(\"/surveys/{surveyId}/questions\")\n\tpublic ResponseEntity<Void> addQuestionToSurvey(\n\t\t\t@PathVariable String surveyId, @RequestBody Question newQuestion) {\n\n\t\tQuestion question = surveyService.addQuestion(surveyId, newQuestion);\n\n\t\tif (question == null)\n\t\t\treturn ResponseEntity.noContent().build();\n\n\t\t// Success - URI of the new resource in Response Header\n\t\t// Status - created\n\t\t// URI -> /surveys/{surveyId}/questions/{questionId}\n\t\t// question.getQuestionId()\n\t\tURI location = ServletUriComponentsBuilder.fromCurrentRequest().path(\n\t\t\t\t\"/{id}\").buildAndExpand(question.getId()).toUri();\n\n\t\t// Status\n\t\treturn ResponseEntity.created(location).build();\n\t}\n\n}\n```\n\nsrc/main/java/com/in28minutes/springboot/jpa/User.java New\n\n```\npackage com.in28minutes.springboot.jpa;\n\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\n\n@Entity\npublic class User {\n\n\t@Id\n\t@GeneratedValue(strategy = GenerationType.AUTO)\n\tprivate Long id;\n\n\tprivate String name;\n\tprivate String role;\n\n\tprotected User() {\n\t}\n\n\tpublic User(String name, String role) {\n\t\tsuper();\n\t\tthis.name = name;\n\t\tthis.role = role;\n\t}\n\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic String getRole() {\n\t\treturn role;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"User [id=\" + id + \", name=\" + name + \", role=\" + role + \"]\";\n\t}\n\n}\n```\n\nsrc/main/java/com/in28minutes/springboot/jpa/UserCommandLineRunner.java New\n\n```\npackage com.in28minutes.springboot.jpa;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.CommandLineRunner;\nimport org.springframework.stereotype.Component;\n\n@Component\npublic class UserCommandLineRunner implements CommandLineRunner {\n\n\tprivate static final Logger log = LoggerFactory\n\t\t\t.getLogger(UserCommandLineRunner.class);\n\n\t@Autowired\n\tprivate UserRepository repository;\n\n\t@Override\n\tpublic void run(String... args) throws Exception {\n\n\t\trepository.save(new User(\"Ranga\", \"Admin\"));\n\t\trepository.save(new User(\"Ravi\", \"User\"));\n\t\trepository.save(new User(\"Satish\", \"Admin\"));\n\t\trepository.save(new User(\"Raghu\", \"User\"));\n\n\t\tfor (User user : repository.findAll()) {\n\t\t\tlog.info(user.toString());\n\t\t}\n\n\t\tlog.info(\"Admin users are.....\");\n\t\tlog.info(\"____________________\");\n\t\tfor (User user : repository.findByRole(\"Admin\")) {\n\t\t\tlog.info(user.toString());\n\t\t}\n\n\t}\n\n}\n```\n\nsrc/main/java/com/in28minutes/springboot/jpa/UserRepository.java New\n\n```\npackage com.in28minutes.springboot.jpa;\n\nimport java.util.List;\n\nimport org.springframework.data.repository.CrudRepository;\n\npublic interface UserRepository extends CrudRepository<User, Long> {\n\tList<User> findByRole(String role);\n}\n```\n\nsrc/main/java/com/in28minutes/springboot/jpa/UserRestRepository.java New\n\n```\npackage com.in28minutes.springboot.jpa;\n\nimport java.util.List;\n\nimport org.springframework.data.repository.PagingAndSortingRepository;\nimport org.springframework.data.repository.query.Param;\nimport org.springframework.data.rest.core.annotation.RepositoryRestResource;\n\n@RepositoryRestResource(path = \"users\", collectionResourceRel = \"users\")\npublic interface UserRestRepository extends\n\t\tPagingAndSortingRepository<User, Long> {\n\tList<User> findByRole(@Param(\"role\") String role);\n}\n```\n\nsrc/main/java/com/in28minutes/springboot/model/Question.java New\n\n```\npackage com.in28minutes.springboot.model;\n\nimport java.util.List;\n\npublic class Question {\n\tprivate String id;\n\tprivate String description;\n\tprivate String correctAnswer;\n\tprivate List<String> options;\n\n\t// Needed by Caused by: com.fasterxml.jackson.databind.JsonMappingException:\n\t// Can not construct instance of com.in28minutes.springboot.model.Question:\n\t// no suitable constructor found, can not deserialize from Object value\n\t// (missing default constructor or creator, or perhaps need to add/enable\n\t// type information?)\n\tpublic Question() {\n\n\t}\n\n\tpublic Question(String id, String description, String correctAnswer,\n\t\t\tList<String> options) {\n\t\tsuper();\n\t\tthis.id = id;\n\t\tthis.description = description;\n\t\tthis.correctAnswer = correctAnswer;\n\t\tthis.options = options;\n\t}\n\n\tpublic String getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(String id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getDescription() {\n\t\treturn description;\n\t}\n\n\tpublic String getCorrectAnswer() {\n\t\treturn correctAnswer;\n\t}\n\n\tpublic List<String> getOptions() {\n\t\treturn options;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn String\n\t\t\t\t.format(\"Question [id=%s, description=%s, correctAnswer=%s, options=%s]\",\n\t\t\t\t\t\tid, description, correctAnswer, options);\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + ((id == null) ? 0 : id.hashCode());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tQuestion other = (Question) obj;\n\t\tif (id == null) {\n\t\t\tif (other.id != null)\n\t\t\t\treturn false;\n\t\t} else if (!id.equals(other.id))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n}\n```\n\nsrc/main/java/com/in28minutes/springboot/model/Survey.java New\n\n```\npackage com.in28minutes.springboot.model;\n\nimport java.util.List;\n\npublic class Survey {\n\tprivate String id;\n\tprivate String title;\n\tprivate String description;\n\tprivate List<Question> questions;\n\n\tpublic Survey(String id, String title, String description,\n\t\t\tList<Question> questions) {\n\t\tsuper();\n\t\tthis.id = id;\n\t\tthis.title = title;\n\t\tthis.description = description;\n\t\tthis.questions = questions;\n\t}\n\n\tpublic String getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(String id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getTitle() {\n\t\treturn title;\n\t}\n\n\tpublic void setTitle(String title) {\n\t\tthis.title = title;\n\t}\n\n\tpublic String getDescription() {\n\t\treturn description;\n\t}\n\n\tpublic void setDescription(String description) {\n\t\tthis.description = description;\n\t}\n\n\tpublic List<Question> getQuestions() {\n\t\treturn questions;\n\t}\n\n\tpublic void setQuestions(List<Question> questions) {\n\t\tthis.questions = questions;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Survey [id=\" + id + \", title=\" + title + \", description=\"\n\t\t\t\t+ description + \", questions=\" + questions + \"]\";\n\t}\n\n}\n```\n\nsrc/main/java/com/in28minutes/springboot/service/SurveyService.java New\n\n```\npackage com.in28minutes.springboot.service;\n\nimport java.math.BigInteger;\nimport java.security.SecureRandom;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\nimport org.springframework.stereotype.Component;\n\nimport com.in28minutes.springboot.model.Question;\nimport com.in28minutes.springboot.model.Survey;\n\n@Component\npublic class SurveyService {\n\tprivate static List<Survey> surveys = new ArrayList<>();\n\tstatic {\n\t\tQuestion question1 = new Question(\"Question1\",\n\t\t\t\t\"Largest Country in the World\", \"Russia\", Arrays.asList(\n\t\t\t\t\t\t\"India\", \"Russia\", \"United States\", \"China\"));\n\t\tQuestion question2 = new Question(\"Question2\",\n\t\t\t\t\"Most Populus Country in the World\", \"China\", Arrays.asList(\n\t\t\t\t\t\t\"India\", \"Russia\", \"United States\", \"China\"));\n\t\tQuestion question3 = new Question(\"Question3\",\n\t\t\t\t\"Highest GDP in the World\", \"United States\", Arrays.asList(\n\t\t\t\t\t\t\"India\", \"Russia\", \"United States\", \"China\"));\n\t\tQuestion question4 = new Question(\"Question4\",\n\t\t\t\t\"Second largest english speaking country\", \"India\", Arrays\n\t\t\t\t\t\t.asList(\"India\", \"Russia\", \"United States\", \"China\"));\n\n\t\tList<Question> questions = new ArrayList<>(Arrays.asList(question1,\n\t\t\t\tquestion2, question3, question4));\n\n\t\tSurvey survey = new Survey(\"Survey1\", \"My Favorite Survey\",\n\t\t\t\t\"Description of the Survey\", questions);\n\n\t\tsurveys.add(survey);\n\t}\n\n\tpublic List<Survey> retrieveAllSurveys() {\n\t\treturn surveys;\n\t}\n\n\tpublic Survey retrieveSurvey(String surveyId) {\n\t\tfor (Survey survey : surveys) {\n\t\t\tif (survey.getId().equals(surveyId)) {\n\t\t\t\treturn survey;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic List<Question> retrieveQuestions(String surveyId) {\n\t\tSurvey survey = retrieveSurvey(surveyId);\n\n\t\tif (survey == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\treturn survey.getQuestions();\n\t}\n\n\tpublic Question retrieveQuestion(String surveyId, String questionId) {\n\t\tSurvey survey = retrieveSurvey(surveyId);\n\n\t\tif (survey == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\tfor (Question question : survey.getQuestions()) {\n\t\t\tif (question.getId().equals(questionId)) {\n\t\t\t\treturn question;\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}\n\n\tprivate SecureRandom random = new SecureRandom();\n\n\tpublic Question addQuestion(String surveyId, Question question) {\n\t\tSurvey survey = retrieveSurvey(surveyId);\n\n\t\tif (survey == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\tString randomId = new BigInteger(130, random).toString(32);\n\t\tquestion.setId(randomId);\n\n\t\tsurvey.getQuestions().add(question);\n\n\t\treturn question;\n\t}\n}\n```\n\nsrc/main/resources/application-dev.properties New\n\n```\nlogging.level.org.springframework: TRACE\n```\n\nsrc/main/resources/application-prod.properties New\n\n```\nlogging.level.org.springframework: INFO\n```\n\nsrc/main/resources/application.properties New\n\n```\nlogging.level.org.springframework: DEBUG\napp.name=in28Minutes\nwelcome.message=Welcome message from property file! Welcome to ${app.name}\n\nbasic.value=true\nbasic.message=Welcome to in28minutes\nbasic.number=200\n```\n\nsrc/test/java/com/in28minutes/springboot/controller/SurveyControllerIT.java New\n\n```\npackage com.in28minutes.springboot.controller;\n\nimport static org.junit.Assert.assertTrue;\n\nimport java.util.Arrays;\nimport java.util.List;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.skyscreamer.jsonassert.JSONAssert;\nimport org.springframework.boot.context.embedded.LocalServerPort;\nimport org.springframework.boot.test.context.SpringBootTest;\nimport org.springframework.boot.test.web.client.TestRestTemplate;\nimport org.springframework.core.ParameterizedTypeReference;\nimport org.springframework.http.HttpEntity;\nimport org.springframework.http.HttpHeaders;\nimport org.springframework.http.HttpMethod;\nimport org.springframework.http.MediaType;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.test.context.junit4.SpringRunner;\n\nimport com.in28minutes.springboot.Application;\nimport com.in28minutes.springboot.model.Question;\n\n@RunWith(SpringRunner.class)\n@SpringBootTest(classes = Application.class,\n\t\twebEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)\npublic class SurveyControllerIT {\n\n\t@LocalServerPort\n\tprivate int port;\n\n\t//NEEDS REFACTORING\n\t@Test\n\tpublic void testRetrieveSurveyQuestion() {\n\n\t\tString url = \"http://localhost:\" + port\n\t\t\t\t+ \"/surveys/Survey1/questions/Question1\";\n\n\t\tTestRestTemplate restTemplate = new TestRestTemplate();\n\n\t\tHttpHeaders headers = new HttpHeaders();\n\n\t\theaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));\n\n\t\tHttpEntity<String> entity = new HttpEntity<String>(null, headers);\n\n\t\tResponseEntity<String> response = restTemplate.exchange(url,\n\t\t\t\tHttpMethod.GET, entity, String.class);\n\n\t\tString expected = \"{id:Question1,description:Largest Country in the World,correctAnswer:Russia}\";\n\n\t\tJSONAssert.assertEquals(expected, response.getBody(), false);\n\t}\n\n\t//NEEDS REFACTORING\n\t@Test\n\tpublic void retrieveAllSurveyQuestions() throws Exception {\n\n\t\tString url = \"http://localhost:\" + port + \"/surveys/Survey1/questions\";\n\n\t\tTestRestTemplate restTemplate = new TestRestTemplate();\n\n\t\tHttpHeaders headers = new HttpHeaders();\n\n\t\theaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));\n\n\t\tResponseEntity<List<Question>> response = restTemplate.exchange(url,\n\t\t\t\tHttpMethod.GET, new HttpEntity<String>(\"DUMMY_DOESNT_MATTER\",\n\t\t\t\t\t\theaders),\n\t\t\t\tnew ParameterizedTypeReference<List<Question>>() {\n\t\t\t\t});\n\n\t\tQuestion sampleQuestion = new Question(\"Question1\",\n\t\t\t\t\"Largest Country in the World\", \"Russia\", Arrays.asList(\n\t\t\t\t\t\t\"India\", \"Russia\", \"United States\", \"China\"));\n\n\t\tassertTrue(response.getBody().contains(sampleQuestion));\n\t}\n\n\t//NEEDS REFACTORING\n\t@Test\n\tpublic void addQuestion() {\n\n\t\tString url = \"http://localhost:\" + port + \"/surveys/Survey1/questions\";\n\n\t\tTestRestTemplate restTemplate = new TestRestTemplate();\n\n\t\tHttpHeaders headers = new HttpHeaders();\n\n\t\theaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));\n\n\t\tQuestion question = new Question(\"DOESNTMATTER\", \"Question1\", \"Russia\",\n\t\t\t\tArrays.asList(\"India\", \"Russia\", \"United States\", \"China\"));\n\n\t\tHttpEntity entity = new HttpEntity<Question>(question, headers);\n\n\t\tResponseEntity<String> response = restTemplate.exchange(url,\n\t\t\t\tHttpMethod.POST, entity, String.class);\n\n\t\tString actual = response.getHeaders().get(HttpHeaders.LOCATION).get(0);\n\n\t\tassertTrue(actual.contains(\"/surveys/Survey1/questions/\"));\n\n\t}\n\n}\n```\n\n## Step23.md\n\n#### What You Will Learn during this Step:\n\n- Lets do some cleanup\n- Lets Refactor the SurveyControllerIT.java\n\n#### Exercises\n\n- Test and make sure everything is working fine\n\n#### Files List\n\nsrc/test/java/com/in28minutes/springboot/controller/SurveyControllerIT.java\n\n```\npackage com.in28minutes.springboot.controller;\n\nimport static org.junit.Assert.assertTrue;\n\nimport java.util.Arrays;\nimport java.util.List;\n\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.skyscreamer.jsonassert.JSONAssert;\nimport org.springframework.boot.context.embedded.LocalServerPort;\nimport org.springframework.boot.test.context.SpringBootTest;\nimport org.springframework.boot.test.web.client.TestRestTemplate;\nimport org.springframework.core.ParameterizedTypeReference;\nimport org.springframework.http.HttpEntity;\nimport org.springframework.http.HttpHeaders;\nimport org.springframework.http.HttpMethod;\nimport org.springframework.http.MediaType;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.test.context.junit4.SpringRunner;\n\nimport com.in28minutes.springboot.Application;\nimport com.in28minutes.springboot.model.Question;\n\n@RunWith(SpringRunner.class)\n@SpringBootTest(classes = Application.class,\n\t\twebEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)\npublic class SurveyControllerIT {\n\n\t@LocalServerPort\n\tprivate int port;\n\n\tTestRestTemplate restTemplate = new TestRestTemplate();\n\n\tHttpHeaders headers = new HttpHeaders();\n\n\t@Before\n\tpublic void before() {\n\n\t\theaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));\n\n\t}\n\n\t@Test\n\tpublic void testRetrieveSurveyQuestion() {\n\n\t\tHttpEntity<String> entity = new HttpEntity<String>(null, headers);\n\n\t\tResponseEntity<String> response = restTemplate.exchange(\n\t\t\t\tcreateURLWithPort(\"/surveys/Survey1/questions/Question1\"),\n\t\t\t\tHttpMethod.GET, entity, String.class);\n\n\t\tString expected = \"{id:Question1,description:Largest Country in the World,correctAnswer:Russia}\";\n\n\t\tJSONAssert.assertEquals(expected, response.getBody(), false);\n\t}\n\n\t@Test\n\tpublic void retrieveAllSurveyQuestions() throws Exception {\n\n\t\tResponseEntity<List<Question>> response = restTemplate.exchange(\n\t\t\t\tcreateURLWithPort(\"/surveys/Survey1/questions\"),\n\t\t\t\tHttpMethod.GET, new HttpEntity<String>(\"DUMMY_DOESNT_MATTER\",\n\t\t\t\t\t\theaders),\n\t\t\t\tnew ParameterizedTypeReference<List<Question>>() {\n\t\t\t\t});\n\n\t\tQuestion sampleQuestion = new Question(\"Question1\",\n\t\t\t\t\"Largest Country in the World\", \"Russia\", Arrays.asList(\n\t\t\t\t\t\t\"India\", \"Russia\", \"United States\", \"China\"));\n\n\t\tassertTrue(response.getBody().contains(sampleQuestion));\n\t}\n\n\t@Test\n\tpublic void addQuestion() {\n\n\t\tQuestion question = new Question(\"DOESNTMATTER\", \"Question1\", \"Russia\",\n\t\t\t\tArrays.asList(\"India\", \"Russia\", \"United States\", \"China\"));\n\n\t\tHttpEntity entity = new HttpEntity<Question>(question, headers);\n\n\t\tResponseEntity<String> response = restTemplate.exchange(\n\t\t\t\tcreateURLWithPort(\"/surveys/Survey1/questions\"),\n\t\t\t\tHttpMethod.POST, entity, String.class);\n\n\t\tString actual = response.getHeaders().get(HttpHeaders.LOCATION).get(0);\n\n\t\tassertTrue(actual.contains(\"/surveys/Survey1/questions/\"));\n\n\t}\n\n\tprivate String createURLWithPort(final String uri) {\n\t\treturn \"http://localhost:\" + port + uri;\n\t}\n\n}\n```\n\n## Step24.md\n\n#### What You Will Learn during this Step:\n\n- Write a Unit Test for retrieving a specific question from a survey.\n- Different between Unit Test and Integration Test\n- Basics of Mocking\n- MockMvc framework\n- @MockBean\n\n> Programming Tip - Become an expert at Mockito - https://courses.in28minutes.com/p/mockito-for-beginner-in-5-steps\n\n#### Exercises\n\n- Write unit test for retrieve all questions for a survey\n\n#### Files List\n\nsrc/test/java/com/in28minutes/springboot/controller/SurveyControllerTest.java New\n\n```\npackage com.in28minutes.springboot.controller;\n\nimport java.util.Arrays;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.mockito.Mockito;\nimport org.skyscreamer.jsonassert.JSONAssert;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;\nimport org.springframework.boot.test.mock.mockito.MockBean;\nimport org.springframework.http.MediaType;\nimport org.springframework.test.context.junit4.SpringRunner;\nimport org.springframework.test.web.servlet.MockMvc;\nimport org.springframework.test.web.servlet.MvcResult;\nimport org.springframework.test.web.servlet.RequestBuilder;\nimport org.springframework.test.web.servlet.request.MockMvcRequestBuilders;\n\nimport com.in28minutes.springboot.model.Question;\nimport com.in28minutes.springboot.service.SurveyService;\n\n@RunWith(SpringRunner.class)\n@WebMvcTest(value = SurveyController.class)\npublic class SurveyControllerTest {\n\n\t@Autowired\n\tprivate MockMvc mockMvc;\n\n\t// Mock @Autowired\n\t@MockBean\n\tprivate SurveyService surveyService;\n\n\t@Test\n\tpublic void retrieveDetailsForQuestion() throws Exception {\n\t\tQuestion mockQuestion = new Question(\"Question1\",\n\t\t\t\t\"Largest Country in the World\", \"Russia\", Arrays.asList(\n\t\t\t\t\t\t\"India\", \"Russia\", \"United States\", \"China\"));\n\n\t\tMockito.when(\n\t\t\t\tsurveyService.retrieveQuestion(Mockito.anyString(), Mockito\n\t\t\t\t\t\t.anyString())).thenReturn(mockQuestion);\n\n\t\tRequestBuilder requestBuilder = MockMvcRequestBuilders.get(\n\t\t\t\t\"/surveys/Survey1/questions/Question1\").accept(\n\t\t\t\tMediaType.APPLICATION_JSON);\n\n\t\tMvcResult result = mockMvc.perform(requestBuilder).andReturn();\n\n\t\tString expected = \"{id:Question1,description:Largest Country in the World,correctAnswer:Russia}\";\n\n\t\tJSONAssert.assertEquals(expected, result.getResponse()\n\t\t\t\t.getContentAsString(), false);\n\n\t\t// Assert\n\t}\n}\n```\n\n## Step25.md\n\n#### What You Will Learn during this Step:\n\n- Exercise from previous step\n- Unit test for createTodo\n\n#### Files List\n\nsrc/test/java/com/in28minutes/springboot/controller/SurveyControllerTest.java Modified\n\n```\n\n\t@Test\n\tpublic void createSurveyQuestion() throws Exception {\n\t\tQuestion mockQuestion = new Question(\"1\", \"Smallest Number\", \"1\",\n\t\t\t\tArrays.asList(\"1\", \"2\", \"3\", \"4\"));\n\n\t\tString questionJson = \"{\\\"description\\\":\\\"Smallest Number\\\",\\\"correctAnswer\\\":\\\"1\\\",\\\"options\\\":[\\\"1\\\",\\\"2\\\",\\\"3\\\",\\\"4\\\"]}\";\n\t\t//surveyService.addQuestion to respond back with mockQuestion\n\t\tMockito.when(\n\t\t\t\tsurveyService.addQuestion(Mockito.anyString(), Mockito\n\t\t\t\t\t\t.any(Question.class))).thenReturn(mockQuestion);\n\n\t\t//Send question as body to /surveys/Survey1/questions\n\t\tRequestBuilder requestBuilder = MockMvcRequestBuilders.post(\n\t\t\t\t\"/surveys/Survey1/questions\")\n\t\t\t\t.accept(MediaType.APPLICATION_JSON).content(questionJson)\n\t\t\t\t.contentType(MediaType.APPLICATION_JSON);\n\n\t\tMvcResult result = mockMvc.perform(requestBuilder).andReturn();\n\n\t\tMockHttpServletResponse response = result.getResponse();\n\n\t\tassertEquals(HttpStatus.CREATED.value(), response.getStatus());\n\n\t\tassertEquals(\"http://localhost/surveys/Survey1/questions/1\", response\n\t\t\t\t.getHeader(HttpHeaders.LOCATION));\n\t}\n```\n\n## Step26.md\n\n#### What You Will Learn during this Step:\n\n- Securing our services with Basic Authentication using Spring Security\n- Executing Requests using Basic Authentication with Postman\n- default user name is user\n- default security password is printed in console\n\n#### Useful Snippets and References\n\nFirst Snippet\n\n```\n        <dependency>\n            <groupId>org.springframework.boot</groupId>\n            <artifactId>spring-boot-starter-security</artifactId>\n        </dependency>\n```\n\nSecond Snippet\n\n```\nUsing default security password:\n```\n\nThird Snippet : Executing a GET to http://localhost:8080/surveys/Survey1/questions/\n\n```\n{\n  \"timestamp\": 1483514297025,\n  \"status\": 401,\n  \"error\": \"Unauthorized\",\n  \"message\": \"Full authentication is required to access this resource\",\n  \"path\": \"/surveys/Survey1/questions/\"\n}\n```\n\n## Step27.md\n\n#### What You Will Learn during this Step:\n\n- Configure different user roles for survey and other services\n- Update integration tests\n- Update unit tests\n\n#### Files List\n\npom.xml Modified\nNew Lines\n\n```\n<dependency>\n    <groupId>org.springframework.boot</groupId>\n    <artifactId>spring-boot-starter-security</artifactId>\n</dependency>\n```\n\nsrc/main/java/com/in28minutes/springboot/security/SecurityConfig.java New\n\n```\npackage com.in28minutes.springboot.security;\n\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;\nimport org.springframework.security.config.annotation.web.builders.HttpSecurity;\nimport org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;\n\n@Configuration\npublic class SecurityConfig extends WebSecurityConfigurerAdapter {\n\t// Authentication : User --> Roles\n\tprotected void configure(AuthenticationManagerBuilder auth)\n\t\t\tthrows Exception {\n\t\tauth.inMemoryAuthentication().passwordEncoder(org.springframework.security.crypto.password.NoOpPasswordEncoder.getInstance()).withUser(\"user1\").password(\"secret1\")\n\t\t\t\t.roles(\"USER\").and().withUser(\"admin1\").password(\"secret1\")\n\t\t\t\t.roles(\"USER\", \"ADMIN\");\n\t}\n\n\t// Authorization : Role -> Access\n\t// survey -> USER\n\tprotected void configure(HttpSecurity http) throws Exception {\n\t\thttp.httpBasic().and().authorizeRequests().antMatchers(\"/surveys/**\")\n\t\t\t\t.hasRole(\"USER\").antMatchers(\"/users/**\").hasRole(\"USER\")\n\t\t\t\t.antMatchers(\"/**\").hasRole(\"ADMIN\").and().csrf().disable()\n\t\t\t\t.headers().frameOptions().disable();\n\t}\n\n}\n```\n\nsrc/test/java/com/in28minutes/springboot/controller/SurveyControllerIT.java Modified\nNew Lines\n\n```\n@RunWith(SpringRunner.class)\n@SpringBootTest(classes = Application.class,\n\t\twebEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)\npublic class SurveyControllerIT {\n\n\t//Other Code \n\n\tHttpHeaders headers = new HttpHeaders();\n\n\t@Before\n\tpublic void before() {\n\t\theaders.add(\"Authorization\", createHttpAuthenticationHeaderValue(\n\t\t\t\t\"user1\", \"secret1\"));\n\t\theaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));\n\t}\n    //Other Code \n\t\n\tprivate String createHttpAuthenticationHeaderValue(String userId,\n\t\t\tString password) {\n\n\t\tString auth = userId + \":\" + password;\n\n\t\tbyte[] encodedAuth = Base64.encode(auth.getBytes(Charset\n\t\t\t\t.forName(\"US-ASCII\")));\n\n\t\tString headerValue = \"Basic \" + new String(encodedAuth);\n\n\t\treturn headerValue;\n\t}\n\n}\n```\n\nsrc/test/java/com/in28minutes/springboot/controller/SurveyControllerTest.java Modified\n\n```\n@WebMvcTest(value = SurveyController.class, secure = false)\n```\n\n## Step28.md\n\n#### What You Will Learn during this Step:\n\n- A Deep Dive into Autoconfiguration\n- spring-boot-autoconfigure-1.4.0.RELEASE.jar\n- /META-INF/spring.factories\n- Package org.springframework.boot.autoconfigure\n- Lets look at the log in debug mode!\n- Examples\n- JdbcTemplateAutoConfiguration\n- HttpMessageConvertersAutoConfiguration\n- Programming Tips\n- Understand Design Patterns\n- https://www.youtube.com/watch?v=Vp7q_pE7Fzg\n- Understand Modern Development Practices\n- https://www.youtube.com/watch?v=0Kqzfyp-w4s\n\n#### Useful Snippets and References\n\n```\n        String[] beanNames = ctx.getBeanDefinitionNames();\n        Arrays.sort(beanNames);\n\n        for (String beanName : beanNames) {\n            System.out.println(beanName);\n        }\n```\n\n"
  },
  {
    "path": "_blog/articles/2017-10-13-spring-in-10-steps.md",
    "content": "---\nlayout:     post\ntitle:      Spring Framework Tutorial for Beginners - Your First 10 Steps\ndate:       2025-09-24 12:31:19\nsummary:    Learn the basics of Spring Framework setting up a very simple example.\ncategories: SpringFramework\npermalink:  /spring-tutorial-for-beginners\nimage: /images/spring-framework-category.png\n---\n\nThe Spring Framework is just as popular today as it was 12 years ago when I first used it.  \nHow has it managed to stay relevant in an ever-changing world where software architecture has evolved so dramatically?\n\n### What you will learn\n\n- Spring Framework Fundamentals\n    - Dependency Injection\n    - Constructor and Setter Injection\n    - Autowiring\n- Key Annotations: `@Component`, `@Autowired`, `@Primary`\n- Overview of Core Spring Modules\n- Overview of Major Spring Projects\n\n### Section Introduction\n\nWelcome to this section on the Spring Framework.  \nHere, we will guide you through setting up a simple Spring project and introduce key concepts such as tight coupling, loose coupling, dependency injection, inversion of control, and autowiring. You will also get a high-level overview of the Spring ecosystem:\n\n- What are Spring Modules?\n- What are Spring Projects?\n\nFinally, we’ll explore why the Spring Framework continues to be so popular.\n\n### The First 10 Steps in Spring\n\n#### Step 1: Create a Spring Project with Spring Initializr\n\nOne of the most important features of the Spring Framework is **dependency injection**, which enables the creation of loosely coupled applications. To fully appreciate dependency injection, it’s essential to first understand **tight coupling** and how Spring helps us move toward **loose coupling**.\n\nWe’ll begin by setting up a simple example that highlights these concepts.\n\nCreating a Spring project with **Spring Initializr** is straightforward:\n\n> Spring Initializr [http://start.spring.io/](http://start.spring.io/) is a powerful tool to quickly bootstrap your Spring Boot projects.\n\n\n![Image](/images/spring-initializr-spring-in-10-steps.png \"Spring Initializr\")   \n\nAs shown in the image above, follow these steps:\n\n- Launch **Spring Initializr** and configure it as follows:\n    - Group: `com.in28minutes.spring.basics`\n    - Artifact: `spring-in-5-steps`\n    - Do not select any additional dependencies.\n        - By default, the Basic Starter is included, which provides the core Spring Framework and the Spring Test Starter.\n- Click the **Generate** button to create a new project.\n- Import the project into **Eclipse**.\n- To understand all the files that are part of this project, refer to the provided resource.\n\n#### Step 2: Understanding Tight Coupling with the Binary Search Algorithm Example\n\nNext, set up an example of **tight coupling** using the Binary Search and Bubble Sort algorithms, as illustrated in the diagram below.\n\n\n![Image](/images/SpringIn10Steps-BinarySearchTightlyCoupleWithBubbleSort.png \"Spring In 10 Steps - Tight Coupling\") \n\nHowever, we have a problem with the above implementation. If we want to use binary search with a different sort algorithm, I would need to change the code.\n\nWe want to make the binary search algorithm loosely coupled so that it can work with any sorting algorithm. \n\n> Think about the solution before moving to the next step!\n\n#### Step 3 : Making the Binary Search Algorithm Example Loosely Coupled\n\nIntroduce an interface to make the Binary Search loosely coupled to the sort algorithm.\n\n```java\npackage com.in28minutes.spring.basics.springin5steps;\n\npublic interface SortAlgorithm {\n\tpublic int[] sort(int[] numbers);\n}\n```\n\n```java\npublic class BinarySearchImpl {\n\n    private SortAlgorithm sortAlgorithm;\n\n}    \n```\t\n\n\n#### Step 4 : Using Spring to Manage Dependencies-@Component, @Autowired\n\n> In the previous steps, we wrote code to create objects using the bubble sort algorithm and binary search. We also managed the dependencies. It would be great if some framework could take control of the creation of the beans and autowire the dependencies.\n\nThat's where the Spring Framework comes in!\n\nLet's start using Spring to do autowiring.\n\nNotes\n\n- The sort algorithm is a dependency of the binary search.\n\n\n```java\n@Component\npublic class BinarySearchImpl {\n\n\t@Autowired\n\tprivate SortAlgorithm sortAlgorithm;\n```\t\n\n\n```java\n@Component\npublic class BubbleSortAlgorithm implements SortAlgorithm {\n\tpublic int[] sort(int[] numbers) {\n\t\t// Logic for Bubble Sort\n\t\treturn numbers;\n\t}\n}\n```\n\n#### Step 5 : What is happening in the background?\n\nEnable debug logging to observe what’s happening behind the scenes.\n\n**/src/main/resources/application.properties**\n```properties\nlogging.level.org.springframework = debug\n```\n\n- Spring performs a component scan on the parent package com.in28minutes.spring.basics.springin5steps to discover classes annotated with @Component.\n- It identifies available components and their dependencies.\n- It determines that BinarySearchImpl depends on SortAlgorithm.\n- Since SortAlgorithm itself has no dependencies, Spring creates an instance of it and automatically wires it into an instance of BinarySearchImpl.\n\n#### Step 6 : Dynamic auto wiring and troubleshooting-@Primary\n\nWhat if we add one more SortAlgorithm?\n\n```java\npackage com.in28minutes.spring.basics.springin5steps;\n\nimport org.springframework.stereotype.Component;\n\n@Component\npublic class QuickSortAlgorithm implements SortAlgorithm {\n\tpublic int[] sort(int[] numbers) {\n\t\t// Logic for Quick Sort\n\t\treturn numbers;\n\t}\n}\n```\n\nThere are now two matching SortAlgorithm instances. Spring throws an exception because it doesn’t know which one to use.\n\nWe can use the @Primary annotation to mark one of the SortAlgorithm implementations as the default or preferred choice.\n\n```java\npackage com.in28minutes.spring.basics.springin5steps;\n\nimport org.springframework.context.annotation.Primary;\nimport org.springframework.stereotype.Component;\n\n@Component\n@Primary\npublic class BubbleSortAlgorithm implements SortAlgorithm {\n\tpublic int[] sort(int[] numbers) {\n\t\t// Logic for Bubble Sort\n\t\treturn numbers;\n\t}\n}\n```\n#### Step 7: Inject Constructor and Setter\n\nConstructor Injection\n![Image](/images/SpringIn10Steps-ConstructorInjection.png \"Spring In 10 Step - Constructor Injection \") \n\nSetter Injection\n![Image](/images/SpringIn10Steps-SetterInjection.png \"Spring In 10 Step - Setter Injection\") \n \n#### Step 8 : Spring Modules\n\nSpring is designed in a highly modular way, allowing us to use specific modules independently without needing the others.\n\n![Image](/images/SpringIn10Steps-SpringModules.png \"Spring In 10 Steps - Spring Modules\") \n\nNotes\n- **Spring Beans, Core, and Context** form the foundation of the Spring Framework — they are responsible for creating the application context, managing bean lifecycles, and handling dependency injection (autowiring).\n- Spring provides excellent integration with both data access and integration layers. \n- One of the key data access modules is Spring JDBC, which simplifies working with JDBC. Code that typically requires around twenty-five lines in plain JDBC can often be written in just five to ten lines using Spring JDBC. Spring also integrates seamlessly with JPA and ORM frameworks such as **Hibernate**.\n- **Spring JMS** enables communication between applications using JMS. You can send and receive messages through queues, and perform object-to-XML transformations when required.\n- **Spring** has strong integration with web frameworks like **Struts**, and it also offers its own web framework called **Spring MVC**.\n- **Cross-Cutting Concerns** refer to functionalities that affect multiple layers of an application, such as security and logging. Through **aspect-oriented programming (AOP)**, Spring makes it easy to handle these concerns. The **Spring AOP** module provides basic AOP capabilities, and Spring also offers excellent integration with **AspectJ**.\n- **Spring** provides robust support for unit testing through the **Spring Test** framework.\n\n#### Step 9 : Spring Projects\n\nSpring projects offer solutions to various challenges commonly faced by enterprise applications.\n\n![Image](/images/SpringIn10Steps-SpringProjects.png \"Spring In 10 Steps - Spring Projects\")\n\n### Notes\n\n- **Spring Boot** is one of the most popular frameworks for developing microservices today. It makes application development fast and easy. With features like starter projects, auto-configuration, and actuators, Spring Boot simplifies building production-ready applications.\n- The world is moving towards the **cloud**, and everyone wants to deploy their applications there. Therefore, it’s not enough to just develop good applications — we need to build **cloud-native applications**. These applications should support dynamic configuration and connectivity. Cloud-native applications require many additional features, and **Spring Cloud** helps in enabling microservices for the cloud.\n- **Spring Data** provides a consistent and simplified way to access data. In the past, most applications connected only to relational SQL databases. Today, we have a mix of data sources — relational, NoSQL, and others. Spring Data ensures that accessing data from different sources remains consistent and easy to manage.\n- **Spring Integration** addresses the challenges of application integration. It implements the patterns described in the book *Enterprise Integration Patterns*.\n- **Spring Batch** focuses on batch processing applications, which have specific requirements — such as restarting failed jobs, tracking execution details, and monitoring progress. Spring Batch provides these capabilities, making it easy to develop robust batch applications.\n- **Spring Security** is an essential module for protecting applications. Whether you are developing a web application or a RESTful service, Spring Security provides comprehensive solutions to secure them.\n- **Spring HATEOAS** enables you to create HATEOAS-compliant REST services. In REST, it’s not enough to just return data — it’s also important to include related links that guide the consumer on possible next actions. Spring HATEOAS makes implementing this pattern simple and effective.\n\n\nSo far, we’ve explored seven Spring projects, which just scratch the surface. There are many more, including **Spring Web Services**, **Spring Sessions**, **Spring Social**, **Spring Mobile**, and **Spring Android**, each designed to solve problems in specific areas.\n\n> Spring has not limited itself to just the core framework; it has expanded into a wide range of projects.\n\n\n#### Step 10 : Why Is Spring Popular?\n![Image](/images/SpringIn10Steps-SpringPopularity.png \"Spring In 10 Steps - Spring Popularity\")\nSpring is one of the very few frameworks that remains as popular today as it was 15 years ago.\n\n**How has Spring maintained its popularity over the past 15 years?**\n\n- **Unit Testing** – One of the main reasons for Spring’s popularity is that it enables writing highly testable code. The core feature of Spring is **dependency injection (DI)**. When used properly, DI makes writing unit tests for your code straightforward. Spring also integrates well with testing frameworks like `JUnit` and `Mockito`, allowing developers to write effective unit tests quickly.\n- **Zero Plumbing Code** – Spring reduces boilerplate code. For example, exception handling is simplified because Spring makes most exceptions unchecked, minimizing unnecessary plumbing code.\n- **Architectural Flexibility** – Spring is highly modular. It offers modules and projects for specific purposes, allowing you to use only the parts you need. For instance, even though Spring has a robust MVC framework (**Spring MVC**), it still provides excellent support for other MVC frameworks like Struts. Similarly, while Spring MVC provides REST support, Spring also integrates well with **JAX-RS** and **Jersey**. Using Spring does not restrict your architectural choices.\n- **Staying Current with Trends** – Spring remains relevant by evolving with industry trends. For example, with the rise of microservices and cloud computing, Spring has introduced projects like **Spring Cloud** and **Spring Boot** to help developers build modern, cloud-native applications efficiently.\n\n## Example of Complete Code\n\n### /pom.xml\n\n```xml\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\n\t<groupId>com.in28minutes.spring.basics</groupId>\n\t<artifactId>spring-in-5-steps</artifactId>\n\t<version>0.0.1-SNAPSHOT</version>\n\t<packaging>jar</packaging>\n\n\t<name>spring-in-5-steps</name>\n\t<description>Demo project for Spring Boot</description>\n\n\t<parent>\n\t\t<groupId>org.springframework.boot</groupId>\n\t\t<artifactId>spring-boot-starter-parent</artifactId>\n\t\t<version>4.0.0-M2</version>\n\t\t<relativePath/> <!-- lookup parent from repository -->\n\t</parent>\n\n\t<properties>\n\t\t<java.version>21</java.version>\n\t</properties>\n\n\t<dependencies>\n\t\t<dependency>\n\t\t\t<groupId>org.springframework.boot</groupId>\n\t\t\t<artifactId>spring-boot-starter</artifactId>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>org.springframework.boot</groupId>\n\t\t\t<artifactId>spring-boot-starter-test</artifactId>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t</dependencies>\n\n\t<build>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.springframework.boot</groupId>\n\t\t\t\t<artifactId>spring-boot-maven-plugin</artifactId>\n\t\t\t</plugin>\n\t\t</plugins>\n\t</build>\n\n\t<repositories>\n\t\t<repository>\n\t\t\t<id>spring-milestones</id>\n\t\t\t<name>Spring Milestones</name>\n\t\t\t<url>https://repo.spring.io/milestone</url>\n\t\t\t<snapshots>\n\t\t\t\t<enabled>false</enabled>\n\t\t\t</snapshots>\n\t\t</repository>\n   </repositories>\n\n   <pluginRepositories>\n\t\t<pluginRepository>\n\t\t\t<id>spring-milestones</id>\n\t\t\t<name>Spring Milestones</name>\n\t\t\t<url>https://repo.spring.io/milestone</url>\n\t\t\t<snapshots>\n\t\t\t\t<enabled>false</enabled>\n\t\t\t</snapshots>\n\t\t</pluginRepository>\n\t</pluginRepositories>\n\n\n</project>\n```\n---\n\n### /src/main/java/com/in28minutes/spring/basics/springin5steps/BinarySearchImpl.java\n\n```java\npackage com.in28minutes.spring.basics.springin5steps;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Component;\n\n@Component\npublic class BinarySearchImpl {\n\n\t@Autowired\n\tprivate SortAlgorithm sortAlgorithm;\n\t\n\tpublic int binarySearch(int[] numbers, int numberToSearchFor) {\n\n\t\tint[] sortedNumbers = sortAlgorithm.sort(numbers);\n\t\tSystem.out.println(sortAlgorithm);\n\t\t// Search the array\n\t\treturn 3;\n\t}\n\n}\n```\n---\n\n### /src/main/java/com/in28minutes/spring/basics/springin5steps/BubbleSortAlgorithm.java\n\n```java\npackage com.in28minutes.spring.basics.springin5steps;\n\nimport org.springframework.context.annotation.Primary;\nimport org.springframework.stereotype.Component;\n\n@Component\n@Primary\npublic class BubbleSortAlgorithm implements SortAlgorithm {\n\tpublic int[] sort(int[] numbers) {\n\t\t// Logic for Bubble Sort\n\t\treturn numbers;\n\t}\n}\n```\n---\n\n### /src/main/java/com/in28minutes/spring/basics/springin5steps/QuickSortAlgorithm.java\n\n```java\npackage com.in28minutes.spring.basics.springin5steps;\n\nimport org.springframework.stereotype.Component;\n\n@Component\npublic class QuickSortAlgorithm implements SortAlgorithm {\n\tpublic int[] sort(int[] numbers) {\n\t\t// Logic for Quick Sort\n\t\treturn numbers;\n\t}\n}\n```\n---\n\n### /src/main/java/com/in28minutes/spring/basics/springin5steps/SortAlgorithm.java\n\n```java\npackage com.in28minutes.spring.basics.springin5steps;\n\npublic interface SortAlgorithm {\n\tpublic int[] sort(int[] numbers);\n}\n```\n---\n\n### /src/main/java/com/in28minutes/spring/basics/springin5steps/SpringIn5StepsApplication.java\n\n```java\npackage com.in28minutes.spring.basics.springin5steps;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.context.ApplicationContext;\n\n@SpringBootApplication\npublic class SpringIn5StepsApplication {\n\n\t// What are the beans?\n\t// What are the dependencies of a bean?\n\t// Where to search for beans? => No need\n\n\tpublic static void main(String[] args) {\n\n\t\t// BinarySearchImpl binarySearch =\n\t\t// new BinarySearchImpl(new QuickSortAlgorithm());\n\t\t// Application Context\n\t\tApplicationContext applicationContext = SpringApplication.run(SpringIn5StepsApplication.class, args);\n\t\t\n\t\tBinarySearchImpl binarySearch = applicationContext.getBean(BinarySearchImpl.class);\n\t\t\n\t\tint result = binarySearch.binarySearch(new int[] { 12, 4, 6 }, 3);\n\n\t\tSystem.out.println(result);\n\t}\n}\n```\n---\n\n### /src/main/resources/application.properties\n\n```properties\nlogging.level.org.springframework = debug\n```\n---\n\n### /src/main/resources/log.txt\n\n```\nSearching directory [/in28Minutes/git/getting-started-in-5-steps/spring-in-5-steps/target/classes/com/in28minutes/spring/basics/springin5steps] for files matching pattern [/in28Minutes/git/getting-started-in-5-steps/spring-in-5-steps/target/classes/com/in28minutes/spring/basics/springin5steps/**/*.class]\nIdentified candidate component class: file [/in28Minutes/git/getting-started-in-5-steps/spring-in-5-steps/target/classes/com/in28minutes/spring/basics/springin5steps/BinarySearchImpl.class]\nIdentified candidate component class: file [/in28Minutes/git/getting-started-in-5-steps/spring-in-5-steps/target/classes/com/in28minutes/spring/basics/springin5steps/BubbleSortAlgorithm.class]\n\nCreating instance of bean 'binarySearchImpl'\nCreating instance of bean 'bubbleSortAlgorithm'\nFinished creating instance of bean 'bubbleSortAlgorithm'\n\nConstuctor-Autowiring by type from bean name 'binarySearchImpl' via constructor to bean named 'bubbleSortAlgorithm'\nSetter-Autowiring by type from bean name 'binarySearchImpl' to bean name 'bubbleSortAlgorithm'\nNo Setter or Constructor-Autowiring by type from bean name 'binarySearchImpl' to bean name 'bubbleSortAlgorithm'\n\nFinished creating instance of bean 'binarySearchImpl'\n```\n---\n\n### /src/test/java/com/in28minutes/spring/basics/springin5steps/SpringIn5StepsApplicationTests.java\n\n```java\npackage com.in28minutes.spring.basics.springin5steps;\n\nimport org.junit.jupiter.api.Test;\nimport org.junit.jupiter.api.extension.ExtendWith;\nimport org.springframework.boot.test.context.SpringBootTest;\nimport org.springframework.test.context.junit.jupiter.SpringExtension;\n\n@ExtendWith(SpringExtension.class)\n@SpringBootTest\npublic class SpringIn5StepsApplicationTests {\n\n\t@Test\n\tpublic void contextLoads() {\n\t}\n\n}\n```\n---"
  },
  {
    "path": "_blog/articles/2017-10-14-spring-interview-questions.md",
    "content": "---\nlayout:     post\ntitle:      Spring Interview Questions and Answers - Course\ndate:       2025-10-06 12:31:19\nsummary:    It is difficult to prepare for the spring interview. There are several spring modules and spring projects that you must examine and be prepared to answer questions on. You would need to get a solid understanding of the new Spring features as well as the principles you used in your projects. This course provides code examples that cover 200+ Spring Interview Questions and Answers on Spring, Spring Boot, Spring MVC, Spring JDBC, JPA, AOP, RESTful Services, and SOAP Web Services. \ncategories: SpringBoot\npermalink:  /spring-and-spring-boot-interview-guide\nimage: /images/spring-framework-category.png\n\n---\n\nThe Spring Framework is the most widely used Java framework, continuously evolving to keep up with modern architectures. Among its many projects, Spring Boot stands out as the most popular framework for building RESTful applications and microservices.\n\nPreparing for Spring and Spring Boot interviews can be challenging due to the vast number of Spring modules and projects you need to know. A strong understanding of both the latest Spring features and the core principles applied in real-world projects is essential.\n\nThis course provides hands-on code examples covering 200+ Spring interview questions and answers, including topics on Spring Core, Spring Boot, Spring MVC, Spring JDBC, JPA, AOP, RESTful Services, and SOAP Web Services. It’s designed to help you build confidence and master the key concepts required for interviews.\n\n\n\n## GitHub Repository\n> https://github.com/in28minutes/spring-interview-guide\n\n## Presentation\n- https://github.com/in28minutes/spring-interview-guide/raw/master/spring-interview-questions.pdf\n\n## What Will I Learn?\n\n- Learn to answer **200+ interview questions** on **Spring, Spring Boot, and Spring MVC**.\n- Understand questions on the basics of **JPA, Spring Data, Spring Data JPA, and Spring AOP**.\n- Learn to answer questions on **RESTful Web Services** and **SOAP Web Services** using Spring and Spring Boot.\n- Master the basics of the Spring Framework, including **IOC, Application Context, Dependency Injection, Bean Scope, and Component Scanning**.\n- Get familiar with essential **Spring annotations**: `@Component`, `@Service`, `@Repository`, `@Controller`, `@Autowired`, `@Primary`, `@Qualifier`, and `@PostConstruct`.\n- Understand the core features of **Spring Boot**: **Starters, Auto-Configuration, Actuator, and Externalized Configuration**.\n- Learn the **best practices** for using Spring and Spring Boot effectively.\n- Explore approaches for **handling validation errors** in Spring MVC and Spring REST.\n- Learn **RESTful service strategies** for versioning and content negotiation.\n- Understand **best practices for documenting RESTful services** using **Swagger**.\n\nA list of questions discussed for each topic is listed below.\n\n## Spring\n\n- What is **Loose Coupling**?\n- What is a **Dependency**?\n- What is **IOC (Inversion of Control)**?\n- What is **Dependency Injection**?\n- Can you give a few examples of **Dependency Injection**?\n- What is **Auto Wiring**?\n- What are the important roles of an **IOC container**?\n- What are **BeanFactory** and **ApplicationContext**?\n- Can you compare **BeanFactory** with **ApplicationContext**?\n- How do you create an **ApplicationContext** with Spring?\n- How does Spring know where to search for components or beans?\n- What is a **Component Scan**?\n- How do you define a component scan in **XML** and **Java configurations**?\n- How is it done with **Spring Boot**?\n- What does `@Component` signify?\n- What does `@Autowired` signify?\n- What’s the difference between `@Controller`, `@Component`, `@Repository`, and `@Service` annotations in Spring?\n- What is the **default scope** of a bean?\n- Are Spring beans **thread-safe**?\n- What other scopes are available?\n- How is Spring’s **singleton bean** different from the **Gang of Four (GoF) Singleton Pattern**?\n- What are the different types of **Dependency Injection**?\n- What is **Setter Injection**?\n- What is **Constructor Injection**?\n- How do you choose between setter and constructor injections?\n- What are the different options available to create **ApplicationContexts** for Spring?\n- What is the difference between **XML** and **Java Configurations** for Spring?\n- How do you choose between XML and Java Configurations?\n- How does Spring do **autowiring**?\n- What are the different kinds of matching used by Spring for autowiring?\n- How do you debug problems with the Spring Framework?\n- How do you solve **NoUniqueBeanDefinitionException**?\n- How do you solve **NoSuchBeanDefinitionException**?\n- What is `@Primary`?\n- What is `@Qualifier`?\n- What is **CDI (Contexts and Dependency Injection)**?\n- Does Spring support CDI?\n- Would you recommend using CDI or Spring annotations?\n- What are the major features in different versions of Spring?\n- What are the new features in **Spring Framework 4.0**?\n- What are the new features in **Spring Framework 5.0**?\n- What are the important **Spring Modules**?\n- What are the important **Spring Projects**?\n- What is the simplest way to ensure a single version of all Spring-related dependencies?\n- Name some of the **design patterns** used in the Spring Framework.\n- What do you think about the Spring Framework?\n- Why is Spring popular?\n- Can you give a **big picture** overview of the Spring Framework?\n\n## Spring MVC\n\n- What is **Model 1 architecture**?\n- What is **Model 2 architecture**?\n- What is **Model 2 Front Controller architecture**?\n- Can you show an example **controller method** in Spring MVC?\n- Can you explain a simple **request flow** in Spring MVC?\n- What is a **ViewResolver**?\n- What is **Model**?\n- What is **ModelAndView**?\n- What is **RequestMapping**?\n- What is **DispatcherServlet**?\n- How do you set up **DispatcherServlet**?\n- What is a **form-backing object**?\n- How is **validation** done using Spring MVC?\n- What is **BindingResult**?\n- How do you map **validation results** to your view?\n- What are **Spring Form Tags**?\n- What is a **Path Variable**?\n- What is a **Model Attribute**?\n- What is a **Session Attribute**?\n- What is an **initBinder**?\n- How do you set the **default date format** with Spring?\n- Why is Spring MVC so popular?\n\n## Spring Boot\n\n- What is **Spring Boot**?\n- What are the important **goals** of Spring Boot?\n- What are the important **features** of Spring Boot?\n- Compare **Spring Boot** vs **Spring**.\n- Compare **Spring Boot** vs **Spring MVC**.\n- What is the importance of `@SpringBootApplication`?\n- What is **Auto Configuration**?\n- How can we find more information about Auto Configuration?\n- What is an **embedded server**? Why is it important?\n- What is the default embedded server in Spring Boot?\n- What are other embedded servers supported by Spring Boot?\n- What are **Starter Projects**?\n- Can you give examples of important starter projects?\n- What is **Starter Parent**?\n- What are the different things defined in Starter Parent?\n- How does Spring Boot enforce **common dependency management** for all its starter projects?\n- What is **Spring Initializr**?\n- What is **application.properties**?\n- What are some important things that can be customized in **application.properties**?\n- How do you **externalize configuration** using Spring Boot?\n- How can you add **custom application properties** using Spring Boot?\n- What is `@ConfigurationProperties`?\n- What is a **profile**?\n- How do you define beans for a specific profile?\n- How do you create an application configuration for a specific profile?\n- How do you have different configurations for different environments?\n- What is **Spring Boot Actuator**?\n- How do you monitor web services using Spring Boot Actuator?\n- How do you find more information about your application environment using Spring Boot?\n- What is a **CommandLineRunner**?\n\n## Database Connectivity – JDBC, Spring JDBC & JPA\n\n- What is **Spring JDBC**? How is it different from JDBC?\n- What is a **JdbcTemplate**?\n- What is a **RowMapper**?\n- What is **JPA**?\n- What is **Hibernate**?\n- How do you define an **entity** in JPA?\n- What is an **EntityManager**?\n- What is a **Persistence Context**?\n- How do you map relationships in JPA?\n- What are the different types of relationships in JPA?\n- How do you define **One-to-One Mapping** in JPA?\n- How do you define **One-to-Many Mapping** in JPA?\n- How do you define **Many-to-Many Mapping** in JPA?\n- How do you define a **datasource** in a Spring context?\n- What is the use of **persistence.xml**?\n- How do you configure **EntityManagerFactory** and **TransactionManager**?\n- How do you define **transaction management** for Spring–Hibernate integration?\n\n## Spring Data\n\n- What is **Spring Data**?\n- What is the need for Spring Data?\n- What is **Spring Data JPA**?\n- What is a **CrudRepository**?\n- What is a **PagingAndSortingRepository**?\n\n## Unit Testing\n\n- How does the Spring Framework make **unit testing** easy?\n- What is **Mockito**?\n- What is your favorite **mocking framework**?\n- How do you create **mock data** with Mockito?\n- What are the different mocking annotations you have worked with?\n- What is **MockMvc**?\n- What is `@WebMvcTest`?\n- What is `@MockBean`?\n- How do you write a **unit test** with MockMvc?\n- What is **JSONAssert**?\n- How do you write an **integration test** with Spring Boot?\n- What is `@SpringBootTest`?\n- What is `@LocalServerPort`?\n- What is **TestRestTemplate**?\n\n## AOP\n\n- What are **cross-cutting concerns**?\n- How do you implement cross-cutting concerns in a web application?\n- If you want to log every request to a web application, what are your options?\n- If you want to track the performance of every request, what options do you have?\n- What is an **Aspect** and a **Pointcut** in AOP?\n- What are the different types of **AOP advices**?\n- What is **weaving**?\n- Compare **Spring AOP** vs **AspectJ**.\n\n## SOAP Web Services\n\n- What is a **Web Service**?\n- What is a **SOAP Web Service**?\n- What is **SOAP**?\n- What is a **SOAP Envelope**?\n- What are **SOAP Header** and **SOAP Body**?\n- Can you give an example of **SOAP Request** and **SOAP Response**?\n- What kind of information is sent in a **SOAP Header**?\n- Can you give an example of a SOAP Header with **authentication information**?\n- What is **WSDL (Web Service Definition Language)**?\n- What are the different parts of a WSDL?\n- What is **Contract-First Approach**?\n- What is an **XSD**?\n- Can you give an example of an XSD?\n- What is **JAXB**?\n- How do you configure a **JAXB Plugin**?\n- What is an **Endpoint**?\n- Can you show an example endpoint written with Spring Web Services?\n- What is a **MessageDispatcherServlet**?\n- How do you configure a MessageDispatcherServlet?\n- How do you generate a WSDL using Spring Web Services?\n- How do you implement **error handling** for SOAP Web Services?\n- What is a **SOAP Fault**?\n\n## RESTful Web Services\n\n- What is **REST**?\n- What are the key concepts in designing RESTful APIs?\n- What are the best practices for RESTful services?\n- Can you show code for an example **GET Resource** method with Spring REST?\n- What happens when we return a bean from a **RequestMapping** method?\n- What is **GetMapping** and what are related methods in Spring MVC?\n- Can you show code for an example **POST Resource** method with Spring REST?\n- What is the appropriate **HTTP Response Status** for successful resource creation?\n- Why do we use **ResponseEntity** in a RESTful service?\n- What is **HATEOAS**? Can you give an example response?\n- How do we implement HATEOAS using Spring?\n- How do you document RESTful web services?\n- What is **Swagger Documentation**?\n- How do you automate the generation of Swagger documentation from RESTful web services?\n- How do you add **custom information** to Swagger documentation?\n- What is **Swagger-UI**?\n- What is the \"representation\" of a resource?\n- What is **Content Negotiation**? Which HTTP header is used?\n- How do we implement content negotiation using Spring Boot?\n- How do you add **XML support** to your RESTful services in Spring Boot?\n- How do you implement **exception handling** for RESTful web services?\n- What are best practices for handling exceptions in RESTful web services?\n- What are the different **error statuses** to return in RESTful web services?\n- How would you implement them using Spring Boot?\n- What HTTP response status should you return for **validation errors**?\n- How do you handle validation errors in RESTful web services?\n- Why do we need **versioning** for RESTful web services?\n- What versioning options are available?\n- How do you implement versioning for RESTful web services?\n\n\n## Java and Spring Interview Guides\n\n[![Image](/images/Course-Spring-Framework-Interview-Guide-200-Questions-Answers.png \"Spring Framework Interview Guide - 200+ Questions & Answers\")](https://links.in28minutes.com/MISC-SPRING-INTERVIEW)\n\n\n"
  },
  {
    "path": "_blog/articles/2017-10-15-spring-master-class.md",
    "content": "---\nlayout:     post\ntitle:      Spring Framework Tutorial For Beginners - 100 Steps\ndate:       2025-10-06 12:31:19\nsummary:    Discover the secrets of the Spring Framework. From the worlds of IOC (Inversion of Control), DI (Dependency Injection), and Application Context to Spring Boot, AOP, JDBC, and JPA. Prepare for an amazing adventure.\ncategories: SpringFramework\npermalink:  /spring-master-class\nimage: /images/spring-framework-category.png\n\n---\n\nDiscover the Secrets of the Spring Framework!\n\nDive into the worlds of IOC (Inversion of Control), DI (Dependency Injection), and Application Context, and explore Spring Boot, AOP, JDBC, and JPA. Prepare yourself for an exciting journey through one of the most powerful and widely used Java frameworks.\n\nEven after more than a decade, the Spring Framework remains as popular today as it was 12 years ago when I first started using it.\n\n> How is this feasible in a very dynamic environment where designs have altered dramatically?\n\n## Course Link\n\n[![Image](/images/Course-Spring-Framework-Master-Class---Beginner-to-Expert.png \"Spring Master Class - Beginner to Expert\")](https://links.in28minutes.com/MISC-SPRING){:target=\"_blank\"}\n\n\n## What You Will Learn\n\n- **Spring Framework fundamentals**, including **Dependency Injection**, **IOC Container**, **Application Context**, and **BeanFactory**.\n- How to use essential **Spring annotations** such as `@Autowired`, `@Component`, `@Service`, `@Repository`, `@Configuration`, and `@Primary`.\n- A thorough understanding of **Spring MVC**, including **DispatcherServlet**, **Model**, **Controllers**, and **ViewResolver**.\n- How to work with **Spring Boot Starters**, including **Spring Boot Starter Web**, **Starter Data JPA**, and **Starter Test**.\n- Fundamentals of **Spring Boot**, **Spring AOP**, **Spring JDBC**, and **JPA**.\n- Basics of development tools such as **Eclipse**, **Maven**, **JUnit**, and **Mockito**.\n- Step-by-step guidance to create a simple **web application** using **JSP, Servlets, and Spring MVC**.\n- How to construct **unit tests** using **XML**, **Java Application Contexts**, and **Mockito**.\n\n\n## Getting Started\n\n### Installing Tools\n\n- **Installation Resources**\n    - **Video:** [Installation Guide Video](https://www.youtube.com/playlist?list=PLBBog2r6uMCSmMVTW_QmDLyASBvovyAO3)\n    - **PDF:** [Installation Guide PDF](https://github.com/in28minutes/SpringIn28Minutes/blob/master/InstallationGuide-JavaEclipseAndMaven_v2.pdf)\n    - **More Details:** [Getting Started in 5 Steps](https://github.com/in28minutes/getting-started-in-5-steps)\n\n- **Troubleshooting**\n    - [50-page Troubleshooting Guide with 200+ Errors and Questions Answered](https://github.com/in28minutes/in28minutes-initiatives/blob/master/The-in28Minutes-TroubleshootingGuide-And-FAQ)\n\n### Running Examples\n\n1. Clone the Git repository or download the ZIP file.\n2. Unzip the archive (if you downloaded a ZIP).\n3. Open **Command Prompt** and navigate to the folder containing `pom.xml`.\n4. Open **Eclipse**:\n    - Go to **File → Import → Existing Maven Project**\n    - Navigate to the folder where you unzipped the project\n    - Select the correct project and finish the import\n5. Locate the **Spring Boot Application file** annotated with `@SpringBootApplication`.\n6. Right-click the file and select **Run as Java Program**.\n7. You are all set!\n\n- For further help, refer to the [Installation Guide Video](https://www.youtube.com/playlist?list=PLBBog2r6uMCSmMVTW_QmDLyASBvovyAO3).\n\n\n## Spring Level 1 through Level 6 Section Overview\n\n| Title | Category | GitHub |\n|------------------------|:------------------:|:--------------:|\n| Spring Framework in 10 Steps | Spring - Level 1 | [Project Folder on GitHub](https://github.com/in28minutes/spring-master-class/tree/master/01-spring-in-depth) |\n| Spring in Depth | Spring - Level 2 | [Project Folder on GitHub](https://github.com/in28minutes/spring-master-class/tree/master/01-spring-in-depth) |\n| Unit Testing with Spring Framework | Spring - Level 3 | [Project Folder on GitHub](https://github.com/in28minutes/spring-master-class/tree/master/01-spring-in-depth) |\n| Spring Boot in 10 Steps | Spring - Level 4 | [Project Folder on GitHub](https://github.com/in28minutes/spring-master-class/tree/master/00-framework-tool-introductions/05.Spring-Boot-Introduction-In-10-Steps) |\n| Spring AOP | Spring - Level 5 | [Project Folder on GitHub](https://github.com/in28minutes/spring-master-class/tree/master/03-spring-aop) |\n| Spring JDBC and JPA | Spring - Level 6 | [Project Folder on GitHub](https://github.com/in28minutes/spring-master-class/tree/master/04-spring-jdbc-to-jpa) |\n\n## 5 Bonus Sections - Introduction to Tools and Frameworks\n\n| Title | Category | GitHub |\n|------------------------|:------------------:|:--------------:|\n| Eclipse in 5 Steps | Introduction | [Project Folder on GitHub](https://github.com/in28minutes/spring-master-class/tree/master/00-framework-tool-introductions/01.Eclipse-Introduction-in-5-steps) |\n| Maven in 5 Steps | Introduction | [Project Folder on GitHub](https://github.com/in28minutes/spring-master-class/tree/master/00-framework-tool-introductions/02.Maven-Introduction-In-5-Steps) |\n| JUnit in 5 Steps | Introduction | [Project Folder on GitHub](https://github.com/in28minutes/spring-master-class/tree/master/00-framework-tool-introductions/03.JUnit-Introduction-In-5-Steps) |\n| Mockito in 5 Steps | Introduction | [Project Folder on GitHub](https://github.com/in28minutes/spring-master-class/tree/master/00-framework-tool-introductions/04.Mockito-Introduction-In-5-Steps) |\n| Basic Web Application with Spring MVC | Introduction | [Project Folder on GitHub]() |\n\n## Section Details\n\n### Spring Level 1 - First 10 Steps in Spring\n\n| Title | Category | GitHub |\n|------------------------|:------------------:|:--------------:|\n| Spring Framework in 10 Steps | Spring - Level 1 | [Project Folder on GitHub](https://github.com/in28minutes/spring-master-class/tree/master/01-spring-in-depth) |\n\n**Steps Covered:**\n\n1. Setting up a Spring Project using [start.spring.io](http://start.spring.io)\n2. Understanding Tight Coupling using the Binary Search Algorithm example\n3. Making the Binary Search Algorithm example **loosely coupled**\n4. Using Spring to manage dependencies - `@Component`, `@Autowired`\n5. Understanding what happens **in the background**\n6. Dynamic autowiring and troubleshooting - `@Primary`\n7. Constructor and Setter Injection\n8. Overview of Spring Modules\n9. Overview of Spring Projects\n10. Why is Spring popular?\n\n#### Step 1: Setting up a Spring Project using [start.spring.io](http://start.spring.io)\n\n**Dependency Injection (DI)** is a crucial element of the Spring Framework. Spring helps in developing **loosely coupled applications**, which makes your code easier to maintain and test.\n\nTo understand dependency injection, you first need to grasp the concept of **tight coupling** and how to build **loosely coupled programs**. We'll start with a simple example to illustrate tight coupling and the benefits of DI.\n\nCreating a Spring project using **Spring Initializr** is straightforward and quick.\n\n> **Spring Initializr** ([http://start.spring.io/](http://start.spring.io/)) is a powerful tool to **bootstrap your Spring Boot projects** with the required dependencies and project structure.\n\n\n![Image](/images/spring-initializr-spring-in-10-steps.png \"Spring Initializr\")   \n\nAs shown in the image above, follow these steps to set up your Spring project:\n\n1. **Launch Spring Initializr** and configure the project:\n    - **Group:** `com.in28minutes.spring.basics`\n    - **Artifact:** `spring-in-5-steps`\n    - **Dependencies:** Do not select any dependencies\n        - By default, the **Basic Starter** is included, which contains the core Spring Framework and the Spring Test starter.\n\n2. **Click \"Generate Project\"** to download the project archive.\n\n3. **Import the project into Eclipse or IntelliJ IDE**:\n    - Go to **File → Import → Existing Maven Project**\n    - Navigate to the folder where you downloaded/extracted the project\n    - Select the project and finish the import.\n\n4. **Optional:** If you want to understand all the files included in the project, refer to the detailed guide [here](#).\n\n\n#### Step 2: Understanding Tight Coupling using the Binary Search Algorithm Example\n\nTo illustrate **tight coupling**, we will create an example using the **Binary Search** and **Bubble Sort** algorithms.\n\nIn a tightly coupled design, the **Binary Search class directly depends on a specific implementation of the Bubble Sort algorithm**, making it difficult to change or test the sorting logic independently.\n\n> This example will help you understand why tight coupling is undesirable and how **Dependency Injection** in Spring can help decouple components.\n\n\n![Image](/images/SpringIn10Steps-BinarySearchTightlyCoupleWithBubbleSort.png \"Spring In 10 Steps - Tight Coupling\") \n\nUnfortunately, the above implementation has a limitation: **if we want to use Binary Search with a different sorting algorithm, we would need to update the code**.\n\nOur goal is to **loosely couple** the Binary Search algorithm so that it can work with **any sorting algorithm** without modifying the Binary Search class itself.\n\n\n> Consider the solution before advancing to next stage!\n\n#### Step 3: Making the Binary Search Algorithm Example Loosely Coupled\n\nTo **loosen the coupling** between the Binary Search and the sorting algorithm, we introduce an **interface** for the sorting behavior.\n\nBy programming to an interface instead of a concrete class, the **Binary Search class can now work with any sorting algorithm** that implements this interface.\n\n> This is the foundation of **Dependency Injection** in Spring, allowing components to be easily replaced or tested independently.\n\n\n```java\npackage com.in28minutes.spring.basics.springin5steps;\n\npublic interface SortAlgorithm {\n\tint[] sort(int[] numbers);\n}\n```\n\n```java\npublic class BinarySearchImpl {\n\n    private SortAlgorithm sortAlgorithm;\n}\n```\n\n#### Step 4 : Using Spring to Manage Dependencies - @Component, @Autowired\n\n> We developed code to construct objects for the bubble sort algorithm and binary search in the previous phases. We also took care of the dependencies. It would be wonderful indeed if some framework can take charge of generation of the beans and autowiring the dependencies.\n\nThis is where Spring Framework comes into play!\n\nLet's get started with autowiring using Spring.\n\nNotes\n- Sort algorithm is a dependency of the binary search.\n\n\n```java\n@Component\npublic class BinarySearchImpl {\n\n    @Autowired\n    private SortAlgorithm sortAlgorithm;\n}\n```\n\n```java\n@Component\npublic class BubbleSortAlgorithm implements SortAlgorithm {\n\tpublic int[] sort(int[] numbers) {\n\t\t// Logic for Bubble Sort\n\t\treturn numbers;\n\t}\n}\n```\n\n#### Step 5: What is Happening in the Background?\n\nYou can activate **debug logging** to understand what Spring is doing behind the scenes.\n\n**Add the following to your** `/src/main/resources/application.properties`:\n\n```properties\nlogging.level.org.springframework=debug\n```\n\n- Spring performs a **component scan** on the parent package `com.in28minutes.spring.basics.springin5steps` to locate all **components** — classes annotated with `@Component`.\n- It identifies all **components and their dependencies**.\n- It detects that `BinarySearchImpl` has a dependency on `SortAlgorithm`.\n- Since `SortAlgorithm` has no further dependencies, Spring **creates an instance of it** and **autowires it into `BinarySearchImpl`** automatically.\n\n\n#### Step 6 : Dynamic auto wiring and Troubleshooting - @Primary\n\nWhat if we add one more SortAlgorithm?\n\n```java\npackage com.in28minutes.spring.basics.springin5steps;\n\nimport org.springframework.stereotype.Component;\n\n@Component\npublic class QuickSortAlgorithm implements SortAlgorithm {\n\tpublic int[] sort(int[] numbers) {\n\t\t// Logic for Quick Sort\n\t\treturn numbers;\n\t}\n}\n```\n\nThere are now two SortAlgorithm implementations available. Spring throws an exception because it doesn’t know which one to use.\n\nWe can use the @Primary annotation to tell Spring which SortAlgorithm implementation should be preferred when multiple options exist.\n\n```java\npackage com.in28minutes.spring.basics.springin5steps;\n\nimport org.springframework.context.annotation.Primary;\nimport org.springframework.stereotype.Component;\n\n@Component\n@Primary\npublic class BubbleSortAlgorithm implements SortAlgorithm {\n\tpublic int[] sort(int[] numbers) {\n\t\t// Logic for Bubble Sort\n\t\treturn numbers;\n\t}\n}\n```\n#### Step 7 : Constructor and Setter Injection\n\nConstructor Injection\n![Image](/images/SpringIn10Steps-ConstructorInjection.png \"Spring In 10 Step - Constructor Injection \") \n\nSetter Injection\n![Image](/images/SpringIn10Steps-SetterInjection.png \"Spring In 10 Step - Setter Injection\") \n \n#### Step 8 : Spring Modules\n\nSpring’s modular design lets us use only the modules we need, without depending on the rest.\n\n![Image](/images/SpringIn10Steps-SpringModules.png \"Spring In 10 Steps - Spring Modules\") \n\n#### Step 9 : Spring Projects\n\nThe Spring projects offer comprehensive solutions to common problems encountered in enterprise application development.\n\n![Image](/images/SpringIn10Steps-SpringProjects.png \"Spring In 10 Steps - Spring Projects\")\n\nWe’re looking at just seven Spring projects — that’s only the tip of the iceberg! There are many others like Spring Web Services, Spring Session, Spring Social, Spring Mobile, and Spring Android, each solving different kinds of problems.\n\n> Spring has evolved beyond the core framework and now encompasses a wide range of projects addressing different aspects of application development.\n\n#### Step 10 : Why is Spring Popular?\n![Image](/images/SpringIn10Steps-SpringPopularity.png \"Spring In 10 Steps - Spring Popularity\") \nSpring is one of the very few frameworks that remains as popular today as it was 15 years back. \n\n### Spring Level 2 - Spring in Depth\n\n| **Title** | **Category** | **GitHub** |\n|------------|:-------------:|------------|\n| Spring in Depth | Spring - Level 2 | [Project Folder on GitHub](https://github.com/in28minutes/spring-master-class/tree/master/01-spring-in-depth) |\n\n#### Topics Covered\n- **Step 11** – Dependency Injection: More Examples\n- **Step 12** – Autowiring in Depth: *by Name* and `@Primary`\n- **Step 13** – Autowiring in Depth: Using `@Qualifier` Annotation\n- **Step 14** – Scope of a Bean: *Prototype* and *Singleton*\n- **Step 15** – Complex Scenarios with Bean Scopes: Mixing *Prototype* and *Singleton*\n- **Step 15B** – Difference Between Spring Singleton and GoF Singleton\n- **Step 16** – Using Component Scan to Detect and Register Beans\n- **Step 17** – Lifecycle of a Bean: `@PostConstruct` and `@PreDestroy`\n- **Step 18** – Container and Dependency Injection (CDI): `@Named`, `@Inject`\n- **Step 19** – Removing Spring Boot from a Basic Application\n- **Step 20** – Fixing Minor Issues: Add Logback and Close Application Context\n- **Step 21** – Defining Spring Application Context Using XML – Part 1\n- **Step 22** – Defining Spring Application Context Using XML – Part 2\n- **Step 23** – Mixing XML Configuration with Component Scan for Annotation-Based Beans\n- **Step 24** – IoC Container vs ApplicationContext vs BeanFactory\n- **Step 25** – `@Component` vs `@Service` vs `@Repository` vs `@Controller`\n- **Step 26** – Reading Values from an External Properties File\n\n\n#### Step 11 - Dependency Injection - A few more examples\n#### Step 12 - Autowiring in Depth - by Name and @Primary\n#### Step 13 - Autowiring in Depth - @Qualifier annotation\n\n```java\n@Component\n@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)\npublic class BinarySearchImpl {\n\n\t@Autowired\n\t@Qualifier(\"bubble\")\n\tprivate SortAlgorithm sortAlgorithm;\n```\n\n```java\n@Component\n@Qualifier(\"bubble\")\npublic class BubbleSortAlgorithm implements SortAlgorithm {\n```\n\n```java\n@Component\n@Qualifier(\"quick\")\npublic class QuickSortAlgorithm implements SortAlgorithm {\n```\n\n#### Step 14 - Scope of a Bean - Prototype and Singleton\n\n#### Step 15 - Complex scenarios with Scope of a Spring Bean - Mix of Prototype and Singleton\n\n```java\npackage com.in28minutes.spring.basics.springin5steps.scope;\n\nimport org.springframework.beans.factory.config.ConfigurableBeanFactory;\nimport org.springframework.context.annotation.Scope;\nimport org.springframework.context.annotation.ScopedProxyMode;\nimport org.springframework.stereotype.Component;\n\n@Component\n@Scope(value=ConfigurableBeanFactory.SCOPE_PROTOTYPE, \n\t\tproxyMode = ScopedProxyMode.TARGET_CLASS)\npublic class JdbcConnection {\n\tpublic JdbcConnection() {\n\t\tSystem.out.println(\"JDBC Connection\");\n\t}\n}\n```\n\n```java\npackage com.in28minutes.spring.basics.springin5steps.scope;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Component;\n\n@Component\npublic class PersonDAO {\n\n\t@Autowired\n\tJdbcConnection jdbcConnection;\n\n\tpublic JdbcConnection getJdbcConnection() {\n\t\treturn jdbcConnection;\n\t}\n\n\tpublic void setJdbcConnection(JdbcConnection jdbcConnection) {\n\t\tthis.jdbcConnection = jdbcConnection;\n\t}\n}\n```\n\n```java\npackage com.in28minutes.spring.basics.springin5steps;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.context.ApplicationContext;\n\nimport com.in28minutes.spring.basics.springin5steps.scope.PersonDAO;\n\n@SpringBootApplication\npublic class SpringIn5StepsScopeApplication {\n\t\n\tprivate static final Logger LOGGER = LoggerFactory.getLogger(SpringIn5StepsScopeApplication.class); \n\t\n\tpublic static void main(String[] args) {\n\n\t\tvar applicationContext = \n\t\t\t\tSpringApplication.run(SpringIn5StepsScopeApplication.class, args);\n\t\t\n\t\tvar personDao = \n\t\t\t\tapplicationContext.getBean(PersonDAO.class);\n\t\t\n\t\tvar personDao2 = \n\t\t\t\tapplicationContext.getBean(PersonDAO.class);\n\t\t\n\t\tLOGGER.info(\"{}\", personDao);\n\t\tLOGGER.info(\"{}\", personDao.getJdbcConnection());\n\t\t\n\t\tLOGGER.info(\"{}\", personDao2);\n\t\tLOGGER.info(\"{}\", personDao.getJdbcConnection());\n\t\t\n\t}\n}\n```\n\n#### Step 15B -  Difference Between Spring Singleton and GOF Singleton\n\n#### Step 16 - Using Component Scan to scan for beans\n\n```java\npackage com.in28minutes.spring.basics.componentscan;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Component;\n\n@Component\npublic class ComponentDAO {\n\n\t@Autowired\n\tComponentJdbcConnection jdbcConnection;\n\n\tpublic ComponentJdbcConnection getJdbcConnection() {\n\t\treturn jdbcConnection;\n\t}\n\n\tpublic void setComponentJdbcConnection(ComponentJdbcConnection jdbcConnection) {\n\t\tthis.jdbcConnection = jdbcConnection;\n\t}\n}\n```\n\n```java\npackage com.in28minutes.spring.basics.componentscan;\n\nimport org.springframework.beans.factory.config.ConfigurableBeanFactory;\nimport org.springframework.context.annotation.Scope;\nimport org.springframework.context.annotation.ScopedProxyMode;\nimport org.springframework.stereotype.Component;\n\n@Component\n@Scope(value=ConfigurableBeanFactory.SCOPE_PROTOTYPE, \n\t\tproxyMode = ScopedProxyMode.TARGET_CLASS)\npublic class ComponentJdbcConnection {\n\tpublic ComponentJdbcConnection() {\n\t\tSystem.out.println(\"JDBC Connection\");\n\t}\n}\n```\n\n```java\npackage com.in28minutes.spring.basics.springin5steps;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.annotation.ComponentScan;\n\nimport com.in28minutes.spring.basics.componentscan.ComponentDAO;\n\n@SpringBootApplication\n@ComponentScan(\"com.in28minutes.spring.basics.componentscan\")\npublic class SpringIn5StepsComponentScanApplication {\n\t\n\tprivate static Logger LOGGER = \n\t\t\tLoggerFactory.getLogger(SpringIn5StepsComponentScanApplication.class); \n\t\n\tpublic static void main(String[] args) {\n\n\t\tvar applicationContext = SpringApplication.run(SpringIn5StepsComponentScanApplication.class, args);\n\t\t\n\t\tvar componentDAO = applicationContext.getBean(ComponentDAO.class);\n\t\t\n\t\tLOGGER.info(\"{}\", componentDAO);\n\t\t\n\t}\n}\n```\n\n#### Step 17 - Lifecycle of a Bean - @PostConstruct and @PreDestroy\n\nBinarySearchImpl.java\n```\n\t@PostConstruct\n\tpublic void postConstruct() {\n\t\tlogger.info(\"postConstruct\");\n\t}\n\n\t@PreDestroy\n\tpublic void preDestroy() {\n\t\tlogger.info(\"preDestroy\");\n\t}\n\n```\n#### Step 18 - Container and Dependency Injection (CDI) - @Named, @Inject\n\n/pom.xml\n```\n<dependency>\n    <groupId>jakarta.inject</groupId>\n    <artifactId>jakarta.inject-api</artifactId>\n    <version>2.0.1</version>\n</dependency>\n\n```\n\n```java\npackage com.in28minutes.spring.basics.springin5steps;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.context.ApplicationContext;\n\nimport com.in28minutes.spring.basics.springin5steps.cdi.SomeCdiBusiness;\n\n@SpringBootApplication\npublic class SpringIn5StepsCdiApplication {\n\t\n\tprivate static Logger LOGGER = \n\t\t\tLoggerFactory.getLogger(SpringIn5StepsCdiApplication.class); \n\t\n\tpublic static void main(String[] args) {\n\n\t\tvar applicationContext = \n\t\t\t\tSpringApplication.run(SpringIn5StepsCdiApplication.class, args);\n\t\t\n\t\tvar business = \n\t\t\t\tapplicationContext.getBean(SomeCdiBusiness.class);\n\t\t\n\t\tLOGGER.info(\"{} dao-{}\", business, business.getSomeCDIDAO());\n\t}\n}\n```\n\n```java\npackage com.in28minutes.spring.basics.springin5steps.cdi;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\n\n@Named\npublic class SomeCdiBusiness {\n\t\n\t@Inject\n\tSomeCdiDao someCdiDao;\n\n\tpublic SomeCdiDao getSomeCDIDAO() {\n\t\treturn someCdiDao;\n\t}\n\n\tpublic void setSomeCDIDAO(SomeCdiDao someCdiDao) {\n\t\tthis.someCdiDao = someCdiDao;\n\t}\n}\n```\n\n```java\npackage com.in28minutes.spring.basics.springin5steps.cdi;\n\nimport jakarta.inject.Named;\n\n@Named\npublic class SomeCdiDao {\n\n}\n```\n\n#### Step 19 - Removing Spring Boot in Basic Application\n\npom.xml\n```xml\n<dependency>\n\t<groupId>org.springframework</groupId>\n\t<artifactId>spring-core</artifactId>\n</dependency>\n<dependency>\n\t<groupId>org.springframework</groupId>\n\t<artifactId>spring-context</artifactId>\n</dependency>\n<dependency>\n\t<groupId>org.slf4j</groupId>\n\t<artifactId>slf4j-api</artifactId>\n</dependency>\n<dependency>\n\t<groupId>ch.qos.logback</groupId>\n\t<artifactId>logback-classic</artifactId>\n</dependency>\n\n```\n\n```java\npackage com.in28minutes.spring.basics.springin5steps;\n\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.annotation.AnnotationConfigApplicationContext;\nimport org.springframework.context.annotation.ComponentScan;\nimport org.springframework.context.annotation.Configuration;\n\nimport com.in28minutes.spring.basics.springin5steps.basic.BinarySearchImpl;\n\n@Configuration\n@ComponentScan\npublic class SpringIn5StepsBasicApplication {\n\n\tpublic static void main(String[] args) {\n\n\t\tvar applicationContext =\n\t\t\t\tnew AnnotationConfigApplicationContext(SpringIn5StepsBasicApplication.class);\n\n```\n\n#### Step 20 - Fixing minor stuff - Add Logback and Close Application Context\n\n```\n<dependency>\n\t<groupId>ch.qos.logback</groupId>\n\t<artifactId>logback-classic</artifactId>\n</dependency>\n```\n\n```java\n@Configuration\n@ComponentScan\npublic class SpringIn5StepsBasicApplication {\n\n\tpublic static void main(String[] args) {\n\n\t\ttry (var applicationContext = \n\t\t\t\tnew AnnotationConfigApplicationContext(\n\t\t\t\tSpringIn5StepsBasicApplication.class)) {\n\t\t\t//No change in code\n\t\t}\n\t}\n}\n```\nSame changes in \n- SpringIn5StepsCdiApplication\n- SpringIn5StepsComponentScanApplication\n- SpringIn5StepsScopeApplication\n\n#### Step 21 - Defining Spring Application Context using XML - Part 1\n#### Step 22 - Defining Spring Application Context using XML - Part 2\n```java\npackage com.in28minutes.spring.basics.springin5steps;\n\nimport org.springframework.context.annotation.ComponentScan;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.context.support.ClassPathXmlApplicationContext;\n\nimport com.in28minutes.spring.basics.springin5steps.xml.XmlPersonDAO;\n\n@Configuration\n@ComponentScan\npublic class SpringIn5StepsXMLContextApplication {\n\n\tpublic static void main(String[] args) {\n\n\t\ttry (var applicationContext = new ClassPathXmlApplicationContext(\n\t\t\t\t\"applicationContext.xml\")) {\n\n\t\t\tvar personDao = applicationContext.getBean(XmlPersonDAO.class);\n\t\t\tSystem.out.println(personDao);\n\t\t\tSystem.out.println(personDao.getXmlJdbcConnection());\n\t\t}\n\t}\n}\n```\n\n```java\npackage com.in28minutes.spring.basics.springin5steps.xml;\n\npublic class XmlJdbcConnection {\n\tpublic XmlJdbcConnection() {\n\t\tSystem.out.println(\"JDBC Connection\");\n\t}\n}\n```\n\n```java\npackage com.in28minutes.spring.basics.springin5steps.xml;\n\npublic class XmlPersonDAO {\n\n\tXmlJdbcConnection xmlJdbcConnection;\n\n\tpublic XmlJdbcConnection getXmlJdbcConnection() {\n\t\treturn xmlJdbcConnection;\n\t}\n\n\tpublic void setXmlJdbcConnection(XmlJdbcConnection jdbcConnection) {\n\t\tthis.xmlJdbcConnection = jdbcConnection;\n\t}\n}\n```\n\n```xml\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<beans xmlns=\"http://www.springframework.org/schema/beans\"\n    xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n    xsi:schemaLocation=\"http://www.springframework.org/schema/beans\n        http://www.springframework.org/schema/beans/spring-beans.xsd\">\n\n    <bean id=\"xmlJdbcConnection\" \n    \tclass=\"com.in28minutes.spring.basics.springin5steps.xml.XmlJdbcConnection\">\n    </bean>\n\n    <bean id=\"xmlPersonDAO\" class=\"com.in28minutes.spring.basics.springin5steps.xml.XmlPersonDAO\">\n    \t\t<property name=\"xmlJdbcConnection\" ref=\"xmlJdbcConnection\"/>\n    </bean>\n\n</beans>\n```\n\n#### Step 23 - Mixing XML Context with Component Scan for Beans defined with Annotations\n\n```java\npublic class SpringIn5StepsXMLContextApplication {\n\n\tprivate static final Logger LOGGER = LoggerFactory.getLogger(SpringIn5StepsScopeApplication.class);\n\n\tpublic static void main(String[] args) {\n\n\t\ttry (var applicationContext = new ClassPathXmlApplicationContext(\n\t\t\t\t\"applicationContext.xml\")) {\n\n\t\t\tLOGGER.info(\"Beans Loaded -> {}\", (Object) applicationContext.getBeanDefinitionNames());\n\t\t\t// [xmlJdbcConnection, xmlPersonDAO]\n```\n\n```xml\n\t<context:component-scan base-package=\"com.in28minutes.spring.basics\"/>\n```\n\n#### Step 24 - IOC Container vs Application Context vs Bean Factory\n#### Step 25 - @Component vs @Service vs @Repository vs @Controller\n\n```java\n@Repository\npublic class ComponentDAO { }\n\n```\n\n```java\n@Service\n@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)\npublic class BinarySearchImpl { }\n```\n\n```java\n@Service\n@Qualifier(\"bubble\")\npublic class BubbleSortAlgorithm implements SortAlgorithm { }\n```\n\n```java\n@Service\n@Qualifier(\"quick\")\npublic class QuickSortAlgorithm implements SortAlgorithm { }\n```\n\n```java\n@Repository\npublic class PersonDAO { }\n```\n#### Step 26 - Read values from external properties file\n\n```java\npackage com.in28minutes.spring.basics.springin5steps;\n\nimport org.springframework.context.annotation.AnnotationConfigApplicationContext;\nimport org.springframework.context.annotation.ComponentScan;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.context.annotation.PropertySource;\n\nimport com.in28minutes.spring.basics.springin5steps.properties.SomeExternalService;\n\n@Configuration\n@ComponentScan\n// \n@PropertySource(\"classpath:app.properties\")\npublic class SpringIn5StepsPropertiesApplication {\n\n\tpublic static void main(String[] args) {\n\n\t\ttry (var applicationContext = new AnnotationConfigApplicationContext(\n\t\t\t\tSpringIn5StepsPropertiesApplication.class)) {\n\n\t\t\tvar service = applicationContext.getBean(SomeExternalService.class);\n\t\t\tSystem.out.println(service.returnServiceURL());\n\t\t}\n\t}\n}\n```\n\n```java\npackage com.in28minutes.spring.basics.springin5steps.properties;\n\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.stereotype.Component;\n\n@Component\npublic class SomeExternalService {\n\t\n\t@Value(\"${external.service.url}\")\n\tprivate String url;\n\t\n\tpublic String returnServiceURL(){\n\t\treturn url;\n\t}\n\n}\n```\n\n/src/main/resources/app.properties\n\n```properties\nexternal.service.url=http://someserver.dev.com/service\n```\n\n### Spring Level 3 - Unit Testing with Spring Framework\n\n### Spring Level 3 - Unit Testing with Spring Framework\n\n| **Title** | **Category** | **GitHub** |\n|------------|:-------------:|------------|\n| Unit Testing with Spring Framework | Spring - Level 3 | [Project Folder on GitHub](https://github.com/in28minutes/spring-master-class/tree/master/01-spring-in-depth){:target='_blank'} |\n\n#### Topics Covered\n- **Step 27** – Spring Unit Testing with Java-Based Configuration\n- **Step 28** – Spring Unit Testing with XML-Based Configuration\n- **Step 29** – Spring Unit Testing with Mockito\n\n\n#### Step 27 - Spring Unit Testing with a Java Context\n\n```xml\n<dependency>\n\t<groupId>org.springframework</groupId>\n\t<artifactId>spring-test</artifactId>\n</dependency>\n<dependency>\n\t<groupId>junit</groupId>\n\t<artifactId>junit</artifactId>\n</dependency>\n```\n\n```java\n@RunWith(SpringRunner.class)\n//@SpringBootTest\npublic class SpringIn5StepsBasicApplicationTests {\n```\n\n```java\npackage com.in28minutes.spring.basics.springin5steps.basic;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\nimport com.in28minutes.spring.basics.springin5steps.SpringIn5StepsBasicApplication;\nimport org.junit.jupiter.api.Test;\nimport org.junit.jupiter.api.extension.ExtendWith;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.test.context.ContextConfiguration;\nimport org.springframework.test.context.junit.jupiter.SpringExtension;\n\n// Load the context\n// replaced @RunWith with @ExtendWith\n// replaced SpringRunner.class with SpringExtension.class\n@ExtendWith(SpringExtension.class)\n@ContextConfiguration(classes = SpringIn5StepsBasicApplication.class)\npublic class BinarySearchTest {\n\n    // Get this bean from the context\n    @Autowired\n    BinarySearchImpl binarySearch;\n\n    @Test\n    public void testBasicScenario() {\n\n        // call method on binarySearch\n        int actualResult = binarySearch.binarySearch(new int[]{}, 5);\n\n        // check if the value is correct\n        assertEquals(3, actualResult);\n\n    }\n\n}\n\n```\n\n#### Step 28 - Spring Unit Testing with an XML Context\n\n/src/test/resources/testContext.xml\n```xml\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<beans xmlns=\"http://www.springframework.org/schema/beans\"\n    xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n    xmlns:context=\"http://www.springframework.org/schema/context\"\n    xsi:schemaLocation=\"http://www.springframework.org/schema/beans\n        http://www.springframework.org/schema/beans/spring-beans.xsd\n        http://www.springframework.org/schema/context\n        http://www.springframework.org/schema/context/spring-context.xsd\">\n\t\n\t<import resource=\"classpath:applicationContext.xml\"/>\n\t\n</beans>\n```\n\n```java\npackage com.in28minutes.spring.basics.springin5steps.basic;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\nimport org.junit.jupiter.api.Test;\nimport org.junit.jupiter.api.extension.ExtendWith;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.test.context.ContextConfiguration;\nimport org.springframework.test.context.junit.jupiter.SpringExtension;\n\n// Load the context\n// replaced @RunWith with @ExtendWith\n// replaced SpringRunner.class with SpringExtension.class\n@ExtendWith(SpringExtension.class)\n@ContextConfiguration(locations = \"/testContext.xml\")\npublic class BinarySearchXMLConfigurationTest {\n\n    // Get this bean from the context\n    @Autowired\n    BinarySearchImpl binarySearch;\n\n    @Test\n    public void testBasicScenario() {\n\n        // call method on binarySearch\n        int actualResult = binarySearch.binarySearch(new int[]{}, 5);\n\n        // check if the value is correct\n        assertEquals(3, actualResult);\n\n    }\n\n}\n\n```\n\n#### Step 29 - Spring Unit Testing with Mockito\n\n```java\npublic class SomeCdiBusiness {\n\n\t// SAME OLD CODE\n\n\tpublic int findGreatest() {\n\t\tint greatest = Integer.MIN_VALUE;\n        int[] data = someCdiDao.getData();\n        var result = Arrays.stream(data).max();\n\n        if (result.isPresent()) {\n            greatest = result.getAsInt();\n        }\n\n        return greatest;\n\t}\n\n}\n```\n\nAdd a new method\n```java\npackage com.in28minutes.spring.basics.springin5steps.cdi;\n\nimport jakarta.inject.Named;\n\n@Named\npublic class SomeCdiDao {\n\t\n\tpublic int[] getData() {\n\t\treturn new int[] {5, 89,100};\n\t}\n\n}\n```\n\n\n```java\npackage com.in28minutes.spring.basics.springin5steps.cdi;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\nimport org.junit.jupiter.api.Test;\nimport org.junit.jupiter.api.extension.ExtendWith;\nimport org.mockito.InjectMocks;\nimport org.mockito.Mock;\nimport org.mockito.Mockito;\nimport org.mockito.junit.jupiter.MockitoExtension;\n\n// replaced @RunWith with @ExtendWith\n// replaced MockitoJUnitRunner.class with MockitoExtension.class\n@ExtendWith(MockitoExtension.class)\npublic class SomeCdiBusinessTest {\n\n    // Inject Mock\n    @InjectMocks\n    SomeCdiBusiness business;\n\n    // Create Mock\n    @Mock\n    SomeCdiDao daoMock;\n\n    @Test\n    public void testBasicScenario() {\n        Mockito.when(daoMock.getData()).thenReturn(new int[]{2, 4});\n        assertEquals(4, business.findGreatest());\n    }\n\n    @Test\n    public void testBasicScenario_NoElements() {\n        Mockito.when(daoMock.getData()).thenReturn(new int[]{});\n        assertEquals(Integer.MIN_VALUE, business.findGreatest());\n    }\n\n    @Test\n    public void testBasicScenario_EqualElements() {\n        Mockito.when(daoMock.getData()).thenReturn(new int[]{2, 2});\n        assertEquals(2, business.findGreatest());\n    }\n\n}\n\n```\n\n```xml\n<dependency>\n\t<groupId>org.mockito</groupId>\n\t<artifactId>mockito-core</artifactId>\n</dependency>\n```\n\n### Spring Level 4 - Introduction To Spring Boot\n### Spring Level 4 - Spring Boot in 10 Steps\n\n| **Title** | **Category** | **GitHub** |\n|------------|:-------------:|------------|\n| Spring Boot in 10 Steps | Spring - Level 4 | [Project Folder on GitHub](https://github.com/in28minutes/spring-master-class/tree/master/00-framework-tool-introductions/05.Spring-Boot-Introduction-In-10-Steps) |\n\n#### Topics Covered\n- **Step 1** – Introduction to Spring Boot: Goals and Key Features\n- **Step 2** – Developing Spring Applications Before Spring Boot\n- **Step 3** – Using Spring Initializr to Create a Spring Boot Application\n- **Step 4** – Creating a Simple REST Controller\n- **Step 5** – Understanding Spring Boot Auto-Configuration\n- **Step 6** – Spring Boot vs Spring MVC\n- **Step 7** – Spring Boot Starter Projects: *Starter Web* and *Starter JPA*\n- **Step 8** – Overview of Different Spring Boot Starter Projects\n- **Step 9** – Exploring Spring Boot Actuator\n- **Step 10** – Using Spring Boot Developer Tools\n\n\n#### Step 1 : Introduction to Spring Boot - Goals and Important Features\n\n### Spring Boot Overview\n\n#### Goals\n- Enable building production-ready applications quickly\n- Provide common non-functional features:\n    - Embedded servers\n    - Metrics\n    - Health checks\n    - Externalized configuration\n\n#### What Spring Boot is NOT\n- ZERO code generation\n- Neither an application server nor a web server\n\n#### Key Features\n- **Quick Starter Projects with Auto-Configuration**\n    - Web\n    - JPA\n- **Embedded Servers**\n    - Tomcat, Jetty, or Undertow\n- **Production-Ready Features**\n    - Metrics and health checks\n    - Externalized configuration\n\n\n#### Step 2 : Developing Spring Applications before Spring Boot\n\n> Recommended Reading - http://www.springboottutorial.com/spring-boot-vs-spring-mvc-vs-spring\n\n#### Step 3 : Using Spring Initializr to create a Spring Boot Application\n\n> https://start.spring.io\n\n#### Step 4 : Creating a Simple REST Controller\n\n/src/main/java/com/in28minutes/springboot/basics/springbootin10steps/BooksController.java\n\n```java\npackage com.in28minutes.springboot.basics.springbootin10steps;\n\nimport java.util.List;\n\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.RestController;\n\n@RestController\npublic class BooksController {\n\t@GetMapping(\"/books\")\n\tpublic List<Book> getAllBooks() {\n\t\treturn List.of(\n\t\t\t\tnew Book(1L, \"Mastering Spring 5.2\", \"Ranga Karanam\"));\n\t}\n}\n```\n\n#### Step 5 : What is Spring Boot Auto Configuration?\n\n> Recommended Reading - http://www.springboottutorial.com/spring-boot-auto-configuration\n\nSpring-based applications often require extensive configuration. For example:\n\nWhen using Spring MVC, we need to configure: component scanning, DispatcherServlet, a view resolver, WebJars (for serving static content), and other components.\n\nWhen using Hibernate/JPA, we need to configure: a datasource, an EntityManagerFactory, a TransactionManager, among several other things.\n\nSpring Boot introduces a new approach to simplify this process. It asks: Can we make configuration smarter? For instance, when a Spring MVC jar is added to an application, can some beans be auto-configured automatically? Spring Boot provides exactly this capability, reducing the need for manual configuration.\n\n#### Step 6 : Spring Boot vs Spring MVC\n\n> Recommended Reading - http://www.springboottutorial.com/spring-boot-vs-spring-mvc-vs-spring\n\n### Spring, Spring MVC, and Spring Boot Overview\n\n- **Spring** is all about **Dependency Injection**.\n    - It makes it easy to develop **loosely coupled applications**.\n    - It improves **testability** of applications.\n\n- **Spring MVC** brings **loose coupling** to web application development with features like:\n    - DispatcherServlet\n    - View Resolver\n    - And other components\n\n- **Spring Boot** eliminates the need for extensive manual configuration with Spring and Spring MVC.\n    - You can use Spring and Spring MVC without writing a lot of boilerplate configuration.\n    - **Goal:** Enable **production-ready applications** quickly\n\n  Key features of Spring Boot:\n    - **Actuator** – Enables advanced monitoring and tracing of applications\n    - **Embedded Server Integrations** – Since the server is integrated into the application, there’s **no need for a separate application server**\n    - **Default Error Handling** – Provides standard error pages and exception handling\n\n\n#### Step 7 : Spring Boot Starter Projects - Starter Web and Starter JPA\n\n> Recommended Reading - http://www.springboottutorial.com/spring-boot-starter-projects\n\n### Spring Boot Starters\n\n**Starters** are convenient sets of dependency descriptors that you can include in your application. They provide a **one-stop-shop** for all the Spring and related technologies you need, without having to hunt through sample code or manually copy multiple dependency descriptors.\n\nFor example, if you want to get started with Spring and JPA for database access, simply include the `spring-boot-starter-data-jpa` dependency in your project — and you’re ready to go.\n\n---\n\n#### Step 8: Overview of Different Spring Boot Starter Projects\n\nSpring Boot starter projects help you **quickly get started** with developing specific types of applications.\n\n**Examples of Spring Boot Starters:**\n\n- `spring-boot-starter-web-services` – SOAP Web Services\n- `spring-boot-starter-web` – Web & RESTful applications\n- `spring-boot-starter-test` – Unit testing and integration testing\n- `spring-boot-starter-jdbc` – Traditional JDBC\n- `spring-boot-starter-hateoas` – Add HATEOAS features to your services\n- `spring-boot-starter-security` – Authentication and authorization using Spring Security\n- `spring-boot-starter-data-jpa` – Spring Data JPA with Hibernate\n- `spring-boot-starter-cache` – Enable Spring Framework’s caching support\n- `spring-boot-starter-data-rest` – Expose simple REST services using Spring Data REST\n- `spring-boot-starter-actuator` – Add monitoring and tracing capabilities out-of-the-box\n- `spring-boot-starter-undertow`, `spring-boot-starter-jetty`, `spring-boot-starter-tomcat` – Choose your embedded servlet container\n- `spring-boot-starter-logging` – Logging using Logback\n- `spring-boot-starter-log4j2` – Logging using Log4j2\n\n\n### Step 9: Spring Boot Actuator\n\nSpring Boot Actuator provides a wide range of REST endpoints, all compatible with the **HAL specification**. You can use a **HAL browser** to explore the data offered by these services.\n\n**Actuator exposes various data about your application**, including:\n\n> application info, metrics, dump, beans, environment properties, configuration properties, audit events, heap dump, loggers, trace, health mappings, and auto-configuration.\n\nIn short, Actuator provides **rich metadata** to monitor and manage your Spring Boot application.\n\n---\n\n### Step 10: Spring Boot Developer Tools\n\n- Normally, you need to restart your server for every Java or JSP change.\n- **Spring Boot Developer Tools** enables **automatic reloading** of modified changes, improving development productivity.\n\n\n### Spring Level 5 - Spring AOP\n\n### Spring Level 5 - Spring AOP\n\n| **Title** | **Category** | **GitHub** |\n|------------|:-------------:|------------|\n| Spring AOP | Spring - Level 5 | [Project Folder on GitHub](https://github.com/in28minutes/spring-master-class/tree/master/03-spring-aop) |\n\n#### Steps Covered\n- **Step 01** – Setting up AOP Example: Part 1\n- **Step 02** – Setting up AOP Example: Part 2\n- **Step 03** – Defining a `@Before` Advice\n- **Step 04** – Understanding AOP Terminology: Pointcut, Advice, Aspect, Join Point, Weaving, and Weaver\n- **Step 05** – Using `@After`, `@AfterReturning`, `@AfterThrowing` Advices\n- **Step 06** – Using `@Around` Advice to Implement Performance Tracing\n- **Step 07** – Best Practice: Use a Common Pointcut Configuration\n- **Step 08** – Quick Summary of Other Pointcuts\n- **Step 09** – Creating Custom Annotation and an Aspect for Tracking Execution Time\n\n### Step 01 – Setting up AOP Example: Part 1\n\nCreating a Spring AOP project with **Spring Initializr** is straightforward.\n\n> **Spring Initializr**: [http://start.spring.io/](http://start.spring.io/) is a great tool to bootstrap your Spring Boot projects.\n\n#### Steps\n1. Launch **Spring Initializr** and configure the project:\n    - **Group**: `com.in28minutes.spring.aop`\n    - **Artifact**: `spring-aop`\n    - **Dependencies**:\n        - AOP\n2. Click **Generate Project**.\n3. Import the generated project into **Eclipse**.\n4. (Optional) To understand all the files included in the project, refer to the Spring Initializr project structure.\n\n\n#### Step 02 - Setting up AOP Example - Part 2\n\n```java\npackage com.in28minutes.spring.aop.springaop;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\n\n@Service\npublic class Business1 {\n\t\n\tprivate final Logger logger = LoggerFactory.getLogger(this.getClass());\n\n\t@Autowired\n\tprivate Dao1 dao1;\n\t\n\tpublic String calculateSomething(){\n\t\tString value = dao1.retrieveSomething();\n\t\tlogger.info(\"In Business - {}\", value);\n\t\treturn value;\n\t}\n}\n```\n---\n\n```java\npackage com.in28minutes.spring.aop.springaop;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\n\n@Service\npublic class Business2 {\n\t\n\t@Autowired\n\tprivate Dao2 dao2;\n\t\n\tpublic String calculateSomething(){\n\t\t//Business Logic\n\t\treturn dao2.retrieveSomething();\n\t}\n}\n```\n---\n\n```java\npackage com.in28minutes.spring.aop.springaop;\n\nimport org.springframework.stereotype.Repository;\n\n@Repository\npublic class Dao1 {\n\n\tpublic String retrieveSomething(){\n\t\treturn \"Dao1\";\n\t}\n\n}\n```\n---\n\n\n```java\npackage com.in28minutes.spring.aop.springaop;\n\nimport org.springframework.stereotype.Repository;\n\n@Repository\npublic class Dao2 {\n\n\tpublic String retrieveSomething(){\n\t\treturn \"Dao2\";\n\t}\n\n}\n```\n\n#### Step 03 - Defining an @Before advice\n\n```java\npublic class SpringAopApplication implements CommandLineRunner {\n\n    private final Logger logger = LoggerFactory.getLogger(this.getClass());\n\n    @Autowired\n    private Business1 business1;\n\n    @Autowired\n    private Business2 business2;\n\n    @Override\n    public void run(String... args) throws Exception {\n        logger.info(business1.calculateSomething());\n        logger.info(business2.calculateSomething());\n    }\n}\n```\n\n```java\npackage com.in28minutes.spring.aop.springaop.aspect;\n\nimport org.aspectj.lang.JoinPoint;\nimport org.aspectj.lang.annotation.Aspect;\nimport org.aspectj.lang.annotation.Before;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.context.annotation.Configuration;\n\n//AOP\n//Configuration\n@Aspect\n@Configuration\npublic class UseAccessAspect {\n\t\n\tprivate final Logger logger = LoggerFactory.getLogger(this.getClass());\n\t\n\t//What kind of method calls I would intercept\n\t//execution(* PACKAGE.*.*(..))\n\t\n\t@Before(\"execution(* com.in28minutes.spring.aop.springaop.business.*.*(..))\")\n\tpublic void before(JoinPoint joinPoint){\n\t\tlogger.info(\" Check for user access \");\n\t\tlogger.info(\" Allowed execution for {}\", joinPoint);\n\t}\n}\n```\n#### Step 04 - Understand AOP Terminology - Pointcut, Advice, Aspect, Join Point, Weaving and Weaver\n#### Step 05 - Using @After, @AfterReturning, @AfterThrowing advices\n#### Step 06 - Using @Around advice to implement performance tracing\n```java\npackage com.in28minutes.spring.aop.springaop.aspect;\n\nimport org.aspectj.lang.JoinPoint;\nimport org.aspectj.lang.annotation.After;\nimport org.aspectj.lang.annotation.AfterReturning;\nimport org.aspectj.lang.annotation.AfterThrowing;\nimport org.aspectj.lang.annotation.Aspect;\nimport org.aspectj.lang.annotation.Before;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.context.annotation.Configuration;\n\n//AOP\n//Configuration\n@Aspect\n@Configuration\npublic class AfterAopAspect {\n\n\tprivate final Logger logger = LoggerFactory.getLogger(this.getClass());\n\n\t@AfterReturning(value = \"execution(* com.in28minutes.spring.aop.springaop.business.*.*(..))\", \n\t\t\treturning = \"result\")\n\tpublic void afterReturning(JoinPoint joinPoint, Object result) {\n\t\tlogger.info(\"{} returned with value {}\", joinPoint, result);\n\t}\n\t\n\t@After(value = \"execution(* com.in28minutes.spring.aop.springaop.business.*.*(..))\")\n\tpublic void after(JoinPoint joinPoint) {\n\t\tlogger.info(\"after execution of {}\", joinPoint);\n\t}\n}\n```\n\n```java\npackage com.in28minutes.spring.aop.springaop.aspect;\n\nimport org.aspectj.lang.ProceedingJoinPoint;\nimport org.aspectj.lang.annotation.Around;\nimport org.aspectj.lang.annotation.Aspect;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.context.annotation.Configuration;\n\n@Aspect\n@Configuration\npublic class MethodExecutionCalculationAspect {\n\n\tprivate final Logger logger = LoggerFactory.getLogger(this.getClass());\n\n\t@Around(\"execution(* com.in28minutes.spring.aop.springaop.business.*.*(..))\")\n\tpublic void around(ProceedingJoinPoint joinPoint) throws Throwable {\n\t\tlong startTime = System.currentTimeMillis();\n\n\t\tjoinPoint.proceed();\n\n\t\tlong timeTaken = System.currentTimeMillis() - startTime;\n\t\tlogger.info(\"Time Taken by {} is {}\", joinPoint, timeTaken);\n\t}\n}\n```\n\n```java\npackage com.in28minutes.spring.aop.springaop.aspect;\n\nimport org.aspectj.lang.JoinPoint;\nimport org.aspectj.lang.annotation.Aspect;\nimport org.aspectj.lang.annotation.Before;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.context.annotation.Configuration;\n\n//AOP\n//Configuration\n@Aspect\n@Configuration\npublic class UserAccessAspect {\n\t\n\tprivate final Logger logger = LoggerFactory.getLogger(this.getClass());\n\t\n\t//What kind of method calls I would intercept\n\t//execution(* PACKAGE.*.*(..))\n\t//Weaving & Weaver\n\t@Before(\"execution(* com.in28minutes.spring.aop.springaop.data.*.*(..))\")\n\tpublic void before(JoinPoint joinPoint){\n\t\t//Advice\n\t\tlogger.info(\" Check for user access \");\n\t\tlogger.info(\" Allowed execution for {}\", joinPoint);\n\t}\n}\n```\n\n#### Step 07 - Best Practice : Use common Pointcut Configuration\n\n```java\npackage com.in28minutes.spring.aop.springaop.aspect;\n\nimport org.aspectj.lang.annotation.Pointcut;\n\npublic class CommonJoinPointConfig {\n\t\n\t@Pointcut(\"execution(* com.in28minutes.spring.aop.springaop.data.*.*(..))\")\n\tpublic void dataLayerExecution(){}\n\t\n\t@Pointcut(\"execution(* com.in28minutes.spring.aop.springaop.business.*.*(..))\")\n\tpublic void businessLayerExecution(){}\n\n}\n```\n\n```java\npublic class MethodExecutionCalculationAspect {\n\n    private Logger logger = LoggerFactory.getLogger(this.getClass());\n\n    @Around(\"com.in28minutes.spring.aop.springaop.aspect.CommonJoinPointConfig.businessLayerExecution()\")\n}\n```\npublic class AfterAopAspect\n```java\n\t@AfterReturning(value = \"com.in28minutes.spring.aop.springaop.aspect.CommonJoinPointConfig.businessLayerExecution()\", returning = \"result\")\n\t@After(value = \"com.in28minutes.spring.aop.springaop.aspect.CommonJoinPointConfig.businessLayerExecution()\")\n```\n\n```java\npublic class UserAccessAspect {\n\n    @Before(\"com.in28minutes.spring.aop.springaop.aspect.CommonJoinPointConfig.dataLayerExecution()\")\n}\n```\n\n#### Step 08 - Quick summary of other Pointcuts\n\n#### Step 09 - Creating Custom Annotation and an Aspect for Tracking Time\n\n```java\npackage com.in28minutes.spring.aop.springaop.aspect;\n\nimport org.aspectj.lang.annotation.Pointcut;\n\npublic class CommonJoinPointConfig {\n\t\n\t@Pointcut(\"execution(* com.in28minutes.spring.aop.springaop.data.*.*(..))\")\n\tpublic void dataLayerExecution(){}\n\t\n\t@Pointcut(\"execution(* com.in28minutes.spring.aop.springaop.business.*.*(..))\")\n\tpublic void businessLayerExecution(){}\n\t\n\t@Pointcut(\"dataLayerExecution() && businessLayerExecution()\")\n\tpublic void allLayerExecution(){}\n\t\n\t@Pointcut(\"bean(*dao*)\")\n\tpublic void beanContainingDao(){}\n\t\n\t@Pointcut(\"within(com.in28minutes.spring.aop.springaop.data..*)\")\n\tpublic void dataLayerExecutionWithWithin(){}\n\n\t@Pointcut(\"@annotation(com.in28minutes.spring.aop.springaop.aspect.TrackTime)\")\n\tpublic void trackTimeAnnotation(){}\n\n}\n```\n```java\npackage com.in28minutes.spring.aop.springaop.aspect;\n\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\n@Target(ElementType.METHOD)\n@Retention(RetentionPolicy.RUNTIME)\npublic @interface TrackTime {\n\n}\n```\n\n\n```java\n@Aspect\n@Configuration\npublic class MethodExecutionCalculationAspect {\n\n\t@Around(\"com.in28minutes.spring.aop.springaop.aspect.CommonJoinPointConfig.trackTimeAnnotation()\")\n\tpublic void around(ProceedingJoinPoint joinPoint) throws Throwable {\n```\n\n```java\npublic class Business1 {\n\t\t\n\t@TrackTime\n\tpublic String calculateSomething(){\n\n```\n\n```java\n@Repository\npublic class Dao1 {\n\n    @TrackTime\n    public String retrieveSomething() {\n    }\n}\n```\n\n### Spring Level 6 - Spring JDBC and JPA\n### Spring Level 6 – Spring JDBC and JPA\n\n| **Title** | **Category** | **GitHub** |\n|------------|:-------------:|------------|\n| Spring JDBC and JPA | Spring - Level 6 | [Project Folder on GitHub](https://github.com/in28minutes/spring-master-class/tree/master/04-spring-jdbc-to-jpa) |\n\n#### Steps Covered\n- **Step 01** – Setting up a project with JDBC, JPA, H2, and Web dependencies\n- **Step 02** – Launching the H2 Console\n- **Step 03** – Creating a database table in H2\n- **Step 04** – Populating data into the `Person` table\n- **Step 05** – Implementing `findAll` persons Spring JDBC query method\n- **Step 06** – Executing the `findAll` method using `CommandLineRunner`\n- **Step 07** – Quick Review: JDBC vs Spring JDBC\n- **Step 08** – Understanding Spring Boot auto-configuration (What’s in the background?)\n- **Step 09** – Implementing `findById` Spring JDBC query method\n- **Step 10** – Implementing `deleteById` Spring JDBC update method\n- **Step 11** – Implementing `insert` and `update` Spring JDBC update methods\n- **Step 12** – Creating a custom Spring JDBC `RowMapper`\n- **Step 13** – Quick introduction to JPA\n- **Step 14** – Defining the `Person` entity\n- **Step 15** – Implementing `findById` JPA repository method\n- **Step 16** – Implementing `insert` and `update` JPA repository methods\n- **Step 17** – Implementing `deleteById` JPA repository method\n- **Step 18** – Implementing `findAll` using JPQL Named Query\n- **Step 19** – Introduction to Spring Data JPA\n- **Step 20** – Connecting to other databases\n\n### Step 01 – Setting up a Project with JDBC, JPA, H2, and Web Dependencies\n\nCreating a Spring JDBC project with **Spring Initializr** is straightforward.\n\n> **Spring Initializr**: [http://start.spring.io/](http://start.spring.io/) is a great tool to bootstrap Spring Boot projects.\n\n#### Steps\n1. Launch **Spring Initializr** and configure the project:\n    - **Group**: `com.in28minutes.database`\n    - **Artifact**: `database-demo`\n    - **Dependencies**:\n        - Web\n        - JDBC\n        - JPA\n        - H2\n2. Click **Generate Project**.\n3. Import the generated project into **Eclipse**.\n4. (Optional) To understand all the files included in the project, refer to the Spring Initializr project structure.\n\n\n#### Step 02 - Launching up H2 Console\n\n/src/main/resources/application.properties \n```properties\nspring.h2.console.enabled=true\n```\n\nLaunching H2\n- URL - http://localhost:8080/h2-console\n- Make sure to check the db url - jdbc:h2:mem:testdb\n\n\n#### Step 03 - Creating a Database Table in H2\n\n/src/main/resources/data.sql\n\n```sql\ncreate table person\n(\n   id integer not null,\n   name varchar(255) not null,\n   location varchar(255),\n   birth_date timestamp,\n   primary key(id)\n);\n```\n\n#### Step 04 - Populate data into Person Table\n#### Step 05 - Implement findAll persons Spring JDBC Query Method\n\n```java\npackage com.in28minutes.database.databasedemo.entity;\n\nimport java.util.Date;\n\npublic class Person {\n\tprivate int id;\n\tprivate String name;\n\tprivate String location;\n\tprivate Date birthDate;\n\n\tpublic Person(int id, String name, String location, Date birthDate) {\n\t\tsuper();\n\t\tthis.id = id;\n\t\tthis.name = name;\n\t\tthis.location = location;\n\t\tthis.birthDate = birthDate;\n\t}\n\n\tpublic int getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(int id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic String getLocation() {\n\t\treturn location;\n\t}\n\n\tpublic void setLocation(String location) {\n\t\tthis.location = location;\n\t}\n\n\tpublic Date getBirthDate() {\n\t\treturn birthDate;\n\t}\n\n\tpublic void setBirthDate(Date birthDate) {\n\t\tthis.birthDate = birthDate;\n\t}\n\n}\n```\n---\n\n/src/main/java/com/in28minutes/database/databasedemo/jdbc/PersonJbdcDao.java\n\n```java\npackage com.in28minutes.database.databasedemo.jdbc;\n\nimport java.util.List;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.jdbc.core.BeanPropertyRowMapper;\nimport org.springframework.jdbc.core.JdbcTemplate;\nimport org.springframework.stereotype.Repository;\n\nimport com.in28minutes.database.databasedemo.entity.Person;\n\n@Repository\npublic class PersonJbdcDao {\n\t@Autowired\n\tJdbcTemplate jdbcTemplate;\n\n\tpublic List<Person> findAll() {\n\t\treturn jdbcTemplate.query(\"select * from person\", \n\t\t\t\tnew BeanPropertyRowMapper(Person.class));\n\t}\n}\n```\n---\n\nAdd insert statements into data.sql\n/src/main/resources/data.sql\n```sql\nINSERT INTO PERSON (ID, NAME, LOCATION, BIRTH_DATE ) \nVALUES(10001,  'Ranga', 'Hyderabad',CURRENT_DATE());\nINSERT INTO PERSON (ID, NAME, LOCATION, BIRTH_DATE ) \nVALUES(10002,  'James', 'New York',CURRENT_DATE());\nINSERT INTO PERSON (ID, NAME, LOCATION, BIRTH_DATE ) \nVALUES(10003,  'Pieter', 'Amsterdam',CURRENT_DATE());\n```\n#### Step 06 - Execute the findAll method using CommandLineRunner\n\n```java\npublic class DatabaseDemoApplication implements CommandLineRunner {\n\t\n\tprivate final Logger logger = LoggerFactory.getLogger(this.getClass());\n\t\n\t@Autowired\n\tPersonJbdcDao dao;\n\t\n\t@Override\n\tpublic void run(String... args) throws Exception {\n\t\tlogger.info(\"All users -> {}\", dao.findAll());\n```\n\nModified\n```java\n@Repository\npublic class PersonJbdcDao {\n\t@Autowired\n\tJdbcTemplate jdbcTemplate;\n\n\tpublic List<Person> findAll() {\n\t\treturn jdbcTemplate.query(\"select * from person\", \n\t\t\t\tnew BeanPropertyRowMapper<Person>(Person.class));\n\t}\n}\n```\n\n#### Step 07 - A Quick Review - JDBC vs Spring JDBC\n#### Step 08 - What's in the background? Understanding Spring Boot Autoconfiguration\n#### Step 09 - Implementing findById Spring JDBC Query Method\n#### Step 10 - Implementing deleteById Spring JDBC Update Method\n\nModified\n```java\npackage com.in28minutes.database.databasedemo.jdbc;\n\nimport java.util.List;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.jdbc.core.BeanPropertyRowMapper;\nimport org.springframework.jdbc.core.JdbcTemplate;\nimport org.springframework.stereotype.Repository;\n\nimport com.in28minutes.database.databasedemo.entity.Person;\n\n@Repository\npublic class PersonJbdcDao {\n\n\t@Autowired\n\tJdbcTemplate jdbcTemplate;\n\n\tpublic List<Person> findAll() {\n\t\treturn jdbcTemplate.query(\"select * from person\", new BeanPropertyRowMapper<Person>(Person.class));\n\t}\n\n\tpublic Person findById(int id) {\n\t\treturn jdbcTemplate.queryForObject\n\t\t\t\t(\"select * from person where id=?\", new Object[] { id },\n\t\t\t\tnew BeanPropertyRowMapper<Person>(Person.class));\n\t}\n\t\n\tpublic int deleteById(int id) {\n\t\treturn jdbcTemplate.update\n\t\t\t\t(\"delete from person where id=?\", new Object[] { id });\n\t}\n\n\t\n}\n```\nDatabaseDemoApplication\n```shell\n\t\tlogger.info(\"User id 10001 -> {}\", dao.findById(10001));\n\t\tlogger.info(\"Deleting 10002 -> No of Rows Deleted - {}\", dao.deleteById(10002));\n\n```\n#### Step 11 - Implementing insert and update Spring JDBC Update Methods\n\n```java\n\tpublic int deleteById(int id) {\n\t\treturn jdbcTemplate.update(\"delete from person where id=?\", new Object[] { id });\n\t}\n\n\tpublic int insert(Person person) {\n\t\treturn jdbcTemplate.update(\"insert into person (id, name, location, birth_date) \" + \"values(?,  ?, ?, ?)\",\n\t\t\t\tnew Object[] { person.getId(), person.getName(), person.getLocation(),\n\t\t\t\t\t\tnew Timestamp(person.getBirthDate().getTime()) });\n\t}\n\n\tpublic int update(Person person) {\n\t\treturn jdbcTemplate.update(\"update person \" + \" set name = ?, location = ?, birth_date = ? \" + \" where id = ?\",\n\t\t\t\tnew Object[] { person.getName(), person.getLocation(), new Timestamp(person.getBirthDate().getTime()),\n\t\t\t\t\t\tperson.getId() });\n\t}\n```\n\n```java\n\tlogger.info(\"Deleting 10002 -> No of Rows Deleted - {}\", \n\t\t\t\tdao.deleteById(10002));\n\t\t\n\t\tlogger.info(\"Inserting 10004 -> {}\", \n\t\t\t\tdao.insert(new Person(10004, \"Tara\", \"Berlin\", new Date())));\n\t\t\n\t\tlogger.info(\"Update 10003 -> {}\", \n\t\t\t\tdao.update(new Person(10003, \"Pieter\", \"Utrecht\", new Date())));\n\t\n```\n#### Step 12 - Creating a custom Spring JDBC RowMapper\n\nInner class in PersonJbdcDao\n```java\nstatic class PersonRowMapper implements RowMapper<Person>{\n\t@Override\n\tpublic Person mapRow(ResultSet rs, int rowNum) throws SQLException {\n\t\tPerson person = new Person();\n\t\tperson.setId(rs.getInt(\"id\"));\n\t\tperson.setName(rs.getString(\"name\"));\n\t\tperson.setLocation(rs.getString(\"location\"));\n\t\tperson.setBirthDate(rs.getTimestamp(\"birth_date\"));\n\t\treturn person;\n\t}\n\t\n}\n\npublic List<Person> findAll() {\n\treturn jdbcTemplate.query(\"select * from person\", new PersonRowMapper());\n}\n```\n\nPersonJbdcDao\n```\n```\n\n#### Step 13 - Quick introduction to JPA\n#### Step 14 - Defining Person Entity\n\n```java\npackage com.in28minutes.database.databasedemo.entity;\n\nimport java.util.Date;\n\nimport jakarta.persistence.Entity;\nimport jakarta.persistence.GeneratedValue;\nimport jakarta.persistence.Id;\n\n@Entity\npublic class Person {\n\t\n\t@Id\n\t@GeneratedValue\n\tprivate int id;\n\t\n\t//No change in rest of the code\t\n\t\n}\n```\n\n#### Step 15 - Implementing findById JPA Repository Method\n\nDatabaseDemoApplication renamed to SpringJdbcDemoApplication\n\n```java\npackage com.in28minutes.database.databasedemo.jpa;\n\nimport jakarta.persistence.EntityManager;\nimport jakarta.persistence.PersistenceContext;\nimport jakarta.transaction.Transactional;\n\nimport org.springframework.stereotype.Repository;\n\nimport com.in28minutes.database.databasedemo.entity.Person;\n\n@Repository\n@Transactional\npublic class PersonJpaRepository {\n\t\n\t//connect to the database\n\t@PersistenceContext\n\tEntityManager entityManager;\n\t\n\tpublic Person findById(int id) {\n\t\treturn entityManager.find(Person.class, id);//JPA\n\t}\n}\n```\n---\n\n/src/main/resources/application.properties\n```\nspring.jpa.show-sql=true\nspring.datasource.url=jdbc:h2:mem:testdb\nspring.data.jpa.repositories.bootstrap-mode=default\n```\n/src/main/resources/data.sql - Comment Everything\n```\n/*\n*/\n```\n\n\nJpaDemoApplication\n```java\npackage com.in28minutes.database.databasedemo;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.CommandLineRunner;\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\nimport com.in28minutes.database.databasedemo.jpa.PersonJpaRepository;\n\n@SpringBootApplication\npublic class JpaDemoApplication implements CommandLineRunner {\n\n\tprivate final Logger logger = LoggerFactory.getLogger(this.getClass());\n\n\t@Autowired\n\tPersonJpaRepository repository;\n\n\tpublic static void main(String[] args) {\n\t\tSpringApplication.run(JpaDemoApplication.class, args);\n\t}\n\n\t@Override\n\tpublic void run(String... args) throws Exception {\n\t\t\n\t\tlogger.info(\"User id 10001 -> {}\", repository.findById(10001));\n\n\t\t/*\n\t\tlogger.info(\"All users -> {}\", repository.findAll());\n\t\tlogger.info(\"Deleting 10002 -> No of Rows Deleted - {}\", \n\t\t\t\trepository.deleteById(10002));\n\t\t\n\t\tlogger.info(\"Inserting 10004 -> {}\", \n\t\t\t\trepository.insert(new Person(10004, \"Tara\", \"Berlin\", new Date())));\n\t\t\n\t\tlogger.info(\"Update 10003 -> {}\", \n\t\t\t\trepository.update(new Person(10003, \"Pieter\", \"Utrecht\", new Date())));\n\t\t*/\n\t}\n}\n```\n\n\n#### Step 16 - Implementing insert and update JPA Repository Methods\n#### Step 17 - Implementing deleteById JPA Repository Method\n#### Step 18 - Implementing findAll using JPQL Named Query\n```java\n    logger.info(\"Inserting -> {}\", \n            repository.insert(new Person(\"Tara\", \"Berlin\", new Date())));\n    repository.deleteById(10002);\n\n```\n\n```java\n@Entity\n@NamedQuery(name=\"find_all_persons\", query=\"select p from Person p\")\npublic class Person { }\n```\n\n```java\npackage com.in28minutes.database.databasedemo.jpa;\n\nimport java.util.List;\n\nimport jakarta.persistence.EntityManager;\nimport jakarta.persistence.PersistenceContext;\nimport jakarta.persistence.TypedQuery;\nimport jakarta.transaction.Transactional;\n\nimport org.springframework.stereotype.Repository;\n\nimport com.in28minutes.database.databasedemo.entity.Person;\n\n@Repository\n@Transactional\npublic class PersonJpaRepository {\n\n\t// connect to the database\n\t@PersistenceContext\n\tEntityManager entityManager;\n\n\tpublic List<Person> findAll() {\n\t\tvar namedQuery = entityManager.createNamedQuery(\"find_all_persons\", Person.class);\n\t\treturn namedQuery.getResultList();\n\t}\n\n\tpublic Person findById(int id) {\n\t\treturn entityManager.find(Person.class, id);// JPA\n\t}\n\n\tpublic Person update(Person person) {\n\t\treturn entityManager.merge(person);\n\t}\n\n\tpublic Person insert(Person person) {\n\t\treturn entityManager.merge(person);\n\t}\n\n\tpublic void deleteById(int id) {\n\t\tvar person = findById(id);\n\t\tentityManager.remove(person);\n\t}\n\n}\n```\n\n#### Step 19 - Introduction to Spring Data JPA\n\nJpaDemoApplication - comment out @SpringBootApplication\n\n```java\npackage com.in28minutes.database.databasedemo.springdata;\n\nimport org.springframework.data.jpa.repository.JpaRepository;\nimport org.springframework.stereotype.Repository;\n\nimport com.in28minutes.database.databasedemo.entity.Person;\n\n@Repository\npublic interface PersonSpringDataRepository \n\t\t\t\textends JpaRepository<Person, Integer>{\n}\n```\n\n```java\npackage com.in28minutes.database.databasedemo;\n\nimport java.util.Date;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.CommandLineRunner;\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\nimport com.in28minutes.database.databasedemo.entity.Person;\nimport com.in28minutes.database.databasedemo.springdata.PersonSpringDataRepository;\n\n@SpringBootApplication\npublic class SpringDataDemoApplication implements CommandLineRunner {\n\n\tprivate final Logger logger = LoggerFactory.getLogger(this.getClass());\n\n\t@Autowired\n\tPersonSpringDataRepository repository;\n\n\tpublic static void main(String[] args) {\n\t\tSpringApplication.run(SpringDataDemoApplication.class, args);\n\t}\n\n\t@Override\n\tpublic void run(String... args) throws Exception {\n\t\t\n\t\tlogger.info(\"User id 10001 -> {}\", repository.findById(10001));\n\t\t\n\t\tlogger.info(\"Inserting -> {}\", \n\t\t\t\trepository.save(new Person(\"Tara\", \"Berlin\", new Date())));\n\t\t\n\t\tlogger.info(\"Update 10003 -> {}\", \n\t\t\t\trepository.save(new Person(10003, \"Pieter\", \"Utrecht\", new Date())));\n\t\t\n\t\trepository.deleteById(10002);\n\n\t\tlogger.info(\"All users -> {}\", repository.findAll());\n\t}\n}\n```\n\n#### Step 20 - Connecting to Other Databases\n\n\n#### Connecting to My SQL and Other Databases\n\nSpring Boot makes it easy to switch databases! Yeah, really simple.\n\n##### Steps\n- Install MySQL and Setup Schema\n- Remove H2 dependency from pom.xml\n- Add MySQL (or your database) dependency to pom.xml\n```xml\n<dependency>\n    <groupId>mysql</groupId>\n    <artifactId>mysql-connector-java</artifactId>\n</dependency>\n```\n- Configure application.properties\n\n```properties\nspring.jpa.hibernate.ddl-auto=none\nspring.datasource.url=jdbc:mysql://localhost:3306/person_example\nspring.datasource.username=personuser\nspring.datasource.password=YOUR_PASSWORD\n```\n\n- Restart the app and You are ready!\n\n> Spring Boot can set up the database for you using Hibernate\n\n### Things to Note About Spring Boot JPA Schema Management\n\n- **Spring Boot chooses a default value** for `spring.jpa.hibernate.ddl-auto` based on whether your database is embedded or not:\n    - **Embedded database** → default is `create-drop`\n    - **Non-embedded database** → default is `none`\n\n- **`spring.jpa.hibernate.ddl-auto`** controls automatic schema management in Hibernate:\n    - `none` – No action will be performed\n    - `create-only` – Database creation will be generated\n    - `drop` – Database dropping will be generated\n    - `create` – Database will be dropped and then created\n    - `validate` – Validates the database schema\n    - `update` – Updates the database schema to match the entities\n\n- **Reference:** [Hibernate User Guide – Schema Management](https://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/Hibernate_User_Guide.html#configurations-hbmddl){:target=\"_blank\"}\n\n\napplication.properties\n```properties\n#none, validate, update, create, create-drop\nspring.jpa.hibernate.ddl-auto=create\n```\n\n##### Installing and Setting Up MySQL\n\n- **Install MySQL:**\n    - Official documentation: [Installing MySQL](https://dev.mysql.com/doc/en/installing.html)\n    - Detailed tutorial: [MySQL Tutorial](http://www.mysqltutorial.org/install-mysql/)\n    - Troubleshooting guide: [MySQL Troubleshooting](https://dev.mysql.com/doc/refman/en/problems.html)\n\n- **Start the MySQL server** (as a service)\n\n- **Create a database and user:**\n    1. Open **Command Prompt** (Windows) or **Terminal** (macOS/Linux)\n    2. Execute the following commands:\n       ```sql\n       -- Example commands\n       CREATE DATABASE my_database;\n       CREATE USER 'my_user'@'localhost' IDENTIFIED BY 'my_password';\n       GRANT ALL PRIVILEGES ON my_database.* TO 'my_user'@'localhost';\n       FLUSH PRIVILEGES;\n       ```\n\n\n```shell\nmysql --user=user_name --password db_name\ncreate database person_example;\ncreate user 'personuser'@'localhost' identified by 'YOUR_PASSWORD';\ngrant all on person_example.* to 'personuser'@'localhost';\n```\n\n- Execute following sql queries to create the table and insert the data\n\nTable\n\n```sql\ncreate table person\n(\n\tid integer not null,\n\tbirth_date timestamp,\n\tlocation varchar(255),\n\tname varchar(255),\n\tprimary key (id)\n);\n\n```\n\nData\n\n```sql\nINSERT INTO PERSON (ID, NAME, LOCATION, BIRTH_DATE ) VALUES(10001,  'Ranga', 'Hyderabad',CURRENT_DATE());\nINSERT INTO PERSON (ID, NAME, LOCATION, BIRTH_DATE ) VALUES(10002,  'James', 'New York',CURRENT_DATE());\nINSERT INTO PERSON (ID, NAME, LOCATION, BIRTH_DATE ) VALUES(10003,  'Pieter', 'Amsterdam',CURRENT_DATE());\n```\n\n#### Notes\n\n##### JdbcTemplate AutoConfiguration\n```shell\n=========================\nAUTO-CONFIGURATION REPORT\n=========================\n\nDataSourceAutoConfiguration matched:\n   - @ConditionalOnClass found required classes 'javax.sql.DataSource', 'org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition)\n\nDataSourceTransactionManagerAutoConfiguration matched:\n   - @ConditionalOnClass found required classes 'org.springframework.jdbc.core.JdbcTemplate', 'org.springframework.transaction.PlatformTransactionManager'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition)\n\nH2ConsoleAutoConfiguration matched:\n   - @ConditionalOnClass found required class 'org.h2.server.web.WebServlet'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition)\n   - found ConfigurableWebEnvironment (OnWebApplicationCondition)\n   - @ConditionalOnProperty (spring.h2.console.enabled=true) matched (OnPropertyCondition)\n\nJdbcTemplateAutoConfiguration matched:\n   - @ConditionalOnClass found required classes 'javax.sql.DataSource', 'org.springframework.jdbc.core.JdbcTemplate'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition)\n   - @ConditionalOnSingleCandidate (types: javax.sql.DataSource; SearchStrategy: all) found a primary bean from beans 'dataSource' (OnBeanCondition)\n\nJdbcTemplateAutoConfiguration.JdbcTemplateConfiguration#jdbcTemplate matched:\n   - @ConditionalOnMissingBean (types: org.springframework.jdbc.core.JdbcOperations; SearchStrategy: all) did not find any beans (OnBeanCondition)\n\n```\n\n### Bonus Section – Basic Web Application\n\nThis section covers the fundamentals of building a web application using Spring MVC, JSP, and Servlets.\n\n#### Topics Covered\n- Understand the basics of **HTTP**\n- **HTTP Requests** – GET/POST, request parameters\n- **HTTP Responses** – Status codes: 200, 404, 500, etc.\n- Introduction to **JSP**, **Servlets**, **Scriptlets**, and **EL (Expression Language)**\n- **HTML Forms** – Method, action, and form data\n- Basics of using **Maven**, **Tomcat**, and **Eclipse**\n- Using **request attributes** to pass data (model) between Servlet and view\n\n#### Spring MVC Steps\n- **Step 11** – Configure the application to use Spring MVC\n- **Step 12** – First Spring MVC Controller (`@Controller`, `@ResponseBody`)\n- **Step 13** – Redirect to Login JSP (`LoginController`, view resolver, `@ResponseBody`)\n- **Step 14** – DispatcherServlet configuration and Log4j integration\n- **Step 15** – Show user ID and password on the welcome page (`ModelMap`, `@RequestParam`)\n- **Step 16** – Create `LoginService` and remove all legacy JEE Servlets code\n- **Step 17** – Spring **autowiring** and dependency management (`@Autowired`, `@Service`)\n\n\n### Step 01 – Up and Running with a Web Application in Tomcat\n\nIn this step, we will quickly set up a **running web application**.\n\n> **Tip:** This is one of the few steps where you copy code directly! The goal is to ensure that your web application runs correctly without errors.\n\n**Run the project**:\n- Use **Eclipse** → `Run As` → `Maven Build` → `tomcat7:run`\n\n\nYou can copy code from \n- [Step 01 on GitHub Repository](https://github.com/in28minutes/JavaWebApplicationStepByStep/blob/master/Step01.md)\n\n\\pom.xml\n\n```xml\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\t<groupId>com.in28minutes</groupId>\n\t<artifactId>in28Minutes-first-webapp</artifactId>\n\t<version>0.0.1-SNAPSHOT</version>\n\t<packaging>war</packaging>\n\t<dependencies>\n\t\t<dependency>\n\t\t\t<groupId>javax</groupId>\n\t\t\t<artifactId>javaee-web-api</artifactId>\n\t\t\t<version>8.0.1</version>\n\t\t\t<scope>provided</scope>\n\t\t</dependency>\n\t</dependencies>\n\t<build>\n\t\t<pluginManagement>\n\t\t\t<plugins>\n\t\t\t\t<plugin>\n\t\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t\t<artifactId>maven-compiler-plugin</artifactId>\n\t\t\t\t\t<version>3.2</version>\n\t\t\t\t\t<configuration>\n\t\t\t\t\t\t<verbose>true</verbose>\n\t\t\t\t\t\t<source>1.7</source>\n\t\t\t\t\t\t<target>1.7</target>\n\t\t\t\t\t\t<showWarnings>true</showWarnings>\n\t\t\t\t\t</configuration>\n\t\t\t\t</plugin>\n\t\t\t\t<plugin>\n\t\t\t\t\t<groupId>org.apache.tomcat.maven</groupId>\n\t\t\t\t\t<artifactId>tomcat7-maven-plugin</artifactId>\n\t\t\t\t\t<version>2.2</version>\n\t\t\t\t\t<configuration>\n\t\t\t\t\t\t<path>/</path>\n\t\t\t\t\t\t<contextReloadable>true</contextReloadable>\n\t\t\t\t\t</configuration>\n\t\t\t\t</plugin>\n\t\t\t</plugins>\n\t\t</pluginManagement>\n\t</build>\n</project>\n```\n\n\\src\\main\\java\\webapp\\LoginServlet.java\n\n```java\npackage webapp;\n\nimport java.io.IOException;\nimport java.io.PrintWriter;\n\nimport javax.servlet.annotation.WebServlet;\nimport javax.servlet.http.HttpServlet;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\n\n/*\n * Browser sends Http Request to Web Server\n * \n * Code in Web Server => Input:HttpRequest, Output: HttpResponse\n * JEE with Servlets\n * \n * Web Server responds with Http Response\n */\n\n\n@WebServlet(urlPatterns = \"/login.do\")\npublic class LoginServlet extends HttpServlet {\n\n\t@Override\n\tprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {\n\t\tPrintWriter out = response.getWriter();\n\t\tout.println(\"<html>\");\n\t\tout.println(\"<head>\");\n\t\tout.println(\"<title>Yahoo!!!!!!!!</title>\");\n\t\tout.println(\"</head>\");\n\t\tout.println(\"<body>\");\n\t\tout.println(\"My First Servlet\");\n\t\tout.println(\"</body>\");\n\t\tout.println(\"</html>\");\n\n\t}\n\n}\n```\n\\src\\main\\webapp\\WEB-INF\\web.xml\n```xml\n<!-- webapp/WEB-INF/web.xml -->\n<web-app xmlns=\"http://java.sun.com/xml/ns/javaee\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd\"\n\tversion=\"3.0\">\n\n\t<display-name>To do List</display-name>\n\n\t<welcome-file-list>\n\t\t<welcome-file>login.do</welcome-file>\n\t</welcome-file-list>\n\n</web-app>\n```\nJava Platform, Enterprise Edition (Java EE) JEE6\n\nServlet is a Java programming language class used to extend the capabilities of servers  that host applications accessed by means of a request-response programming model.\n\nNotes\n- ```extends javax.servlet.http.HttpServlet``` - All servlets should extend HttpServlet class\n- ```@WebServlet(urlPatterns = \"/login.do\")``` - Provide the url pattern to access the servlet\n- ```doGet(HttpServletRequest request, HttpServletResponse response)``` - To handle the RequestMethod GET we need to implement doGet method.\n\nConfiguring welcome-file-list in web.xml will ensure that url http://localhost:8080/ redirects to http://localhost:8080/login.do\n\n```xml\n<welcome-file-list>\n\t<welcome-file>login.do</welcome-file>\n</welcome-file-list>\n```\n\n### Step 02 : First JSP\n\n[Complete code](https://github.com/in28minutes/JavaWebApplicationStepByStep/blob/master/Step02.md)\n\n#### Notes\n- Create LoginServlet again\n- Redirect to a view - JSP\n\n#### Code Snippets and Examples\n\nRedirect to a view - JSP\n\n\\src\\main\\java\\webapp\\LoginServlet.java\n```java\nrequest\n .getRequestDispatcher(\"/WEB-INF/views/login.jsp\")\n .forward(request, response);\n```\n\n\\src\\main\\webapp\\WEB-INF\\views\\login.jsp\n```jsp\n<html>\n<head>\n<title>Yahoo!!</title>\n</head>\n<body>\nMy First JSP!!!\n</body>\n</html>\n```\n\n### Step 03 : Adding a Get Parameter name\n\n[Complete code](https://github.com/in28minutes/JavaWebApplicationStepByStep/blob/master/Step03.md)\n\n#### Notes\n- Passing a Request Parameter Name\n\n#### Code Snippets and Examples\n\nWe read the request parameter and set it as a request attribute. Request attributes can be accessed from the view (jsp).\n\n\\src\\main\\java\\webapp\\LoginServlet.java\n\n```java\nrequest.setAttribute(\"name\", \n\t\trequest.getParameter(\"name\"));\n```\n\n\\src\\main\\webapp\\WEB-INF\\views\\login.jsp\n```\nMy First JSP!!! My name is ${name}\n```\n\n### Step 04 : Adding another Get Parameter Password\n\n[Complete code](https://github.com/in28minutes/JavaWebApplicationStepByStep/blob/master/Step04.md)\n\n#### Code Snippets and Examples\n\n\\src\\main\\java\\webapp\\LoginServlet.java\n```\nrequest.setAttribute(\"password\",\n                  request.getParameter(\"password\"));\n```\n\n\\src\\main\\webapp\\WEB-INF\\views\\login.jsp\n```\nMy First JSP!!! My name is ${name} and password is ${password}\n```\n\n### Step 05 : Let's add a form\n\n[Complete code](https://github.com/in28minutes/JavaWebApplicationStepByStep/blob/master/Step05.md)\n\n#### Code Snippets and Examples\n\n\\src\\main\\java\\webapp\\LoginServlet.java\n```java\n@Override\nprotected void doGet(HttpServletRequest request, HttpServletResponse response)\n\t\tthrows IOException, ServletException {\n\trequest\n\t\t.getRequestDispatcher(\"/WEB-INF/views/login.jsp\")\n\t\t.forward(request, response);\n}\n```\n\n\\src\\main\\webapp\\WEB-INF\\views\\login.jsp\n```jsp\n<html>\n<head>\n<title>Yahoo!!</title>\n</head>\n<body>\n\t<form action=\"/login.do\" method=\"POST\">\n\t\tName : <input type=\"text\" /> <input type=\"submit\" />\n\t</form>\n</body>\n</html>\n```\n\n\\src\\main\\webapp\\WEB-INF\\views\\welcome.jsp\n```html\n<html>\n<head>\n<title>Yahoo!!</title>\n</head>\n<body>\nWelcome ${name}\n</body>\n</html>\n```\n\n### Step 06 : New Form and doPost\n\n[Complete code](https://github.com/in28minutes/JavaWebApplicationStepByStep/blob/master/Step06.md)\n\n\\src\\main\\java\\webapp\\LoginServlet.java\n```java\n@Override\nprotected void doPost(HttpServletRequest request, HttpServletResponse response)\n\t\tthrows IOException, ServletException {\n\trequest.setAttribute(\"name\", request.getParameter(\"name\"));\n\trequest.getRequestDispatcher(\"/WEB-INF/views/welcome.jsp\").forward(request, response);\n}\n```\n\n\\src\\main\\webapp\\WEB-INF\\views\\welcome.jsp\n```html\n<html>\n<head>\n<title>Yahoo!!</title>\n</head>\n<body>\nWelcome ${name}\n</body>\n</html>\n```\n\n### Step 07 : Adding Password and Validation of User Id\n\n[Complete code](https://github.com/in28minutes/JavaWebApplicationStepByStep/blob/master/Step07.md)\n\n#### Code Snippets and Examples\n\n\\src\\main\\java\\webapp\\LoginService.java\n```java\npublic class LoginService {\n\tpublic boolean validateUser(String user, String password) {\n\t\treturn user.equalsIgnoreCase(\"in28Minutes\") && password.equals(\"dummy\");\n\t}\n\n}\n```\n\n\\src\\main\\java\\webapp\\LoginServlet.java\n```java\n@Override\nprotected void doPost(HttpServletRequest request, HttpServletResponse response)\n\t\tthrows IOException, ServletException {\n\tString name = request.getParameter(\"name\");\n\tString password = request.getParameter(\"password\");\n\n\tboolean isValidUser = service.validateUser(name, password);\n\n\tif (isValidUser) {\n\t\trequest.setAttribute(\"name\", name);\n\t\trequest.getRequestDispatcher(\"/WEB-INF/views/welcome.jsp\")\n\t\t\t\t.forward(request, response);\n\t} else {\n\t\trequest.setAttribute(\"errorMessage\", \"Invalid Credentials!!\");\n\t\trequest.getRequestDispatcher(\"/WEB-INF/views/login.jsp\")\n\t\t\t\t.forward(request, response);\n\t}\n}\n```\n\n\\src\\main\\webapp\\WEB-INF\\views\\login.jsp\n```html\n<html>\n<head>\n<title>Yahoo!!</title>\n</head>\n<body>\n\t<p><font color=\"red\">${errorMessage}</font></p>\n\t<form action=\"/login.do\" method=\"POST\">\n\t\tName : <input name=\"name\" type=\"text\" /> Password : <input name=\"password\" type=\"password\" /> <input type=\"submit\" />\n\t</form>\n</body>\n</html>\n```\n\n\n###  Step 11 : Configure application to use Spring MVC\n\n#### What we will do\n\nBefore we start with the Flows, we need to configure application to use Spring MVC\n- Lets do a little bit of Refactoring. Mini Step 1: Rename package webapp to com.in28minutes.jee\n- We need Spring MVC Framework and its dependencies. Mini Step 2 : Add required jars to the project\n- Spring MVC uses Front Controller Pattern -> Dispatcher Servlet. Mini Step 3 : Add Dispatcher Servlet to web.xml\n- DispatcherServlet needs an Spring Application Context to launch. We will create an xml (/WEB-INF/todo-servlet.xml). Mini Step 4: Add Spring Context\n\n#### Useful Snippets\npom.xml\n```xml\n    <dependency>\n        <groupId>org.springframework</groupId>\n        <artifactId>spring-webmvc</artifactId>\n        <version>6.0.6</version>\n    </dependency>\n```\nweb.xml\n```xml\n    <servlet>\n        <servlet-name>dispatcher</servlet-name>\n        <servlet-class>\n            org.springframework.web.servlet.DispatcherServlet\n        </servlet-class>\n        <init-param>\n            <param-name>contextConfigLocation</param-name>\n            <param-value>/WEB-INF/todo-servlet.xml</param-value>\n        </init-param>\n        <load-on-startup>1</load-on-startup>\n    </servlet>\n\n    <servlet-mapping>\n        <servlet-name>dispatcher</servlet-name>\n        <url-pattern>/spring-mvc/*</url-pattern>\n    </servlet-mapping>\n```\ntodo-servlet.xml\n```xml\n\t<beans xmlns=\"http://www.springframework.org/schema/beans\"\n\t    xmlns:context=\"http://www.springframework.org/schema/context\"\n\t    xmlns:mvc=\"http://www.springframework.org/schema/mvc\"\n\t    xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\t    xsi:schemaLocation=\"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd\n\t    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd\n\t    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd\">\n\t\n\t    <context:component-scan base-package=\"com.in28minutes\" />\n\t\n\t    <mvc:annotation-driven />\n\t    \n\t</beans>\n\n```\n\n\n#### Flows:\n- Flow 1. Login Servlet -> GET -> login.jsp\n- Flow 2. Login Servlet -> POST (Success) -> welcome.jsp\n- Flow 3. Login Servlet -> POST (Failure) -> login.jsp (with error message)\n\n#### Files List\n### \\\\src\\main\\webapp\\WEB-INF\\views\\login.jsp Deleted\n### \\pom.xml Deleted\n### \\src\\main\\java\\webapp\\LoginService.java Deleted\n### \\src\\main\\java\\webapp\\LoginServlet.java Deleted\n### \\src\\main\\webapp\\WEB-INF\\views\\welcome.jsp Deleted\n### \\src\\main\\webapp\\WEB-INF\\web.xml Deleted\n\n\n##### /pom.xml New\n```\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\t<groupId>com.in28minutes</groupId>\n\t<artifactId>in28Minutes-springmvc</artifactId>\n\t<version>0.0.1-SNAPSHOT</version>\n\t<packaging>war</packaging>\n\n\t<dependencies>\n\t\t<dependency>\n\t\t\t<groupId>javax</groupId>\n\t\t\t<artifactId>javaee-web-api</artifactId>\n\t\t\t<version>8.0.1</version>\n\t\t\t<scope>provided</scope>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>org.springframework</groupId>\n\t\t\t<artifactId>spring-webmvc</artifactId>\n\t\t\t<version>6.0.6</version>\n\t\t</dependency>\n\t</dependencies>\n\n\t<build>\n\t\t<pluginManagement>\n\t\t\t<plugins>\n\t\t\t\t<plugin>\n\t\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t\t<artifactId>maven-compiler-plugin</artifactId>\n\t\t\t\t\t<version>3.2</version>\n\t\t\t\t\t<configuration>\n\t\t\t\t\t\t<verbose>true</verbose>\n\t\t\t\t\t\t<source>1.8</source>\n\t\t\t\t\t\t<target>1.8</target>\n\t\t\t\t\t\t<showWarnings>true</showWarnings>\n\t\t\t\t\t</configuration>\n\t\t\t\t</plugin>\n\t\t\t\t<plugin>\n\t\t\t\t\t<groupId>org.apache.tomcat.maven</groupId>\n\t\t\t\t\t<artifactId>tomcat7-maven-plugin</artifactId>\n\t\t\t\t\t<version>2.2</version>\n\t\t\t\t\t<configuration>\n\t\t\t\t\t\t<path>/</path>\n\t\t\t\t\t\t<contextReloadable>true</contextReloadable>\n\t\t\t\t\t</configuration>\n\t\t\t\t</plugin>\n\t\t\t</plugins>\n\t\t</pluginManagement>\n\t</build>\n</project>\n```\n##### /src/main/java/com/in28minutes/jee/LoginService.java New\n```java\npackage com.in28minutes.jee;\n\npublic class LoginService {\n\tpublic boolean validateUser(String user, String password) {\n\t\treturn user.equalsIgnoreCase(\"in28Minutes\") && password.equals(\"dummy\");\n\t}\n\n}\n```\n##### /src/main/java/com/in28minutes/jee/LoginServlet.java New\n```java\npackage com.in28minutes.jee;\n\nimport java.io.IOException;\n\nimport jakarta.servlet.ServletException;\nimport jakarta.servlet.annotation.WebServlet;\nimport jakarta.servlet.http.HttpServlet;\nimport jakarta.servlet.http.HttpServletRequest;\nimport jakarta.servlet.http.HttpServletResponse;\n\n@WebServlet(urlPatterns = \"/login.do\")\npublic class LoginServlet extends HttpServlet {\n\n\tprivate LoginService service = new LoginService();\n\n\t@Override\n\tprotected void doGet(HttpServletRequest request,\n\t\t\tHttpServletResponse response) throws IOException, ServletException {\n\t\trequest.getRequestDispatcher(\"/WEB-INF/views/login.jsp\").forward(\n\t\t\t\trequest, response);\n\t}\n\n\t@Override\n\tprotected void doPost(HttpServletRequest request,\n\t\t\tHttpServletResponse response) throws IOException, ServletException {\n\t\tString name = request.getParameter(\"name\");\n\t\tString password = request.getParameter(\"password\");\n\n\t\tboolean isValidUser = service.validateUser(name, password);\n\n\t\tif (isValidUser) {\n\t\t\trequest.setAttribute(\"name\", name);\n\t\t\trequest.getRequestDispatcher(\"/WEB-INF/views/welcome.jsp\").forward(\n\t\t\t\t\trequest, response);\n\t\t} else {\n\t\t\trequest.setAttribute(\"errorMessage\", \"Invalid Credentials!!\");\n\t\t\trequest.getRequestDispatcher(\"/WEB-INF/views/login.jsp\").forward(\n\t\t\t\t\trequest, response);\n\t\t}\n\t}\n\n}\n```\n##### /src/main/webapp/WEB-INF/todo-servlet.xml New\n```xml\n<beans xmlns=\"http://www.springframework.org/schema/beans\"\n    xmlns:context=\"http://www.springframework.org/schema/context\"\n    xmlns:mvc=\"http://www.springframework.org/schema/mvc\"\n    xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n    xsi:schemaLocation=\"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd\n    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd\n    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd\">\n\n    <context:component-scan base-package=\"com.in28minutes\" />\n\n    <mvc:annotation-driven />\n    \n</beans>\n```\n##### /src/main/webapp/WEB-INF/views/login.jsp New\n```html\n<html>\n<head>\n<title>Yahoo!!</title>\n</head>\n<body>\n    <p><font color=\"red\">${errorMessage}</font></p>\n    <form action=\"/login.do\" method=\"POST\">\n        Name : <input name=\"name\" type=\"text\" /> Password : <input name=\"password\" type=\"password\" /> <input type=\"submit\" />\n    </form>\n</body>\n</html>\n```\n##### /src/main/webapp/WEB-INF/views/welcome.jsp New\n```html\n<html>\n<head>\n<title>Yahoo!!</title>\n</head>\n<body>\nWelcome ${name}\n</body>\n</html>\n```\n##### /src/main/webapp/WEB-INF/web.xml New\n```xml\n<web-app xmlns=\"http://java.sun.com/xml/ns/javaee\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n    xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd\"\n    version=\"3.0\">\n\n    <display-name>To do List</display-name>\n\n    <servlet>\n        <servlet-name>dispatcher</servlet-name>\n        <servlet-class>\n            org.springframework.web.servlet.DispatcherServlet\n        </servlet-class>\n        <init-param>\n            <param-name>contextConfigLocation</param-name>\n            <param-value>/WEB-INF/todo-servlet.xml</param-value>\n        </init-param>\n        <load-on-startup>1</load-on-startup>\n    </servlet>\n\n    <servlet-mapping>\n        <servlet-name>dispatcher</servlet-name>\n        <url-pattern>/spring-mvc/*</url-pattern>\n    </servlet-mapping>\n</web-app>\n```\n\n###  Step 12 : First Spring MVC Controller, @ResponseBody, @Controller\n\n####  First Spring MVC Controller\n- @RequestMapping(value = \"/login\", method = RequestMethod.GET)\n- http://localhost:8080/spring-mvc/login\n- web.xml - <url-pattern>/spring-mvc/*</url-pattern>\n- Why @ResponseBody?\n- Importance of RequestMapping method\n- Can I have multiple urls rendered from Same Controller?\n\n```java\npackage com.in28minutes.springmvc;\n\nimport org.springframework.stereotype.Controller;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.ResponseBody;\n\n@Controller\npublic class LoginController {\n\n\t@RequestMapping(value = \"/login\")\n\t@ResponseBody\n\tpublic String sayHello() {\n\t\treturn \"Hello World dummy\";\n\t}\n}\n\n```\n\n###  Step 13 : Redirect to Login JSP - LoginController, @ResponseBody - and View Resolver\n\n##### /src/main/java/com/in28minutes/springmvc/login/LoginController.java New\n```java\npackage com.in28minutes.springmvc.login;\n\nimport org.springframework.stereotype.Controller;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\n\n@Controller\npublic class LoginController {\n\t@RequestMapping(value = \"/login\", method = RequestMethod.GET)\n\tpublic String showLoginPage() {\n\t\treturn \"login\";\n\t}\n}\n```\n##### /src/main/webapp/WEB-INF/todo-servlet.xml Modified\nNew Lines\n```xml\n    <bean\n        class=\"org.springframework.web.servlet.view.InternalResourceViewResolver\">\n        <property name=\"prefix\">\n            <value>/WEB-INF/views/</value>\n        </property>\n        <property name=\"suffix\">\n            <value>.jsp</value>\n        </property>\n    </bean>\n```\n\n#### Redirect to Log in JSP\n- View Resolver in `todo-servlet.xml`\n- Update LoginController\n- Remove @ResponseBody\n- More about View Resolver\n\n#### Snippets\n\n```xml\n  <bean\n        class=\"org.springframework.web.servlet.view.InternalResourceViewResolver\">\n        <property name=\"prefix\">\n            <value>/WEB-INF/views/</value>\n        </property>\n        <property name=\"suffix\">\n            <value>.jsp</value>\n        </property>\n    </bean>\n```\n\n###  Step 14 : DispatcherServlet and Log4j\n\n##### /pom.xml Modified\nNew Lines\n```xml\n<dependency>\n\t<groupId>log4j</groupId>\n\t<artifactId>log4j</artifactId>\n\t<version>1.2.17</version>\n</dependency>\n```\n\n##### /src/main/resources/log4j.properties New\n```properties\nlog4j.rootLogger=TRACE, Appender1, Appender2\n \nlog4j.appender.Appender1=org.apache.log4j.ConsoleAppender\nlog4j.appender.Appender1.layout=org.apache.log4j.PatternLayout\nlog4j.appender.Appender1.layout.ConversionPattern=%-7p %d [%t] %c %x - %m%n\n \n```\n##### /src/main/webapp/WEB-INF/views/login.jsp Modified\nNew Lines\n```html\n    <form action=\"/spring-mvc/login\" method=\"POST\">\n```\n##### /src/main/webapp/WEB-INF/views/welcome.jsp Modified\nNew Lines\n```\nWelcome ${name}. \n```\n### Understanding DispatcherServlet and Spring MVC Request Flow\n\n#### What We Want to Do\n- Understand the **importance of `DispatcherServlet`** in Spring MVC.\n- Add **Log4j** for logging to better understand the request flow.\n\n#### Spring MVC Request Flow\n1. `DispatcherServlet` receives the HTTP request.\n2. It identifies the **appropriate controller** based on the URL.\n3. Controller executes the **business logic**.\n4. Controller returns:\n    - **Model** (data)\n    - **View Name** (logical view)\n5. `DispatcherServlet` resolves the view using the **ViewResolver**.\n6. `DispatcherServlet` makes the model available to the view and executes it.\n7. `DispatcherServlet` returns the **HTTP response** back to the client.\n\n> Flow diagram reference: [Spring MVC Flow](http://docs.spring.io/spring-framework/docs/2.0.8/reference/images/mvc.png){:target=\"_blank\"}\n\n---\n\n### Step 15 – Show UserID and Password on the Welcome Page (`ModelMap` and `@RequestParam`)\n\n- Display **user ID** and **password** on the welcome page (without using Spring Security).\n- Use **`ModelMap`** to pass data from controller to view.\n- Use **`@RequestParam`** to capture request parameters.\n\n#### Example Controller\n```java\n@Controller\npublic class WelcomeController {\n\n    @RequestMapping(value = \"/welcome\", method = RequestMethod.POST)\n    public String showWelcomePage(@RequestParam String name,\n                                  @RequestParam String password,\n                                  ModelMap model) {\n        model.addAttribute(\"name\", name);\n        model.addAttribute(\"password\", password);\n        return \"welcome\"; // Returns welcome.jsp\n    }\n}\n```\n\n##### /src/main/java/com/in28minutes/springmvc/login/LoginController.java Modified\nNew Lines\n```java\n\n\t@RequestMapping(value = \"/login\", method = RequestMethod.POST)\n\tpublic String handleUserLogin(ModelMap model, @RequestParam String name,\n\t\t\t@RequestParam String password) {\n\t\tmodel.put(\"name\", name);\n\t\tmodel.put(\"password\", password);\n\t\treturn \"welcome\";\n\t}\n\n```\n##### /src/main/webapp/WEB-INF/views/welcome.jsp Modified\nNew Lines\n```\nWelcome ${name}. You entered ${password}\n```\n\n###  Step 16 : LoginService and Remove all JEE Servlets based code\n\n- Use LoginService to validate userid and password.\n- Remove all the old controller code and lets use only Spring MVC here on. \n- For now : We are not using Spring Autowiring for LoginService.\n- Change URL to http://localhost:8080/login\n\n\n##### /src/main/java/com/in28minutes/jee/LoginService.java Deleted\n##### /src/main/java/com/in28minutes/jee/LoginServlet.java Deleted\n\n##### /src/main/java/com/in28minutes/springmvc/login/LoginController.java Deleted\n\n##### /src/main/java/com/in28minutes/login/LoginController.java New\n\n```java\npackage com.in28minutes.login;\n\nimport org.springframework.stereotype.Controller;\nimport org.springframework.ui.ModelMap;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\nimport org.springframework.web.bind.annotation.RequestParam;\n\nimport com.in28minutes.login.LoginService;\n\n@Controller\npublic class LoginController {\n\n\tprivate LoginService loginService = new LoginService();\n\n\t@RequestMapping(value = \"/login\", method = RequestMethod.GET)\n\tpublic String showLoginPage() {\n\t\treturn \"login\";\n\t}\n\n\t@RequestMapping(value = \"/login\", method = RequestMethod.POST)\n\tpublic String handleUserLogin(ModelMap model, @RequestParam String name,\n\t\t\t@RequestParam String password) {\n\n\t\tif (!loginService.validateUser(name, password)) {\n\t\t\tmodel.put(\"errorMessage\", \"Invalid Credentials\");\n\t\t\treturn \"login\";\n\t\t}\n\n\t\tmodel.put(\"name\", name);\n\t\treturn \"welcome\";\n\t}\n}\n```\n\n##### /src/main/java/com/in28minutes/login/LoginService.java New\n```java\npackage com.in28minutes.login;\n\npublic class LoginService {\n\tpublic boolean validateUser(String user, String password) {\n\t\treturn user.equalsIgnoreCase(\"in28Minutes\") && password.equals(\"dummy\");\n\t}\n\n}\n```\n\n##### /src/main/webapp/WEB-INF/views/login.jsp Modified\nNew Lines\n```html\n    <form action=\"/login\" method=\"POST\">\n```\n##### /src/main/webapp/WEB-INF/views/welcome.jsp Modified\nNew Lines\n```shell\nWelcome ${name}. You are now authenticated.\n```\n\n##### /src/main/webapp/WEB-INF/web.xml Modified\nNew Lines\n```\n        <url-pattern>/</url-pattern>\n```\n\n### Step 17 – Spring Auto-wiring and Dependency Management (`@Autowired` and `@Service`)\n\nIn this step, we will learn about **Spring’s dependency injection** and how **auto-wiring** simplifies wiring of beans.\n\n#### Key Concepts\n- **Dependency Management:** Spring manages object creation and wiring, reducing boilerplate code.\n- **`@Service`:** Marks a class as a **service layer component** (Spring-managed bean).\n- **`@Autowired`:** Automatically injects dependent beans into a class.\n\n\n##### /src/main/java/com/in28minutes/login/LoginController.java Modified\nNew Lines\n```java\nimport org.springframework.beans.factory.annotation.Autowired;\n\t@Autowired\n\tprivate LoginService loginService;\n```\n##### /src/main/java/com/in28minutes/login/LoginService.java Modified\nNew Lines\n```java\nimport org.springframework.stereotype.Service;\n@Service\npublic class LoginService { }\n```\n\n### Other Introduction Sections\n| Title              |   Category   | Github                                                                                                                                                        |\n|--------------------|:------------:|---------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| Eclipse in 5 Steps | Introduction | [Project Folder on Github](https://github.com/in28minutes/spring-master-class/tree/master/00-framework-tool-introductions/01.Eclipse-Introduction-in-5-steps) |\n| Maven in 5 Steps   | Introduction | [Project Folder on Github](https://github.com/in28minutes/spring-master-class/tree/master/00-framework-tool-introductions/02.Maven-Introduction-In-5-Steps)   |\n| JUnit in 5 Steps   | Introduction | [Project Folder on Github](https://github.com/in28minutes/spring-master-class/tree/master/00-framework-tool-introductions/03.JUnit-Introduction-In-5-Steps)   |\n| Mockito in 5 Steps | Introduction | [Project Folder on Github](https://github.com/in28minutes/spring-master-class/tree/master/00-framework-tool-introductions/04.Mockito-Introduction-In-5-Steps) |\n| IntelliJ IDEA      | Introduction | [Reference Link](https://www.jetbrains.com/help/idea/installation-guide.html)                                                                                 |\n"
  },
  {
    "path": "_blog/articles/2017-10-16-spring-micro-services.md",
    "content": "---\nlayout:     post\ntitle:      Spring Boot Microservices and RESTful Web Services Tutorial for Beginners\ndate:       2022-10-16 12:31:19\nsummary:    Learn how to create awesome Microservices and RESTful web services with Spring, Spring Boot and Spring Cloud. \ncategories: SpringBootMicroservices\npermalink:  /microservices-and-restful-services-with-spring-boot-for-beginners\nimage: /images/microservices-category.png\n---\n\nLearn how to create awesome Microservices and RESTful Web Services with Spring and Spring Boot.\n\nDeveloping RESTful web services is fun. The combination of Spring Boot, Spring Web MVC, Spring Web Services and JPA makes it even more fun. And its even more fun to create Microservices.\n\nThere are two parts to this course - RESTful web services and Microservices\n\n### Part 1 - RESTful Web Services\n\nArchitectures are moving towards microservices. \n\nRESTful web services are the first step to developing great microservices. Spring Boot, in combination with Spring Web MVC (also called Spring REST) makes it easy to develop RESTful web services. \n\nIn the first part of the course, you will learn the basics of RESTful web services developing resources for a social media application. You will learn to implement these resources with multiple features - versioning, exception handling, documentation (Swagger), basic authentication (Spring Security), filtering and HATEOAS. You will learn the best practices in designing RESTful web services.\n\nIn this part of the course, you will be using Spring (Dependency Management), Spring MVC (or Spring REST), Spring Boot, Spring Security (Authentication and Authorization), Spring Boot Actuator (Monitoring), Swagger (Documentation), Maven (dependencies management), Eclipse (IDE), Postman (REST Services Client) and Tomcat Embedded Web Server. We will help you set up each one of these.\n\n### Part 2 - Microservices\n\nIn the second part of the course, you will learn the basics of Microservices. You will understand how to implement microservices using Spring Cloud.\n\nIn this part of the course, you will learn to establish communication between microservices, enable load balancing, scaling up and down of microservices. You will also learn to centralize configuration of microservices with Spring Cloud Config Server. You will implement Eureka Naming Server and Distributed tracing with Spring Cloud Sleuth and Zipkin. You will create fault toleranct microservices with Zipkin\n\n\n\n## What You will learn\n\n- You will be able to develop and design RESTful web services\n- You will setup Centralized Microservice Configuration with Spring Cloud Config Server\n- You will understand how to implement Exception Handling, Validation, HATEOAS and filtering for RESTful Web Services.\n- You will implement client side load balancing (Ribbon), Dynamic scaling(Eureka Naming Server) and an API Gateway (Zuul)\n- You will learn to implement Distributed tracing for microservices with Spring Cloud Sleuth and Zipkin\n- You will implement Fault Tolerance for microservices with Zipkin\n- You will understand how to version your RESTful Web Services\n- You will understand how to monitor RESTful Services with Spring Boot Actuator\n- You will understand how to document RESTful Web Services with Swagger\n- You will understand the best practices in designing RESTful web services\n- Using Spring Cloud Bus to exchange messages about Configuration updates\n- Simplify communication with other Microservices using Feign REST Client\n\n## Getting Started\n\n### Installing Tools\n\n- Installation \n  - Video : https://www.youtube.com/playlist?list=PLBBog2r6uMCSmMVTW_QmDLyASBvovyAO3\n  - PDF : https://github.com/in28minutes/SpringIn28Minutes/blob/master/InstallationGuide-JavaEclipseAndMaven_v2.pdf\n  - More Details : https://github.com/in28minutes/getting-started-in-5-steps\n- Troubleshooting\n  - [A 50 page troubleshooting guide with more than 200 Errors and Questions answered](https://github.com/in28minutes/in28minutes-initiatives/blob/master/The-in28Minutes-TroubleshootingGuide-And-FAQ)\n\n  \n### Running Examples\n\n- Download the zip or clone the Git repository.\n- Unzip the zip file (if you downloaded one)\n- Open Command Prompt and Change directory (cd) to folder containing pom.xml\n- Open Eclipse \n   - File -> Import -> Existing Maven Project -> Navigate to the folder where you unzipped the zip\n   - Select the right project\n- Choose the Spring Boot Application file (search for @SpringBootApplication)\n- Right Click on the file and Run as Java Application\n- You are all Set\n- For help : use our installation guide - https://www.youtube.com/playlist?list=PLBBog2r6uMCSmMVTW_QmDLyASBvovyAO3\n\n## Course Overview\n\n|Title|Category|Github|\n| -------------------- |--------------|\n|Introduction To Web Services|None|\n|Restful Web Services with Spring Boot|[Project Folder on Github](https://github.com/in28minutes/spring-microservices/tree/master/02.restful-web-services){:target='_blank'}|\n|Microservices with Spring Cloud|[Project Folder on Github](https://github.com/in28minutes/spring-microservices/tree/master/03.microservices){:target='_blank'}|\n\n## 2 Bonus Sections - Introduction to Spring Boot and JPA\n\n|Title|Category|Github|\n| -------------------- |:------------------:|--------------|\n|Spring Boot in 10 Steps|Introduction|[Project Folder on Github](https://github.com/in28minutes/spring-microservices/tree/master/01.framework-introductions/springboot-in-10-steps){:target='_blank'}|\n|JPA in 10 Steps|Introduction|[Project Folder on Github](https://github.com/in28minutes/spring-microservices/tree/master/01.framework-introductions/jpa-in-10-steps){:target='_blank'}|\n\n\n## Step By Step Details\n\n### Introductory Modules\n\n> These sections are in the Appendix. If you are new to Spring Boot or JPA, Do not forget to check these out!\n\n- First 10 Steps in JPA\n- First 10 Steps in Spring Boot\n\n\n### Introduction to Web Services\n- What is a Web Service?\n- Important How Questions related to Web Services\n- Web Services - Key Terminology\n- Introduction to SOAP Web Services\n- Introduction to RESTful Web Services\n- SOAP vs RESTful Web Services\n\n### Restful Web Services with Spring Boot\n\n- Step 01 - Initializing a RESTful Services Project with Spring Boot\n- Step 02 - Understanding the RESTful Services we would create in this course\n- Step 03 - Creating a Hello World Service\n- Step 04 - Enhancing the Hello World Service to return a Bean\n- Step 05 - Quick Review of Spring Boot Auto Configuration and Dispatcher Servlet\n- Step 06 - Enhancing the Hello World Service with a Path Variable\n- Step 07 - Creating User Bean and User Service\n- Step 08 - Implementing GET Methods for User Resource\n- Step 09 - Implementing POST Method to create User Resource\n- Step 10 - Enhancing POST Method to return correct HTTP Status Code and Location\n- Step 11 - Implementing Exception Handling - 404 Resource Not Found\n- Step 12 - Implementing Generic Exception Handling for all Resources\n- Step 13 - Exercise : User Post Resource and Exception Handling\n- Step 14 - Implementing DELETE Method to delete a User Resource\n- Step 15 - Implementing Validations for RESTful Services\n- Step 16 - Implementing HATEOAS for RESTful Services\n- Step 17 - Overview of Advanced RESTful Service Features\n- Step 18 - Internationalization for RESTful Services\n- Step 19 - Content Negotiation - Implementing Support for XML\n- Step 20 - Configuring Auto Generation of Swagger Documentation\n- Step 21 - Introduction to Swagger Documentation Format\n- Step 22 - Enhancing Swagger Documentation with Custom Annotations\n- Step 23 - Monitoring APIs with Spring Boot Actuator\n- Step 24 - Implementing Static Filtering for RESTful Service\n- Step 25 - Implementing Dynamic Filtering for RESTful Service\n- Step 26 - Versioning RESTful Services - Basic Approach with URIs\n- Step 27 - Versioning RESTful Services - Header and Content Negotiation Approach\n- Step 28 - Implementing Basic Authentication with Spring Security\n- Step 29 - Overview of Connecting RESTful Service to JPA\n- Step 30 - Creating User Entity and some test data\n- Step 31 - Updating GET methods on User Resource to use JPA\n- Step 32 - Updating POST and DELETE methods on User Resource to use JPA\n- Step 33 - Creating Post Entity and Many to One Relationship with User Entity\n- Step 34 - Implementing a GET service to retrieve all Posts of a User\n- Step 35 - Implementing a POST service to create a Post for a User\n- Step 36 - Richardson Maturity Model\n- Step 37 - RESTful Web Services - Best Practices\n\n### Microservices with Spring Cloud\n\n- Step 00 - 01 - Introduction to Microservices\n- Step 00 - 02 - Challenges with Microservices\n- Step 00 - 03 - Introduction to Spring Cloud\n- Step 00 - 04 - Advantages of Microservices Architectures\n- Step 00 - 05 - Microservice Components - Standardizing Ports and URL\n- Step 01 - Part 1 - Introduction to Limits Microservice and Spring Cloud Config Server\n- Step 01 - Part 2 - Setting up Limits Microservice\n- Step 02 - Creating a hard coded limits service\n- Step 03 - Enhance limits service to pick up configuration from application properties\n- Step 04 - Setting up Spring Cloud Config Server\n- Step 05 - Installing Git\n- Step 06 - Creating Local Git Repository\n- Step 07 - Connect Spring Cloud Config Server to Local Git Repository\n- Step 08 - Configuration for Multiple Environments in Git Repository\n- Step 09 - Connect Limits Service to Spring Cloud Config Server\n- Step 10 - Configuring Profiles for Limits Service\n- Step 11 - A review of Spring Cloud Config Server\n- Step 12 - Introduction to Currency Conversion and Currency Exchange Microservices\n- Step 13 - Setting up Currency Exchange Microservice\n- Step 14 - Create a simple hard coded currency exchange service\n- Step 15 - Setting up Dynamic Port in the the Response\n- Step 16 - Configure JPA and Initialized Data\n- Step 17 - Create a JPA Repository\n- Step 18 - Setting up Currency Conversion Microservice\n- Step 19 - Creating a service for currency conversion\n- Step 20 - Invoking Currency Exchange Microservice from Currency Conversion Microservice\n- Step 21 - Using Feign REST Client for Service Invocation\n- Step 22 - Setting up client side load balancing with Ribbon\n- Step 23 - Running client side load balancing with Ribbon\n- Step 24 - Understand the need for a Naming Server\n- Step 25 - Setting up Eureka Naming Server\n- Step 26 - Connecting Currency Conversion Microservice to Eureka\n- Step 27 - Connecting Currency Exchange Microservice to Eureka\n- Step 28 - Distributing calls using Eureka and Ribbon\n- Step 29 - A review of implementing Eureka, Ribbon and Feign\n- Step 30 - Introduction to API Gateways\n- Step 31 - Setting up Zuul API Gateway\n- Step 32 - Implementing Zuul Logging Filter\n- Step 33 - Executing a request through Zuul API Gateway\n- Step 34 - Setting up Zuul API Gateway between microservice invocations\n- Step 35 - Introduction to Distributed Tracing\n- Step 36 - Implementing Spring Cloud Sleuth\n- Step 37 - Introduction to Distributed Tracing with Zipkin\n- Step 38 - Installing Rabbit MQ\n- Step 39 - Setting up Distributed Tracing with Zipkin\n- Step 40 - Connecting microservices to Zipkin\n- Step 41 - Using Zipkin UI Dashboard to trace requests\n- Step 42 - Understanding the need for Spring Cloud Bus\n- Step 43 - Implementing Spring Cloud Bus\n- Step 44 - Fault Tolerance with Hystrix\n- Step 99 - FAQ 01 - Microservices Characteristics\n- Step 99 - FAQ 02 - What do you do next?\n\n\n# Course Details\n\n## 02 - RESTful Web Services with Spring Boot\n\nBuilding RESTful web services with Spring Boot is fun. In this section, we will discover why Spring, Spring MVC and Spring Boot is becoming the best framework combination to develop RESTful web services. \n\nYou will learn\n- What is a RESTful Web Service? \n- How to implement RESTful Web Services with Spring and Spring Boot?\n- What are the best practices in designing RESTful Web Services? \n- How to design Resources and GET, POST and DELETE operations?\n- How to implement Validation for RESTful Web Services? \n- How to implement Exception Handling for RESTful Web Services? \n- What is HATEOAS? How to implement HATEOAS for a Resource?\n- What are the different approach in versioning RESTful Services?\n- How to use Postman to execute RESTful Service Requests?\n- How to implement basic authentication with Spring Security?\n- How to implement filtering for RESTful Services?\n- How to monitor RESTful Services with Spring Boot Actuator?\n- How to document RESTful Web Services with Swagger?\n- How to connect RESTful Services to a backend with JPA?\n\n#### Useful Links\n\n- POSTMAN - http://www.getpostman.com\n\n##### Links from course examples\n- Basic Resources\n  - http://localhost:8080/hello-world\n  - http://localhost:8080/hello-world-bean\n  - http://localhost:8080/hello-world/path-variable/Ranga\n  - http://localhost:8080/users/\n  - http://localhost:8080/users/1\n- JPA Resources\n  - http://localhost:8080/jpa/users/\n  - http://localhost:8080/jpa/users/1\n  - http://localhost:8080/jpa/users/10001/posts\n- Filtering\n  - http://localhost:8080/filtering\n  - http://localhost:8080/filtering-list\n- Actuator\n  - http://localhost:8080/actuator\n- Versioning\n  - http://localhost:8080/v1/person\n  - http://localhost:8080/v2/person\n  - http://localhost:8080/person/param\n     - params=[version=1]\n  - http://localhost:8080/person/param\n     - params=[version=2]\n  - http://localhost:8080/person/header\n     - headers=[X-API-VERSION=1]\n  - http://localhost:8080/person/header\n     - headers=[X-API-VERSION=2]\n  - http://localhost:8080/person/produces\n     - produces=[application/vnd.company.app-v1+json]\n  - http://localhost:8080/person/produces\n     - produces=[application/vnd.company.app-v2+json]\n- Swagger\n  - http://localhost:8080/swagger-ui.html\n  - http://localhost:8080/v2/api-docs\n- H2-Console\n  - http://localhost:8080/h2-console\n\n\n##### Error in the Log\n```\nResolved exception caused by Handler execution: \norg.springframework.http.converter.HttpMessageNotWritableException: \nNo converter found for return value of type: \nclass com.in28minutes.rest.webservices.restfulwebservices.HelloWorldBean\n```\n- This happened because there were no getters in HelloWorldBean class\n\n##### Questions to Answer\n\n- What is dispatcher servlet?\n- Who is configuring dispatcher servlet?\n- What does dispatcher servlet do? \n- How does the HelloWorldBean object get converted to JSON?\n- Who is configuring the error mapping?\n\n- Mapping servlet: 'dispatcherServlet' to [/]\n\n- Mapped \"{[/hello-world],methods=[GET]}\" onto \npublic java.lang.String com.in28minutes.rest.webservices.restfulwebservices.HelloWorldController.helloWorld()\n- Mapped \"{[/hello-world-bean],methods=[GET]}\" onto \npublic com.in28minutes.rest.webservices.restfulwebservices.HelloWorldBean com.in28minutes.rest.webservices.restfulwebservices.HelloWorldController.helloWorldBean()\n- Mapped \"{[/error]}\" onto \npublic org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)\n- Mapped \"{[/error],produces=[text/html]}\" onto \npublic org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)\n\n\n\n### Example Requests\n\n#### GET http://localhost:8080/users\n```json\n[\n    {\n        \"id\": 1,\n        \"name\": \"Adam\",\n        \"birthDate\": \"2017-07-19T04:40:20.796+0000\"\n    },\n    {\n        \"id\": 2,\n        \"name\": \"Eve\",\n        \"birthDate\": \"2017-07-19T04:40:20.796+0000\"\n    },\n    {\n        \"id\": 3,\n        \"name\": \"Jack\",\n        \"birthDate\": \"2017-07-19T04:40:20.796+0000\"\n    }\n]\n```\n#### GET http://localhost:8080/users/1\n```json\n{\n    \"id\": 1,\n    \"name\": \"Adam\",\n    \"birthDate\": \"2017-07-19T04:40:20.796+0000\"\n}\n```\n#### POST http://localhost:8080/users\n```json\n{\n    \"name\": \"Ranga\",\n    \"birthDate\": \"2000-07-19T04:29:24.054+0000\"\n}\n```\n\n#### GET http://localhost:8080/users/1000\n- Get request to a non existing resource. \n- The response shows default error message structure auto configured by Spring Boot.\n\n```json\n{\n    \"timestamp\": \"2017-07-19T05:28:37.534+0000\",\n    \"status\": 404,\n    \"error\": \"Not Found\",\n    \"message\": \"id-500\",\n    \"path\": \"/users/500\"\n}\n```\n\n#### GET http://localhost:8080/users/1000\n- Get request to a non existing resource. \n- The response shows a Customized Message Structure\n```json\n{\n    \"timestamp\": \"2017-07-19T05:31:01.961+0000\",\n    \"message\": \"id-500\",\n    \"details\": \"Any details you would want to add\"\n}\n```\n\n#### POST http://localhost:8080/users with Validation Errors\n\n##### Request\n```json\n{\n    \"name\": \"R\",\n    \"birthDate\": \"2000-07-19T04:29:24.054+0000\"\n}\n```\n##### Response - 400 Bad Request\n```json\n{\n    \"timestamp\": \"2017-07-19T09:00:27.912+0000\",\n    \"message\": \"Validation Failed\",\n    \"details\": \"org.springframework.validation.BeanPropertyBindingResult: 1 errors\\nField error in object 'user' on field 'name': rejected value [R]; codes [Size.user.name,Size.name,Size.java.lang.String,Size]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.name,name]; arguments []; default message [name],2147483647,2]; default message [Name should have atleast 2 characters]\"\n}\n```\n#### GET http://localhost:8080/users/1 with HATEOAS\n```json\n{\n    \"id\": 1,\n    \"name\": \"Adam\",\n    \"birthDate\": \"2017-07-19T09:26:18.337+0000\",\n    \"_links\": {\n        \"all-users\": {\n            \"href\": \"http://localhost:8080/users\"\n        }\n    }\n}\n```\n\n\n### XML Representation of Resources\n\n#### GET http://localhost:8080/users\n- Accept application/xml\n\n```xml\n<List>\n    <item>\n        <id>2</id>\n        <name>Eve</name>\n        <birthDate>2017-07-19T10:25:20.450+0000</birthDate>\n    </item>\n    <item>\n        <id>3</id>\n        <name>Jack</name>\n        <birthDate>2017-07-19T10:25:20.450+0000</birthDate>\n    </item>\n    <item>\n        <id>4</id>\n        <name>Ranga</name>\n        <birthDate>2017-07-19T10:25:20.450+0000</birthDate>\n    </item>\n</List>\n```\n\n#### POST http://localhost:8080/users\n- Accept : application/xml\n- Content-Type : application/xml\n\nRequest\n\n```xml\n<item>\n        <name>Ranga</name>\n        <birthDate>2017-07-19T10:25:20.450+0000</birthDate>\n</item>\n```\n\nResponse\n- Status - 201 Created\n\n#### Generating Swagger Documentation\n\n\n```java\n  public static final Contact DEFAULT_CONTACT = new Contact(\n      \"Ranga Karanam\", \"http://www.in28minutes.com\", \"in28minutes@gmail.com\");\n  \n  public static final ApiInfo DEFAULT_API_INFO = new ApiInfo(\n      \"Awesome API Title\", \"Awesome API Description\", \"1.0\",\n      \"urn:tos\", DEFAULT_CONTACT, \n      \"Apache 2.0\", \"http://www.apache.org/licenses/LICENSE-2.0\");\n\n  private static final Set<String> DEFAULT_PRODUCES_AND_CONSUMES = \n      new HashSet<String>(Arrays.asList(\"application/json\",\n          \"application/xml\"));\n\n  @Bean\n  public Docket api() {\n    return new Docket(DocumentationType.SWAGGER_2)\n        .apiInfo(DEFAULT_API_INFO)\n        .produces(DEFAULT_PRODUCES_AND_CONSUMES)\n        .consumes(DEFAULT_PRODUCES_AND_CONSUMES);\n  }\n\n```\n\n#### Resource Method description\n```java\n  @GetMapping(\"/users/{id}\")\n  @ApiOperation(value = \"Finds Users by id\",\n    notes = \"Also returns a link to retrieve all users with rel - all-users\")\n  public Resource<User> retrieveUser(@PathVariable int id) {\n```\n\n#### API Model\n```java\n\n@ApiModel(value=\"User Details\", description=\"Contains all details of a user\")\npublic class User {\n\n  @Size(min=2, message=\"Name should have atleast 2 characters\")\n  @ApiModelProperty(notes = \"Name should have atleast 2 characters\")\n  private String name;\n\n  @Past\n  @ApiModelProperty(notes = \"Birth Date should be in the Past\")\n  private Date birthDate;\n```\n\n#### Filtering\n\n##### Code\n```java\n@JsonIgnoreProperties(value={\"field1\"})\npublic class SomeBean {\n  \n  private String field1;\n  \n  @JsonIgnore\n  private String field2;\n  \n  private String field3;\n\n```\n##### Response\n```json\n{\n    \"field3\": \"value3\"\n}\n```\n\n#### Versioning\n - Media type versioning (a.k.a “content negotiation” or “accept header”)\n   - GitHub\n - (Custom) headers versioning\n   - Microsoft\n - URI Versioning\n   - Twitter\n - Request Parameter versioning \n   - Amazon\n - Factors\n  - URI Pollution\n  - Misuse of HTTP Headers\n  - Caching\n  - Can we execute the request on the browser?\n  - API Documentation\n - No Perfect Solution \n\n##### More\n- https://www.mnot.net/blog/2011/10/25/web_api_versioning_smackdown\n- http://urthen.github.io/2013/05/09/ways-to-version-your-api/\n- http://stackoverflow.com/questions/389169/best-practices-for-api-versioning\n- http://www.lexicalscope.com/blog/2012/03/12/how-are-rest-apis-versioned/\n- https://www.3scale.net/2016/06/api-versioning-methods-a-brief-reference/\n\n\n#### Table Structure\n\n```sql\ncreate table user (\nid integer not null, \nbirth_date timestamp, \nname varchar(255), \nprimary key (id)\n);\n\ncreate table post (\nid integer not null, \ndescription varchar(255), \nuser_id integer, \nprimary key (id)\n);\n\nalter table post \nadd constraint post_to_user_foreign_key\nforeign key (user_id) references user;\n```\n\n\n###  Step 01 - Initializing a RESTful Services Project with Spring Boot\n\nCreating a Spring Project with Spring Initializr is a cake walk. \n\n> Spring Initializr [http://start.spring.io/](http://start.spring.io/){:target=\"_blank\"} is great tool to bootstrap your Spring Boot projects.\n\n![Image](/images/spring-initializr-for-restful-web-services.png \"Spring Initializr\")   \n\nAs shown in the image above, following steps have to be done\n\n- Launch Spring Initializr and choose the following\n  - Choose `com.in28minutes.rest.webservices` as Group\n  - Choose `restful-web-services` as Artifact\n  - Choose Release >= 2.0.0 (Avoid SNAPSHOT!)\n  - Choose following dependencies\n    - Web\n    - DevTools\n    - JPA\n    - H2\n- Click Generate Project.\n- Import the project into Eclipse.\n- If you want to understand all the files that are part of this project, you can go here.\n---\n###  Step 02 - Understanding the RESTful Services we would create in this course\n\n#### Social Media Application Resource Mappings\n\n##### User -> Posts\n- Retrieve all Users      - GET  /users\n- Create a User           - POST /users\n- Retrieve one User       - GET  /users/{id} -> /users/1   \n- Delete a User           - DELETE /users/{id} -> /users/1\n\n- Retrieve all posts for a User - GET /users/{id}/posts \n- Create a posts for a User - POST /users/{id}/posts\n- Retrieve details of a post - GET /users/{id}/posts/{post_id}\n\n\n###  Step 03 - Creating a Hello World Service\n\n```\n@RestController\npublic class HelloWorldController {\n\n  @GetMapping(path = \"/hello-world\")\n  public String helloWorld() {\n    return \"Hello World\";\n  }\n}\n```\n\n###  Step 04 - Enhancing the Hello World Service to return a Bean\n\n```\n  @GetMapping(path = \"/hello-world-bean\")\n  public HelloWorldBean helloWorldBean() {\n    return new HelloWorldBean(\"Hello World\");\n  }\n```\n\n##### /src/main/java/com/in28minutes/rest/webservices/restfulwebservices/HelloWorldBean.java New\n\n```java\npackage com.in28minutes.rest.webservices.restfulwebservices;\n\npublic class HelloWorldBean {\n\n  private String message;\n\n  public HelloWorldBean(String message) {\n    this.message = message;\n  }\n\n  public String getMessage() {\n    return message;\n  }\n\n  public void setMessage(String message) {\n    this.message = message;\n  }\n\n  @Override\n  public String toString() {\n    return String.format(\"HelloWorldBean [message=%s]\", message);\n  }\n\n}\n```\n\n###  Step 05 - Quick Review of Spring Boot Auto Configuration and Dispatcher Servlet\n\nLet us understand Spring Boot Auto Configuration in depth - http://www.springboottutorial.com/spring-boot-auto-configuration\n\n###  Step 06 - Enhancing the Hello World Service with a Path Variable\n\n---\n\n##### /src/main/java/com/in28minutes/rest/webservices/restfulwebservices/HelloWorldController.java\n\n```java\npackage com.in28minutes.rest.webservices.restfulwebservices;\n\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.RestController;\n\n//Controller\n@RestController\npublic class HelloWorldController {\n\n  @GetMapping(path = \"/hello-world\")\n  public String helloWorld() {\n    return \"Hello World\";\n  }\n\n  @GetMapping(path = \"/hello-world-bean\")\n  public HelloWorldBean helloWorldBean() {\n    return new HelloWorldBean(\"Hello World\");\n  }\n  \n  ///hello-world/path-variable/in28minutes\n  @GetMapping(path = \"/hello-world/path-variable/{name}\")\n  public HelloWorldBean helloWorldPathVariable(@PathVariable String name) {\n    return new HelloWorldBean(String.format(\"Hello World, %s\", name));\n  }\n  \n}\n```\n---\n\n##### /src/main/resources/application.properties Modified\nNew Lines\n```\nlogging.level.org.springframework = info\n```\n\n###  Step 07 - Creating User Bean and User Service\n\n##### /src/main/java/com/in28minutes/rest/webservices/restfulwebservices/HelloWorldBean.java \n\nPackage Change\n```\npackage com.in28minutes.rest.webservices.restfulwebservices.helloworld;\n```\n\n##### /src/main/java/com/in28minutes/rest/webservices/restfulwebservices/HelloWorldController.java \n\nPackage Change\n```\npackage com.in28minutes.rest.webservices.restfulwebservices.helloworld;\n```\n\n\n##### /src/main/java/com/in28minutes/rest/webservices/restfulwebservices/user/User.java New\n\n```java\n\npackage com.in28minutes.rest.webservices.restfulwebservices.user;\n\nimport java.util.Date;\n\npublic class User {\n\n  private Integer id;\n\n  private String name;\n\n  private Date birthDate;\n\n  public User(Integer id, String name, Date birthDate) {\n    super();\n    this.id = id;\n    this.name = name;\n    this.birthDate = birthDate;\n  }\n\n  public Integer getId() {\n    return id;\n  }\n\n  public void setId(Integer id) {\n    this.id = id;\n  }\n\n  public String getName() {\n    return name;\n  }\n\n  public void setName(String name) {\n    this.name = name;\n  }\n\n  public Date getBirthDate() {\n    return birthDate;\n  }\n\n  public void setBirthDate(Date birthDate) {\n    this.birthDate = birthDate;\n  }\n\n  @Override\n  public String toString() {\n    return String.format(\"User [id=%s, name=%s, birthDate=%s]\", id, name, birthDate);\n  }\n\n}\n```\n---\n\n##### /src/main/java/com/in28minutes/rest/webservices/restfulwebservices/user/UserDaoService.java New\n\n```java\npackage com.in28minutes.rest.webservices.restfulwebservices.user;\n\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.List;\n\nimport org.springframework.stereotype.Component;\n\n@Component\npublic class UserDaoService {\n  private static List<User> users = new ArrayList<>();\n\n  private static int usersCount = 3;\n\n  static {\n    users.add(new User(1, \"Adam\", new Date()));\n    users.add(new User(2, \"Eve\", new Date()));\n    users.add(new User(3, \"Jack\", new Date()));\n  }\n\n  public List<User> findAll() {\n    return users;\n  }\n\n  public User save(User user) {\n    if (user.getId() == null) {\n      user.setId(++usersCount);\n    }\n    users.add(user);\n    return user;\n  }\n\n  public User findOne(int id) {\n    for (User user : users) {\n      if (user.getId() == id) {\n        return user;\n      }\n    }\n    return null;\n  }\n\n}\n```\n---\n\n###  Step 08 - Implementing GET Methods for User Resource\n\n\n##### /src/main/java/com/in28minutes/rest/webservices/restfulwebservices/user/UserResource.java New\n\n```java\npackage com.in28minutes.rest.webservices.restfulwebservices.user;\n\nimport java.util.List;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.RestController;\n\n@RestController\npublic class UserResource {\n\n  @Autowired\n  private UserDaoService service;\n\n  @GetMapping(\"/users\")\n  public List<User> retrieveAllUsers() {\n    return service.findAll();\n  }\n\n  @GetMapping(\"/users/{id}\")\n  public User retrieveUser(@PathVariable int id) {\n    return service.findOne(id);\n  }\n\n}\n```\n---\n\n##### /src/main/resources/application.properties Modified\n\nNew Lines\n```\n#This is not really needed as this is the default after 2.3.1.RELEASE\nspring.jackson.serialization.write-dates-as-timestamps=false\n```\n\n###  Step 09 - Implementing POST Method to create User Resource\n\n##### /src/main/java/com/in28minutes/rest/webservices/restfulwebservices/user/UserResource.java Modified\n\n```\n  // input - details of user\n  // output - CREATED & Return the created URI\n  @PostMapping(\"/users\")\n  public void createUser(@RequestBody User user){\n    User savedUser = service.save(user);\n  }  \n```\n\n###  Step 10 - Enhancing POST Method to return correct HTTP Status Code and Location\n\n##### /src/main/java/com/in28minutes/rest/webservices/restfulwebservices/user/UserResource.java Modified\n\n```\n  // input - details of user\n  // output - CREATED & Return the created URI\n  @PostMapping(\"/users\")\n  public ResponseEntity<Object> createUser(@RequestBody User user) {\n    User savedUser = service.save(user);\n    // CREATED\n    // /user/{id}     savedUser.getId()\n    \n    URI location = ServletUriComponentsBuilder\n      .fromCurrentRequest()\n      .path(\"/{id}\")\n      .buildAndExpand(savedUser.getId()).toUri();\n    \n    return ResponseEntity.created(location).build();\n    \n  }\n```\n\n###  Step 11 - Implementing Exception Handling - 404 Resource Not Found\n###  Step 12 - Implementing Generic Exception Handling for all Resources\n\n\n##### /src/main/java/com/in28minutes/rest/webservices/restfulwebservices/exception/CustomizedResponseEntityExceptionHandler.java New\n\n```java\npackage com.in28minutes.rest.webservices.restfulwebservices.exception;\n\nimport java.util.Date;\n\nimport org.springframework.http.HttpStatus;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.web.bind.annotation.ControllerAdvice;\nimport org.springframework.web.bind.annotation.ExceptionHandler;\nimport org.springframework.web.bind.annotation.RestController;\nimport org.springframework.web.context.request.WebRequest;\nimport org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;\n\nimport com.in28minutes.rest.webservices.restfulwebservices.user.UserNotFoundException;\n\n@ControllerAdvice\n@RestController\npublic class CustomizedResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {\n\n  @ExceptionHandler(Exception.class)\n  public final ResponseEntity<Object> handleAllExceptions(Exception ex, WebRequest request) {\n    ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(),\n        request.getDescription(false));\n    return new ResponseEntity(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR);\n  }\n\n  @ExceptionHandler(UserNotFoundException.class)\n  public final ResponseEntity<Object> handleUserNotFoundException(UserNotFoundException ex, WebRequest request) {\n    ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(),\n        request.getDescription(false));\n    return new ResponseEntity(errorDetails, HttpStatus.NOT_FOUND);\n  }\n\n}\n```\n---\n\n##### /src/main/java/com/in28minutes/rest/webservices/restfulwebservices/exception/ErrorDetails.java New\n\n```java\npackage com.in28minutes.rest.webservices.restfulwebservices.exception;\n\nimport java.util.Date;\n\npublic class ErrorDetails {\n  private Date timestamp;\n  private String message;\n  private String details;\n\n  public ErrorDetails(Date timestamp, String message, String details) {\n    super();\n    this.timestamp = timestamp;\n    this.message = message;\n    this.details = details;\n  }\n\n  public Date getTimestamp() {\n    return timestamp;\n  }\n\n  public String getMessage() {\n    return message;\n  }\n\n  public String getDetails() {\n    return details;\n  }\n\n}\n```\n---\n##### /src/main/java/com/in28minutes/rest/webservices/restfulwebservices/user/UserNotFoundException.java New\n\n```java\npackage com.in28minutes.rest.webservices.restfulwebservices.user;\n\nimport org.springframework.http.HttpStatus;\nimport org.springframework.web.bind.annotation.ResponseStatus;\n\n@ResponseStatus(HttpStatus.NOT_FOUND)\npublic class UserNotFoundException extends RuntimeException {\n  public UserNotFoundException(String message) {\n    super(message);\n  }\n}\n```\n---\n\n###  Step 13 - Exercise : User Post Resource and Exception Handling\n###  Step 14 - Implementing DELETE Method to delete a User Resource\n\n##### /src/main/java/com/in28minutes/rest/webservices/restfulwebservices/user/UserDaoService.java Modified\n```java\n  public User deleteById(int id) {\n    Iterator<User> iterator = users.iterator();\n    while (iterator.hasNext()) {\n      User user = iterator.next();\n      if (user.getId() == id) {\n        iterator.remove();\n        return user;\n      }\n    }\n    return null;\n  }\n\n```\n---\n\n\n##### /src/main/java/com/in28minutes/rest/webservices/restfulwebservices/user/UserResource.java Modified\n\n```java\n\n  @GetMapping(\"/users/{id}\")\n  public User retrieveUser(@PathVariable int id) {\n    User user = service.findOne(id);\n    \n    if(user==null)\n      throw new UserNotFoundException(\"id-\"+ id);\n    \n    return user;\n  }\n\n  @DeleteMapping(\"/users/{id}\")\n  public void deleteUser(@PathVariable int id) {\n    User user = service.deleteById(id);\n    \n    if(user==null)\n      throw new UserNotFoundException(\"id-\"+ id);   \n  }\n\n  //\n  // input - details of user\n  // output - CREATED & Return the created URI\n  @PostMapping(\"/users\")\n  public ResponseEntity<Object> createUser(@RequestBody User user) {\n    User savedUser = service.save(user);\n    // CREATED\n    // /user/{id}     savedUser.getId()\n    \n    URI location = ServletUriComponentsBuilder\n      .fromCurrentRequest()\n      .path(\"/{id}\")\n      .buildAndExpand(savedUser.getId()).toUri();\n    \n    return ResponseEntity.created(location).build();\n    \n  }\n```\n---\n\n###  Step 15 - Implementing Validations for RESTful Services\n\n##### /src/main/java/com/in28minutes/rest/webservices/restfulwebservices/exception/CustomizedResponseEntityExceptionHandler.java Modified\n\n```java  \n@Override\nprotected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,\n    HttpHeaders headers, HttpStatus status, WebRequest request) {\n  ErrorDetails errorDetails = new ErrorDetails(new Date(), \"Validation Failed\",\n      ex.getBindingResult().toString());\n  return new ResponseEntity(errorDetails, HttpStatus.BAD_REQUEST);\n} \n```\n\n\n##### /src/main/java/com/in28minutes/rest/webservices/restfulwebservices/user/User.java Modified\n\n```java\n  @Size(min=2, message=\"Name should have atleast 2 characters\")\n  private String name;\n\n  @Past\n  private Date birthDate;\n```\n\n##### /src/main/java/com/in28minutes/rest/webservices/restfulwebservices/user/UserResource.java Modified\n\n```java\npublic ResponseEntity<Object> createUser(@Valid @RequestBody User user) {\n```\n\n###  Step 16 - Implementing HATEOAS for RESTful Services\n\n##### /pom.xml Modified\n\n```\n    <dependency>\n      <groupId>org.springframework.boot</groupId>\n      <artifactId>spring-boot-starter-hateoas</artifactId>\n    </dependency>\n```\n\n##### /src/main/java/com/in28minutes/rest/webservices/restfulwebservices/user/UserResource.java Modified\n\n```java\n  @GetMapping(\"/users/{id}\")\n  public Resource<User> retrieveUser(@PathVariable int id) {\n    User user = service.findOne(id);\n    \n    if(user==null)\n      throw new UserNotFoundException(\"id-\"+ id);\n    \n    \n    //\"all-users\", SERVER_PATH + \"/users\"\n    //retrieveAllUsers\n    Resource<User> resource = new Resource<User>(user);\n    \n    ControllerLinkBuilder linkTo = \n        linkTo(methodOn(this.getClass()).retrieveAllUsers());\n    \n    resource.add(linkTo.withRel(\"all-users\"));\n    \n    //HATEOAS\n    \n    return resource;\n  }\n\n  \n  //HATEOAS\n  \n  @PostMapping(\"/users\")\n  public ResponseEntity<Object> createUser(@Valid @RequestBody User user) {\n    User savedUser = service.save(user);\n    // CREATED\n    // /user/{id}     savedUser.getId()\n    \n    URI location = ServletUriComponentsBuilder\n      .fromCurrentRequest()\n      .path(\"/{id}\")\n      .buildAndExpand(savedUser.getId()).toUri();\n    \n    return ResponseEntity.created(location).build();\n    \n  }\n\n```\n\n###  Step 17 - Overview of Advanced RESTful Service Features\n- Step 18 - Internationalization for RESTful Services\n- Step 19 - Content Negotiation - Implementing Support for XML\n- Step 20 - Configuring Auto Generation of Swagger Documentation\n- Step 21 - Introduction to Swagger Documentation Format\n- Step 22 - Enhancing Swagger Documentation with Custom Annotations\n- Step 23 - Monitoring APIs with Spring Boot Actuator\n- Step 24 - Implementing Static Filtering for RESTful Service\n- Step 25 - Implementing Dynamic Filtering for RESTful Service\n- Step 26 - Versioning RESTful Services - Basic Approach with URIs\n- Step 27 - Versioning RESTful Services - Header and Content Negotiation Approach\n- Step 28 - Implementing Basic Authentication with Spring Security\n\n###  Step 18 - Internationalization for RESTful Services\n\n##### /src/main/java/com/in28minutes/rest/webservices/restfulwebservices/RestfulWebServicesApplication.java Modified\nNew Lines\n```\nimport java.util.Locale;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.support.ResourceBundleMessageSource;\nimport org.springframework.web.servlet.LocaleResolver;\nimport org.springframework.web.servlet.i18n.SessionLocaleResolver;\n  \n  @Bean\n  public LocaleResolver localeResolver() {\n    SessionLocaleResolver localeResolver = new SessionLocaleResolver();\n    localeResolver.setDefaultLocale(Locale.US);\n    return localeResolver;\n  }\n\n  @Bean\n  public ResourceBundleMessageSource messageSource() {\n    ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();\n    messageSource.setBasename(\"messages\");\n    return messageSource;\n  }\n\n```\n\n##### /src/main/java/com/in28minutes/rest/webservices/restfulwebservices/helloworld/HelloWorldController.java Modified\nNew Lines\n```\nimport java.util.Locale;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.context.MessageSource;\nimport org.springframework.web.bind.annotation.RequestHeader;\n\n@Autowired\nprivate MessageSource messageSource; \n\n@GetMapping(path = \"/hello-world-internationalized\")\npublic String helloWorldInternationalized(\n    @RequestHeader(name=\"Accept-Language\", required=false) Locale locale) {\n  return messageSource.getMessage(\"good.morning.message\", null, locale);\n}\n```\n---\n\n##### /src/main/resources/messages.properties New\n\n```properties\ngood.morning.message=Good Morning\n```\n---\n\n##### /src/main/resources/messages_fr.properties New\n\n```properties\ngood.morning.message=Bonjour\n```\n---\n\n##### /src/main/resources/messages_nl.properties New\n\n```properties\ngood.morning.message=Goede Morgen\n```\n---\n\n### Step 18 Part 2 - Simplifying Internationalization for RESTful Services\n\n#### Use AcceptHeaderLocaleResolver\n\n```\n@SpringBootApplication\npublic class RestfulWebServicesApplication {\n\n  ....\n\n  @Bean\n  public LocaleResolver localeResolver() {\n    AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();\n    localeResolver.setDefaultLocale(Locale.US);\n    return localeResolver;\n  }\n```\n\n##### /src/main/java/com/in28minutes/rest/webservices/restfulwebservices/helloworld/HelloWorldController.java\n```\n@GetMapping(path = \"/hello-world-internationalized\")\n  public String helloWorldInternationalized() {\n    return messageSource.getMessage(\"good.morning.message\", null, \n                  LocaleContextHolder.getLocale());\n  }\n```\n\n#### Use MessageSource configuration from application.properties\n\n```application.properties\nspring.messages.basename=messages\n\n```\n\n###  Step 19 - Content Negotiation - Implementing Support for XML\n\n##### /pom.xml Modified\n\nNew Lines\n```\n    <dependency>\n      <groupId>com.fasterxml.jackson.dataformat</groupId>\n      <artifactId>jackson-dataformat-xml</artifactId>\n    </dependency>\n\n```\n###  Step 20 - Configuring Auto Generation of Swagger Documentation\n###  Step 21 - Introduction to Swagger Documentation Format\n###  Step 22 - Enhancing Swagger Documentation with Custom Annotations\n\n##### /pom.xml Modified\nNew Lines\n```\n    \n    <dependency>\n      <groupId>io.springfox</groupId>\n      <artifactId>springfox-swagger2</artifactId>\n      <version>2.4.0</version>\n    </dependency>\n\n    <dependency>\n      <groupId>io.springfox</groupId>\n      <artifactId>springfox-swagger-ui</artifactId>\n      <version>2.4.0</version>\n    </dependency>\n```\n\n##### /src/main/java/com/in28minutes/rest/webservices/restfulwebservices/SwaggerConfig.java New\n\n```java\npackage com.in28minutes.rest.webservices.restfulwebservices;\n\nimport java.util.Arrays;\nimport java.util.HashSet;\nimport java.util.Set;\n\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\n\nimport springfox.documentation.service.ApiInfo;\nimport springfox.documentation.service.Contact;\nimport springfox.documentation.spi.DocumentationType;\nimport springfox.documentation.spring.web.plugins.Docket;\nimport springfox.documentation.swagger2.annotations.EnableSwagger2;\n\n@Configuration\n@EnableSwagger2\npublic class SwaggerConfig {\n\n  public static final Contact DEFAULT_CONTACT = new Contact(\n      \"Ranga Karanam\", \"http://www.in28minutes.com\", \"in28minutes@gmail.com\");\n  \n  public static final ApiInfo DEFAULT_API_INFO = new ApiInfo(\n      \"Awesome API Title\", \"Awesome API Description\", \"1.0\",\n      \"urn:tos\", DEFAULT_CONTACT, \n      \"Apache 2.0\", \"http://www.apache.org/licenses/LICENSE-2.0\");\n\n  private static final Set<String> DEFAULT_PRODUCES_AND_CONSUMES = \n      new HashSet<String>(Arrays.asList(\"application/json\",\n          \"application/xml\"));\n\n  @Bean\n  public Docket api() {\n    return new Docket(DocumentationType.SWAGGER_2)\n        .apiInfo(DEFAULT_API_INFO)\n        .produces(DEFAULT_PRODUCES_AND_CONSUMES)\n        .consumes(DEFAULT_PRODUCES_AND_CONSUMES);\n  }\n}\n```\n---\n\n##### /src/main/java/com/in28minutes/rest/webservices/restfulwebservices/UserApiDocumentationConfig.java New\n\n```java\npackage com.in28minutes.rest.webservices.restfulwebservices;\n\nimport io.swagger.annotations.Contact;\nimport io.swagger.annotations.ExternalDocs;\nimport io.swagger.annotations.Info;\nimport io.swagger.annotations.License;\nimport io.swagger.annotations.SwaggerDefinition;\n\n@SwaggerDefinition(\n        info = @Info(\n                description = \"Awesome Resources\",\n                version = \"V12.0.12\",\n                title = \"Awesome Resource API\",\n                contact = @Contact(\n                   name = \"Ranga Karanam\", \n                   email = \"ranga.karanam@in28minutes.com\", \n                   url = \"http://www.in28minutes.com\"\n                ),\n                license = @License(\n                   name = \"Apache 2.0\", \n                   url = \"http://www.apache.org/licenses/LICENSE-2.0\"\n                )\n        ),\n        consumes = {\"application/json\", \"application/xml\"},\n        produces = {\"application/json\", \"application/xml\"},\n        schemes = {SwaggerDefinition.Scheme.HTTP, SwaggerDefinition.Scheme.HTTPS},\n        externalDocs = @ExternalDocs(value = \"Read This For Sure\", url = \"http://in28minutes.com\")\n)\npublic interface UserApiDocumentationConfig {\n\n}\n```\n---\n\n##### /src/main/java/com/in28minutes/rest/webservices/restfulwebservices/user/User.java Modified\n```java\n\n\n@ApiModel(description=\"All details about the user. \")\npublic class User {\n\n  private Integer id;\n\n  @Size(min=2, message=\"Name should have atleast 2 characters\")\n  @ApiModelProperty(notes=\"Name should have atleast 2 characters\")\n  private String name;\n\n  @Past\n  @ApiModelProperty(notes=\"Birth date should be in the past\")\n  private Date birthDate;\n\n```\n---\n\n##### /src/main/java/com/in28minutes/rest/webservices/restfulwebservices/user/UserResource.java Modified\n\n```java\n  @GetMapping(\"/users/{id}\")\n  public Resource<User> retrieveUser(@PathVariable int id) {\n    User user = service.findOne(id);\n    \n    if(user==null)\n      throw new UserNotFoundException(\"id-\"+ id);\n    \n    \n    //\"all-users\", SERVER_PATH + \"/users\"\n    //retrieveAllUsers\n    Resource<User> resource = new Resource<User>(user);\n    \n    ControllerLinkBuilder linkTo = \n        linkTo(methodOn(this.getClass()).retrieveAllUsers());\n    \n    resource.add(linkTo.withRel(\"all-users\"));\n    \n    //HATEOAS\n    \n    return resource;\n  }\n\n```\n###  Step 23 - Monitoring APIs with Spring Boot Actuator\n##### /pom.xml Modified\nNew Lines\n```\n    <dependency>\n      <groupId>org.springframework.boot</groupId>\n      <artifactId>spring-boot-starter-actuator</artifactId>\n    </dependency>\n\n    <dependency>\n      <groupId>org.springframework.data</groupId>\n      <artifactId>spring-data-rest-hal-browser</artifactId>\n    </dependency>\n```\n\n##### application.properties Modified\n```\nmanagement.endpoints.web.exposure.include=*\n```\n\n###  Step 24 - Implementing Static Filtering for RESTful Service\n###  Step 25 - Implementing Dynamic Filtering for RESTful Service\n\n##### /src/main/java/com/in28minutes/rest/webservices/restfulwebservices/UserApiDocumentationConfig.java Deleted\n\n##### /src/main/java/com/in28minutes/rest/webservices/restfulwebservices/filtering/FilteringController.java New\n\n```java\npackage com.in28minutes.rest.webservices.restfulwebservices.filtering;\n\nimport java.util.Arrays;\nimport java.util.List;\n\nimport org.springframework.http.converter.json.MappingJacksonValue;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.RestController;\n\nimport com.fasterxml.jackson.databind.ser.FilterProvider;\nimport com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;\nimport com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;\n\n@RestController\npublic class FilteringController {\n\n  // field1,field2\n  @GetMapping(\"/filtering\")\n  public MappingJacksonValue retrieveSomeBean() {\n    SomeBean someBean = new SomeBean(\"value1\", \"value2\", \"value3\");\n\n    SimpleBeanPropertyFilter filter = SimpleBeanPropertyFilter.filterOutAllExcept(\"field1\", \"field2\");\n\n    FilterProvider filters = new SimpleFilterProvider().addFilter(\"SomeBeanFilter\", filter);\n\n    MappingJacksonValue mapping = new MappingJacksonValue(someBean);\n\n    mapping.setFilters(filters);\n\n    return mapping;\n  }\n\n  // field2, field3\n  @GetMapping(\"/filtering-list\")\n  public MappingJacksonValue retrieveListOfSomeBeans() {\n    List<SomeBean> list = Arrays.asList(new SomeBean(\"value1\", \"value2\", \"value3\"),\n        new SomeBean(\"value12\", \"value22\", \"value32\"));\n\n    SimpleBeanPropertyFilter filter = SimpleBeanPropertyFilter.filterOutAllExcept(\"field2\", \"field3\");\n\n    FilterProvider filters = new SimpleFilterProvider().addFilter(\"SomeBeanFilter\", filter);\n\n    MappingJacksonValue mapping = new MappingJacksonValue(list);\n\n    mapping.setFilters(filters);\n\n    return mapping;\n  }\n\n}\n```\n---\n\n##### /src/main/java/com/in28minutes/rest/webservices/restfulwebservices/filtering/SomeBean.java New\n\n```java\npackage com.in28minutes.rest.webservices.restfulwebservices.filtering;\n\nimport com.fasterxml.jackson.annotation.JsonFilter;\n\n@JsonFilter(\"SomeBeanFilter\")\npublic class SomeBean {\n  \n  private String field1;\n  \n  private String field2;\n  \n  private String field3;\n\n  public SomeBean(String field1, String field2, String field3) {\n    super();\n    this.field1 = field1;\n    this.field2 = field2;\n    this.field3 = field3;\n  }\n\n  public String getField1() {\n    return field1;\n  }\n\n  public void setField1(String field1) {\n    this.field1 = field1;\n  }\n\n  public String getField2() {\n    return field2;\n  }\n\n  public void setField2(String field2) {\n    this.field2 = field2;\n  }\n\n  public String getField3() {\n    return field3;\n  }\n\n  public void setField3(String field3) {\n    this.field3 = field3;\n  }\n\n}\n```\n\n###  Step 26 - Versioning RESTful Services - Basic Approach with URIs\n###  Step 27 - Versioning RESTful Services - Header and Content Negotiation Approach\n\n##### /src/main/java/com/in28minutes/rest/webservices/restfulwebservices/versioning/Name.java New\n\n```java\npackage com.in28minutes.rest.webservices.restfulwebservices.versioning;\n\npublic class Name {\n  private String firstName;\n  private String lastName;\n\n  public Name() {\n  }\n\n  public Name(String firstName, String lastName) {\n    super();\n    this.firstName = firstName;\n    this.lastName = lastName;\n  }\n\n  public String getFirstName() {\n    return firstName;\n  }\n\n  public void setFirstName(String firstName) {\n    this.firstName = firstName;\n  }\n\n  public String getLastName() {\n    return lastName;\n  }\n\n  public void setLastName(String lastName) {\n    this.lastName = lastName;\n  }\n\n}\n```\n---\n\n##### /src/main/java/com/in28minutes/rest/webservices/restfulwebservices/versioning/PersonV1.java New\n\n```java\npackage com.in28minutes.rest.webservices.restfulwebservices.versioning;\n\npublic class PersonV1 {\n  private String name;\n\n  public PersonV1() {\n    super();\n  }\n  \n  public PersonV1(String name) {\n    super();\n    this.name = name;\n  }\n\n  public String getName() {\n    return name;\n  }\n\n  public void setName(String name) {\n    this.name = name;\n  }\n\n  \n}\n```\n---\n\n##### /src/main/java/com/in28minutes/rest/webservices/restfulwebservices/versioning/PersonV2.java New\n\n```java\npackage com.in28minutes.rest.webservices.restfulwebservices.versioning;\n\npublic class PersonV2 {\n  private Name name;\n\n  public PersonV2() {\n    super();\n  }\n\n  public PersonV2(Name name) {\n    super();\n    this.name = name;\n  }\n\n  public Name getName() {\n    return name;\n  }\n\n  public void setName(Name name) {\n    this.name = name;\n  }\n\n}\n```\n---\n\n##### /src/main/java/com/in28minutes/rest/webservices/restfulwebservices/versioning/PersonVersioningController.java New\n\n```java\npackage com.in28minutes.rest.webservices.restfulwebservices.versioning;\n\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.RestController;\n\n@RestController\npublic class PersonVersioningController {\n\n  @GetMapping(\"v1/person\")\n  public PersonV1 personV1() {\n    return new PersonV1(\"Bob Charlie\");\n  }\n\n  @GetMapping(\"v2/person\")\n  public PersonV2 personV2() {\n    return new PersonV2(new Name(\"Bob\", \"Charlie\"));\n  }\n\n  @GetMapping(value = \"/person/param\", params = \"version=1\")\n  public PersonV1 paramV1() {\n    return new PersonV1(\"Bob Charlie\");\n  }\n\n  @GetMapping(value = \"/person/param\", params = \"version=2\")\n  public PersonV2 paramV2() {\n    return new PersonV2(new Name(\"Bob\", \"Charlie\"));\n  }\n\n  @GetMapping(value = \"/person/header\", headers = \"X-API-VERSION=1\")\n  public PersonV1 headerV1() {\n    return new PersonV1(\"Bob Charlie\");\n  }\n\n  @GetMapping(value = \"/person/header\", headers = \"X-API-VERSION=2\")\n  public PersonV2 headerV2() {\n    return new PersonV2(new Name(\"Bob\", \"Charlie\"));\n  }\n\n  @GetMapping(value = \"/person/produces\", produces = \"application/vnd.company.app-v1+json\")\n  public PersonV1 producesV1() {\n    return new PersonV1(\"Bob Charlie\");\n  }\n\n  @GetMapping(value = \"/person/produces\", produces = \"application/vnd.company.app-v2+json\")\n  public PersonV2 producesV2() {\n    return new PersonV2(new Name(\"Bob\", \"Charlie\"));\n  }\n\n}\n```\n---\n\n###  Step 28 - Implementing Basic Authentication with Spring Security\n\n##### /pom.xml Modified\nNew Lines\n```\n    <dependency>\n      <groupId>org.springframework.boot</groupId>\n      <artifactId>spring-boot-starter-security</artifactId>\n    </dependency>\n\n```\n##### /src/main/resources/application.properties Modified\nNew Lines\n```\nspring.security.filter.dispatcher-types=request\nspring.security.user.name=username\nspring.security.user.password=password\n```\n\n###  Step 29 - Overview of Connecting RESTful Service to JPA\n- Step 30 - Creating User Entity and some test data\n- Step 31 - Updating GET methods on User Resource to use JPA\n- Step 32 - Updating POST and DELETE methods on User Resource to use JPA\n- Step 33 - Creating Post Entity and Many to One Relationship with User Entity\n- Step 34 - Implementing a GET service to retrieve all Posts of a User\n- Step 35 - Implementing a POST service to create a Post for a User\n\n###  Step 30 - Creating User Entity and some test data\n###  Step 31 - Updating GET methods on User Resource to use JPA\n###  Step 32 - Updating POST and DELETE methods on User Resource to use JPA\n\n##### /src/main/java/com/in28minutes/rest/webservices/restfulwebservices/user/User.java Modified\nNew Lines\n\n```java\n@ApiModel(description=\"All details about the user. \")\n@Entity\npublic class User {\n\n  @Id\n  @GeneratedValue\n  private Integer id;\n\n```\n---\n\n##### /src/main/java/com/in28minutes/rest/webservices/restfulwebservices/user/UserJPAResource.java New\n\n```java\npackage com.in28minutes.rest.webservices.restfulwebservices.user;\n\nimport static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;\nimport static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;\n\nimport java.net.URI;\nimport java.util.List;\nimport java.util.Optional;\n\nimport javax.validation.Valid;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.hateoas.Resource;\nimport org.springframework.hateoas.mvc.ControllerLinkBuilder;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.web.bind.annotation.DeleteMapping;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.PostMapping;\nimport org.springframework.web.bind.annotation.RequestBody;\nimport org.springframework.web.bind.annotation.RestController;\nimport org.springframework.web.servlet.support.ServletUriComponentsBuilder;\n\n@RestController\npublic class UserJPAResource {\n\n  @Autowired\n  private UserDaoService service;\n  \n  @Autowired\n  private UserRepository userRepository;\n\n  @GetMapping(\"/jpa/users\")\n  public List<User> retrieveAllUsers() {\n    return userRepository.findAll();\n  }\n\n  @GetMapping(\"/jpa/users/{id}\")\n  public Resource<User> retrieveUser(@PathVariable int id) {\n    Optional<User> user = userRepository.findById(id);\n    \n    if(!user.isPresent())\n      throw new UserNotFoundException(\"id-\"+ id);\n    \n    //\"all-users\", SERVER_PATH + \"/users\"\n    //retrieveAllUsers\n    Resource<User> resource = new Resource<User>(user.get());\n    \n    ControllerLinkBuilder linkTo = \n        linkTo(methodOn(this.getClass()).retrieveAllUsers());\n    \n    resource.add(linkTo.withRel(\"all-users\"));\n    \n    //HATEOAS\n    \n    return resource;\n  }\n\n  @DeleteMapping(\"/jpa/users/{id}\")\n  public void deleteUser(@PathVariable int id) {\n    User user = service.deleteById(id);\n    \n    if(user==null)\n      throw new UserNotFoundException(\"id-\"+ id);   \n  }\n\n  //\n  // input - details of user\n  // output - CREATED & Return the created URI\n  \n  //HATEOAS\n  \n  @PostMapping(\"/jpa/users\")\n  public ResponseEntity<Object> createUser(@Valid @RequestBody User user) {\n    User savedUser = service.save(user);\n    \n    URI location = ServletUriComponentsBuilder\n      .fromCurrentRequest()\n      .path(\"/{id}\")\n      .buildAndExpand(savedUser.getId()).toUri();\n    \n    return ResponseEntity.created(location).build();\n    \n  }\n}\n```\n---\n\n##### /src/main/java/com/in28minutes/rest/webservices/restfulwebservices/user/UserRepository.java New\n\n```java\npackage com.in28minutes.rest.webservices.restfulwebservices.user;\n\nimport org.springframework.data.jpa.repository.JpaRepository;\nimport org.springframework.stereotype.Repository;\n\n@Repository\npublic interface UserRepository extends JpaRepository<User, Integer>{\n\n}\n```\n---\n\n##### /src/main/resources/application.properties Modified\nNew Lines\n```\nmanagement.endpoints.web.exposure.include=*\nspring.jpa.show-sql=true\nspring.datasource.url=jdbc:h2:mem:testdb\nspring.data.jpa.repositories.bootstrap-mode=default\nspring.h2.console.enabled=true\n```\n##### /src/main/resources/data.sql New\n\n```\ninsert into user values(1, sysdate(), 'AB');\ninsert into user values(2, sysdate(), 'Jill');\ninsert into user values(3, sysdate(), 'Jam');\n```\n\n###  Step 33 - Creating Post Entity and Many to One Relationship with User Entity\n###  Step 34 - Implementing a GET service to retrieve all Posts of a User\n###  Step 35 - Implementing a POST service to create a Post for a User\n\n\n##### /src/main/java/com/in28minutes/rest/webservices/restfulwebservices/user/Post.java New\n\n```java\npackage com.in28minutes.rest.webservices.restfulwebservices.user;\n\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.Id;\nimport javax.persistence.ManyToOne;\n\nimport com.fasterxml.jackson.annotation.JsonIgnore;\n\n@Entity\npublic class Post {\n  \n  @Id\n  @GeneratedValue\n  private Integer id;\n  private String description;\n  \n  @ManyToOne(fetch=FetchType.LAZY)\n  @JsonIgnore\n  private User user;\n  \n  public Integer getId() {\n    return id;\n  }\n\n  public void setId(Integer id) {\n    this.id = id;\n  }\n\n  public String getDescription() {\n    return description;\n  }\n\n  public void setDescription(String description) {\n    this.description = description;\n  }\n\n  public User getUser() {\n    return user;\n  }\n\n  public void setUser(User user) {\n    this.user = user;\n  }\n\n  @Override\n  public String toString() {\n    return String.format(\"Post [id=%s, description=%s]\", id, description);\n  }\n  \n}\n```\n---\n\n##### /src/main/java/com/in28minutes/rest/webservices/restfulwebservices/user/PostRepository.java New\n\n```java\npackage com.in28minutes.rest.webservices.restfulwebservices.user;\n\nimport org.springframework.data.jpa.repository.JpaRepository;\nimport org.springframework.stereotype.Repository;\n\n@Repository\npublic interface PostRepository extends JpaRepository<Post, Integer>{\n\n}\n```\n---\n\n##### /src/main/java/com/in28minutes/rest/webservices/restfulwebservices/user/User.java Modified\n```java\n  \n  @OneToMany(mappedBy=\"user\")\n  private List<Post> posts;\n\n```\n---\n\n##### /src/main/java/com/in28minutes/rest/webservices/restfulwebservices/user/UserJPAResource.java Modified\n\n\n```java\n\n@RestController\npublic class UserJPAResource {\n\n  @Autowired\n  private UserRepository userRepository;\n  \n  @Autowired\n  private PostRepository postRepository;\n\n  @GetMapping(\"/jpa/users\")\n  public List<User> retrieveAllUsers() {\n    return userRepository.findAll();\n  }\n\n  @GetMapping(\"/jpa/users/{id}\")\n  public Resource<User> retrieveUser(@PathVariable int id) {\n    Optional<User> user = userRepository.findById(id);\n\n    if (!user.isPresent())\n      throw new UserNotFoundException(\"id-\" + id);\n\n    // \"all-users\", SERVER_PATH + \"/users\"\n    // retrieveAllUsers\n    Resource<User> resource = new Resource<User>(user.get());\n\n    ControllerLinkBuilder linkTo = linkTo(methodOn(this.getClass()).retrieveAllUsers());\n\n    resource.add(linkTo.withRel(\"all-users\"));\n\n    // HATEOAS\n\n    return resource;\n  }\n\n  @DeleteMapping(\"/jpa/users/{id}\")\n  public void deleteUser(@PathVariable int id) {\n    userRepository.deleteById(id);\n  }\n\n  //\n  // input - details of user\n  // output - CREATED & Return the created URI\n\n  // HATEOAS\n\n  @PostMapping(\"/jpa/users\")\n  public ResponseEntity<Object> createUser(@Valid @RequestBody User user) {\n    User savedUser = userRepository.save(user);\n\n    URI location = ServletUriComponentsBuilder.fromCurrentRequest().path(\"/{id}\").buildAndExpand(savedUser.getId())\n        .toUri();\n\n    return ResponseEntity.created(location).build();\n\n  }\n  \n  @GetMapping(\"/jpa/users/{id}/posts\")\n  public List<Post> retrieveAllUsers(@PathVariable int id) {\n    Optional<User> userOptional = userRepository.findById(id);\n    \n    if(!userOptional.isPresent()) {\n      throw new UserNotFoundException(\"id-\" + id);\n    }\n    \n    return userOptional.get().getPosts();\n  }\n\n\n  @PostMapping(\"/jpa/users/{id}/posts\")\n  public ResponseEntity<Object> createPost(@PathVariable int id, @RequestBody Post post) {\n    \n    Optional<User> userOptional = userRepository.findById(id);\n    \n    if(!userOptional.isPresent()) {\n      throw new UserNotFoundException(\"id-\" + id);\n    }\n\n    User user = userOptional.get();\n    \n    post.setUser(user);\n    \n    postRepository.save(post);\n    \n    URI location = ServletUriComponentsBuilder.fromCurrentRequest().path(\"/{id}\").buildAndExpand(post.getId())\n        .toUri();\n\n    return ResponseEntity.created(location).build();\n\n  }\n\n}\n```\n---\n\n##### /src/main/resources/data.sql Modified\nNew Lines\n```\ninsert into user values(10001, sysdate(), 'AB');\ninsert into user values(10002, sysdate(), 'Jill');\ninsert into user values(10003, sysdate(), 'Jam');\ninsert into post values(11001, 'My First Post', 10001);\ninsert into post values(11002, 'My Second Post', 10001);\n```\n\n\n##### /src/main/java/com/in28minutes/rest/webservices/restfulwebservices/user/Post.java Deleted\n##### /src/main/java/com/in28minutes/rest/webservices/restfulwebservices/user/PostRepository.java Deleted\n\n\n## Microservices with Spring Cloud\n\nMICROSERVICES\n- REST\n- & Small Well Chosen Deployable Units\n- & Cloud Enabled\n\n### URLs\n\n|     Application       |     URL          |\n| ------------- | ------------- |\n| Limits Service | http://localhost:8080/limits|\n|Spring Cloud Config Server| http://localhost:8888/limits-service/default http://localhost:8888/limits-service/dev|\n|  Currency Converter Service - Direct Call| http://localhost:8100/currency-converter/from/USD/to/INR//usr/local/var/log/rabbitmq/rabbit@localhost.log/usr/local/var/log/rabbitmq/rabbit@localhost.logquantity/10|\n|  Currency Converter Service - Feign| http://localhost:8100/currency-converter-feign/from/EUR/to/INR/quantity/10000|\n| Currency Exchange Service | http://localhost:8000/currency-exchange/from/EUR/to/INR http://localhost:8001/currency-exchange/from/USD/to/INR|\n| Eureka | http://localhost:8761/|\n| Zuul - Currency Exchange & Exchange Services | http://localhost:8765/currency-exchange-service/currency-exchange/from/EUR/to/INR http://localhost:8765/currency-conversion-service/currency-converter-feign/from/USD/to/INR/quantity/10|\n\n### VM Argument\n\n-Dserver.port=8001\n\n### Zipkin Installation\n\nQuick Start Page\n- https://zipkin.io/pages/quickstart\n\nDownloading Zipkin Jar\n- https://search.maven.org/remote_content?g=io.zipkin.java&a=zipkin-server&v=LATEST&c=exec\n\nCommand to run\n```\nRABBIT_URI=amqp://localhost java -jar zipkin-server-2.5.2-exec.jar\n```\n\n\n### Commands\n- mkdir git-configuration-repo\n- cd git-configuration-repo/\n- git init\n- git add -A\n- git commit -m \"first commit\"\n\n### Ports\n\n|     Application       |     Port          |\n| ------------- | ------------- |\n| Limits Service | 8080, 8081, ... |\n| Spring Cloud Config Server | 8888 |\n|  |  |\n| Currency Exchange Service | 8000, 8001, 8002, ..  |\n| Currency Conversion Service | 8100, 8101, 8102, ... |\n| Netflix Eureka Naming Server | 8761 |\n| Netflix Zuul API Gateway Server | 8765 |\n| Zipkin Distributed Tracing Server | 9411 |\n\n\n\n## Step by Step Details\n\n![Image](/images/MicroserviceCommunication.png)\n![Image](/images/Microservices-Chain-Example.png)\n\n\n###  Step 01 - Part 1 - Introduction to Limits Microservice and Spring Cloud Config Server\n\n![Image](/images/SpringCloudConfigServer.png)\n\n### Step 01 - Part 2 - Setting up Limits Microservice\n\nCreating a Spring Project with Spring Initializr is a cake walk. \n\n> Spring Initializr [http://start.spring.io/](http://start.spring.io/){:target=\"_blank\"} is great tool to bootstrap your Spring Boot projects.\n\n![Image](/images/Spring-Initializr-limits-service.png \"Spring Initializr\")   \n\n- Launch Spring Initializr and choose the following\n  - Choose Version 2.3.1.RELEASE or greater\n  - Choose Group as shown in the figure\n  - Choose Artifact as shown in the figure\n  - Choose Dependencies as shown in the figure\n- Click Generate Project.\n- Import the project into Eclipse.\n- If you want to understand all the files that are part of this project, you can go here.\n\n###  Step 02 - Creating a hard coded limits service\n\n###  Step 03 - Enhance limits service to pick up configuration from application properties\n\n\n#### /limits-service/src/main/java/com/in28minutes/microservices/limitsservice/Configuration.java New\n\n```java\npackage com.in28minutes.microservices.limitsservice;\n\nimport org.springframework.boot.context.properties.ConfigurationProperties;\nimport org.springframework.stereotype.Component;\n\n@Component\n@ConfigurationProperties(\"limits-service\")\npublic class Configuration {\n  \n  private int minimum;\n  private int maximum;\n\n  public void setMinimum(int minimum) {\n    this.minimum = minimum;\n  }\n\n  public void setMaximum(int maximum) {\n    this.maximum = maximum;\n  }\n\n  public int getMinimum() {\n    return minimum;\n  }\n\n  public int getMaximum() {\n    return maximum;\n  }\n\n}\n```\n---\n\n#### /limits-service/src/main/java/com/in28minutes/microservices/limitsservice/LimitsConfigurationController.java New\n\n```java\npackage com.in28minutes.microservices.limitsservice;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.RestController;\n\nimport com.in28minutes.microservices.limitsservice.bean.LimitConfiguration;\n\n@RestController\npublic class LimitsConfigurationController {\n\n  @Autowired\n  private Configuration configuration;\n\n  @GetMapping(\"/limits\")\n  public LimitConfiguration retrieveLimitsFromConfigurations() {\n    return new LimitConfiguration(configuration.getMaximum(), \n        configuration.getMinimum());\n  }\n\n}\n```\n---\n\n#### /limits-service/src/main/java/com/in28minutes/microservices/limitsservice/bean/LimitConfiguration.java New\n\n```java\npackage com.in28minutes.microservices.limitsservice.bean;\n\npublic class LimitConfiguration {\n  private int maximum;\n  private int minimum;\n\n  protected LimitConfiguration() {\n\n  }\n\n  public LimitConfiguration(int maximum, int minimum) {\n    super();\n    this.maximum = maximum;\n    this.minimum = minimum;\n  }\n\n  public int getMaximum() {\n    return maximum;\n  }\n\n  public int getMinimum() {\n    return minimum;\n  }\n\n}\n```\n---\n\n#### /limits-service/src/main/resources/application.properties Modified\nNew Lines\n```\nspring.application.name=limits-service\nlimits-service.minimum=9\nlimits-service.maximum=999\n```\n\n###  Step 04 - Setting up Spring Cloud Config Server\nCreating a Spring Project with Spring Initializr is a cake walk. \n\n> Spring Initializr [http://start.spring.io/](http://start.spring.io/){:target=\"_blank\"} is great tool to bootstrap your Spring Boot projects.\n\n![Image](/images/Spring-Initializr-cloud-config-server.png \"Spring Initializr\")   \n\n- Launch Spring Initializr and choose the following\n  - Choose Version 2.3.1.RELEASE or greater\n  - Choose Group as shown in the figure\n  - Choose Artifact as shown in the figure\n  - Choose Dependencies as shown in the figure\n- Click Generate Project.\n- Import the project into Eclipse.\n- If you want to understand all the files that are part of this project, you can go here.\n\n###  Step 05 - Installing Git\n###  Step 06 - Creating Local Git Repository\n###  Step 07 - Connect Spring Cloud Config Server to Local Git Repository\n###  Step 08 - Configuration for Multiple Environments in Git Repository\n\n/git-localconfig-repo/limits-service-dev.properties New\n\n```properties\nlimits-service.minimum=1\nlimits-service.maximum=111\n```\n---\n\n/git-localconfig-repo/limits-service-qa.properties New\n\n```properties\nlimits-service.minimum=2\nlimits-service.maximum=222\n```\n---\n\n/git-localconfig-repo/limits-service.properties New\n\n```properties\nlimits-service.minimum=8\nlimits-service.maximum=888\n```\n---\n\n### /spring-cloud-config-server/src/main/java/com/in28minutes/microservices/springcloudconfigserver/SpringCloudConfigServerApplication.java Modified\n\n```java\npackage com.in28minutes.microservices.springcloudconfigserver;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.cloud.config.server.EnableConfigServer;\n\n@EnableConfigServer\n@SpringBootApplication\npublic class SpringCloudConfigServerApplication {\n\n  public static void main(String[] args) {\n    SpringApplication.run(SpringCloudConfigServerApplication.class, args);\n  }\n}\n```\n---\n\n### /spring-cloud-config-server/src/main/resources/application.properties New\n\n```properties\nspring.application.name=spring-cloud-config-server\nserver.port=8888\nspring.cloud.config.server.git.uri=file:///in28Minutes/git/spring-micro-services/03.microservices/git-localconfig-repo\n```\n---\n\n###  Step 09 - Connect Limits Service to Spring Cloud Config Server\n\n/limits-service/src/main/resources/application.properties Deleted\n\n/limits-service/src/main/resources/bootstrap.properties New\n\n```properties\nspring.application.name=limits-service\nspring.cloud.config.uri=http://localhost:8888\n```\n---\n\n###  Step 10 - Configuring Profiles for Limits Service\n###  Step 11 - A review of Spring Cloud Config Server\n\n/limits-service/src/main/resources/bootstrap.properties Modified\nNew Lines\n```\nspring.profiles.active=qa\n```\n\n###  Step 12 - Introduction to Currency Conversion and Currency Exchange Microservices\n\n![Image](/images/CurrencyConversionMicroserviceDeployment.png)\n![Image](/images/CurrencyExchangeMicroserviceDeployment.png)\n\n###  Step 13 - Setting up Currency Exchange Microservice\n\nCreating a Spring Project with Spring Initializr is a cake walk. \n\n> Spring Initializr [http://start.spring.io/](http://start.spring.io/){:target=\"_blank\"} is great tool to bootstrap your Spring Boot projects.\n\n![Image](/images/Spring-Initializr-currency-exchange-service.png \"Spring Initializr\")   \n\n- Launch Spring Initializr and choose the following\n  - Choose Version 2.3.1.RELEASE or greater\n  - Choose Group as shown in the figure\n  - Choose Artifact as shown in the figure\n  - Choose Dependencies as shown in the figure\n- Click Generate Project.\n- Import the project into Eclipse.\n- If you want to understand all the files that are part of this project, you can go here.\n\n###  Step 14 - Create a simple hard coded currency exchange service\n###  Step 15 - Setting up Dynamic Port in the the Response\n###  Step 16 - Configure JPA and Initialized Data\n###  Step 17 - Create a JPA Repository\n\n/currency-exchange-service/pom.xml New\n\n```xml\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n  xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n\n  <groupId>com.in28minutes.microservices</groupId>\n  <artifactId>currency-exchange-service</artifactId>\n  <version>0.0.1-SNAPSHOT</version>\n  <packaging>jar</packaging>\n\n  <name>currency-exchange-service</name>\n  <description>Demo project for Spring Boot</description>\n\n  <parent>\n    <groupId>org.springframework.boot</groupId>\n    <artifactId>spring-boot-starter-parent</artifactId>\n    <version>2.3.1.RELEASE</version>\n    <relativePath/> <!-- lookup parent from repository -->\n  </parent>\n\n  <properties>\n    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>\n    <java.version>1.8</java.version>\n<maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>\n    <spring-cloud.version>Finchley.M8</spring-cloud.version>\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.springframework.boot</groupId>\n      <artifactId>spring-boot-starter-actuator</artifactId>\n    </dependency>\n    <dependency>\n      <groupId>org.springframework.cloud</groupId>\n      <artifactId>spring-cloud-starter-config</artifactId>\n    </dependency>\n    <dependency>\n      <groupId>org.springframework.boot</groupId>\n      <artifactId>spring-boot-starter-web</artifactId>\n    </dependency>\n    <dependency>\n      <groupId>org.springframework.boot</groupId>\n      <artifactId>spring-boot-starter-data-jpa</artifactId>\n    </dependency>\n    <dependency>\n      <groupId>com.h2database</groupId>\n      <artifactId>h2</artifactId>\n    </dependency>\n\n\n    <dependency>\n      <groupId>org.springframework.boot</groupId>\n      <artifactId>spring-boot-devtools</artifactId>\n      <scope>runtime</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.springframework.boot</groupId>\n      <artifactId>spring-boot-starter-test</artifactId>\n      <scope>test</scope>\n    </dependency>\n  </dependencies>\n\n  <dependencyManagement>\n    <dependencies>\n      <dependency>\n        <groupId>org.springframework.cloud</groupId>\n        <artifactId>spring-cloud-dependencies</artifactId>\n        <version>${spring-cloud.version}</version>\n        <type>pom</type>\n        <scope>import</scope>\n      </dependency>\n    </dependencies>\n  </dependencyManagement>\n\n  <build>\n    <plugins>\n      <plugin>\n        <groupId>org.springframework.boot</groupId>\n        <artifactId>spring-boot-maven-plugin</artifactId>\n      </plugin>\n    </plugins>\n  </build>\n\n\n\n</project>\n```\n---\n\n/currency-exchange-service/src/main/java/com/in28minutes/microservices/currencyexchangeservice/CurrencyExchangeController.java New\n\n```java\npackage com.in28minutes.microservices.currencyexchangeservice;\n\nimport java.math.BigDecimal;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.core.env.Environment;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.RestController;\n\n@RestController\npublic class CurrencyExchangeController {\n  \n  @Autowired\n  private Environment environment;\n  \n  @Autowired\n  private ExchangeValueRepository repository;\n  \n  @GetMapping(\"/currency-exchange/from/{from}/to/{to}\")\n  public ExchangeValue retrieveExchangeValue\n    (@PathVariable String from, @PathVariable String to){\n    \n    ExchangeValue exchangeValue = \n        repository.findByFromAndTo(from, to);\n    \n    exchangeValue.setPort(\n        Integer.parseInt(environment.getProperty(\"local.server.port\")));\n    \n    return exchangeValue;\n  }\n}\n```\n---\n\n/currency-exchange-service/src/main/java/com/in28minutes/microservices/currencyexchangeservice/CurrencyExchangeServiceApplication.java New\n\n```java\npackage com.in28minutes.microservices.currencyexchangeservice;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\n@SpringBootApplication\npublic class CurrencyExchangeServiceApplication {\n\n  public static void main(String[] args) {\n    SpringApplication.run(CurrencyExchangeServiceApplication.class, args);\n  }\n}\n```\n---\n\n/currency-exchange-service/src/main/java/com/in28minutes/microservices/currencyexchangeservice/ExchangeValue.java New\n\n```java\npackage com.in28minutes.microservices.currencyexchangeservice;\n\nimport java.math.BigDecimal;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\n\n@Entity\npublic class ExchangeValue {\n  \n  @Id\n  private Long id;\n  \n  @Column(name=\"currency_from\")\n  private String from;\n  \n  @Column(name=\"currency_to\")\n  private String to;\n  \n  private BigDecimal conversionMultiple;\n  private int port;\n  \n  public ExchangeValue() {\n    \n  }\n  \n\n  public ExchangeValue(Long id, String from, String to, BigDecimal conversionMultiple) {\n    super();\n    this.id = id;\n    this.from = from;\n    this.to = to;\n    this.conversionMultiple = conversionMultiple;\n  }\n\n  public Long getId() {\n    return id;\n  }\n\n  public String getFrom() {\n    return from;\n  }\n\n  public String getTo() {\n    return to;\n  }\n\n  public BigDecimal getConversionMultiple() {\n    return conversionMultiple;\n  }\n  \n  public int getPort() {\n    return port;\n  }\n\n  public void setPort(int port) {\n    this.port = port;\n  }\n\n}\n```\n---\n\n/currency-exchange-service/src/main/java/com/in28minutes/microservices/currencyexchangeservice/ExchangeValueRepository.java New\n\n```java\npackage com.in28minutes.microservices.currencyexchangeservice;\n\nimport org.springframework.data.jpa.repository.JpaRepository;\n\npublic interface ExchangeValueRepository extends \n    JpaRepository<ExchangeValue, Long>{\n  ExchangeValue findByFromAndTo(String from, String to);\n}\n```\n---\n\n/currency-exchange-service/src/main/resources/application.properties New\n\n```properties\nspring.application.name=currency-exchange-service\nserver.port=8000\n\nspring.jpa.show-sql=true\nspring.datasource.url=jdbc:h2:mem:testdb\nspring.data.jpa.repositories.bootstrap-mode=default\nspring.h2.console.enabled=true\n```\n---\n\n/currency-exchange-service/src/main/resources/data.sql New\n\n```\ninsert into exchange_value(id,currency_from,currency_to,conversion_multiple,port)\nvalues(10001,'USD','INR',65,0);\ninsert into exchange_value(id,currency_from,currency_to,conversion_multiple,port)\nvalues(10002,'EUR','INR',75,0);\ninsert into exchange_value(id,currency_from,currency_to,conversion_multiple,port)\nvalues(10003,'AUD','INR',25,0);\n```\n---\n\n/currency-exchange-service/src/test/java/com/in28minutes/microservices/currencyexchangeservice/CurrencyExchangeServiceApplicationTests.java New\n\n```java\npackage com.in28minutes.microservices.currencyexchangeservice;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.springframework.boot.test.context.SpringBootTest;\nimport org.springframework.test.context.junit4.SpringRunner;\n\n@RunWith(SpringRunner.class)\n@SpringBootTest\npublic class CurrencyExchangeServiceApplicationTests {\n\n  @Test\n  public void contextLoads() {\n  }\n\n}\n```\n---\n\n###  Step 18 - Setting up Currency Conversion Microservice\n\nCreating a Spring Project with Spring Initializr is a cake walk. \n\n> Spring Initializr [http://start.spring.io/](http://start.spring.io/){:target=\"_blank\"} is great tool to bootstrap your Spring Boot projects.\n\n![Image](/images/Spring-Initializr-currency-conversion-service.png \"Spring Initializr\")   \n\n- Launch Spring Initializr and choose the following\n  - Choose Version 2.3.1.RELEASE or greater\n  - Choose Group as shown in the figure\n  - Choose Artifact as shown in the figure\n  - Choose Dependencies as shown in the figure\n- Click Generate Project.\n- Import the project into Eclipse.\n- If you want to understand all the files that are part of this project, you can go here.\n\n###  Step 19 - Creating a service for currency conversion\n###  Step 20 - Invoking Currency Exchange Microservice from Currency Conversion Microservice\n\n/currency-conversion-service/pom.xml New\n\n```xml\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n  xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n\n  <groupId>com.in28minutes.microservices</groupId>\n  <artifactId>currency-conversion-service</artifactId>\n  <version>0.0.1-SNAPSHOT</version>\n  <packaging>jar</packaging>\n\n  <name>currency-conversion-service</name>\n  <description>Demo project for Spring Boot</description>\n\n  <parent>\n    <groupId>org.springframework.boot</groupId>\n    <artifactId>spring-boot-starter-parent</artifactId>\n    <version>2.3.1.RELEASE</version>\n    <relativePath/> <!-- lookup parent from repository -->\n  </parent>\n\n  <properties>\n    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>\n    <java.version>1.8</java.version>\n<maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>\n    <spring-cloud.version>Finchley.M8</spring-cloud.version>\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.springframework.boot</groupId>\n      <artifactId>spring-boot-starter-actuator</artifactId>\n    </dependency>\n    <dependency>\n      <groupId>org.springframework.cloud</groupId>\n      <artifactId>spring-cloud-starter-config</artifactId>\n    </dependency>\n    <dependency>\n      <groupId>org.springframework.boot</groupId>\n      <artifactId>spring-boot-starter-web</artifactId>\n    </dependency>\n\n    <dependency>\n      <groupId>org.springframework.boot</groupId>\n      <artifactId>spring-boot-devtools</artifactId>\n      <scope>runtime</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.springframework.boot</groupId>\n      <artifactId>spring-boot-starter-test</artifactId>\n      <scope>test</scope>\n    </dependency>\n  </dependencies>\n\n  <dependencyManagement>\n    <dependencies>\n      <dependency>\n        <groupId>org.springframework.cloud</groupId>\n        <artifactId>spring-cloud-dependencies</artifactId>\n        <version>${spring-cloud.version}</version>\n        <type>pom</type>\n        <scope>import</scope>\n      </dependency>\n    </dependencies>\n  </dependencyManagement>\n\n  <build>\n    <plugins>\n      <plugin>\n        <groupId>org.springframework.boot</groupId>\n        <artifactId>spring-boot-maven-plugin</artifactId>\n      </plugin>\n    </plugins>\n  </build>\n\n\n\n</project>\n```\n---\n\n/currency-conversion-service/src/main/java/com/in28minutes/microservices/currencyconversionservice/CurrencyConversionBean.java New\n\n```java\npackage com.in28minutes.microservices.currencyconversionservice;\n\nimport java.math.BigDecimal;\n\npublic class CurrencyConversionBean {\n  private Long id;\n  private String from;\n  private String to;\n  private BigDecimal conversionMultiple;\n  private BigDecimal quantity;\n  private BigDecimal totalCalculatedAmount;\n  private int port;\n\n  public CurrencyConversionBean() {\n\n  }\n\n  public CurrencyConversionBean(Long id, String from, String to, BigDecimal conversionMultiple, BigDecimal quantity,\n      BigDecimal totalCalculatedAmount, int port) {\n    super();\n    this.id = id;\n    this.from = from;\n    this.to = to;\n    this.conversionMultiple = conversionMultiple;\n    this.quantity = quantity;\n    this.totalCalculatedAmount = totalCalculatedAmount;\n    this.port = port;\n  }\n\n  public Long getId() {\n    return id;\n  }\n\n  public void setId(Long id) {\n    this.id = id;\n  }\n\n  public String getFrom() {\n    return from;\n  }\n\n  public void setFrom(String from) {\n    this.from = from;\n  }\n\n  public String getTo() {\n    return to;\n  }\n\n  public void setTo(String to) {\n    this.to = to;\n  }\n\n  public BigDecimal getConversionMultiple() {\n    return conversionMultiple;\n  }\n\n  public void setConversionMultiple(BigDecimal conversionMultiple) {\n    this.conversionMultiple = conversionMultiple;\n  }\n\n  public BigDecimal getQuantity() {\n    return quantity;\n  }\n\n  public void setQuantity(BigDecimal quantity) {\n    this.quantity = quantity;\n  }\n\n  public BigDecimal getTotalCalculatedAmount() {\n    return totalCalculatedAmount;\n  }\n\n  public void setTotalCalculatedAmount(BigDecimal totalCalculatedAmount) {\n    this.totalCalculatedAmount = totalCalculatedAmount;\n  }\n\n  public int getPort() {\n    return port;\n  }\n\n  public void setPort(int port) {\n    this.port = port;\n  }\n\n}\n```\n---\n\n/currency-conversion-service/src/main/java/com/in28minutes/microservices/currencyconversionservice/CurrencyConversionController.java New\n\n```java\npackage com.in28minutes.microservices.currencyconversionservice;\n\nimport java.math.BigDecimal;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.RestController;\nimport org.springframework.web.client.RestTemplate;\n\n@RestController\npublic class CurrencyConversionController {\n  \n  @GetMapping(\"/currency-converter/from/{from}/to/{to}/quantity/{quantity}\")\n  public CurrencyConversionBean convertCurrency(@PathVariable String from,\n      @PathVariable String to,\n      @PathVariable BigDecimal quantity\n      ){\n    \n    Map<String, String> uriVariables = new HashMap<>();\n    uriVariables.put(\"from\", from);\n    uriVariables.put(\"to\", to);\n\n    ResponseEntity<CurrencyConversionBean> responseEntity = new RestTemplate().getForEntity(\n        \"http://localhost:8000/currency-exchange/from/{from}/to/{to}\", \n        CurrencyConversionBean.class, \n        uriVariables );\n    \n    CurrencyConversionBean response = responseEntity.getBody();\n    \n    return new CurrencyConversionBean(response.getId(),from,to,response.getConversionMultiple(),\n        quantity,quantity.multiply(response.getConversionMultiple()),response.getPort()); \n  }\n\n}\n```\n---\n\n/currency-conversion-service/src/main/java/com/in28minutes/microservices/currencyconversionservice/CurrencyConversionServiceApplication.java New\n\n```java\npackage com.in28minutes.microservices.currencyconversionservice;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\n@SpringBootApplication\npublic class CurrencyConversionServiceApplication {\n\n  public static void main(String[] args) {\n    SpringApplication.run(CurrencyConversionServiceApplication.class, args);\n  }\n}\n```\n---\n\n/currency-conversion-service/src/main/resources/application.properties New\n\n```properties\nspring.application.name=currency-conversion-service\nserver.port=8100\n```\n---\n\n/currency-conversion-service/src/test/java/com/in28minutes/microservices/currencyconversionservice/CurrencyConversionServiceApplicationTests.java New\n\n```java\npackage com.in28minutes.microservices.currencyconversionservice;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.springframework.boot.test.context.SpringBootTest;\nimport org.springframework.test.context.junit4.SpringRunner;\n\n@RunWith(SpringRunner.class)\n@SpringBootTest\npublic class CurrencyConversionServiceApplicationTests {\n\n  @Test\n  public void contextLoads() {\n  }\n\n}\n```\n\n\n###  Step 21 - Using Feign REST Client for Service Invocation\n###  Step 22 - Setting up client side load balancing with Ribbon\n![Image](/images/RibbonClientSideLoadBalancing.png)\n###  Step 23 - Running client side load balancing with Ribbon\n\n/currency-conversion-service/pom.xml Modified\nNew Lines\n```\n     <dependency>\n      <groupId>org.springframework.cloud</groupId>\n      <artifactId>spring-cloud-starter-openfeign</artifactId>\n    </dependency>\n\n    <dependency>\n      <groupId>org.springframework.cloud</groupId>\n      <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>\n    </dependency>\n\n```\n/currency-conversion-service/src/main/java/com/in28minutes/microservices/currencyconversionservice/CurrencyConversionController.java Modified\n```java\n\n@RestController\npublic class CurrencyConversionController {\n\n  @Autowired\n  private CurrencyExchangeServiceProxy proxy;\n\n  @GetMapping(\"/currency-converter/from/{from}/to/{to}/quantity/{quantity}\")\n  public CurrencyConversionBean convertCurrency(@PathVariable String from, @PathVariable String to,\n      @PathVariable BigDecimal quantity) {\n\n    // Feign - Problem 1\n    Map<String, String> uriVariables = new HashMap<>();\n    uriVariables.put(\"from\", from);\n    uriVariables.put(\"to\", to);\n\n    ResponseEntity<CurrencyConversionBean> responseEntity = new RestTemplate().getForEntity(\n        \"http://localhost:8000/currency-exchange/from/{from}/to/{to}\", CurrencyConversionBean.class,\n        uriVariables);\n\n    CurrencyConversionBean response = responseEntity.getBody();\n\n    return new CurrencyConversionBean(response.getId(), from, to, response.getConversionMultiple(), quantity,\n        quantity.multiply(response.getConversionMultiple()), response.getPort());\n  }\n\n  @GetMapping(\"/currency-converter-feign/from/{from}/to/{to}/quantity/{quantity}\")\n  public CurrencyConversionBean convertCurrencyFeign(@PathVariable String from, @PathVariable String to,\n      @PathVariable BigDecimal quantity) {\n\n    CurrencyConversionBean response = proxy.retrieveExchangeValue(from, to);\n\n    return new CurrencyConversionBean(response.getId(), from, to, response.getConversionMultiple(), quantity,\n        quantity.multiply(response.getConversionMultiple()), response.getPort());\n  }\n\n}\n```\n---\n\n/currency-conversion-service/src/main/java/com/in28minutes/microservices/currencyconversionservice/CurrencyConversionServiceApplication.java Modified\nNew Lines\n```\n\n@SpringBootApplication\n@EnableFeignClients(\"com.in28minutes.microservices.currencyconversionservice\")\npublic class CurrencyConversionServiceApplication {\n\n```\n---\n\n/currency-conversion-service/src/main/java/com/in28minutes/microservices/currencyconversionservice/CurrencyExchangeServiceProxy.java New\n\n```java\npackage com.in28minutes.microservices.currencyconversionservice;\n\nimport org.springframework.cloud.openfeign.FeignClient;\nimport org.springframework.cloud.netflix.ribbon.RibbonClient;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.PathVariable;\n\n//@FeignClient(name=\"currency-exchange-service\", url=\"localhost:8000\")\n@FeignClient(name=\"currency-exchange-service\")\n@RibbonClient(name=\"currency-exchange-service\")\npublic interface CurrencyExchangeServiceProxy {\n  @GetMapping(\"/currency-exchange/from/{from}/to/{to}\")\n  public CurrencyConversionBean retrieveExchangeValue\n    (@PathVariable(\"from\") String from, @PathVariable(\"to\") String to);\n}\n```\n---\n\n/currency-conversion-service/src/main/resources/application.properties Modified\nNew Lines\n```\ncurrency-exchange-service.ribbon.listOfServers=http://localhost:8000,http://localhost:8001\n```\n\n###  Step 24 - Understand the need for a Naming Server\n\n![Image](/images/EurekaNamingServer.png)\n![Image](/images/RibbonClientSideLoadBalancing.png)\n\n###  Step 25 - Setting up Eureka Naming Server\n\nCreating a Spring Project with Spring Initializr is a cake walk. \n\n> Spring Initializr [http://start.spring.io/](http://start.spring.io/){:target=\"_blank\"} is great tool to bootstrap your Spring Boot projects.\n\n![Image](/images/Spring-Initializr-eureka-naming-server.png \"Spring Initializr\")   \n\n- Launch Spring Initializr and choose the following\n  - Choose Version 2.3.1.RELEASE or greater\n  - Choose Group as shown in the figure\n  - Choose Artifact as shown in the figure\n  - Choose Dependencies as shown in the figure\n- Click Generate Project.\n- Import the project into Eclipse.\n- If you want to understand all the files that are part of this project, you can go here.\n\n\n### /netflix-eureka-naming-server/pom.xml New\n\n```xml\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n  xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n\n  <groupId>com.in28minutes.microservices</groupId>\n  <artifactId>netflix-eureka-naming-server</artifactId>\n  <version>0.0.1-SNAPSHOT</version>\n  <packaging>jar</packaging>\n\n  <name>netflix-eureka-naming-server</name>\n  <description>Demo project for Spring Boot</description>\n\n  <parent>\n    <groupId>org.springframework.boot</groupId>\n    <artifactId>spring-boot-starter-parent</artifactId>\n    <version>2.3.1.RELEASE</version>\n    <relativePath/> <!-- lookup parent from repository -->\n  </parent>\n\n  <properties>\n    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>\n    <java.version>1.8</java.version>\n<maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>\n    <spring-cloud.version>Finchley.M8</spring-cloud.version>\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.springframework.boot</groupId>\n      <artifactId>spring-boot-starter-actuator</artifactId>\n    </dependency>\n    <dependency>\n      <groupId>org.springframework.cloud</groupId>\n      <artifactId>spring-cloud-starter-config</artifactId>\n    </dependency>\n    <dependency>\n      <groupId>org.springframework.cloud</groupId>\n      <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>\n    </dependency>\n\n    <dependency>\n      <groupId>org.springframework.boot</groupId>\n      <artifactId>spring-boot-devtools</artifactId>\n      <scope>runtime</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.springframework.boot</groupId>\n      <artifactId>spring-boot-starter-test</artifactId>\n      <scope>test</scope>\n    </dependency>\n  </dependencies>\n\n  <dependencyManagement>\n    <dependencies>\n      <dependency>\n        <groupId>org.springframework.cloud</groupId>\n        <artifactId>spring-cloud-dependencies</artifactId>\n        <version>${spring-cloud.version}</version>\n        <type>pom</type>\n        <scope>import</scope>\n      </dependency>\n    </dependencies>\n  </dependencyManagement>\n\n  <build>\n    <plugins>\n      <plugin>\n        <groupId>org.springframework.boot</groupId>\n        <artifactId>spring-boot-maven-plugin</artifactId>\n      </plugin>\n    </plugins>\n  </build>\n\n\n\n</project>\n```\n---\n\n### /netflix-eureka-naming-server/src/main/java/com/in28minutes/microservices/netflixeurekanamingserver/NetflixEurekaNamingServerApplication.java New\n\n```java\npackage com.in28minutes.microservices.netflixeurekanamingserver;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;\n\n@SpringBootApplication\n@EnableEurekaServer\npublic class NetflixEurekaNamingServerApplication {\n\n  public static void main(String[] args) {\n    SpringApplication.run(NetflixEurekaNamingServerApplication.class, args);\n  }\n}\n```\n---\n\n### /netflix-eureka-naming-server/src/main/resources/application.properties New\n\n```properties\n\nspring.application.name=netflix-eureka-naming-server\nserver.port=8761\n\neureka.client.register-with-eureka=false\neureka.client.fetch-registry=false\n```\n---\n\n### /netflix-eureka-naming-server/src/test/java/com/in28minutes/microservices/netflixeurekanamingserver/NetflixEurekaNamingServerApplicationTests.java New\n\n```java\npackage com.in28minutes.microservices.netflixeurekanamingserver;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.springframework.boot.test.context.SpringBootTest;\nimport org.springframework.test.context.junit4.SpringRunner;\n\n@RunWith(SpringRunner.class)\n@SpringBootTest\npublic class NetflixEurekaNamingServerApplicationTests {\n\n  @Test\n  public void contextLoads() {\n  }\n\n}\n```\n---\n\n###  Step 26 - Connecting Currency Conversion Microservice to Eureka\n/currency-conversion-service/pom.xml Modified\nNew Lines\n```\n    <dependency>\n      <groupId>org.springframework.cloud</groupId>\n      <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>\n    </dependency>\n```\n\n/currency-conversion-service/src/main/resources/application.properties Modified\nNew Lines\n```\neureka.client.service-url.default-zone=http://localhost:8761/eureka\n#currency-exchange-service.ribbon.listOfServers=http://localhost:8000,http://localhost:8001\n```\n\n/currency-conversion-service/src/main/java/com/in28minutes/microservices/currencyconversionservice/CurrencyConversionServiceApplication.java Modified\nNew Lines\n```\n@SpringBootApplication\n@EnableDiscoveryClient\npublic class CurrencyConversionServiceApplication {\n```\n---\n\n###  Step 27 - Connecting Currency Exchange Microservice to Eureka\n/currency-exchange-service/pom.xml Modified\nNew Lines\n```\n    <dependency>\n      <groupId>org.springframework.cloud</groupId>\n      <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>\n    </dependency>\n```\n/currency-exchange-service/src/main/java/com/in28minutes/microservices/currencyexchangeservice/CurrencyExchangeServiceApplication.java Modified\nNew Lines\n```java\n@SpringBootApplication\n@EnableDiscoveryClient\npublic class CurrencyExchangeServiceApplication {\n```\n---\n\n/currency-exchange-service/src/main/resources/application.properties Modified\nNew Lines\n```\neureka.client.service-url.default-zone=http://localhost:8761/eureka\n```\n\n###  Step 28 - Distributing calls using Eureka and Ribbon\n/currency-conversion-service/src/main/java/com/in28minutes/microservices/currencyconversionservice/CurrencyConversionServiceApplication.java Modified\nNew Lines\n```\n@SpringBootApplication\n@EnableFeignClients(\"com.in28minutes.microservices.currencyconversionservice\")\n@EnableDiscoveryClient\npublic class CurrencyConversionServiceApplication {\n```\n\n###  Step 29 - A review of implementing Eureka, Ribbon and Feign\n![Image](/images/RibbonClientSideLoadBalancing.png)\n\n###  Step 30 - Introduction to API Gateways\n- Authentication, authorization and security\n- Rate Limits\n- Fault Tolerance\n- Service Aggregation\n\n###  Step 31 - Setting up Zuul API Gateway\n\nCreating a Spring Project with Spring Initializr is a cake walk. \n\n> Spring Initializr [http://start.spring.io/](http://start.spring.io/){:target=\"_blank\"} is great tool to bootstrap your Spring Boot projects.\n\n![Image](/images/Spring-Initializr-zuul-api-gateway.png \"Spring Initializr\")   \n\n- Launch Spring Initializr and choose the following\n  - Choose Version 2.3.1.RELEASE or greater\n  - Choose Group as shown in the figure\n  - Choose Artifact as shown in the figure\n  - Choose Dependencies as shown in the figure\n- Click Generate Project.\n- Import the project into Eclipse.\n- If you want to understand all the files that are part of this project, you can go here.\n\n###  Step 32 - Implementing Zuul Logging Filter\n###  Step 33 - Executing a request through Zuul API Gateway\n###  Step 34 - Setting up Zuul API Gateway between microservice invocations\n\n##### /currency-conversion-service/src/main/java/com/in28minutes/microservices/currencyconversionservice/CurrencyConversionController.java Modified\nNew Lines\n```java\n\n@RestController\npublic class CurrencyConversionController {\n\n  private Logger logger = LoggerFactory.getLogger(this.getClass());\n  \n  @GetMapping(\"/currency-converter/from/{from}/to/{to}/quantity/{quantity}\")\n  public CurrencyConversionBean convertCurrency(@PathVariable String from, @PathVariable String to,\n      @PathVariable BigDecimal quantity) {\n\n    // Feign - Problem 1\n    Map<String, String> uriVariables = new HashMap<>();\n    uriVariables.put(\"from\", from);\n    uriVariables.put(\"to\", to);\n\n    ResponseEntity<CurrencyConversionBean> responseEntity = new RestTemplate().getForEntity(\n        \"http://localhost:8000/currency-exchange/from/{from}/to/{to}\", CurrencyConversionBean.class,\n        uriVariables);\n\n    CurrencyConversionBean response = responseEntity.getBody();\n\n    return new CurrencyConversionBean(response.getId(), from, to, response.getConversionMultiple(), quantity,\n        quantity.multiply(response.getConversionMultiple()), response.getPort());\n  }\n\n  @GetMapping(\"/currency-converter-feign/from/{from}/to/{to}/quantity/{quantity}\")\n  public CurrencyConversionBean convertCurrencyFeign(@PathVariable String from, @PathVariable String to,\n      @PathVariable BigDecimal quantity) {\n\n    CurrencyConversionBean response = proxy.retrieveExchangeValue(from, to);\n\n    logger.info(\"{}\", response);\n    \n    return new CurrencyConversionBean(response.getId(), from, to, response.getConversionMultiple(), quantity,\n        quantity.multiply(response.getConversionMultiple()), response.getPort());\n  }\n\n}\n```\n---\n\n##### /currency-conversion-service/src/main/java/com/in28minutes/microservices/currencyconversionservice/CurrencyExchangeServiceProxy.java Modified\nNew Lines\n```java\n\n//@FeignClient(name=\"currency-exchange-service\", url=\"localhost:8000\")\n//@FeignClient(name=\"currency-exchange-service\")\n@FeignClient(name=\"netflix-zuul-api-gateway-server\")\n@RibbonClient(name=\"currency-exchange-service\")\npublic interface CurrencyExchangeServiceProxy {\n  //@GetMapping(\"/currency-exchange/from/{from}/to/{to}\")\n  @GetMapping(\"/currency-exchange-service/currency-exchange/from/{from}/to/{to}\")\n  public CurrencyConversionBean retrieveExchangeValue\n    (@PathVariable(\"from\") String from, @PathVariable(\"to\") String to);\n}\n```\n\n##### /currency-exchange-service/src/main/java/com/in28minutes/microservices/currencyexchangeservice/CurrencyExchangeController.java Modified\nNew Lines\n```\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nprivate Logger logger = LoggerFactory.getLogger(this.getClass());\n\nlogger.info(\"{}\", exchangeValue);\n```\n\n##### /netflix-zuul-api-gateway-server/pom.xml New\n\n```xml\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n  xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n\n  <groupId>com.in28minutes.microservices</groupId>\n  <artifactId>netflix-zuul-api-gateway-server</artifactId>\n  <version>0.0.1-SNAPSHOT</version>\n  <packaging>jar</packaging>\n\n  <name>netflix-zuul-api-gateway-server</name>\n  <description>Demo project for Spring Boot</description>\n\n  <parent>\n    <groupId>org.springframework.boot</groupId>\n    <artifactId>spring-boot-starter-parent</artifactId>\n    <version>2.3.1.RELEASE</version>\n    <relativePath/> <!-- lookup parent from repository -->\n  </parent>\n\n  <properties>\n    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>\n    <java.version>1.8</java.version>\n<maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>\n    <spring-cloud.version>Finchley.M8</spring-cloud.version>\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.springframework.cloud</groupId>\n      <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>\n    </dependency>\n\n    <dependency>\n      <groupId>org.springframework.cloud</groupId>\n      <artifactId>spring-cloud-starter-netflix-zuul</artifactId>\n    </dependency>\n\n    <dependency>\n      <groupId>org.springframework.boot</groupId>\n      <artifactId>spring-boot-starter-test</artifactId>\n      <scope>test</scope>\n    </dependency>\n  </dependencies>\n\n  <dependencyManagement>\n    <dependencies>\n      <dependency>\n        <groupId>org.springframework.cloud</groupId>\n        <artifactId>spring-cloud-dependencies</artifactId>\n        <version>${spring-cloud.version}</version>\n        <type>pom</type>\n        <scope>import</scope>\n      </dependency>\n    </dependencies>\n  </dependencyManagement>\n\n  <build>\n    <plugins>\n      <plugin>\n        <groupId>org.springframework.boot</groupId>\n        <artifactId>spring-boot-maven-plugin</artifactId>\n      </plugin>\n    </plugins>\n  </build>\n\n\n\n</project>\n```\n---\n\n##### /netflix-zuul-api-gateway-server/src/main/java/com/in28minutes/microservices/netflixzuulapigatewayserver/NetflixZuulApiGatewayServerApplication.java New\n\n```java\npackage com.in28minutes.microservices.netflixzuulapigatewayserver;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.cloud.client.discovery.EnableDiscoveryClient;\nimport org.springframework.cloud.netflix.zuul.EnableZuulProxy;\n\n@EnableZuulProxy\n@EnableDiscoveryClient\n@SpringBootApplication\npublic class NetflixZuulApiGatewayServerApplication {\n\n  public static void main(String[] args) {\n    SpringApplication.run(NetflixZuulApiGatewayServerApplication.class, args);\n  }\n}\n```\n---\n\n##### /netflix-zuul-api-gateway-server/src/main/java/com/in28minutes/microservices/netflixzuulapigatewayserver/ZuulLoggingFilter.java New\n\n```java\npackage com.in28minutes.microservices.netflixzuulapigatewayserver;\n\nimport javax.servlet.http.HttpServletRequest;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.stereotype.Component;\n\nimport com.netflix.zuul.ZuulFilter;\nimport com.netflix.zuul.context.RequestContext;\n\n@Component\npublic class ZuulLoggingFilter extends ZuulFilter{\n\n  private Logger logger = LoggerFactory.getLogger(this.getClass());\n\n  @Override\n  public boolean shouldFilter() {\n    return true;\n  }\n\n  @Override\n  public Object run() {\n    HttpServletRequest request = \n        RequestContext.getCurrentContext().getRequest();\n    logger.info(\"request -> {} request uri -> {}\", \n        request, request.getRequestURI());\n    return null;\n  }\n\n  @Override\n  public String filterType() {\n    return \"pre\";\n  }\n\n  @Override\n  public int filterOrder() {\n    return 1;\n  }\n}\n```\n---\n\n##### /netflix-zuul-api-gateway-server/src/main/resources/application.properties New\n\n```properties\nspring.application.name=netflix-zuul-api-gateway-server\nserver.port=8765\neureka.client.service-url.default-zone=http://localhost:8761/eureka\n```\n---\n\n##### /netflix-zuul-api-gateway-server/src/test/java/com/in28minutes/microservices/netflixzuulapigatewayserver/NetflixZuulApiGatewayServerApplicationTests.java New\n\n```java\npackage com.in28minutes.microservices.netflixzuulapigatewayserver;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.springframework.boot.test.context.SpringBootTest;\nimport org.springframework.test.context.junit4.SpringRunner;\n\n@RunWith(SpringRunner.class)\n@SpringBootTest\npublic class NetflixZuulApiGatewayServerApplicationTests {\n\n  @Test\n  public void contextLoads() {\n  }\n\n}\n```\n\n###  Step 35 - Introduction to Distributed Tracing\n###  Step 36 - Implementing Spring Cloud Sleuth\n/currency-conversion-service/pom.xml Modified\nNew Lines\n```\n    <dependency>\n      <groupId>org.springframework.cloud</groupId>\n      <artifactId>spring-cloud-starter-sleuth</artifactId>\n    </dependency>\n\n\n```\n/currency-conversion-service/src/main/java/com/in28minutes/microservices/currencyconversionservice/CurrencyConversionServiceApplication.java Modified\nNew Lines\n```\n  @Bean\n  public Sampler defaultSampler(){\n    return Sampler.ALWAYS_SAMPLE;\n  }\n```\n\n\n/currency-exchange-service/pom.xml Modified\nNew Lines\n```\n    <dependency>\n      <groupId>org.springframework.cloud</groupId>\n      <artifactId>spring-cloud-starter-sleuth</artifactId>\n    </dependency>\n\n```\n/currency-exchange-service/src/main/java/com/in28minutes/microservices/currencyexchangeservice/CurrencyExchangeServiceApplication.java Modified\nNew Lines\n```\n  @Bean\n  public Sampler defaultSampler(){\n    return Sampler.ALWAYS_SAMPLE;\n  }\n```\n---\n\n/netflix-zuul-api-gateway-server/pom.xml Modified\nNew Lines\n```\n    <dependency>\n      <groupId>org.springframework.cloud</groupId>\n      <artifactId>spring-cloud-starter-sleuth</artifactId>\n    </dependency>\n```\n/netflix-zuul-api-gateway-server/src/main/java/com/in28minutes/microservices/netflixzuulapigatewayserver/NetflixZuulApiGatewayServerApplication.java Modified\nNew Lines\n```\n\n  @Bean\n  public AlwaysSampler defaultSampler(){\n    return new AlwaysSampler();\n  }\n```\n\n\n###  Step 37 - Introduction to Distributed Tracing with Zipkin\n![Image](/images/ZipkinDistributedTracingServer.png)\n\n###  Step 38 - Installing Rabbit MQ\n\n##### Windows\n- https://www.rabbitmq.com/install-windows.html\n- https://www.rabbitmq.com/which-erlang.html\n- http://www.erlang.org/downloads\n- Video - https://www.youtube.com/watch?v=gKzKUmtOwR4\n\n##### Mac\n- https://www.rabbitmq.com/install-homebrew.html\n\n###  Step 39 - Setting up Distributed Tracing with Zipkin\n\nQuick Start Page\n- https://zipkin.io/pages/quickstart\n\nDownloading Zipkin Jar\n- https://search.maven.org/remote_content?g=io.zipkin.java&a=zipkin-server&v=LATEST&c=exec\n\nCommand to run\n```\nRABBIT_URI=amqp://localhost java -jar zipkin-server-2.5.2-exec.jar\n```\n\n###  Step 40 - Connecting microservices to Zipkin\n###  Step 41 - Using Zipkin UI Dashboard to trace requests\n\n/currency-conversion-service/pom.xml Modified\nNew Lines\n```\n    <dependency>\n      <groupId>org.springframework.cloud</groupId>\n      <artifactId>spring-cloud-sleuth-zipkin</artifactId>\n    </dependency>\n\n    <dependency>\n      <groupId>org.springframework.cloud</groupId>\n      <artifactId>spring-cloud-starter-bus-amqp</artifactId>\n    </dependency>\n\n```\n\n/currency-exchange-service/pom.xml Modified\nNew Lines\n```\n    <dependency>\n      <groupId>org.springframework.cloud</groupId>\n      <artifactId>spring-cloud-sleuth-zipkin</artifactId>\n    </dependency>\n\n    <dependency>\n      <groupId>org.springframework.cloud</groupId>\n      <artifactId>spring-cloud-starter-bus-amqp</artifactId>\n    </dependency>\n```\n---\n\n/netflix-zuul-api-gateway-server/pom.xml Modified\nNew Lines\n```\n    <dependency>\n      <groupId>org.springframework.cloud</groupId>\n      <artifactId>spring-cloud-sleuth-zipkin</artifactId>\n    </dependency>\n\n    <dependency>\n      <groupId>org.springframework.cloud</groupId>\n      <artifactId>spring-cloud-starter-bus-amqp</artifactId>\n    </dependency>\n```\n\n###  Step 43 - Implementing Spring Cloud Bus\n\n- http://localhost:8080/actuator/refresh\n- http://localhost:8080/actuator/bus-refresh\n\nbootstrap.properties Modified\n```\nmanagement.endpoints.web.exposure.include=*\n```\n\n###  Step 44 - Fault Tolerance with Hystrix\n\n/03.microservices/limits-service/pom.xml Modified\nNew Lines\n```\n    <dependency>\n      <groupId>org.springframework.cloud</groupId>\n      <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>\n    </dependency>\n\n```\n/03.microservices/limits-service/src/main/java/com/in28minutes/microservices/limitsservice/LimitsConfigurationController.java Modified\nNew Lines\n```java\n@RestController\npublic class LimitsConfigurationController {\n\n  \n  @GetMapping(\"/fault-tolerance-example\")\n  @HystrixCommand(fallbackMethod=\"fallbackRetrieveConfiguration\")\n  public LimitConfiguration retrieveConfiguration() {\n    throw new RuntimeException(\"Not available\");\n  }\n\n  public LimitConfiguration fallbackRetrieveConfiguration() {\n    return new LimitConfiguration(999, 9);\n  }\n\n}\n```\n---\n\n/03.microservices/limits-service/src/main/java/com/in28minutes/microservices/limitsservice/LimitsServiceApplication.java Modified\nNew Lines\n\n```java\n\n@SpringBootApplication\n@EnableHystrix\npublic class LimitsServiceApplication {\n\n```\n---\n\n## More Reading about Microservices\n- Design and Governance of Microservices\n    - https://martinfowler.com/microservices/\n- 12 Factor App \n    - https://12factor.net/\n    - https://dzone.com/articles/the-12-factor-app-a-java-developers-perspective\n- Spring Cloud\n    - http://projects.spring.io/spring-cloud/\n\n"
  },
  {
    "path": "_blog/articles/2017-10-17-spring-web-services.md",
    "content": "---\nlayout:     post\ntitle:      Spring Boot SOAP and RESTful Web Services Tutorial for Beginners\ndate:       2022-10-17 12:31:19\nsummary:    Developing SOAP and RESTful Web Services is fun. The combination of Spring Boot, Spring Web MVC, Spring Web Services and JPA makes it even more fun. There are two parts to this course - RESTful web services and SOAP Web Services.\ncategories: SpringBoot\npermalink:  /soap-and-restful-web-services-with-spring-boot-and-jpa\nimage: /images/spring-boot-application.png\n---\n\nLearn how to create awesome SOAP and RESTful web services with Spring and Spring Boot.\n\nDeveloping SOAP and RESTful web services is fun. The combination of Spring Boot, Spring Web MVC, Spring Web Services and JPA makes it even more fun.\n\nThere are two parts to this course - RESTful web services and SOAP Web Services\n\nArchitectures are moving towards microservices. RESTful web services are the first step to developing great microservices. Spring Boot, in combination with Spring Web MVC (also called Spring REST) makes it easy to develop RESTful web services. \n\nIn this part of the course, you will learn the basics of RESTful web services developing resources for a social media application. You will learn to implement these resources with multiple features - versioning, exception handling, documentation (Swagger), basic authentication (Spring Security), filtering and HATEOAS. You will learn the best practices in designing RESTful web services.\n\nIn this part of the course, you will be using Spring (Dependency Management), Spring MVC (or Spring REST), Spring Boot, Spring Security (Authentication and Authorization), Spring Boot Actuator (Monitoring), Swagger (Documentation), Maven (dependencies management), Eclipse (IDE), Postman (REST Services Client) and Tomcat Embedded Web Server. We will help you set up each one of these.\n\nWhile the use of SOAP Web Services is on the way down, there are still considerable number of web services using this approach. \n\nIn this part of the course, you will learn the basics of implementing SOAP Web Services developing a few web services for a course management application. You will learn to use a Contract first approach - defining XSD (XML Schema Definition) for your requests and responses. You will learn about WSDL (SOAP Header, SOAP Body and SOAP Fault), XSD (XML Schema Definition) and JAXB (Java API for XML Binding). You will implementing three SOAP web services with exception handling and basic security (with WS Security).\n\nIn this part of the course, you will be using Spring (Dependency Management), Spring Web Services , Spring Boot, Spring Security (Authentication and Authorization), Swagger (Documentation), Maven (dependencies management), Eclipse (IDE), Wizdler (SOAP Services Chrome Plugin) and Tomcat Embedded Web Server. We will help you set up each one of these.\n\n## Course Link\n[![Image](/images/Course-Master-Java-Web-Services-and-REST-API-with-Spring-Boot.png \"Master Java Web Services and REST API with Spring Boot\")](https://links.in28minutes.com/MISC-SPRING-WEB-SERVICES){:target=\"_blank\"}\n\n\n\n### You will learn\n- You will be able to develop and design RESTful web services\n- You will understand the best practices in designing RESTful web services\n- You will be able to develop and design SOAP web services\n- You will understand how to connect RESTful Services to a backend with JPA\n- You will understand how to implement Exception Handling, Validation, HATEOAS and filtering for RESTful Web Services.\n- You will understand how to version your RESTful Web Services\n- You will understand how to monitor RESTful Services with Spring Boot Actuator\n- You will understand how to document RESTful Web Services with Swagger\n- You will understand about WSDL, SOAP Header, SOAP Body, SOAP Fault, XSD, JAXB and EndPoint\n- How to implement basic security with WS Security for SOAP Web Services?\n\n\n## Installing Tools\n- Installation Video : https://www.youtube.com/playlist?list=PLBBog2r6uMCSmMVTW_QmDLyASBvovyAO3\n- GIT Repository For Installation : https://github.com/in28minutes/getting-started-in-5-steps\n- PDF : https://github.com/in28minutes/SpringIn28Minutes/blob/master/InstallationGuide-JavaEclipseAndMaven_v2.pdf\n\n## Running Examples\n- Download the zip or clone the Git repository.\n- Unzip the zip file (if you downloaded one)\n- Open Command Prompt and Change directory (cd) to folder containing pom.xml\n- Open Eclipse \n   - File -> Import -> Existing Maven Project -> Navigate to the folder where you unzipped the zip\n   - Select the right project\n- Choose the Spring Boot Application file (search for @SpringBootApplication)\n- Right Click on the file and Run as Java Application\n- You are all Set\n- For help : use our installation guide - https://www.youtube.com/playlist?list=PLBBog2r6uMCSmMVTW_QmDLyASBvovyAO3\n\n## Course Overview\n\n|Title|Github Folder|\n| -------------------- |--------------|\n|Introduction To Web Services|None|\n|SOAP Web Services with Spring and Spring Boot|[Project Folder on Github](https://github.com/in28minutes/spring-web-services/tree/master/soap-web-services){:target='_blank'}|\n|RESTful Web Services with Spring and Spring Boot|[Project Folder on Github](https://github.com/in28minutes/spring-web-services/tree/master/restful-web-services){:target='_blank'}|\n|Connecting RESTful Web Service to JPA|[Project Folder on Github](){:target='_blank'}|\n|RESTful Web Services - Best Practices|None|\n\n## 3 Bonus Sections - Introduction to Spring, Spring Boot and JPA\n\n|Title|Category|Github|\n| -------------------- |:------------------:|--------------|\n|Spring Framework in 10 Steps|Introduction|[Project Folder on Github](https://github.com/in28minutes/spring-web-services/tree/master/spring-in-10-steps){:target='_blank'}|\n|Spring Boot in 10 Steps|Introduction|[Project Folder on Github](https://github.com/in28minutes/spring-web-services/tree/master/springboot-in-10-steps){:target='_blank'}|\n|JPA in 10 Steps|Introduction|[Project Folder on Github](https://github.com/in28minutes/spring-web-services/tree/master/jpa-in-10-steps){:target='_blank'}|\n\n## Introduction to Web Services\n\n### Web Service\n\n> Service delivered over the web?\n\n![Image](/images/Web_Services_Web_Application_To_Manage_Todos.png)\n\n> Is the Todo Management Application a Web Service?\n\n- It delivers HTML output - Not consumable by other applications.\n\n![Image](/images/Web_Services_Application_Layers.png)\n\n- Can I reuse the Business Layer by creating a JAR?\n  - Not Platform independent\n  - Communication of Changes\n  - Managing Dependencies - like Database\n\n\n> How can I make my Todo application consumable by other applications?\n\n\n> That where we get into the concept of a web service!\n\n![Image](/images/Web_Service_Multiple_Application_Interaction.png)\n![Image](/images/Web_Service_Single_Application_Interaction.png)\n![Image](/images/Web_Service_Basic_Interaction.png)\n\n#### Web Service - W3C definition\n\n> Software system designed to support interoperable machine-to-machine interaction over a network.\n\n\n#### 3 Keys\n\n- Designed for machine-to-machine (or application-to-application) interaction\n- Should be interoperable - Not platform dependent\n- Should allow communication over a network\n\n#### How?\n\n> How does data exchange between applications take place?\n\n![Image](/images/Web_Service_Z_ApplicationA_WebService.png)\n![Image](/images/Web_Service_Z_ApplicationA_WebService_Request_Response.png)\n\n> How can we make web services platform independent?\n\n![Image](/images/Web_Service_Z_PlatformIndependence.png)\n\n#### XML\n```xml\n        <getCourseDetailsRequest>\n            <id>Course1</id>\n        </getCourseDetailsRequest>\n```\n\n#### JSON\n\n```json\n[\n  {\n    \"id\": 1,\n    \"name\": \"Even\",\n    \"birthDate\": \"2017-07-10T07:52:48.270+0000\"\n  },\n  {\n    \"id\": 2,\n    \"name\": \"Abe\",\n    \"birthDate\": \"2017-07-10T07:52:48.270+0000\"\n  }\n]\n```\n\n> How does the Application A know the format of Request and Response?\n\n![Image](/images/Web_Service_Service_Definition.png)\n\n> How does Application A and Web Service convert its internal data to (XML or JSON)?\n\n![Image](/images/Web_Service_Z_ApplicationA_WebService_Request_Response.png)\n\n#### Key Terminology\n\n- Request and  Response\n- Message Exchange Format\n  - XML and JSON\n\n#### Key Terminology\n\n- Service Provider or Server\n- Service Consumer or Client\n- Service Definition\n\n#### Key Terminology\n- Transport\n  - HTTP and MQ\n![Image](/images/soapoverhttp.png)\n![Image](/images/soapovermq.png)\n### Web Service Groups\n- SOAP-based\n- REST-styled\n\n> SOAP and REST are not really comparable. \n\n#### SOAP\n\n##### SOAP?\n\n![Image](/images/Web_Service_Basic_Interaction_SOAP.png)\n\n```xml\n        <getCourseDetailsRequest>\n            <id>Course1</id>\n        </getCourseDetailsRequest>\n```\n\n![Image](/images/Web_Service_SOAP-Envelope.svg.png)\n\n![Image](/images/Web_Service_Basic_Interaction_SOAP_2.png)\n\n```xml\n<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <SOAP-ENV:Header/>\n    <SOAP-ENV:Body>\n        <ns2:getCourseDetailsResponse xmlns:ns2=\"http://in28minutes.com/courses\">\n            <ns2:course>\n                <ns2:id>Course1</ns2:id>\n                <ns2:name>Spring</ns2:name>\n                <ns2:description>10 Steps</ns2:description>\n            </ns2:course>\n        </ns2:getCourseDetailsResponse>\n    </SOAP-ENV:Body>\n</SOAP-ENV:Envelope>\n```\n\n##### SOAP\n  - Format\n  \t- SOAP XML Request\n  \t- SOAP XML Response\n  - Transport\n    - SOAP over MQ\n    - SOAP over HTTP\n  - Service Definition\n    - WSDL \n\n## SOAP Web Services with Spring and Spring Boot\n\n### Step 01 - Initialize a Spring Web Services application with Spring Boot\n\nCreating a Spring Project with Spring Initializr is a cake walk. \n\n> Spring Initializr [http://start.spring.io/](http://start.spring.io/){:target=\"_blank\"} is great tool to bootstrap your Spring Boot projects.\n\n![Image](/images/Spring-Initializr-soap-web-service.png \"Spring Initializr\")   \n\n- Launch Spring Initializr and choose the following\n  - Choose Version 2.3.1.RELEASE or greater\n  - Choose Group as shown in the figure\n  - Choose Artifact as shown in the figure\n  - Choose Dependencies as shown in the figure\n- Click Generate Project.\n- Import the project into Eclipse.\n\n\n##### /pom.xml\n\n```xml\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\n\t<groupId>com.in28minutes.soap.webservices</groupId>\n\t<artifactId>soap-course-management</artifactId>\n\t<version>0.0.1-SNAPSHOT</version>\n\t<packaging>jar</packaging>\n\n\t<name>soap-course-management</name>\n\t<description>Demo project for Spring Boot</description>\n\n\t<parent>\n\t\t<groupId>org.springframework.boot</groupId>\n\t\t<artifactId>spring-boot-starter-parent</artifactId>\n\t\t<version>2.3.1.RELEASE</version>\n\t\t<relativePath/> <!-- lookup parent from repository -->\n\t</parent>\n\n\t<properties>\n\t\t<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n\t\t<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>\n\t\t<java.version>1.8</java.version>\n<maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>\n\t</properties>\n\n\t<dependencies>\n\t\t<dependency>\n\t\t\t<groupId>org.springframework.boot</groupId>\n\t\t\t<artifactId>spring-boot-starter-data-jpa</artifactId>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.springframework.boot</groupId>\n\t\t\t<artifactId>spring-boot-starter-web-services</artifactId>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.h2database</groupId>\n\t\t\t<artifactId>h2</artifactId>\n\t\t\t<scope>runtime</scope>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.springframework.boot</groupId>\n\t\t\t<artifactId>spring-boot-starter-test</artifactId>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t</dependencies>\n\n\t<build>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.springframework.boot</groupId>\n\t\t\t\t<artifactId>spring-boot-maven-plugin</artifactId>\n\t\t\t</plugin>\n\t\t</plugins>\n\t</build>\n</project>\n```\n\n##### /src/main/java/com/in28minutes/soap/webservices/soapcoursemanagement/SoapCourseManagementApplication.java\n\n```java\npackage com.in28minutes.soap.webservices.soapcoursemanagement;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\n@SpringBootApplication\npublic class SoapCourseManagementApplication {\n\n\tpublic static void main(String[] args) {\n\t\tSpringApplication.run(SoapCourseManagementApplication.class, args);\n\t}\n}\n```\n\n##### /src/main/resources/application.properties\n\n```properties\n```\n\n##### /src/test/java/com/in28minutes/soap/webservices/soapcoursemanagement/SoapCourseManagementApplicationTests.java\n\n```java\npackage com.in28minutes.soap.webservices.soapcoursemanagement;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.springframework.boot.test.context.SpringBootTest;\nimport org.springframework.test.context.junit4.SpringRunner;\n\n@RunWith(SpringRunner.class)\n@SpringBootTest\npublic class SoapCourseManagementApplicationTests {\n\n\t@Test\n\tpublic void contextLoads() {\n\t}\n\n}\n```\n\n\n### Step 02 - Overview of creating SOAP Web Service using Contract First Approach\n\nLets first define an XSD.\n\n### Step 03 - Define Request and Response XML Structure\n\n##### /example-files/Request.xml\n\n```xml\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<GetCourseDetailsRequest xmlns=\"http://in28minutes.com/courses\" \nxsi:schemaLocation=\"http://in28minutes.com/courses course-details.xsd\" \nxmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n\t<id>123</id> <!-- numbers  -->\n</GetCourseDetailsRequest>\n```\n\n##### /example-files/Response.xml\n\n```xml\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<GetCourseDetailsResponse xmlns=\"http://in28minutes.com/courses\">\n\t<CourseDetails>\n\t\t<id>123</id>\n\t\t<name>Spring in28minutes</name>\n\t\t<description>You would learn the basics of Spring Framework</description>\n\t</CourseDetails>\n</GetCourseDetailsResponse>\n```\n\n### Step 04 - Define XML Schema Definition (XSD) for Request - GetCourseDetailsRequest\n\n##### /example-files/course-details.xsd\n\n```\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<schema xmlns=\"http://www.w3.org/2001/XMLSchema\" \ntargetNamespace=\"http://in28minutes.com/courses\" \nxmlns:tns=\"http://in28minutes.com/courses\" elementFormDefault=\"qualified\">\n\t<element name=\"GetCourseDetailsRequest\">\n\t\t<complexType>\n\t\t\t<sequence>\n\t\t\t\t<element name= \"id\" type=\"integer\"></element>\n\t\t\t</sequence>\t\n\t\t</complexType>\n\t</element>\n</schema>\n\n<!-- \n<GetCourseDetailsRequest xmlns=\"http://in28minutes.com/courses\">\n\t<id>123</id> \n</GetCourseDetailsRequest>\n -->\n```\n\n### Step 05 - Define XML Schema Definition (XSD) for Respone - GetCourseDetailsResponse\n\n##### /example-files/Response.xml Modified\n```\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<GetCourseDetailsResponse xmlns=\"http://in28minutes.com/courses\"\nxmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\nxsi:schemaLocation=\"http://in28minutes.com/courses course-details.xsd\">\n\t<CourseDetails>\n\t\t<id>123</id>\n\t\t<name>Spring in28minutes</name>\n\t\t<description>You would learn the basics of Spring Framework</description>\n\t</CourseDetails>\n</GetCourseDetailsResponse>\n```\n##### /example-files/course-details.xsd Modified\n```\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<schema xmlns=\"http://www.w3.org/2001/XMLSchema\" \ntargetNamespace=\"http://in28minutes.com/courses\" \nxmlns:tns=\"http://in28minutes.com/courses\" elementFormDefault=\"qualified\">\n\t\n\t<element name=\"GetCourseDetailsRequest\">\n\t\t<complexType>\n\t\t\t<sequence>\n\t\t\t\t<element name= \"id\" type=\"integer\"></element>\n\t\t\t</sequence>\t\n\t\t</complexType>\n\t</element>\n\t\n\t<element name=\"GetCourseDetailsResponse\">\n\t\t<complexType>\n\t\t\t<sequence>\n\t\t\t\t<element name= \"CourseDetails\" type=\"tns:CourseDetails\"></element>\n\t\t\t</sequence>\t\n\t\t</complexType>\n\t</element>\n\t\n\t<complexType name=\"CourseDetails\">\n\t\t<sequence>\n\t\t\t<element name=\"id\" type=\"integer\"/>\n\t\t\t<element name=\"name\" type=\"string\"/>\n\t\t\t<element name=\"description\" type=\"string\"/>\n\t\t</sequence>\n\t</complexType>\n\t\n</schema>\t\n```\n\n### Step 06 - More about XML Schema Definition and Implementing XSD Best Practices\n\n##### /example-files/course-details.xsd Modified\n```\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" \ntargetNamespace=\"http://in28minutes.com/courses\" \nxmlns:tns=\"http://in28minutes.com/courses\" elementFormDefault=\"qualified\">\n\t\n\t<xs:element name=\"GetCourseDetailsRequest\">\n\t\t<xs:complexType>\n\t\t\t<xs:sequence>\n\t\t\t\t<xs:element name= \"id\" type=\"xs:integer\"/>\n\t\t\t</xs:sequence>\t\n\t\t</xs:complexType>\n\t</xs:element>\n\t\n\t<xs:element name=\"GetCourseDetailsResponse\">\n\t\t<xs:complexType>\n\t\t\t<xs:sequence>\n\t\t\t\t<xs:element name= \"CourseDetails\" type=\"tns:CourseDetails\"/>\n\t\t\t</xs:sequence>\t\n\t\t</xs:complexType>\n\t</xs:element>\n\t\n\t<xs:complexType name=\"CourseDetails\">\n\t\t<xs:sequence>\n\t\t\t<xs:element name=\"id\" type=\"xs:integer\"/>\n\t\t\t<xs:element name=\"name\" type=\"xs:string\"/>\n\t\t\t<xs:element name=\"description\" type=\"xs:string\"/>\n\t\t</xs:sequence>\n\t</xs:complexType>\n\t\n</xs:schema>\n```\n\n### Step 07 - Introduction to Java API for XML Binding (JAXB) and Configuring JAXB 2 Maven Plugin\n\n### Step 08 - Configuring an Endpoint for GetCourseDetailsRequest\n\n##### /pom.xml Modified\nNew Lines\n```\n<plugin>\n\t<groupId>org.codehaus.mojo</groupId>\n\t<artifactId>jaxb2-maven-plugin</artifactId>\n\t<version>1.6</version>\n\t<executions>\n\t\t<execution>\n\t\t\t<id>xjc</id>\n\t\t\t<goals>\n\t\t\t\t<goal>xjc</goal>\n\t\t\t</goals>\n\t\t</execution>\n\t</executions>\n\t<configuration>\n\t\t<schemaDirectory>${project.basedir}/src/main/resources</schemaDirectory>\n\t\t<outputDirectory>${project.basedir}/src/main/java</outputDirectory>\n\t\t<clearOutputDir>false</clearOutputDir>\n\t</configuration>\n</plugin>\n```\n\n##### /src/main/java/com/in28minutes/soap/webservices/soapcoursemanagement/soap/CourseDetailsEndpoint.java New\n\n```java\npackage com.in28minutes.soap.webservices.soapcoursemanagement.soap;\n\nimport org.springframework.ws.server.endpoint.annotation.Endpoint;\nimport org.springframework.ws.server.endpoint.annotation.PayloadRoot;\nimport org.springframework.ws.server.endpoint.annotation.RequestPayload;\nimport org.springframework.ws.server.endpoint.annotation.ResponsePayload;\n\nimport com.in28minutes.courses.CourseDetails;\nimport com.in28minutes.courses.GetCourseDetailsRequest;\nimport com.in28minutes.courses.GetCourseDetailsResponse;\n\n@Endpoint\npublic class CourseDetailsEndpoint {\n\n\t// method\n\t// input - GetCourseDetailsRequest\n\t// output - GetCourseDetailsResponse\n\n\t// http://in28minutes.com/courses\n\t// GetCourseDetailsRequest\n\t@PayloadRoot(namespace = \"http://in28minutes.com/courses\", localPart = \"GetCourseDetailsRequest\")\n\t@ResponsePayload\n\tpublic GetCourseDetailsResponse processCourseDetailsRequest(@RequestPayload GetCourseDetailsRequest request) {\n\t\tGetCourseDetailsResponse response = new GetCourseDetailsResponse();\n\t\t\n\t\tCourseDetails courseDetails = new CourseDetails();\n\t\tcourseDetails.setId(request.getId());\n\t\tcourseDetails.setName(\"Microservices Course\");\n\t\tcourseDetails.setDescription(\"That would be a wonderful course!\");\n\t\t\n\t\tresponse.setCourseDetails(courseDetails);\n\t\t\n\t\treturn response;\n\t}\n\n}\n```\n\n##### /src/main/resources/course-details.xsd New\n\n```\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" \ntargetNamespace=\"http://in28minutes.com/courses\" \nxmlns:tns=\"http://in28minutes.com/courses\" elementFormDefault=\"qualified\">\n\t\n\t<xs:element name=\"GetCourseDetailsRequest\">\n\t\t<xs:complexType>\n\t\t\t<xs:sequence>\n\t\t\t\t<xs:element name= \"id\" type=\"xs:int\"/>\n\t\t\t</xs:sequence>\t\n\t\t</xs:complexType>\n\t</xs:element>\n\t\n\t<xs:element name=\"GetCourseDetailsResponse\">\n\t\t<xs:complexType>\n\t\t\t<xs:sequence>\n\t\t\t\t<xs:element name= \"CourseDetails\" type=\"tns:CourseDetails\"/>\n\t\t\t</xs:sequence>\t\n\t\t</xs:complexType>\n\t</xs:element>\n\t\n\t<xs:complexType name=\"CourseDetails\">\n\t\t<xs:sequence>\n\t\t\t<xs:element name=\"id\" type=\"xs:int\"/>\n\t\t\t<xs:element name=\"name\" type=\"xs:string\"/>\n\t\t\t<xs:element name=\"description\" type=\"xs:string\"/>\n\t\t</xs:sequence>\n\t</xs:complexType>\n\t\n</xs:schema>\n```\n\n### Step 09 - Spring Web Services Configuration - Message Dispatcher Servlet\n\n### Step 10 - Spring Web Services Configuration - Generating WSDL\n\n##### /pom.xml Modified\nNew Lines\n```\n\t\t<dependency>\n\t\t\t<groupId>wsdl4j</groupId>\n\t\t\t<artifactId>wsdl4j</artifactId>\n\t\t</dependency>\n```\n##### /src/main/java/com/in28minutes/soap/webservices/soapcoursemanagement/soap/WebServiceConfig.java New\n\n```java\npackage com.in28minutes.soap.webservices.soapcoursemanagement.soap;\n\nimport org.springframework.boot.web.servlet.ServletRegistrationBean;\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.core.io.ClassPathResource;\nimport org.springframework.ws.config.annotation.EnableWs;\nimport org.springframework.ws.transport.http.MessageDispatcherServlet;\nimport org.springframework.ws.wsdl.wsdl11.DefaultWsdl11Definition;\nimport org.springframework.xml.xsd.SimpleXsdSchema;\nimport org.springframework.xml.xsd.XsdSchema;\n\n//Enable Spring Web Services\n@EnableWs\n// Spring Configuration\n@Configuration\npublic class WebServiceConfig {\n\t// MessageDispatcherServlet\n\t// ApplicationContext\n\t// url -> /ws/*\n\n\t@Bean\n\tpublic ServletRegistrationBean messageDispatcherServlet(ApplicationContext context) {\n\t\tMessageDispatcherServlet messageDispatcherServlet = new MessageDispatcherServlet();\n\t\tmessageDispatcherServlet.setApplicationContext(context);\n\t\tmessageDispatcherServlet.setTransformWsdlLocations(true);\n\t\treturn new ServletRegistrationBean(messageDispatcherServlet, \"/ws/*\");\n\t}\n\n\t// /ws/courses.wsdl\n\t// course-details.xsd\n\t@Bean(name = \"courses\")\n\tpublic DefaultWsdl11Definition defaultWsdl11Definition(XsdSchema coursesSchema) {\n\t\tDefaultWsdl11Definition definition = new DefaultWsdl11Definition();\n\t\tdefinition.setPortTypeName(\"CoursePort\");\n\t\tdefinition.setTargetNamespace(\"http://in28minutes.com/courses\");\n\t\tdefinition.setLocationUri(\"/ws\");\n\t\tdefinition.setSchema(coursesSchema);\n\t\treturn definition;\n\t}\n\n\t@Bean\n\tpublic XsdSchema coursesSchema() {\n\t\treturn new SimpleXsdSchema(new ClassPathResource(\"course-details.xsd\"));\n\t}\n}\n```\n\n### Step 11 - Using Wizdler to execute SOAP Requests\n\n### Step 12 - Implementing a service - Course Details Service - backend with in memory array list\n\n##### /pom.xml Modified\nNew Lines\n```\n\t\t<dependency>\n\t\t\t<groupId>org.springframework.boot</groupId>\n\t\t\t<artifactId>spring-boot-devtools</artifactId>\n\t\t</dependency>\n```\n##### /src/main/java/com/in28minutes/soap/webservices/soapcoursemanagement/soap/CourseDetailsEndpoint.java Modified\n```java\n@Endpoint\npublic class CourseDetailsEndpoint {\n\t\n\t@Autowired\n\tCourseDetailsService service;\n\n\t// method\n\t// input - GetCourseDetailsRequest\n\t// output - GetCourseDetailsResponse\n\n\t// http://in28minutes.com/courses\n\t// GetCourseDetailsRequest\n\t@PayloadRoot(namespace = \"http://in28minutes.com/courses\", localPart = \"GetCourseDetailsRequest\")\n\t@ResponsePayload\n\tpublic GetCourseDetailsResponse processCourseDetailsRequest(@RequestPayload GetCourseDetailsRequest request) {\n\t\t\n\t\tCourse course = service.findById(request.getId());\n\n\t\treturn mapCourse(course);\n\t}\n\n\tprivate GetCourseDetailsResponse mapCourse(Course course) {\n\t\tGetCourseDetailsResponse response = new GetCourseDetailsResponse();\n\t\t\n\t\tCourseDetails courseDetails = new CourseDetails();\n\t\t\n\t\tcourseDetails.setId(course.getId());\n\t\t\n\t\tcourseDetails.setName(course.getName());\n\t\t\n\t\tcourseDetails.setDescription(course.getDescription());\n\t\t\n\t\tresponse.setCourseDetails(courseDetails);\n\t\t\n\t\treturn response;\n\t}\n\n}\n```\n\n##### /src/main/java/com/in28minutes/soap/webservices/soapcoursemanagement/soap/bean/Course.java New\n\n```java\npackage com.in28minutes.soap.webservices.soapcoursemanagement.soap.bean;\n\npublic class Course {\n\tprivate int id;\n\tprivate String name;\n\tprivate String description;\n\t\n\t\n\tpublic Course(int id, String name, String description) {\n\t\tsuper();\n\t\tthis.id = id;\n\t\tthis.name = name;\n\t\tthis.description = description;\n\t}\n\n\tpublic int getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(int id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic String getDescription() {\n\t\treturn description;\n\t}\n\n\tpublic void setDescription(String description) {\n\t\tthis.description = description;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn String.format(\"Course [id=%s, name=%s, description=%s]\", id, name, description);\n\t}\n\n}\n```\n\n##### /src/main/java/com/in28minutes/soap/webservices/soapcoursemanagement/soap/service/CourseDetailsService.java New\n\n```java\npackage com.in28minutes.soap.webservices.soapcoursemanagement.soap.service;\n\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.List;\n\nimport org.springframework.stereotype.Component;\n\nimport com.in28minutes.soap.webservices.soapcoursemanagement.soap.bean.Course;\n\n@Component\npublic class CourseDetailsService {\n\n\tprivate static List<Course> courses = new ArrayList<>();\n\n\tstatic {\n\t\tCourse course1 = new Course(1, \"Spring\", \"10 Steps\");\n\t\tcourses.add(course1);\n\n\t\tCourse course2 = new Course(2, \"Spring MVC\", \"10 Examples\");\n\t\tcourses.add(course2);\n\n\t\tCourse course3 = new Course(3, \"Spring Boot\", \"6K Students\");\n\t\tcourses.add(course3);\n\n\t\tCourse course4 = new Course(4, \"Maven\", \"Most popular maven course on internet!\");\n\t\tcourses.add(course4);\n\t}\n\n\t// course - 1\n\tpublic Course findById(int id) {\n\t\tfor (Course course : courses) {\n\t\t\tif (course.getId() == id)\n\t\t\t\treturn course;\n\t\t}\n\t\treturn null;\n\t}\n\n\t// courses\n\tpublic List<Course> findAll() {\n\t\treturn courses;\n\t}\n\n\tpublic int deleteById(int id) {\n\t\tIterator<Course> iterator = courses.iterator();\n\t\twhile (iterator.hasNext()) {\n\t\t\tCourse course = iterator.next();\n\t\t\tif (course.getId() == id) {\n\t\t\t\titerator.remove();\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t}\n\t\treturn 0;\n\t}\n\n\t// updating course & new course\n}\n```\n\n### Step 13 - Implementing SOAP Web Service for GetAllCourseDetailsRequest\n\n\n##### /src/main/java/com/in28minutes/soap/webservices/soapcoursemanagement/soap/CourseDetailsEndpoint.java Modified\nNew Lines\n```\n\n@Endpoint\npublic class CourseDetailsEndpoint {\n\n\t@Autowired\n\tCourseDetailsService service;\n\n\t// method\n\t// input - GetCourseDetailsRequest\n\t// output - GetCourseDetailsResponse\n\n\t// http://in28minutes.com/courses\n\t// GetCourseDetailsRequest\n\t@PayloadRoot(namespace = \"http://in28minutes.com/courses\", localPart = \"GetCourseDetailsRequest\")\n\t@ResponsePayload\n\tpublic GetCourseDetailsResponse processCourseDetailsRequest(@RequestPayload GetCourseDetailsRequest request) {\n\n\t\tCourse course = service.findById(request.getId());\n\n\t\treturn mapCourseDetails(course);\n\t}\n\n\tprivate GetCourseDetailsResponse mapCourseDetails(Course course) {\n\t\tGetCourseDetailsResponse response = new GetCourseDetailsResponse();\n\t\tresponse.setCourseDetails(mapCourse(course));\n\t\treturn response;\n\t}\n\n\tprivate GetAllCourseDetailsResponse mapAllCourseDetails(List<Course> courses) {\n\t\tGetAllCourseDetailsResponse response = new GetAllCourseDetailsResponse();\n\t\tfor (Course course : courses) {\n\t\t\tCourseDetails mapCourse = mapCourse(course);\n\t\t\tresponse.getCourseDetails().add(mapCourse);\n\t\t}\n\t\treturn response;\n\t}\n\n\tprivate CourseDetails mapCourse(Course course) {\n\t\tCourseDetails courseDetails = new CourseDetails();\n\n\t\tcourseDetails.setId(course.getId());\n\n\t\tcourseDetails.setName(course.getName());\n\n\t\tcourseDetails.setDescription(course.getDescription());\n\t\treturn courseDetails;\n\t}\n\n\t@PayloadRoot(namespace = \"http://in28minutes.com/courses\", localPart = \"GetAllCourseDetailsRequest\")\n\t@ResponsePayload\n\tpublic GetAllCourseDetailsResponse processAllCourseDetailsRequest(\n\t\t\t@RequestPayload GetAllCourseDetailsRequest request) {\n\n\t\tList<Course> courses = service.findAll();\n\n\t\treturn mapAllCourseDetails(courses);\n\t}\n\n}\n```\n\n##### /src/main/resources/course-details.xsd Modified\nNew Lines\n```\n<xs:element name=\"GetAllCourseDetailsResponse\">\n\t<xs:complexType>\n\t\t<xs:sequence>\n\t\t\t<xs:element name=\"CourseDetails\" type=\"tns:CourseDetails\" \n\t\t\t\t\t\tmaxOccurs=\"unbounded\"/>\n\t\t</xs:sequence>\t\n\t</xs:complexType>\n</xs:element>\n\n\n<xs:complexType name=\"CourseDetails\">\n\t<xs:sequence>\n\t\t<xs:element name=\"id\" type=\"xs:int\"/>\n\t\t<xs:element name=\"name\" type=\"xs:string\"/>\n\t\t<xs:element name=\"description\" type=\"xs:string\"/>\n\t</xs:sequence>\n</xs:complexType>\n\n```\n\n### Step 14 - Quick introduction to different parts of a WSDL\n![Image](/images/Web_Services_WSDL_HighLevel.png)\n![Image](/images/Web_Services_WSDL_LowLevel.png)\n![Image](/images/SOAP_WEB_SERVICE_Initial_Setup_Overview.png)\n![Image](/images/SOAPWebServiceClientAndServiceProvider.png)\n\n### Step 15 - Implementing SOAP Web Service for DeleteCourseDetailsRequest\n\n##### /src/main/java/com/in28minutes/soap/webservices/soapcoursemanagement/soap/CourseDetailsEndpoint.java Modified\nNew Lines\n\n```java\n\n@PayloadRoot(namespace = \"http://in28minutes.com/courses\", localPart = \"DeleteCourseDetailsRequest\")\n@ResponsePayload\npublic DeleteCourseDetailsResponse deleteCourseDetailsRequest(\n\t\t@RequestPayload DeleteCourseDetailsRequest request) {\n\n\tint status = service.deleteById(request.getId());\n\n\tDeleteCourseDetailsResponse response = new DeleteCourseDetailsResponse();\n\tresponse.setStatus(status);\n\t\n\treturn response;\n}\n\n```\n\n##### /src/main/resources/course-details.xsd Modified\nNew Lines\n```\n\t<xs:element name=\"DeleteCourseDetailsRequest\">\n\t\t<xs:complexType>\n\t\t\t<xs:sequence>\n\t\t\t\t<xs:element name= \"id\" type=\"xs:int\"/>\n\t\t\t</xs:sequence>\t\n\t\t</xs:complexType>\n\t</xs:element>\n\n\t<xs:element name=\"DeleteCourseDetailsResponse\">\n\t\t<xs:complexType>\n\t\t\t<xs:sequence>\n\t\t\t\t<!-- 1 is success 0 for failure -->\n\t\t\t\t<xs:element name= \"status\" type=\"xs:int\"/>\n\t\t\t</xs:sequence>\t\n\t\t</xs:complexType>\n\t</xs:element>\n```\n\n### Step 16 - Improving the DeleteCourseDetailsRequest - Using an Enum for Status\n### Step 17 - Exception Handling and SOAP Fault Responses\n\n##### /src/main/java/com/in28minutes/soap/webservices/soapcoursemanagement/soap/CourseDetailsEndpoint.java Modified\n\n```java\n\t@PayloadRoot(namespace = \"http://in28minutes.com/courses\", localPart = \"GetCourseDetailsRequest\")\n\t@ResponsePayload\n\tpublic GetCourseDetailsResponse processCourseDetailsRequest(@RequestPayload GetCourseDetailsRequest request) {\n\n\t\tCourse course = service.findById(request.getId());\n\n\t\tif (course == null)\n\t\t\tthrow new CourseNotFoundException(\"Invalid Course Id \" + request.getId());\n\n\t\treturn mapCourseDetails(course);\n\t}\n\n\t@PayloadRoot(namespace = \"http://in28minutes.com/courses\", localPart = \"DeleteCourseDetailsRequest\")\n\t@ResponsePayload\n\tpublic DeleteCourseDetailsResponse deleteCourseDetailsRequest(@RequestPayload DeleteCourseDetailsRequest request) {\n\n\t\tStatus status = service.deleteById(request.getId());\n\n\t\tDeleteCourseDetailsResponse response = new DeleteCourseDetailsResponse();\n\t\tresponse.setStatus(mapStatus(status));\n\n\t\treturn response;\n\t}\n\n\tprivate com.in28minutes.courses.Status mapStatus(Status status) {\n\t\tif (status == Status.FAILURE)\n\t\t\treturn com.in28minutes.courses.Status.FAILURE;\n\t\treturn com.in28minutes.courses.Status.SUCCESS;\n\t}\n```\n\n##### /src/main/java/com/in28minutes/soap/webservices/soapcoursemanagement/soap/exception/CourseNotFoundException.java New\n\n```java\npackage com.in28minutes.soap.webservices.soapcoursemanagement.soap.exception;\n\nimport org.springframework.ws.soap.server.endpoint.annotation.FaultCode;\nimport org.springframework.ws.soap.server.endpoint.annotation.SoapFault;\n\n@SoapFault(faultCode=FaultCode.CUSTOM, \n\tcustomFaultCode=\"{http://in28minutes.com/courses}001_COURSE_NOT_FOUND\")\npublic class CourseNotFoundException extends RuntimeException {\n\n\tprivate static final long serialVersionUID = 3518170101751491969L;\n\n\tpublic CourseNotFoundException(String message) {\n\t\tsuper(message);\n\t}\n\n}\n```\n\n##### /src/main/java/com/in28minutes/soap/webservices/soapcoursemanagement/soap/service/CourseDetailsService.java Modified\n```java\n\t\n\tpublic enum Status {\n\t\tSUCCESS, FAILURE;\n\t}\n\n\tpublic Status deleteById(int id) {\n\t\tIterator<Course> iterator = courses.iterator();\n\t\twhile (iterator.hasNext()) {\n\t\t\tCourse course = iterator.next();\n\t\t\tif (course.getId() == id) {\n\t\t\t\titerator.remove();\n\t\t\t\treturn Status.SUCCESS;\n\t\t\t}\n\t\t}\n\t\treturn Status.FAILURE;\n\t}\n\n```\n\n##### /src/main/resources/course-details.xsd Modified\nNew Lines\n```\n\t<xs:element name=\"DeleteCourseDetailsResponse\">\n\t\t<xs:complexType>\n\t\t\t<xs:sequence>\n\t\t\t\t<xs:element name= \"status\" type=\"tns:Status\"/>\n\t\t\t</xs:sequence>\t\n\t\t</xs:complexType>\n\t</xs:element>\n\t\n\t<xs:simpleType name=\"Status\">\n\t\t<xs:restriction base=\"xs:string\">\n\t\t\t<xs:enumeration value=\"SUCCESS\"/>\n\t\t\t<xs:enumeration value=\"FAILURE\"/>\n\t\t</xs:restriction>\n\t</xs:simpleType>\n\n```\n\n### Step 18 - Implementing Security for SOAP Web Services with WS Security\n\n##### /example-files/Request-Security.xml New\n\n```xml\n<Envelope xmlns=\"http://schemas.xmlsoap.org/soap/envelope/\">\n\t<Header>\n\t\t<wsse:Security\n\t\t\txmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"\n\t\t\tmustUnderstand=\"1\">\n\t\t\t<wsse:UsernameToken>\n\t\t\t\t<wsse:Username>user</wsse:Username>\n\t\t\t\t<wsse:Password>password</wsse:Password>\n\t\t\t</wsse:UsernameToken>\n\t\t</wsse:Security>\n\t</Header>\n\t<Body>\n\t\t<GetCourseDetailsRequest xmlns=\"http://in28minutes.com/courses\">\n\t\t\t<id>1</id>\n\t\t</GetCourseDetailsRequest>\n\t</Body>\n</Envelope>\n```\n##### /example-files/Response-Fault.xml New\n\n```xml\n<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">\n\t<SOAP-ENV:Header />\n\t<SOAP-ENV:Body>\n\t\t<SOAP-ENV:Fault>\n\t\t\t<faultcode xmlns:ns0=\"http://in28minutes.com/courses\">ns0:001_COURSE_NOT_FOUND</faultcode>\n\t\t\t<faultstring xml:lang=\"en\">Invalid Course Id 1234</faultstring>\n\t\t</SOAP-ENV:Fault>\n\t</SOAP-ENV:Body>\n</SOAP-ENV:Envelope>\n```\n\n##### /pom.xml Modified\nNew Lines\n```\n\t\t<dependency>\n\t\t\t<groupId>org.springframework.ws</groupId>\n\t\t\t<artifactId>spring-ws-security</artifactId>\n\t\t\t<exclusions>\n\t\t\t\t<exclusion>\n\t\t\t\t\t<groupId>org.springframework.security</groupId>\n\t\t\t\t\t<artifactId>spring-security-core</artifactId>\n\t\t\t\t</exclusion>\n\t\t\t</exclusions>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.sun.xml.wss</groupId>\n\t\t\t<artifactId>xws-security</artifactId>\n\t\t\t<version>3.0</version>\n\t\t\t<exclusions>\n\t\t\t\t<exclusion>\n\t\t\t\t\t<groupId>javax.xml.crypto</groupId>\n\t\t\t\t\t<artifactId>xmldsig</artifactId>\n\t\t\t\t</exclusion>\n\t\t\t</exclusions>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>javax.activation</groupId>\n\t\t\t<artifactId>activation</artifactId>\n\t\t\t<version>1.1.1</version>\n\t\t</dependency>\n\t\t\n```\n\n##### /src/main/java/com/in28minutes/soap/webservices/soapcoursemanagement/soap/WebServiceConfig.java Modified\n```java\n\t\n\n\t//XwsSecurityInterceptor\n\t@Bean\n\tpublic XwsSecurityInterceptor securityInterceptor(){\n\t\tXwsSecurityInterceptor securityInterceptor = new XwsSecurityInterceptor();\n\t\t//Callback Handler -> SimplePasswordValidationCallbackHandler\n\t\tsecurityInterceptor.setCallbackHandler(callbackHandler());\n\t\t//Security Policy -> securityPolicy.xml\n\t\tsecurityInterceptor.setPolicyConfiguration(new ClassPathResource(\"securityPolicy.xml\"));\n\t\treturn securityInterceptor;\n\t}\n\t\n\t@Bean\n\tpublic SimplePasswordValidationCallbackHandler callbackHandler() {\n\t\tSimplePasswordValidationCallbackHandler handler = new SimplePasswordValidationCallbackHandler();\n\t\thandler.setUsersMap(Collections.singletonMap(\"user\", \"password\"));\n\t\treturn handler;\n\t}\n\n\t//Interceptors.add -> XwsSecurityInterceptor\n\t@Override\n\tpublic void addInterceptors(List<EndpointInterceptor> interceptors) {\n\t\tinterceptors.add(securityInterceptor());\n\t}\n\n```\n\n##### /src/main/java/com/in28minutes/soap/webservices/soapcoursemanagement/soap/exception/CourseNotFoundException.java Modified\n```java\n@SoapFault(faultCode = FaultCode.CUSTOM, customFaultCode = \"{http://in28minutes.com/courses}001_COURSE_NOT_FOUND\")\npublic class CourseNotFoundException extends RuntimeException {\n\n```\n\n##### /src/main/resources/course-details.xsd Modified\n```\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n\ttargetNamespace=\"http://in28minutes.com/courses\" xmlns:tns=\"http://in28minutes.com/courses\"\n\telementFormDefault=\"qualified\">\n\n\t<xs:element name=\"GetCourseDetailsRequest\">\n\t\t<xs:complexType>\n\t\t\t<xs:sequence>\n\t\t\t\t<xs:element name=\"id\" type=\"xs:int\" />\n\t\t\t</xs:sequence>\n\t\t</xs:complexType>\n\t</xs:element>\n\n\t<xs:element name=\"GetCourseDetailsResponse\">\n\t\t<xs:complexType>\n\t\t\t<xs:sequence>\n\t\t\t\t<xs:element name=\"CourseDetails\" type=\"tns:CourseDetails\" />\n\t\t\t</xs:sequence>\n\t\t</xs:complexType>\n\t</xs:element>\n\n\t<xs:element name=\"GetAllCourseDetailsRequest\">\n\t\t<xs:complexType>\n\t\t</xs:complexType>\n\t</xs:element>\n\n\t<xs:element name=\"GetAllCourseDetailsResponse\">\n\t\t<xs:complexType>\n\t\t\t<xs:sequence>\n\t\t\t\t<xs:element name=\"CourseDetails\" type=\"tns:CourseDetails\"\n\t\t\t\t\tmaxOccurs=\"unbounded\" />\n\t\t\t</xs:sequence>\n\t\t</xs:complexType>\n\t</xs:element>\n\n\t<xs:element name=\"DeleteCourseDetailsRequest\">\n\t\t<xs:complexType>\n\t\t\t<xs:sequence>\n\t\t\t\t<xs:element name=\"id\" type=\"xs:int\" />\n\t\t\t</xs:sequence>\n\t\t</xs:complexType>\n\t</xs:element>\n\n\t<xs:element name=\"DeleteCourseDetailsResponse\">\n\t\t<xs:complexType>\n\t\t\t<xs:sequence>\n\t\t\t\t<xs:element name=\"status\" type=\"tns:Status\" />\n\t\t\t</xs:sequence>\n\t\t</xs:complexType>\n\t</xs:element>\n\n\t<xs:simpleType name=\"Status\">\n\t\t<xs:restriction base=\"xs:string\">\n\t\t\t<xs:enumeration value=\"SUCCESS\" />\n\t\t\t<xs:enumeration value=\"FAILURE\" />\n\t\t</xs:restriction>\n\t</xs:simpleType>\n\n\t<xs:complexType name=\"CourseDetails\">\n\t\t<xs:sequence>\n\t\t\t<xs:element name=\"id\" type=\"xs:int\" />\n\t\t\t<xs:element name=\"name\" type=\"xs:string\" />\n\t\t\t<xs:element name=\"description\" type=\"xs:string\" />\n\t\t</xs:sequence>\n\t</xs:complexType>\n\n</xs:schema>\n```\n##### /src/main/resources/securityPolicy.xml New\n\n```xml\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<xwss:SecurityConfiguration \n\txmlns:xwss=\"http://java.sun.com/xml/ns/xwss/config\">\n\t<xwss:RequireUsernameToken\n\t\tpasswordDigestRequired=\"false\" nonceRequired=\"false\" />\n</xwss:SecurityConfiguration>\n```\n\n### Example Requests and Responses\n\n```xml\n<Envelope xmlns=\"http://schemas.xmlsoap.org/soap/envelope/\">\n\t<Header>\n\t\t<wsse:Security\n\t\t\txmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"\n\t\t\tmustUnderstand=\"1\">\n\t\t\t<wsse:UsernameToken>\n\t\t\t\t<wsse:Username>user</wsse:Username>\n\t\t\t\t<wsse:Password>password</wsse:Password>\n\t\t\t</wsse:UsernameToken>\n\t\t</wsse:Security>\n\t</Header>\n\t<Body>\n\t\t<GetCourseDetailsRequest xmlns=\"http://in28minutes.com/courses\">\n\t\t\t<id>1</id>\n\t\t</GetCourseDetailsRequest>\n\t</Body>\n</Envelope>\n```\n\n##### /example-files/Request.xml\n\n```xml\n<Envelope xmlns=\"http://schemas.xmlsoap.org/soap/envelope/\">\n\t<Body>\n\t\t<GetCourseDetailsRequest xmlns=\"http://in28minutes.com/courses\">\n\t\t\t<id>1</id>\n\t\t</GetCourseDetailsRequest>\n\t</Body>\n</Envelope>\n```\n\n##### /example-files/Response-Fault.xml\n\n```xml\n<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">\n\t<SOAP-ENV:Header />\n\t<SOAP-ENV:Body>\n\t\t<SOAP-ENV:Fault>\n\t\t\t<faultcode xmlns:ns0=\"http://in28minutes.com/courses\">ns0:001_COURSE_NOT_FOUND</faultcode>\n\t\t\t<faultstring xml:lang=\"en\">Invalid Course Id 1234</faultstring>\n\t\t</SOAP-ENV:Fault>\n\t</SOAP-ENV:Body>\n</SOAP-ENV:Envelope>\n```\n\n##### /example-files/Response.xml\n\n```xml\n<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <SOAP-ENV:Header/>\n    <SOAP-ENV:Body>\n        <ns2:GetCourseDetailsResponse xmlns:ns2=\"http://in28minutes.com/courses\">\n            <ns2:CourseDetails>\n                <ns2:id>1</ns2:id>\n                <ns2:name>Spring</ns2:name>\n                <ns2:description>10 Steps</ns2:description>\n            </ns2:CourseDetails>\n        </ns2:GetCourseDetailsResponse>\n    </SOAP-ENV:Body>\n</SOAP-ENV:Envelope>\n```\n\n\n### REST\n\n> REpresentational State Transfer\n\n\n> REST is a style of software architecture for distributed hypermedia systems\n\n#### Make best use of HTTP\n\n![Image](/images/REST_Block_Structure.png)\n\n![Image](/images/Web_Service_Browser_Server__Interaction.png)\n\n#### Key abstraction - Resource\n\n- A resource has an URI (Uniform Resource Identifier)\n - /users/Ranga/todos/1\n - /users/Ranga/todos\n - /users/Ranga\n- A resource can have different representations\n - XML\n - HTML\n - JSON\n\n##### Example\n\n- Create a User - POST    /users\n- Delete a User - DELETE  /users/1\n- Get all Users - GET     /users\n- Get one Users - GET     /users/1 \n\n#### REST\n\n- Data Exchange Format\n\t- No Restriction. JSON is popular\n- Transport\n\t- Only HTTP\n- Service Definition\n\t- No Standard. WADL/Swagger/...\n\n#### REST vs SOAP\n\n- Restrictions vs Architectural Approach\n- Data Exchange Format\n- Service Definition\n- Transport\n- Ease of implementation\n\n```xml\n<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <SOAP-ENV:Header/>\n    <SOAP-ENV:Body>\n        <ns2:GetCourseDetailsRequest xmlns:ns2=\"http://in28minutes.com/courses\">\n                <ns2:id>Course1</ns2:id>\n        </ns2:GetCourseDetailsRequest>\n    </SOAP-ENV:Body>\n</SOAP-ENV:Envelope>\n```\n\n```xml\n<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <SOAP-ENV:Header/>\n    <SOAP-ENV:Body>\n        <ns2:GetCourseDetailsResponse xmlns:ns2=\"http://in28minutes.com/courses\">\n            <ns2:CourseDetails>\n                <ns2:id>Course1</ns2:id>\n                <ns2:name>Spring</ns2:name>\n                <ns2:description>10 Steps</ns2:description>\n            </ns2:CourseDetails>\n        </ns2:GetCourseDetailsResponse>\n    </SOAP-ENV:Body>\n</SOAP-ENV:Envelope>\n```\n\n### Richardson Maturity Model\n\n#### Level 0\n\n##### Expose SOAP web services in REST style\n- http://server/getPosts\n- http://server/deletePosts\n- http://server/doThis\n\n\n#### Level 1\n\n- Expose Resources with proper URI\n\t- http://server/accounts\n\t- http://server/accounts/10\n- Improper use of HTTP Methods\n\n#### Level 2\n\n- Level 1 + HTTP Methods\n\n#### Level 3\n\n- Level 2 + HATEOAS\n\t- Data + Next Possible Actions\n\n#### Best Practices in RESTful Design\n\n- Consumer First\n- Make best use of HTTP\n  - Request Methods\n    - GET\n    - POST\n    - PUT\n    - DELETE\n  - Response Status\n    - 200 - SUCCESS\n    - 404 - RESOURCE NOT FOUND\n    - 400 - BAD REQUEST\n    - 201 - CREATED\n    - 401 - UNAUTHORIZED\n    - 500 - SERVER ERROR\n- No Secure Info in URI\n- Use Plurals\n  - Prefer /users to /user\n  - Prefer /users/1 to /user/1\n- Use Nouns for Resources\n- For Exceptions\n  - Define a Consistent Approach\n    - /search\n    - PUT /gists/{id}/star\n    - DELETE /gists/{id}/star\n- Consumer First\n- Define Organizational Standards\n  - YARAS - https://github.com/darrin/yaras\n    - Naming Resources\n    - Request Response Structures\n    - Common Features Standardization\n      - Error Handling\n      - Versioning\n      - Searching\n      - Filtering\n      - Support for Mock Responses\n      - HATEOAS\n- Build a Framework\n- Focus on Decentralized Governance\n\nFor more - http://www.in28minutes.com/microservices-and-restful-services-with-spring-boot-for-beginners\n\n"
  },
  {
    "path": "_blog/articles/2017-10-18-springboot-in-10-steps.md",
    "content": "---\nlayout:     post\ntitle:      Spring Boot Tutorial For Beginners in 10 Steps\ndate:       2023-03-17 12:31:19\nsummary:    An Overview of Spring Boot in 10 Easy Steps Set up a basic Spring Boot project example to learn the fundamentals of Spring Boot.\ncategories: SpringBoot\npermalink:  /spring-boot-introduction-in-10-steps\nimage: /images/spring-boot-category.png\n---\n\n## Spring Boot Goals:\n\n- Allows for the rapid development of production-ready apps.\n- It provides common non-functional features.\n\t- Embedded servers\n\t- Metrics\n\t- Health checks\n\t- Externalized configuration\n\n\n\n## What Spring Boot is NOT!\n- ZERO code generation.\n- There is no application server or web server.\n\n## Features\n- Quick Starter Projects with Auto Configuration\n\t- Web\n\t- JPA\n- Embedded Servers \n\t- Tomcat, Jetty or Undertow\n- Production-ready features\n\t- Metrics and health checks \n\t- Externalized configuration\n \n## URLs\n- http://localhost:8080/books => Few hardcoded books \n\n\n## Step by Step Details\n- Step 1 : Introduction to Spring Boot—Goals and Important Features\n- Step 2: Create Spring Applications Prior to Spring Boot\n- Step 3: Creating a Spring Boot Application with Spring Initializr\n- Step 4 : Creating a Simple REST Controller\n- Step 5 : What is Spring Boot Auto Configuration?\n\t- Recommended Reading-http://www.springboottutorial.com/spring-boot-auto-configuration\n\t- Spring-based apps may be highly customised. Spring MVC requires us to configure component scan, dispatcher servlet, view resolver, and web jars (for serving static content), among other things. We would need to configure a datasource, an entity management factory, and a transaction manager, among other things, when using Hibernate/JPA. The Spring Boot introduces a different way of thinking about this: Can we incorporate more intelligence into this? Can we automatically setup certain beans when a spring mvc jar is introduced to an application?\n- Step 6 : Spring Boot vs. Spring vs. Spring MVC\n\t- Recommended Reading-http://www.springboottutorial.com/spring-boot-vs-spring-mvc-vs-spring\n\t- Spring is about `Dependency Injection`. It makes it easy to develop *loosely coupled applications*. It makes applications *testable*.\n\t- Spring MVC brings loose coupling to web MVC application development with features like `Dispatcher Servlet, View Resolver`, etc.\n\t- Spring Boot eliminates the need for manual configuration with Spring and Spring MVC. You can use Spring and Spring MVC without needing a lot of configuration. \n\t- Spring Boot aims to enable production-ready applications in quick time.\n\t\t- **Actuator** : Enables Advanced `Monitoring and Tracing` of applications.\n\t\t- **Embedded Server Integrations** : Because the server is built into the application, I don't need to install a separate application server on the server.\n\t\t- Default Error Handling\n- Step 7 : Spring Boot Starter Projects: Starter Web and Starter JPA\n\t- Recommended Reading-http://www.springboottutorial.com/spring-boot-starter-projects\n\t- `Starters` are a set of convenient `dependency descriptors` that you can include in your application. You get a one-stop-shop for all the Spring and related technology that you need, without having to hunt through sample code and copy-paste loads of dependency descriptors. *For example*, if you want to get started using Spring and JPA for database access, just include the `spring-boot-starter-data-jpa` dependency in your project, and you are good to go.\n- Step 8: A Summary of the Different Spring Boot Starter Projects\n\t- As we see from Spring Boot Starter Web, starter projects help us to quickly get started with developing specific types of applications.\n\t- `spring-boot-starter-web-services`-*SOAP Web Services*\n\t- `spring-boot-starter-web`-*Web & RESTful applications*\n\t- `spring-boot-starter-test`-*Unit Testing and Integration Testing*\n\t- `spring-boot-starter-jdbc`-*Traditional JDBC*\n\t- `spring-boot-starter-hateoas`-*Add HATEOAS features to your services.*\n\t- `spring-boot-starter-security`-*Authentication and Authorization using Spring Security*\n\t- `spring-boot-starter-data-jpa`-*Spring Data JPA with Hibernate*\n\t- `spring-boot-starter-cache`-*Enabling Spring Framework’s caching support*\n\t- `spring-boot-starter-data-rest`-*Expose Simple REST Services using Spring Data REST*\n\t- `spring-boot-starter-actuator`-*To add advanced features such as monitoring and tracing to your application right away.*\n\t- `spring-boot-starter-undertow, spring-boot-starter-jetty, spring-boot-starter-tomcat`-*To pick your specific choice of Embedded Servlet Container*\n\t- `spring-boot-starter-logging`-*For Logging using Logback*\n\t- `spring-boot-starter-log4j2`-*Logging using Log4j2*\n- Step 9 : Spring Boot Actuator\n\t- The Spring Boot starter actuator actually exposes a lot of REST services, and these services are compliant with the standard called the HAL standard. And we would use a hal explorer so that we can browse through the data which is provided by these services. The Spring Boot Actuator exposes a lot of data-application info: `metrics, dump, beans, env, config properties, audit events, heap dump, loggers, trace, health mappings, and auto config`. *The Actuator provides more metadata about your application.* \n- Step 10 : Spring Boot Developer Tools\n\t- Why do you need to restart your server for every Java and JSP change?\n\t- The Spring Boot Developer Tools enable dynamic reloading of modified changes.\n- Spring Boot - Conclusion\n\n\n## Complete Code Example\n\n### /pom.xml\n\n```xml\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\n\t<groupId>com.in28minutes.springboot.basics</groupId>\n\t<artifactId>springboot-in-10-steps</artifactId>\n\t<version>0.0.1-SNAPSHOT</version>\n\t<packaging>jar</packaging>\n\n\t<name>springboot-in-10-steps</name>\n\t<description>Demo project for Spring Boot</description>\n\n\t<parent>\n\t\t<groupId>org.springframework.boot</groupId>\n\t\t<artifactId>spring-boot-starter-parent</artifactId>\n\t\t<version>3.0.4</version>\n\t\t<relativePath/> <!-- lookup parent from repository -->\n\t</parent>\n\n\t<properties>\n\t\t<java.version>17</java.version>\n\t</properties>\n\n\t<dependencies>\n\t\t<dependency>\n\t\t\t<groupId>org.springframework.boot</groupId>\n\t\t\t<artifactId>spring-boot-starter-web</artifactId>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>org.springframework.boot</groupId>\n\t\t\t<artifactId>spring-boot-starter-actuator</artifactId>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>org.springframework.data</groupId>\n\t\t\t<artifactId>spring-data-rest-hal-explorer</artifactId>\n\t\t</dependency>\n\n        <!-- \n\t\t<dependency>\n\t\t\t<groupId>org.springframework.boot</groupId>\n\t\t\t<artifactId>spring-boot-starter-data-jpa</artifactId>\n\t\t</dependency>\n\t\t -->\n\t\t\n\t\t<dependency>\n\t\t\t<groupId>org.springframework.boot</groupId>\n\t\t\t<artifactId>spring-boot-starter-test</artifactId>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>org.springframework.boot</groupId>\n\t\t\t<artifactId>spring-boot-devtools</artifactId>\n\t\t</dependency>\n\n\t</dependencies>\n\n\t<build>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.springframework.boot</groupId>\n\t\t\t\t<artifactId>spring-boot-maven-plugin</artifactId>\n\t\t\t</plugin>\n\t\t</plugins>\n\t</build>\n\n\t<repositories>\n\t\t<repository>\n\t\t\t<id>spring-milestones</id>\n\t\t\t<name>Spring Milestones</name>\n\t\t\t<url>https://repo.spring.io/milestone</url>\n\t\t\t<snapshots>\n\t\t\t\t<enabled>false</enabled>\n\t\t\t</snapshots>\n\t\t</repository>\n   </repositories>\n\n   <pluginRepositories>\n\t\t<pluginRepository>\n\t\t\t<id>spring-milestones</id>\n\t\t\t<name>Spring Milestones</name>\n\t\t\t<url>https://repo.spring.io/milestone</url>\n\t\t\t<snapshots>\n\t\t\t\t<enabled>false</enabled>\n\t\t\t</snapshots>\n\t\t</pluginRepository>\n\t</pluginRepositories>\n</project>\n```\n---\n\n### /src/main/java/com/in28minutes/springboot/basics/springbootin10steps/Book.java\n\n```java\npackage com.in28minutes.springboot.basics.springbootin10steps;\n\npublic record Book(long id, String name, String author) {\n\tpublic static String UNKNOWN_AUTHOR = \"Unknown\";\n    public static String UNNAMED = \"Unnamed\";\n\n\t  public Book {\n\t\t    Objects.requireNonNull(name);\n\t\t    Objects.requireNonNull(author);\n\t  }\n\t\n\t  public Book(String name) {\n\t\t this(name, UNKNOWN_AUTHOR);\n\t  }\n\t\n\t  public static Book unnamed(String author) {\n\t\treturn new Book(UNNAMED, author);\n\t  }\n\n}\n``` \n---\n\n### /src/main/java/com/in28minutes/springboot/basics/springbootin10steps/BooksController.java\n\n```java\npackage com.in28minutes.springboot.basics.springbootin10steps;\n\nimport java.util.List;\n\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.RestController;\n\n@RestController\npublic class BooksController {\n\t@GetMapping(\"/books\")\n\tpublic List<Book> getAllBooks() {\n\t\treturn List.of(new Book(1L, \"Mastering Spring 5.2\", \"Ranga Karanam\"));\n\t}\n}\n```\n---\n\n### /src/main/java/com/in28minutes/springboot/basics/springbootin10steps/SpringbootIn10StepsApplication.java\n\n```java\npackage com.in28minutes.springboot.basics.springbootin10steps;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.ConfigurableApplicationContext;\n\n@SpringBootApplication\npublic class SpringbootIn10StepsApplication {\n\n\tpublic static void main(String[] args) {\n\t\tvar applicationContext = \n\t\t\t\tSpringApplication.run(SpringbootIn10StepsApplication.class, args);\n\t\t\n\t\t\n\t\tapplicationContext.getBeanDefinitionNames()\n\t\t                  .forEach(System.out::println)\n\t}\n}\n```\n---\n\n### /src/main/resources/application.properties\n\n```properties\n#logging.level.org.springframework = DEBUG\nmanagement.endpoints.web.exposure.include=*\n```\n---\n\n### /src/test/java/com/in28minutes/springboot/basics/springbootin10steps/SpringbootIn10StepsApplicationTests.java\n\n```java\npackage com.in28minutes.springboot.basics.springbootin10steps;\n\nimport org.junit.jupiter.api.Test;\nimport org.junit.jupiter.api.extension.ExtendWith;\nimport org.springframework.boot.test.context.SpringBootTest;\nimport org.springframework.test.context.junit.jupiter.SpringExtension;\n\n@ExtendWith(SpringExtension.class)\n@SpringBootTest\npublic class SpringbootIn10StepsApplicationTests {\n\n\t@Test\n\tpublic void contextLoads() {\n\t}\n\n}\n```\n---\n"
  },
  {
    "path": "_blog/articles/2017-10-19-SpringMvcStepByStep.md",
    "content": "---\nlayout:     post\ntitle:      Spring MVC Tutorial for Beginners - in 25 Easy Steps\ndate:       2022-10-19 12:31:19\nsummary:    In this course, you will learn the basics developing a Basic Todo Management Application using Spring MVC with Login and Logout functionalities.\ncategories: SpringFramework\npermalink:  /spring-mvc-tutorial-for-beginners\nimage: /images/spring-framework-category.png\n---\n\nDeveloping your first Spring MVC Web Application is fun.\n\nIn this course, you will learn the basics developing a Basic Todo Management Application using Spring MVC with Login and Logout functionalities.\n\nYou will build the website step by step - in more than 25 steps. This course would be a perfect first step as an introduction to Java Web Application Development.\n\nYou will be using Spring (Dependency Management), Spring MVC, Spring Security (Authentication and Authorization), BootStrap (Styling Pages), Maven (dependencies management), Eclipse (IDE) and Tomcat Web Server. We will help you set up each one of these.\n\n## Course Link\n[![Image](/images/Course-Spring-MVC-For-Beginners-Build-Java-Web-App-in-25-Steps.png \"Spring MVC For Beginners : Build Java Web App in 25 Steps\")](https://links.in28minutes.com/MISC-SPRING-MVC){:target=\"_blank\"}\n\n\n\n## You will learn\n\nYou will learn about\n- DispatcherServlet\n- Basic Todo Management Application with Login/Logout\n- Model, Controllers, ViewResolver and Filters\n- Forms - DataBinding, Validation\n- Annotation based approach - @RequestParam, @PathVariable, @ModelAttribute, @SessionAttributes etc\n- Bootstrap to style the page\n- Spring Security\n- Internationalization\n- Exception Handling\n- Basic REST Services\n\n## Step Wise Details\n\n- Step 11 : Configure application to use Spring MVC\n- Step 12 : First Spring MVC Controller, @ResponseBody, @Controller\n- Step 13 : Redirect to Login JSP - LoginController, @ResponseBody - and View Resolver\n- Step 14 : DispatcherServlet and Log4j\n- Step 15 : Show userid and password on the welcome page - ModelMap and @RequestParam\n- Step 16 : LoginService and Remove all JEE Servlets based code\n- Step 17 : Spring Auto-wiring and Dependency Management - @Autowired and @Service\n- Step 18 : Create TodoController and list-todos view. Make TodoService a @Service and inject it.\n- Step 19 : Web Application Architecture\n- Step 20 : More about Spring Framework\n- Step 21 : Session vs Model vs Request - @SessionAttributes\n- Step 22 : New Todo and redirect to a Controller\n- Step 23 : JSTL\n- Step 24 : Bootstrap - using Webjars\n- Step 25 : Let's delete a Todo\n- Step 26 : Use Bootstrap to format and add HTML5 Validations\n- Step 27 : Introduce JSR 349 Validations using Hibernate Validator First Command Bean.\n- Step 28 : Let's update a Todo\n- Step 29 : Let's add a Target Date for Todo - Use initBinder to Handle Date Fields\n- Step 30 : Navigation bar and JSP Fragments\n- Step 31 : Let's prepare for Spring Security\n- Step 32 : Initial Setup for Spring Security\n- Step 33 : Refactor and add Logout Functionality using Spring Security\n- Step 34 : Exception Handling in Spring MVC - @ControllerAdvice, @ExceptionHandler and error-page in web dot xml\n- Step 35 : Let's add Internationalization - i18n\n- Step 36 : Basic Spring Rest Services - @RestController and jackson-databind\n- Step 37 : More Rest Services - @PathVariable\n\n\n## Step By Step Details\n\n### Step 01 : Up and running with a Web Application in Tomcat\n\nIn this step, we will quickly setup a running web application.\n\n> Tip : This is one of the few steps where you copy code in! We would want to ensure that you have a running web application without any mistakes.\n\nYou can run the project using Run as > Maven build > tomcat7:run.\n\nYou can copy code from \n- [Step 01 on Github Repository](https://github.com/in28minutes/JavaWebApplicationStepByStep/blob/master/Step01.md)\n\n\\pom.xml\n\n```xml\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\t<groupId>com.in28minutes</groupId>\n\t<artifactId>in28Minutes-first-webapp</artifactId>\n\t<version>0.0.1-SNAPSHOT</version>\n\t<packaging>war</packaging>\n\t<dependencies>\n\t\t<dependency>\n\t\t\t<groupId>javax</groupId>\n\t\t\t<artifactId>javaee-web-api</artifactId>\n\t\t\t<version>6.0</version>\n\t\t\t<scope>provided</scope>\n\t\t</dependency>\n\t</dependencies>\n\t<build>\n\t\t<pluginManagement>\n\t\t\t<plugins>\n\t\t\t\t<plugin>\n\t\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t\t<artifactId>maven-compiler-plugin</artifactId>\n\t\t\t\t\t<version>3.2</version>\n\t\t\t\t\t<configuration>\n\t\t\t\t\t\t<verbose>true</verbose>\n\t\t\t\t\t\t<source>1.7</source>\n\t\t\t\t\t\t<target>1.7</target>\n\t\t\t\t\t\t<showWarnings>true</showWarnings>\n\t\t\t\t\t</configuration>\n\t\t\t\t</plugin>\n\t\t\t\t<plugin>\n\t\t\t\t\t<groupId>org.apache.tomcat.maven</groupId>\n\t\t\t\t\t<artifactId>tomcat7-maven-plugin</artifactId>\n\t\t\t\t\t<version>2.2</version>\n\t\t\t\t\t<configuration>\n\t\t\t\t\t\t<path>/</path>\n\t\t\t\t\t\t<contextReloadable>true</contextReloadable>\n\t\t\t\t\t</configuration>\n\t\t\t\t</plugin>\n\t\t\t</plugins>\n\t\t</pluginManagement>\n\t</build>\n</project>\n```\n\n\\src\\main\\java\\webapp\\LoginServlet.java\n\n```java\npackage webapp;\n\nimport java.io.IOException;\nimport java.io.PrintWriter;\n\nimport javax.servlet.annotation.WebServlet;\nimport javax.servlet.http.HttpServlet;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\n\n/*\n * Browser sends Http Request to Web Server\n * \n * Code in Web Server => Input:HttpRequest, Output: HttpResponse\n * JEE with Servlets\n * \n * Web Server responds with Http Response\n */\n\n\n@WebServlet(urlPatterns = \"/login.do\")\npublic class LoginServlet extends HttpServlet {\n\n\t@Override\n\tprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {\n\t\tPrintWriter out = response.getWriter();\n\t\tout.println(\"<html>\");\n\t\tout.println(\"<head>\");\n\t\tout.println(\"<title>Yahoo!!!!!!!!</title>\");\n\t\tout.println(\"</head>\");\n\t\tout.println(\"<body>\");\n\t\tout.println(\"My First Servlet\");\n\t\tout.println(\"</body>\");\n\t\tout.println(\"</html>\");\n\n\t}\n\n}\n```\n\\src\\main\\webapp\\WEB-INF\\web.xml\n```xml\n<!-- webapp/WEB-INF/web.xml -->\n<web-app xmlns=\"http://java.sun.com/xml/ns/javaee\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd\"\n\tversion=\"3.0\">\n\n\t<display-name>To do List</display-name>\n\n\t<welcome-file-list>\n\t\t<welcome-file>login.do</welcome-file>\n\t</welcome-file-list>\n\n</web-app>\n```\nJava Platform, Enterprise Edition (Java EE) JEE6\n\nServlet is a Java programming language class used to extend the capabilities of servers  that host applications accessed by means of a request-response programming model.\n\nNotes\n- ```extends javax.servlet.http.HttpServlet``` - All servlets should extend HttpServlet class\n- ```@WebServlet(urlPatterns = \"/login.do\")``` - Provide the url pattern to access the servlet\n- ```doGet(HttpServletRequest request, HttpServletResponse response)``` - To handle the RequestMethod GET we need to implement doGet method.\n\nConfiguring welcome-file-list in web.xml will ensure that url http://localhost:8080/ redirects to http://localhost:8080/login.do\n\n```xml\n<welcome-file-list>\n\t<welcome-file>login.do</welcome-file>\n</welcome-file-list>\n```\n\n### Step 02 : First JSP\n\n[Complete code](https://github.com/in28minutes/JavaWebApplicationStepByStep/blob/master/Step02.md)\n\n#### Notes\n- Create LoginServlet again\n- Redirect to a view - JSP\n\n#### Code Snippets and Examples\n\nRedirect to a view - JSP\n\n\\src\\main\\java\\webapp\\LoginServlet.java\n```java\nrequest\n .getRequestDispatcher(\"/WEB-INF/views/login.jsp\")\n .forward(request, response);\n```\n\n\\src\\main\\webapp\\WEB-INF\\views\\login.jsp\n```jsp\n<html>\n<head>\n<title>Yahoo!!</title>\n</head>\n<body>\nMy First JSP!!!\n</body>\n</html>\n```\n\n\n\n### Step 03 : Adding a Get Parameter name\n\n[Complete code](https://github.com/in28minutes/JavaWebApplicationStepByStep/blob/master/Step03.md)\n\n#### Notes\n- Passing a Request Parameter Name\n\n#### Code Snippets and Examples\n\nWe read the request parameter and set it as a request attribute. Request attributes can be accessed from the view (jsp).\n\n\\src\\main\\java\\webapp\\LoginServlet.java\n\n```java\nrequest.setAttribute(\"name\", \n\t\trequest.getParameter(\"name\"));\n```\n\n\\src\\main\\webapp\\WEB-INF\\views\\login.jsp\n```\nMy First JSP!!! My name is ${name}\n```\n\n### Step 04 : Adding another Get Parameter Password\n\n[Complete code](https://github.com/in28minutes/JavaWebApplicationStepByStep/blob/master/Step04.md)\n\n#### Code Snippets and Examples\n\n\\src\\main\\java\\webapp\\LoginServlet.java\n```\nrequest.setAttribute(\"password\",\n                  request.getParameter(\"password\"));\n```\n\n\\src\\main\\webapp\\WEB-INF\\views\\login.jsp\n```\nMy First JSP!!! My name is ${name} and password is ${password}\n```\n\n### Step 05 : Let's add a form\n\n[Complete code](https://github.com/in28minutes/JavaWebApplicationStepByStep/blob/master/Step05.md)\n\n#### Code Snippets and Examples\n\n\\src\\main\\java\\webapp\\LoginServlet.java\n```\n@Override\nprotected void doGet(HttpServletRequest request, HttpServletResponse response)\n\t\tthrows IOException, ServletException {\n\trequest\n\t\t.getRequestDispatcher(\"/WEB-INF/views/login.jsp\")\n\t\t.forward(request, response);\n}\n```\n\n\\src\\main\\webapp\\WEB-INF\\views\\login.jsp\n```jsp\n<html>\n<head>\n<title>Yahoo!!</title>\n</head>\n<body>\n\t<form action=\"/login.do\" method=\"POST\">\n\t\tName : <input type=\"text\" /> <input type=\"submit\" />\n\t</form>\n</body>\n</html>\n```\n\n\\src\\main\\webapp\\WEB-INF\\views\\welcome.jsp\n```\n<html>\n<head>\n<title>Yahoo!!</title>\n</head>\n<body>\nWelcome ${name}\n</body>\n</html>\n```\n\n### Step 06 : New Form and doPost\n\n[Complete code](https://github.com/in28minutes/JavaWebApplicationStepByStep/blob/master/Step06.md)\n\n\\src\\main\\java\\webapp\\LoginServlet.java\n```\n@Override\nprotected void doPost(HttpServletRequest request, HttpServletResponse response)\n\t\tthrows IOException, ServletException {\n\trequest.setAttribute(\"name\", request.getParameter(\"name\"));\n\trequest.getRequestDispatcher(\"/WEB-INF/views/welcome.jsp\").forward(request, response);\n}\n```\n\n\\src\\main\\webapp\\WEB-INF\\views\\welcome.jsp\n```\n<html>\n<head>\n<title>Yahoo!!</title>\n</head>\n<body>\nWelcome ${name}\n</body>\n</html>\n```\n\n### Step 07 : Adding Password and Validation of User Id\n\n[Complete code](https://github.com/in28minutes/JavaWebApplicationStepByStep/blob/master/Step07.md)\n\n#### Code Snippets and Examples\n\n\\src\\main\\java\\webapp\\LoginService.java\n```\npublic class LoginService {\n\tpublic boolean validateUser(String user, String password) {\n\t\treturn user.equalsIgnoreCase(\"in28Minutes\") && password.equals(\"dummy\");\n\t}\n\n}\n```\n\n\\src\\main\\java\\webapp\\LoginServlet.java\n```\n@Override\nprotected void doPost(HttpServletRequest request, HttpServletResponse response)\n\t\tthrows IOException, ServletException {\n\tString name = request.getParameter(\"name\");\n\tString password = request.getParameter(\"password\");\n\n\tboolean isValidUser = service.validateUser(name, password);\n\n\tif (isValidUser) {\n\t\trequest.setAttribute(\"name\", name);\n\t\trequest.getRequestDispatcher(\"/WEB-INF/views/welcome.jsp\")\n\t\t\t\t.forward(request, response);\n\t} else {\n\t\trequest.setAttribute(\"errorMessage\", \"Invalid Credentials!!\");\n\t\trequest.getRequestDispatcher(\"/WEB-INF/views/login.jsp\")\n\t\t\t\t.forward(request, response);\n\t}\n}\n```\n\n\\src\\main\\webapp\\WEB-INF\\views\\login.jsp\n```\n<html>\n<head>\n<title>Yahoo!!</title>\n</head>\n<body>\n\t<p><font color=\"red\">${errorMessage}</font></p>\n\t<form action=\"/login.do\" method=\"POST\">\n\t\tName : <input name=\"name\" type=\"text\" /> Password : <input name=\"password\" type=\"password\" /> <input type=\"submit\" />\n\t</form>\n</body>\n</html>\n```\n\n\n###  Step 11 : Configure application to use Spring MVC\n\n#### What we will do\n\nBefore we start with the Flows, we need to configure application to use Spring MVC\n- Lets do a little bit of Refactoring. Mini Step 1: Rename package webapp to com.in28minutes.jee\n- We need Spring MVC Framework and its dependencies. Mini Step 2 : Add required jars to the project\n- Spring MVC uses Front Controller Pattern -> Dispatcher Servlet. Mini Step 3 : Add Dispatcher Servlet to web.xml\n- DispatcherServlet needs an Spring Application Context to launch. We will create an xml (/WEB-INF/todo-servlet.xml). Mini Step 4: Add Spring Context\n\n#### Useful Snippets\npom.xml\n```\n\t\t<dependency>\n\t\t\t<groupId>org.springframework</groupId>\n\t\t\t<artifactId>spring-webmvc</artifactId>\n\t\t\t<version>4.2.2.RELEASE</version>\n\t\t</dependency>\n```\nweb.xml\n```\n\t    <servlet>\n\t        <servlet-name>dispatcher</servlet-name>\n\t        <servlet-class>\n\t            org.springframework.web.servlet.DispatcherServlet\n\t        </servlet-class>\n\t        <init-param>\n\t            <param-name>contextConfigLocation</param-name>\n\t            <param-value>/WEB-INF/todo-servlet.xml</param-value>\n\t        </init-param>\n\t        <load-on-startup>1</load-on-startup>\n\t    </servlet>\n\t\n\t    <servlet-mapping>\n\t        <servlet-name>dispatcher</servlet-name>\n\t        <url-pattern>/spring-mvc/*</url-pattern>\n\t    </servlet-mapping>\n```\ntodo-servlet.xml\n```\n\t<beans xmlns=\"http://www.springframework.org/schema/beans\"\n\t    xmlns:context=\"http://www.springframework.org/schema/context\"\n\t    xmlns:mvc=\"http://www.springframework.org/schema/mvc\"\n\t    xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\t    xsi:schemaLocation=\"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd\n\t    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd\n\t    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd\">\n\t\n\t    <context:component-scan base-package=\"com.in28minutes\" />\n\t\n\t    <mvc:annotation-driven />\n\t    \n\t</beans>\n\n```\n\n\n#### Flows:\n- Flow 1. Login Servlet -> GET -> login.jsp\n- Flow 2. Login Servlet -> POST (Success) -> welcome.jsp\n- Flow 3. Login Servlet -> POST (Failure) -> login.jsp (with error message)\n\n#### Files List\n### \\\\src\\main\\webapp\\WEB-INF\\views\\login.jsp Deleted\n### \\pom.xml Deleted\n### \\src\\main\\java\\webapp\\LoginService.java Deleted\n### \\src\\main\\java\\webapp\\LoginServlet.java Deleted\n### \\src\\main\\webapp\\WEB-INF\\views\\welcome.jsp Deleted\n### \\src\\main\\webapp\\WEB-INF\\web.xml Deleted\n\n\n##### /pom.xml New\n```\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\t<groupId>com.in28minutes</groupId>\n\t<artifactId>in28Minutes-springmvc</artifactId>\n\t<version>0.0.1-SNAPSHOT</version>\n\t<packaging>war</packaging>\n\n\t<dependencies>\n\t\t<dependency>\n\t\t\t<groupId>javax</groupId>\n\t\t\t<artifactId>javaee-web-api</artifactId>\n\t\t\t<version>6.0</version>\n\t\t\t<scope>provided</scope>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>org.springframework</groupId>\n\t\t\t<artifactId>spring-webmvc</artifactId>\n\t\t\t<version>4.2.2.RELEASE</version>\n\t\t</dependency>\n\t</dependencies>\n\n\t<build>\n\t\t<pluginManagement>\n\t\t\t<plugins>\n\t\t\t\t<plugin>\n\t\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t\t<artifactId>maven-compiler-plugin</artifactId>\n\t\t\t\t\t<version>3.2</version>\n\t\t\t\t\t<configuration>\n\t\t\t\t\t\t<verbose>true</verbose>\n\t\t\t\t\t\t<source>1.8</source>\n\t\t\t\t\t\t<target>1.8</target>\n\t\t\t\t\t\t<showWarnings>true</showWarnings>\n\t\t\t\t\t</configuration>\n\t\t\t\t</plugin>\n\t\t\t\t<plugin>\n\t\t\t\t\t<groupId>org.apache.tomcat.maven</groupId>\n\t\t\t\t\t<artifactId>tomcat7-maven-plugin</artifactId>\n\t\t\t\t\t<version>2.2</version>\n\t\t\t\t\t<configuration>\n\t\t\t\t\t\t<path>/</path>\n\t\t\t\t\t\t<contextReloadable>true</contextReloadable>\n\t\t\t\t\t</configuration>\n\t\t\t\t</plugin>\n\t\t\t</plugins>\n\t\t</pluginManagement>\n\t</build>\n</project>\n```\n##### /src/main/java/com/in28minutes/jee/LoginService.java New\n```\npackage com.in28minutes.jee;\n\npublic class LoginService {\n\tpublic boolean validateUser(String user, String password) {\n\t\treturn user.equalsIgnoreCase(\"in28Minutes\") && password.equals(\"dummy\");\n\t}\n\n}\n```\n##### /src/main/java/com/in28minutes/jee/LoginServlet.java New\n```\npackage com.in28minutes.jee;\n\nimport java.io.IOException;\n\nimport javax.servlet.ServletException;\nimport javax.servlet.annotation.WebServlet;\nimport javax.servlet.http.HttpServlet;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\n\n@WebServlet(urlPatterns = \"/login.do\")\npublic class LoginServlet extends HttpServlet {\n\n\tprivate LoginService service = new LoginService();\n\n\t@Override\n\tprotected void doGet(HttpServletRequest request,\n\t\t\tHttpServletResponse response) throws IOException, ServletException {\n\t\trequest.getRequestDispatcher(\"/WEB-INF/views/login.jsp\").forward(\n\t\t\t\trequest, response);\n\t}\n\n\t@Override\n\tprotected void doPost(HttpServletRequest request,\n\t\t\tHttpServletResponse response) throws IOException, ServletException {\n\t\tString name = request.getParameter(\"name\");\n\t\tString password = request.getParameter(\"password\");\n\n\t\tboolean isValidUser = service.validateUser(name, password);\n\n\t\tif (isValidUser) {\n\t\t\trequest.setAttribute(\"name\", name);\n\t\t\trequest.getRequestDispatcher(\"/WEB-INF/views/welcome.jsp\").forward(\n\t\t\t\t\trequest, response);\n\t\t} else {\n\t\t\trequest.setAttribute(\"errorMessage\", \"Invalid Credentials!!\");\n\t\t\trequest.getRequestDispatcher(\"/WEB-INF/views/login.jsp\").forward(\n\t\t\t\t\trequest, response);\n\t\t}\n\t}\n\n}\n```\n##### /src/main/webapp/WEB-INF/todo-servlet.xml New\n```\n<beans xmlns=\"http://www.springframework.org/schema/beans\"\n    xmlns:context=\"http://www.springframework.org/schema/context\"\n    xmlns:mvc=\"http://www.springframework.org/schema/mvc\"\n    xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n    xsi:schemaLocation=\"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd\n    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd\n    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd\">\n\n    <context:component-scan base-package=\"com.in28minutes\" />\n\n    <mvc:annotation-driven />\n    \n</beans>\n```\n##### /src/main/webapp/WEB-INF/views/login.jsp New\n```\n<html>\n<head>\n<title>Yahoo!!</title>\n</head>\n<body>\n    <p><font color=\"red\">${errorMessage}</font></p>\n    <form action=\"/login.do\" method=\"POST\">\n        Name : <input name=\"name\" type=\"text\" /> Password : <input name=\"password\" type=\"password\" /> <input type=\"submit\" />\n    </form>\n</body>\n</html>\n```\n##### /src/main/webapp/WEB-INF/views/welcome.jsp New\n```\n<html>\n<head>\n<title>Yahoo!!</title>\n</head>\n<body>\nWelcome ${name}\n</body>\n</html>\n```\n##### /src/main/webapp/WEB-INF/web.xml New\n```\n<web-app xmlns=\"http://java.sun.com/xml/ns/javaee\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n    xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd\"\n    version=\"3.0\">\n\n    <display-name>To do List</display-name>\n\n    <servlet>\n        <servlet-name>dispatcher</servlet-name>\n        <servlet-class>\n            org.springframework.web.servlet.DispatcherServlet\n        </servlet-class>\n        <init-param>\n            <param-name>contextConfigLocation</param-name>\n            <param-value>/WEB-INF/todo-servlet.xml</param-value>\n        </init-param>\n        <load-on-startup>1</load-on-startup>\n    </servlet>\n\n    <servlet-mapping>\n        <servlet-name>dispatcher</servlet-name>\n        <url-pattern>/spring-mvc/*</url-pattern>\n    </servlet-mapping>\n</web-app>\n```\n\n###  Step 12 : First Spring MVC Controller, @ResponseBody, @Controller\n\n#First Spring MVC Controller\n- @RequestMapping(value = \"/login\", method = RequestMethod.GET)\n- http://localhost:8080/spring-mvc/login\n- web.xml - <url-pattern>/spring-mvc/*</url-pattern>\n- Why @ResponseBody?\n- Importance of RequestMapping method\n- Can I have multiple urls rendered from Same Controller?\n\n#Snippets\n```\npackage com.in28minutes.springmvc;\n\nimport org.springframework.stereotype.Controller;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.ResponseBody;\n\n@Controller\npublic class LoginController {\n\n\t@RequestMapping(value = \"/login\")\n\t@ResponseBody\n\tpublic String sayHello() {\n\t\treturn \"Hello World dummy\";\n\t}\n}\n\n```\n\n###  Step 13 : Redirect to Login JSP - LoginController, @ResponseBody - and View Resolver\n\n##### /src/main/java/com/in28minutes/springmvc/login/LoginController.java New\n```\npackage com.in28minutes.springmvc.login;\n\nimport org.springframework.stereotype.Controller;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\n\n@Controller\npublic class LoginController {\n\t@RequestMapping(value = \"/login\", method = RequestMethod.GET)\n\tpublic String showLoginPage() {\n\t\treturn \"login\";\n\t}\n}\n```\n##### /src/main/webapp/WEB-INF/todo-servlet.xml Modified\nNew Lines\n```\n    <bean\n        class=\"org.springframework.web.servlet.view.InternalResourceViewResolver\">\n        <property name=\"prefix\">\n            <value>/WEB-INF/views/</value>\n        </property>\n        <property name=\"suffix\">\n            <value>.jsp</value>\n        </property>\n    </bean>\n```\n\n#### Redirect to Login JSP\n- View Resolver in todo-servlet.xml\n- Update LoginController\n- Remove @ResponseBody\n- More about View Resolver\n\n#### Snippets\n\n```\n  <bean\n        class=\"org.springframework.web.servlet.view.InternalResourceViewResolver\">\n        <property name=\"prefix\">\n            <value>/WEB-INF/views/</value>\n        </property>\n        <property name=\"suffix\">\n            <value>.jsp</value>\n        </property>\n    </bean>\n```\n\n###  Step 14 : DispatcherServlet and Log4j\n\n##### /pom.xml Modified\nNew Lines\n```\n<dependency>\n\t<groupId>log4j</groupId>\n\t<artifactId>log4j</artifactId>\n\t<version>1.2.17</version>\n</dependency>\n```\n\n##### /src/main/resources/log4j.properties New\n```\nlog4j.rootLogger=TRACE, Appender1, Appender2\n \nlog4j.appender.Appender1=org.apache.log4j.ConsoleAppender\nlog4j.appender.Appender1.layout=org.apache.log4j.PatternLayout\nlog4j.appender.Appender1.layout.ConversionPattern=%-7p %d [%t] %c %x - %m%n\n \n```\n##### /src/main/webapp/WEB-INF/views/login.jsp Modified\nNew Lines\n```\n    <form action=\"/spring-mvc/login\" method=\"POST\">\n```\n##### /src/main/webapp/WEB-INF/views/welcome.jsp Modified\nNew Lines\n```\nWelcome ${name}. \n```\n#### What we want to do:\n- Understand importance of DispatcherServlet.\n- Add Logging Framework Log4j to understand the flow much more. \n\n#### Spring MVC Request Flow\n- DispatcherServlet receives HTTP Request. \n- DispatcherServlet identifies the right Controller based on the URL.\n- Controller executes Business Logic.\n- Controller returns a) Model b) View Name Back to DispatcherServlet.\n- DispatcherServlet identifies the correct view (ViewResolver).\n- DispatcherServlet makes the model available to view and executes it.\n- DispatcherServlet returns HTTP Response Back.\n- Flow : http://docs.spring.io/spring-framework/docs/2.0.8/reference/images/mvc.png\n\n###  Step 15 : Show userid and password on the welcome page - ModelMap and @RequestParam\n\n##### /src/main/java/com/in28minutes/springmvc/login/LoginController.java Modified\nNew Lines\n```java\n\n\t@RequestMapping(value = \"/login\", method = RequestMethod.POST)\n\tpublic String handleUserLogin(ModelMap model, @RequestParam String name,\n\t\t\t@RequestParam String password) {\n\t\tmodel.put(\"name\", name);\n\t\tmodel.put(\"password\", password);\n\t\treturn \"welcome\";\n\t}\n}\n```\n##### /src/main/webapp/WEB-INF/views/welcome.jsp Modified\nNew Lines\n```\nWelcome ${name}. You entered ${password}\n```\n#### What we will do:\n- Show userid and password on the welcome page.\n- We will not use Spring Security for now.\n- ModelMap model\n- @RequestParam String name\n\n###  Step 16 : LoginService and Remove all JEE Servlets based code\n\n##### /src/main/java/com/in28minutes/jee/LoginService.java Deleted\n##### /src/main/java/com/in28minutes/jee/LoginServlet.java Deleted\n\n##### /src/main/java/com/in28minutes/springmvc/login/LoginController.java Deleted\n\n##### /src/main/java/com/in28minutes/login/LoginController.java New\n```\npackage com.in28minutes.login;\n\nimport org.springframework.stereotype.Controller;\nimport org.springframework.ui.ModelMap;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\nimport org.springframework.web.bind.annotation.RequestParam;\n\nimport com.in28minutes.login.LoginService;\n\n@Controller\npublic class LoginController {\n\n\tprivate LoginService loginService = new LoginService();\n\n\t@RequestMapping(value = \"/login\", method = RequestMethod.GET)\n\tpublic String showLoginPage() {\n\t\treturn \"login\";\n\t}\n\n\t@RequestMapping(value = \"/login\", method = RequestMethod.POST)\n\tpublic String handleUserLogin(ModelMap model, @RequestParam String name,\n\t\t\t@RequestParam String password) {\n\n\t\tif (!loginService.validateUser(name, password)) {\n\t\t\tmodel.put(\"errorMessage\", \"Invalid Credentials\");\n\t\t\treturn \"login\";\n\t\t}\n\n\t\tmodel.put(\"name\", name);\n\t\treturn \"welcome\";\n\t}\n}\n```\n\n##### /src/main/java/com/in28minutes/login/LoginService.java New\n```\npackage com.in28minutes.login;\n\npublic class LoginService {\n\tpublic boolean validateUser(String user, String password) {\n\t\treturn user.equalsIgnoreCase(\"in28Minutes\") && password.equals(\"dummy\");\n\t}\n\n}\n```\n\n##### /src/main/webapp/WEB-INF/views/login.jsp Modified\nNew Lines\n```\n    <form action=\"/login\" method=\"POST\">\n```\n##### /src/main/webapp/WEB-INF/views/welcome.jsp Modified\nNew Lines\n```\nWelcome ${name}. You are now authenticated.\n```\n\n##### /src/main/webapp/WEB-INF/web.xml Modified\nNew Lines\n```\n        <url-pattern>/</url-pattern>\n```\n#### What we will do:\n- Use LoginService to validate userid and password.\n- Remove all the old controller code and lets use only Spring MVC here on. \n- For now : We are not using Spring Autowiring for LoginService.\n- Change URL to http://localhost:8080/login\n\n###  Step 17 : Spring Auto-wiring and Dependency Management - @Autowired and @Service\n\n##### /src/main/java/com/in28minutes/login/LoginController.java Modified\nNew Lines\n```\nimport org.springframework.beans.factory.annotation.Autowired;\n\t@Autowired\n\tprivate LoginService loginService;\n```\n##### /src/main/java/com/in28minutes/login/LoginService.java Modified\nNew Lines\n```\nimport org.springframework.stereotype.Service;\n@Service\npublic class LoginService {\n```\n#### What we will do:\n- Learn about Spring Auto-wiring and Dependency Management.\n- Use Auto-wiring to wire LoginService.\n- @Autowired, @Service\n\n###  Step 18 : Create TodoController and list-todos view. Make TodoService a @Service and inject it.\n\n##### /src/main/java/com/in28minutes/model/Todo.java New\n```\npackage com.in28minutes.model;\n\nimport java.util.Date;\n\npublic class Todo {\n\tprivate int id;\n\tprivate String user;\n\tprivate String desc;\n\tprivate Date targetDate;\n\tprivate boolean isDone;\n\n\tpublic Todo(int id, String user, String desc, Date targetDate, boolean isDone) {\n\t\tsuper();\n\t\tthis.id = id;\n\t\tthis.user = user;\n\t\tthis.desc = desc;\n\t\tthis.targetDate = targetDate;\n\t\tthis.isDone = isDone;\n\t}\n\n\tpublic int getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(int id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getUser() {\n\t\treturn user;\n\t}\n\n\tpublic void setUser(String user) {\n\t\tthis.user = user;\n\t}\n\n\tpublic String getDesc() {\n\t\treturn desc;\n\t}\n\n\tpublic void setDesc(String desc) {\n\t\tthis.desc = desc;\n\t}\n\n\tpublic Date getTargetDate() {\n\t\treturn targetDate;\n\t}\n\n\tpublic void setTargetDate(Date targetDate) {\n\t\tthis.targetDate = targetDate;\n\t}\n\n\tpublic boolean isDone() {\n\t\treturn isDone;\n\t}\n\n\tpublic void setDone(boolean isDone) {\n\t\tthis.isDone = isDone;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + id;\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tTodo other = (Todo) obj;\n\t\tif (id != other.id)\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn String.format(\n\t\t\t\t\"Todo [id=%s, user=%s, desc=%s, targetDate=%s, isDone=%s]\", id,\n\t\t\t\tuser, desc, targetDate, isDone);\n\t}\n\n}\n```\n##### /src/main/java/com/in28minutes/todo/TodoController.java New\n```\npackage com.in28minutes.todo;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.ui.ModelMap;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\n\nimport com.in28minutes.todo.service.TodoService;\n\n@Controller\npublic class TodoController {\n\n\t@Autowired\n\tprivate TodoService service;\n\n\t@RequestMapping(value = \"/list-todos\", method = RequestMethod.GET)\n\tpublic String showLoginPage(ModelMap model) {\n\t\tmodel.addAttribute(\"todos\", service.retrieveTodos(\"in28Minutes\"));\n\t\treturn \"list-todos\";\n\t}\n}\n```\n##### /src/main/java/com/in28minutes/todo/service/TodoService.java New\n```\npackage com.in28minutes.todo.service;\n\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.Iterator;\nimport java.util.List;\n\nimport org.springframework.stereotype.Service;\n\nimport com.in28minutes.model.Todo;\n\n@Service\npublic class TodoService {\n\tprivate static List<Todo> todos = new ArrayList<Todo>();\n\tprivate static int todoCount = 3;\n\n\tstatic {\n\t\ttodos.add(new Todo(1, \"in28Minutes\", \"Learn Spring MVC\", new Date(),\n\t\t\t\tfalse));\n\t\ttodos.add(new Todo(2, \"in28Minutes\", \"Learn Struts\", new Date(), false));\n\t\ttodos.add(new Todo(3, \"in28Minutes\", \"Learn Hibernate\", new Date(),\n\t\t\t\tfalse));\n\t}\n\n\tpublic List<Todo> retrieveTodos(String user) {\n\t\tList<Todo> filteredTodos = new ArrayList<Todo>();\n\t\tfor (Todo todo : todos) {\n\t\t\tif (todo.getUser().equals(user))\n\t\t\t\tfilteredTodos.add(todo);\n\t\t}\n\t\treturn filteredTodos;\n\t}\n\n\tpublic void addTodo(String name, String desc, Date targetDate, boolean isDone) {\n\t\ttodos.add(new Todo(++todoCount, name, desc, targetDate, isDone));\n\t}\n\n\tpublic void deleteTodo(int id) {\n\t\tIterator<Todo> iterator = todos.iterator();\n\t\twhile (iterator.hasNext()) {\n\t\t\tTodo todo = iterator.next();\n\t\t\tif (todo.getId() == id) {\n\t\t\t\titerator.remove();\n\t\t\t}\n\t\t}\n\t}\n}\n```\n##### /src/main/webapp/WEB-INF/views/list-todos.jsp New\n```\n<html>\n<head>\n<title>Todos for ${name}</title>\n</head>\n<body>\n<H1>Your Todos</H1>\n ${todos}\n</body>\n</html>\n```\n##### /src/main/webapp/WEB-INF/views/welcome.jsp Modified\nNew Lines\n```\nWelcome ${name}. You are now authenticated. <a href=\"/list-todos\">Click here</a> to start maintaining your todo's.\n```\n#### What we will do:\n- Create TodoController and list-todos.jsp\n- Make TodoService a @Service and inject it\n\n### Pending for Next Step New\n- ${name} is not available in list-todos.jsp\n- in28Minutes is hardcoded in TodoController\n\n###  Step 19 : Web Application Architecture\n\n#### What we will do:\n- Lets discuss about Architecture of web applications\n\n###  Step 20 : More about Spring Framework\n\n#### What we will do:\n- Lets discuss about Spring\n\n###  Step 21 : Session vs Model vs Request - @SessionAttributes\n\n##### /src/main/java/com/in28minutes/login/LoginController.java Modified\nNew Lines\n```\nimport org.springframework.web.bind.annotation.SessionAttributes;\n@SessionAttributes(\"name\")\npublic class LoginController {\n```\n##### /src/main/java/com/in28minutes/todo/TodoController.java Modified\nNew Lines\n```\n@Controller\n@SessionAttributes(\"name\")\npublic class TodoController {\n\n\t@Autowired\n\tprivate TodoService service;\n\n\t@RequestMapping(value = \"/list-todos\", method = RequestMethod.GET)\n\tpublic String showLoginPage(ModelMap model, String name) {\n\t\tString user = (String) model.get(\"name\");\n\t\tmodel.addAttribute(\"todos\", service.retrieveTodos(user));\n\t\treturn \"list-todos\";\n\t}\n}\n```\n#### What we will do:\n- Session vs Model vs Request.\n- Be cautious about what you use Session for.\n- @SessionAttributes(\"name\") and how it works?\n- Why use Model?  \"adding elements directly to the HttpServletRequest (as request attributes) would seem to serve the same purpose.  The reason to do this is obvious when taking a look at one of the requirements we have set for the MVC framework:  It should be as view-agnostic as possible, which means we’d like to be able to incorporate view technologies not bound to the HttpServletRequest as well.\" - Rod Johnson et. al’s book Professional Java Development with the Spring Framework \n- Spring documentation states that the @SessionAttributes annotation “list the names of model attributes which should be transparently stored in the session or some conversational storage.” \n\n###  Step 22 : New Todo and redirect to a Controller\n\n##### /src/main/java/com/in28minutes/todo/TodoController.java Modified\nNew Lines\n```\n\t@RequestMapping(value = \"/list-todos\", method = RequestMethod.GET)\n\tpublic String showTodosList(ModelMap model) {\n\t\tString user = (String) model.get(\"name\");\n\t\tmodel.addAttribute(\"todos\", service.retrieveTodos(user));\n\t\treturn \"list-todos\";\n\t}\n\n\t@RequestMapping(value = \"/add-todo\", method = RequestMethod.GET)\n\tpublic String showTodoPage() {\n\t\treturn \"todo\";\n\t}\n\n\t@RequestMapping(value = \"/add-todo\", method = RequestMethod.POST)\n\tpublic String addTodo(ModelMap model, @RequestParam String desc) {\n\t\tservice.addTodo((String) model.get(\"name\"), desc, new Date(), false);\n\t\tmodel.clear();// to prevent request parameter \"name\" to be passed\n\t\treturn \"redirect:/list-todos\";\n\t}\n```\n##### /src/main/webapp/WEB-INF/views/list-todos.jsp Modified\nNew Lines\n```\n <a class=\"button\" href=\"/add-todo\">Add</a>\n```\n##### /src/main/webapp/WEB-INF/views/login.jsp Modified\nNew Lines\n```\n<title>Login Page</title>\n```\n##### /src/main/webapp/WEB-INF/views/todo.jsp New\n```\n<html>\n<head>\n<title>Login Page</title>\n</head>\n<body>\n    <form action=\"/add-todo\" method=\"POST\">\n        Description : <input name=\"desc\" type=\"text\" /> <input type=\"submit\" value=\"add\" />\n    </form>\n</body>\n</html>\n```\n#### What we will do:\n- Add Facility to add New Todo\n- todo.jsp\n- Importance of redirect:/list-todos\n- Importance of model.clear();\n\n###  Step 23 : JSTL\n\n##### /pom.xml Modified\nNew Lines\n```\n<dependency>\n\t<groupId>javax.servlet</groupId>\n\t<artifactId>jstl</artifactId>\n\t<version>1.2</version>\n</dependency>\n```\n##### /src/main/webapp/WEB-INF/views/list-todos.jsp Modified\nNew Lines\n```\n<%@ taglib uri=\"http://java.sun.com/jsp/jstl/core\" prefix=\"c\"%>\n\t<H1>Your Todos</H1>\n\t<div>\n\t\t<table>\n\t\t\t<caption>Your Todos are</caption>\n\n\t\t\t<thead>\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Description</th>\n\t\t\t\t\t<th>Date</th>\n\t\t\t\t\t<th>Completed</th>\n\t\t\t\t</tr>\n\t\t\t</thead>\n\n\t\t\t<tbody>\n\t\t\t\t<c:forEach items=\"${todos}\" var=\"todo\">\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td>${todo.desc}</td>\n\t\t\t\t\t\t<td>${todo.targetDate}</td>\n\t\t\t\t\t\t<td>${todo.done}</td>\n\t\t\t\t\t</tr>\n\t\t\t\t</c:forEach>\n\t\t\t</tbody>\n\t\t</table>\n\t</div>\n\n\t<a class=\"button\" href=\"/add-todo\">Add</a>\n```\n\n#### What we will do:\n- Display Todos in a table using JSTL Tags\n- <%@ taglib uri=\"http://java.sun.com/jsp/jstl/core\" prefix=\"c\"%>\n- Add Dependency for jstl\n\n###  Step 24 : Bootstrap - using Webjars\n\n##### /pom.xml Modified\nNew Lines\n```\n        <dependency>\n            <groupId>org.webjars</groupId>\n            <artifactId>bootstrap</artifactId>\n            <version>3.3.6</version>\n        </dependency>\n        <dependency>\n            <groupId>org.webjars</groupId>\n            <artifactId>jquery</artifactId>\n            <version>1.9.1</version>\n        </dependency>\n        \n```\n##### /src/main/webapp/WEB-INF/todo-servlet.xml Modified\nNew Lines\n```\n    <mvc:resources mapping=\"/webjars/**\" location=\"/webjars/\"/>\n```\n##### /src/main/webapp/WEB-INF/views/list-todos.jsp Modified\nNew Lines\n```\n<link href=\"webjars/bootstrap/3.3.6/css/bootstrap.min.css\"\n    rel=\"stylesheet\">\n\n<div class=\"container\">\n\n\t<table class=\"table table-striped\">\n\n<a class=\"button\" href=\"/add-todo\">Add</a>\n\n<script src=\"webjars/jquery/1.9.1/jquery.min.js\"></script>\n<script src=\"webjars/bootstrap/3.3.6/js/bootstrap.min.js\"></script>\n```\n#### What we will do:\n- Add bootstrap to give basic formatting to the page : We use bootstrap classes container,table and table-striped.\n- We will use webjars\n\n#### Useful Snippets\n```     \n        <dependency>\n            <groupId>org.webjars</groupId>\n            <artifactId>bootstrap</artifactId>\n            <version>3.3.6</version>\n        </dependency>\n        <dependency>\n            <groupId>org.webjars</groupId>\n            <artifactId>jquery</artifactId>\n            <version>1.9.1</version>\n        </dependency>\n        \n  \t\t<mvc:resources mapping=\"/webjars/**\" location=\"/webjars/\"/>\n  \n\t\t<script src=\"webjars/jquery/1.9.1/jquery.min.js\"></script>\n\t    <script src=\"webjars/bootstrap/3.3.6/js/bootstrap.min.js\"></script>\n\t\t<link href=\"webjars/bootstrap/3.3.6/css/bootstrap.min.css\"\n\t    \t\trel=\"stylesheet\">\n\n```\n\n###  Step 25 : Let's delete a Todo\n\n##### /src/main/java/com/in28minutes/todo/TodoController.java Modified\nNew Lines\n```\n\n\t@RequestMapping(value = \"/delete-todo\", method = RequestMethod.GET)\n\tpublic String deleteTodo(@RequestParam int id) {\n\t\tservice.deleteTodo(id);\n\n\t\treturn \"redirect:/list-todos\";\n\t}\n\n```\n##### /src/main/java/com/in28minutes/todo/service/TodoService.java Modified\nNew Lines\n```\n\tpublic void addTodo(String name, String desc, Date targetDate,\n\t\t\tboolean isDone) {\n\t\ttodos.add(new Todo(++todoCount, name, desc, targetDate, isDone));\n\t}\n```\n##### /src/main/webapp/WEB-INF/views/list-todos.jsp Modified\nNew Lines\n```\n<th></th>\n<td>\n\t<a type=\"button\" class=\"btn btn-warning\" \n\t\thref=\"/delete-todo?id=${todo.id}\">Delete</a>\n</td>\n<a type=\"button\" class=\"btn btn-success\" href=\"/add-todo\">Add</a>\n```\n\n#### What we will do:\n- Add functionality to delete a todo\n\n#### Useful Snippets\n```     \n\t<a type=\"button\" class=\"btn btn-warning\" \n\t\thref=\"/delete-todo?id=${todo.id}\">Delete</a>\n```\n\n###  Step 26 : Use Bootstrap to format and add HTML5 Validations\n\n##### /src/main/webapp/WEB-INF/views/todo.jsp Modified\nNew Lines\n```\n<title>Your Todo</title>\n<link href=\"webjars/bootstrap/3.3.6/css/bootstrap.min.css\"\n\trel=\"stylesheet\">\n\n\t<div class=\"container\">\n\t\t<form action=\"/add-todo\" method=\"post\">\n\t\t\t<fieldset class=\"form-group\">\n\t\t\t\t<label>Description</label>\n\t\t\t\t<input name=\"desc\" type=\"text\" class=\"form-control\" required=\"required\"/>\n\t\t\t</fieldset>\n\t\t\t<button type=\"submit\" class=\"btn btn-success\">Add</button>\n\t\t</form>\n\t</div>\n\n\t<script src=\"webjars/jquery/1.9.1/jquery.min.js\"></script>\n\t<script src=\"webjars/bootstrap/3.3.6/js/bootstrap.min.js\"></script>\n\n```\n#### What we will do:\nIn this short step:\n- Format Add Todo Page\n- Add Html5 Form Validations\n\n#### Useful Snippets\n```     \n\t<fieldset class=\"form-group\">\n\t\t<label>Description</label>\n\t\t<input name=\"desc\" type=\"text\" class=\"form-control\" required=\"required\"/>\n\t</fieldset>\n\n```\n\n###  Step 27 : Introduce JSR 349 Validations using Hibernate Validator First Command Bean.\n\n##### /pom.xml Modified\nNew Lines\n```\n<dependency>\n\t<groupId>org.hibernate</groupId>\n\t<artifactId>hibernate-validator</artifactId>\n\t<version>5.0.2.Final</version>\n</dependency>\n\t\t\n```\n##### /src/main/java/com/in28minutes/model/Todo.java Modified\nNew Lines\n```\n\t@Size(min = 10, message = \"Enter atleast 10 Characters.\")\n\tprivate String desc;\n```\n##### /src/main/java/com/in28minutes/todo/TodoController.java Modified\nNew Lines\n```\n\t@RequestMapping(value = \"/add-todo\", method = RequestMethod.GET)\n\tpublic String showAddTodoPage(ModelMap model) {\n\t\tmodel.addAttribute(\"todo\", new Todo());\n\t\treturn \"todo\";\n\t}\n\n\t@RequestMapping(value = \"/add-todo\", method = RequestMethod.POST)\n\tpublic String addTodo(ModelMap model, @Valid Todo todo, BindingResult result) {\n\n\t\tif (result.hasErrors())\n\t\t\treturn \"todo\";\n\n\t\tservice.addTodo((String) model.get(\"name\"), todo.getDesc(), new Date(),\n\t\t\t\tfalse);\n\t\tmodel.clear();// to prevent request parameter \"name\" to be passed\n\t\treturn \"redirect:/list-todos\";\n\t}\n\n```\n##### /src/main/webapp/WEB-INF/views/todo.jsp Modified\nNew Lines\n```\n<%@taglib uri=\"http://www.springframework.org/tags/form\" prefix=\"form\"%>\n\t\t<form:form method=\"post\" commandName=\"todo\">\n\t\t\t\t<form:label path=\"desc\">Description</form:label>\n\t\t\t\t<form:input path=\"desc\" type=\"text\" class=\"form-control\"\n\t\t\t\t\trequired=\"required\"/>\n\t\t\t\t<form:errors path=\"desc\" cssClass=\"text-warning\" />\n\t\t</form:form>\n```\n#### What we will do:\n- Lets use a command bean for Todo\n- Add Validations\n- The JSR 303 and JSR 349 defines specification for the Bean Validation API (version 1.0 and 1.1, respectively), and Hibernate Validator is the reference implementation.\n\n#### Useful Snippets\n```     \n\t\t<%@taglib uri=\"http://www.springframework.org/tags/form\" prefix=\"form\"%>\n\n\t\t<form:form action=\"/add-todo\" method=\"post\" commandName=\"todo\">\n\t\t\t<fieldset class=\"form-group\">\n\t\t\t\t<form:label path=\"desc\">Description</form:label>\n\t\t\t\t<form:input path=\"desc\" type=\"text\" class=\"form-control\" required=\"required\"/>\n\t\t\t</fieldset>\n\t\t</form:form>\n\t\t\n\t\t<dependency>\n    \t\t\t<groupId>org.hibernate</groupId>\n    \t\t\t<artifactId>hibernate-validator</artifactId>\n    \t\t\t<version>5.0.2.Final</version>\n \t\t</dependency>\n\n\t\t@Size(min = 10, message = \"Enter atleast 10 Characters.\")\n\t\t\n\t\t@Valid Todo todo, BindingResult result\n\n\t\tif (result.hasErrors())\n\t\t\treturn \"todo\";\n\t\t\n\t\t<form:errors path=\"desc\" cssClass=\"text-warning\" />\n\t\t\n```\n###  Step 28 : Let's update a Todo\n\n##### /src/main/java/com/in28minutes/todo/TodoController.java Modified\nNew Lines\n```\n\n\t@RequestMapping(value = \"/update-todo\", method = RequestMethod.GET)\n\tpublic String showUpdateTodoPage(ModelMap model, @RequestParam int id) {\n\t\tmodel.addAttribute(\"todo\", service.retrieveTodo(id));\n\t\treturn \"todo\";\n\t}\n\n\t@RequestMapping(value = \"/update-todo\", method = RequestMethod.POST)\n\tpublic String updateTodo(ModelMap model, @Valid Todo todo,\n\t\t\tBindingResult result) {\n\t\tif (result.hasErrors())\n\t\t\treturn \"todo\";\n\n\t\ttodo.setUser(\"in28Minutes\"); //TODO:Remove Hardcoding Later\n\t\tservice.updateTodo(todo);\n\n\t\tmodel.clear();// to prevent request parameter \"name\" to be passed\n\t\treturn \"redirect:/list-todos\";\n\t}\n\n```\n##### /src/main/java/com/in28minutes/todo/service/TodoService.java Modified\nNew Lines\n```\n\n\tpublic Todo retrieveTodo(int id) {\n\t\tfor (Todo todo : todos) {\n\t\t\tif (todo.getId() == id)\n\t\t\t\treturn todo;\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic void updateTodo(Todo todo) {\n\t\ttodos.remove(todo);\n\t\ttodos.add(todo);\n\t}\n\n```\n##### /src/main/webapp/WEB-INF/views/list-todos.jsp Modified\nNew Lines\n```\n\t<a type=\"button\" class=\"btn btn-primary\" \n\t\thref=\"/update-todo?id=${todo.id}\">Edit</a>\n```\n##### /src/main/webapp/WEB-INF/views/todo.jsp Modified\nNew Lines\n```\n\t<form:hidden path=\"id\"/>\n\t<button type=\"submit\" class=\"btn btn-success\">Submit</button>\n```\n#### What we will do:\n- Add Update Functionality\n- Lets Use the Same JSP as earlier.\n\n#### Useful Snippets\n```\n\tpublic Todo retrieveTodo(int id) {\n\t\tfor (Todo todo : todos) {\n\t\t\tif (todo.getId() == id)\n\t\t\t\treturn todo;\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic void updateTodo(Todo todo) {\n\t\ttodos.remove(todo);\n\t\ttodos.add(todo);\n\t}\n   \n   todo.setUser(\"in28Minutes\"); //TODO:Remove Hardcoding Later\n   service.updateTodo(todo);\n   \n   <form:hidden path=\"id\"/>  \n```\n\n###  Step 29 : Let's add a Target Date for Todo - Use initBinder to Handle Date Fields\n\n##### /pom.xml Modified\nNew Lines\n```\n<dependency>\n\t<groupId>org.webjars</groupId>\n\t<artifactId>bootstrap-datepicker</artifactId>\n\t<version>1.0.1</version>\n</dependency>\n```\n##### /src/main/java/com/in28minutes/todo/TodoController.java Modified\nNew Lines\n```\n\t@InitBinder\n\tprotected void initBinder(WebDataBinder binder) {\n\t\tSimpleDateFormat dateFormat = new SimpleDateFormat(\"dd/MM/yyyy\");\n\t\tbinder.registerCustomEditor(Date.class, new CustomDateEditor(\n\t\t\t\tdateFormat, false));\n\t}\n\n```\n##### /src/main/webapp/WEB-INF/views/list-todos.jsp Modified\nNew Lines\n```\n<%@ taglib uri=\"http://java.sun.com/jsp/jstl/fmt\" prefix=\"fmt\"%>\n\trel=\"stylesheet\">\n\n<td><fmt:formatDate pattern=\"dd/MM/yyyy\"\n\t\tvalue=\"${todo.targetDate}\" /></td>\n<td><a type=\"button\" class=\"btn btn-primary\"\n\thref=\"/update-todo?id=${todo.id}\">Edit</a> <a type=\"button\"\n\tclass=\"btn btn-warning\" href=\"/delete-todo?id=${todo.id}\">Delete</a>\n\n<script src=\"webjars/bootstrap/3.3.6/js/bootstrap.min.js\"></script>\n```\n\n##### /src/main/webapp/WEB-INF/views/todo.jsp Modified\nNew Lines\n```\n    <div class=\"container\">\n        <form:form method=\"post\" commandName=\"todo\">\n            <form:hidden path=\"id\" />\n            <fieldset class=\"form-group\">\n                <form:label path=\"desc\">Description</form:label>\n                <form:input path=\"desc\" type=\"text\" class=\"form-control\"\n                    required=\"required\" />\n                <form:errors path=\"desc\" cssClass=\"text-warning\" />\n            </fieldset>\n            <fieldset class=\"form-group\">\n                <form:label path=\"targetDate\">Target Date</form:label>\n                <form:input path=\"targetDate\" type=\"text\" class=\"form-control\"\n                    required=\"required\" />\n                <form:errors path=\"targetDate\" cssClass=\"text-warning\" />\n            </fieldset>\n            <button type=\"submit\" class=\"btn btn-success\">Submit</button>\n        </form:form>\n    </div>\n    <script src=\"webjars/jquery/1.9.1/jquery.min.js\"></script>\n    <script src=\"webjars/bootstrap/3.3.6/js/bootstrap.min.js\"></script>\n    <script\n        src=\"webjars/bootstrap-datepicker/1.0.1/js/bootstrap-datepicker.js\"></script>\n    <script>\n        $('#targetDate').datepicker({\n            format : 'dd/mm/yyyy'\n        });\n    </script>\n```\n#### What we will do:\n- Make real use of the Target Date Field\n- initBinder method\n\n#### Useful Snippets\n```\n\t<%@ taglib uri=\"http://java.sun.com/jsp/jstl/fmt\" prefix=\"fmt\"%>\n\t<fmt:formatDate pattern=\"dd/MM/yyyy\"\n\t\t\t\t\t\t\t\t\tvalue=\"${todo.targetDate}\" />\n\t\t\t\t\t\t\t\t\t\n\t\n\t@InitBinder\n\tprotected void initBinder(WebDataBinder binder) {\n\t\tSimpleDateFormat dateFormat = new SimpleDateFormat(\"dd/MM/yyyy\");\n\t\tbinder.registerCustomEditor(Date.class, new CustomDateEditor(\n\t\t\t\tdateFormat, false));\n\t}\n\t\n\t<dependency>\n\t\t<groupId>org.webjars</groupId>\n\t\t<artifactId>bootstrap-datepicker</artifactId>\n\t\t<version>1.0.1</version>\n\t</dependency>\n\t\n\t<script\n\t\tsrc=\"webjars/bootstrap-datepicker/1.0.1/js/bootstrap-datepicker.js\"></script>\n\n\t<script>\n\t\t$('#targetDate').datepicker({\n\t\t\tformat : 'dd/mm/yyyy'\n\t\t});\n\t</script>\n\t\t\n```\n\n###  Step 30 : Navigation bar and JSP Fragments\n\n##### /src/main/java/com/in28minutes/todo/TodoController.java Modified\nNew Lines\n```\n\t@RequestMapping(value = \"/add-todo\", method = RequestMethod.POST)\n\tpublic String addTodo(ModelMap model, @Valid Todo todo, BindingResult result) {\n\n\t\tif (result.hasErrors())\n\t\t\treturn \"todo\";\n\n\t\tservice.addTodo((String) model.get(\"name\"), todo.getDesc(),\n\t\t\t\ttodo.getTargetDate(), false);\n\t\tmodel.clear();// to prevent request parameter \"name\" to be passed\n\t\treturn \"redirect:/list-todos\";\n\t}\n```\n##### /src/main/webapp/WEB-INF/views/common/footer.jspf New\n```\n\n<script src=\"webjars/jquery/1.9.1/jquery.min.js\"></script>\n<script src=\"webjars/bootstrap/3.3.6/js/bootstrap.min.js\"></script>\n<script\n\tsrc=\"webjars/bootstrap-datepicker/1.0.1/js/bootstrap-datepicker.js\"></script>\n\n</body>\n</html>\n```\n##### /src/main/webapp/WEB-INF/views/common/header.jspf New\n```\n<%@taglib uri=\"http://www.springframework.org/tags/form\" prefix=\"form\"%>\n<%@ taglib uri=\"http://java.sun.com/jsp/jstl/core\" prefix=\"c\"%>\n<%@ taglib uri=\"http://java.sun.com/jsp/jstl/fmt\" prefix=\"fmt\"%>\n<html>\n<head>\n<title>Todos Application</title>\n<link href=\"webjars/bootstrap/3.3.6/css/bootstrap.min.css\"\n\trel=\"stylesheet\">\n</head>\n\n<body>\n\n```\n##### /src/main/webapp/WEB-INF/views/common/navigation.jspf New\n```\n<nav role=\"navigation\" class=\"navbar navbar-default\">\n\n\t<div class=\"\">\n\t\t<a href=\"http://www.in28minutes.com\" class=\"navbar-brand\">in28Minutes</a>\n\t</div>\n\n\t<div class=\"navbar-collapse\">\n\t\t<ul class=\"nav navbar-nav\">\n\t\t\t<li class=\"active\"><a href=\"/login\">Home</a></li>\n\t\t\t<li><a href=\"/list-todos\">Todos</a></li>\n\n\t\t</ul>\n\t</div>\n\n</nav>\n```\n##### /src/main/webapp/WEB-INF/views/list-todos.jsp Modified\nNew Lines\n```\n<%@ include file=\"common/header.jspf\"%>\n<%@ include file=\"common/navigation.jspf\"%>\n<div class=\"container\">\n\t<table class=\"table table-striped\">\n\t\t<caption>Your Todos are</caption>\n\t\t<thead>\n\t\t\t<tr>\n\t\t\t\t<th>Description</th>\n\t\t\t\t<th>Date</th>\n\t\t\t\t<th>Completed</th>\n\t\t\t\t<th></th>\n\t\t\t</tr>\n\t\t</thead>\n\t\t<tbody>\n\t\t\t<c:forEach items=\"${todos}\" var=\"todo\">\n\t\t\t\t\t<td>${todo.desc}</td>\n\t\t\t\t\t<td><fmt:formatDate pattern=\"dd/MM/yyyy\"\n\t\t\t\t\t\t\tvalue=\"${todo.targetDate}\" /></td>\n\t\t\t\t\t<td>${todo.done}</td>\n\t\t\t\t\t<td><a type=\"button\" class=\"btn btn-primary\"\n\t\t\t\t\t\thref=\"/update-todo?id=${todo.id}\">Edit</a> <a type=\"button\"\n\t\t\t\t\t\tclass=\"btn btn-warning\" href=\"/delete-todo?id=${todo.id}\">Delete</a>\n\t\t\t\t\t</td>\n\t\t\t</c:forEach>\n\t\t</tbody>\n\t</table>\n\t<div>\n\t\t<a type=\"button\" class=\"btn btn-success\" href=\"/add-todo\">Add</a>\n\t</div>\n</div>\n<%@ include file=\"common/footer.jspf\"%>\n```\n##### /src/main/webapp/WEB-INF/views/login.jsp Modified\nNew Lines\n```\n<%@ include file=\"common/header.jspf\"%>\n<%@ include file=\"common/navigation.jspf\"%>\n<div class=\"container\">\n\t<p>\n\t\t<font color=\"red\">${errorMessage}</font>\n\t</p>\n\t<form action=\"/login\" method=\"POST\">\n\t\t<fieldset class=\"form-group\">\n\t\t\t<label>Name</label> <input name=\"name\" type=\"text\"\n\t\t\t\tclass=\"form-control\" />\n\t\t</fieldset>\n\t\t<fieldset class=\"form-group\">\n\t\t\t<label>Password</label> <input name=\"password\" type=\"password\"\n\t\t\t\tclass=\"form-control\" />\n\t\t</fieldset>\n\t\t<button type=\"submit\" class=\"btn btn-success\">Submit</button>\n\t</form>\n\n</div>\n\n<%@ include file=\"common/footer.jspf\"%>\n```\n##### /src/main/webapp/WEB-INF/views/todo.jsp Modified\nNew Lines\n```\n<%@ include file=\"common/header.jspf\"%>\n<%@ include file=\"common/navigation.jspf\"%>\n<div class=\"container\">\n\t<form:form method=\"post\" commandName=\"todo\">\n\t\t<form:hidden path=\"id\" />\n\t\t<fieldset class=\"form-group\">\n\t\t\t<form:label path=\"desc\">Description</form:label>\n\t\t\t<form:input path=\"desc\" type=\"text\" class=\"form-control\"\n\t\t\t\trequired=\"required\" />\n\t\t\t<form:errors path=\"desc\" cssClass=\"text-warning\" />\n\t\t</fieldset>\n\t\t<fieldset class=\"form-group\">\n\t\t\t<form:label path=\"targetDate\">Target Date</form:label>\n\t\t\t<form:input path=\"targetDate\" type=\"text\" class=\"form-control\"\n\t\t\t\trequired=\"required\" />\n\t\t\t<form:errors path=\"targetDate\" cssClass=\"text-warning\" />\n\t\t</fieldset>\n\t\t<button type=\"submit\" class=\"btn btn-success\">Submit</button>\n\t</form:form>\n</div>\n<%@ include file=\"common/footer.jspf\"%>\n<script>\n\t$('#targetDate').datepicker({\n\t\tformat : 'dd/mm/yyyy'\n\t});\n</script>\n```\n##### /src/main/webapp/WEB-INF/views/welcome.jsp Modified\nNew Lines\n```\n<%@ include file=\"common/header.jspf\"%>\n<%@ include file=\"common/navigation.jspf\"%>\n<div class=\"container\">\n\tWelcome ${name}. You are now authenticated.\n</div>\n\n<%@ include file=\"common/footer.jspf\"%>\n```\n#### What we will do:\n- Add a navigation bar\n- Use JSP Fragments\n- Exercise : Align the login & welcome pages.\n- Exercise : Highlight the correct menu item.\n\n#### Useful Snippets\n```\n<nav role=\"navigation\" class=\"navbar navbar-default\">\n\t<div class=\"\">\n\t\t<a href=\"http://www.in28minutes.com\" class=\"navbar-brand\">in28Minutes</a>\n\t</div>\n\t<div class=\"navbar-collapse\">\n\t\t<ul class=\"nav navbar-nav\">\n\t\t\t<li class=\"active\"><a href=\"/login\">Home</a></li>\n\t\t\t<li><a href=\"/list-todos\">Todos</a></li>\n\n\t\t</ul>\n\t</div>\n</nav>\n```\n\n###  Step 31 : Let's prepare for Spring Security\n\n##### /src/main/java/com/in28minutes/login/LoginController.java Modified\nNew Lines\n```\n\t@RequestMapping(value = \"/\", method = RequestMethod.GET)\n\tpublic String showWelcomePage(ModelMap model) {\n\t\tmodel.put(\"name\", \"in28Minutes\");\n\t\treturn \"welcome\";\n\t}\n```\n##### /src/main/java/com/in28minutes/todo/TodoController.java Modified\nNew Lines\n```\n\n\t@RequestMapping(value = \"/list-todos\", method = RequestMethod.GET)\n\tpublic String showTodosList(ModelMap model) {\n\t\tString user = getLoggedInUserName(model);\n\t\tmodel.addAttribute(\"todos\", service.retrieveTodos(user));\n\t\treturn \"list-todos\";\n\t}\n\n\t@RequestMapping(value = \"/add-todo\", method = RequestMethod.POST)\n\tpublic String addTodo(ModelMap model, @Valid Todo todo, BindingResult result) {\n\n\t\tif (result.hasErrors())\n\t\t\treturn \"todo\";\n\n\t\tservice.addTodo(getLoggedInUserName(model), todo.getDesc(),\n\t\t\t\ttodo.getTargetDate(), false);\n\t\tmodel.clear();// to prevent request parameter \"name\" to be passed\n\t\treturn \"redirect:/list-todos\";\n\t}\n\n\tprivate String getLoggedInUserName(ModelMap model) {\n\t\treturn (String) model.get(\"name\");\n\t}\n\n```\n##### /src/main/webapp/WEB-INF/views/common/navigation.jspf Modified\nNew Lines\n```\n\t\t\t<li class=\"active\"><a href=\"/\">Home</a></li>\n```\n##### /src/main/webapp/WEB-INF/views/login.jsp Deleted\n#### What we will do:\n- Prepare for Using Spring Security\n- Remove All the Login Related Functionality\n- Make Welcome the default page - with some hardcoding to start with.\n- Refactor getLoggedInUserName\n- Update Home Page Link in navigation\n\n#### Useful Snippets\n```\n```\n\n###  Step 32 : Initial Setup for Spring Security\n\n##### /pom.xml Modified\nNew Lines\n```\n\t\t<dependency>\n\t\t\t<groupId>org.springframework.security</groupId>\n\t\t\t<artifactId>spring-security-web</artifactId>\n\t\t\t<version>4.0.1.RELEASE</version>\n  \t\t</dependency>\n\n       <dependency>\n            <groupId>org.springframework.security</groupId>\n            <artifactId>spring-security-config</artifactId>\n            <version>4.0.1.RELEASE</version>\n        </dependency>\t\n```\n##### /src/main/java/com/in28minutes/security/SecurityConfiguration.java New\n```\npackage com.in28minutes.security;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;\nimport org.springframework.security.config.annotation.web.builders.HttpSecurity;\nimport org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;\nimport org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;\n\n@Configuration\n@EnableWebSecurity\npublic class SecurityConfiguration extends WebSecurityConfigurerAdapter {\n\n\t@Autowired\n\tpublic void configureGlobalSecurity(AuthenticationManagerBuilder auth)\n\t\t\tthrows Exception {\n\t\tauth.inMemoryAuthentication().passwordEncoder(org.springframework.security.crypto.password.NoOpPasswordEncoder.getInstance()).withUser(\"in28Minutes\").password(\"dummy\")\n\t\t\t\t.roles(\"USER\", \"ADMIN\");\n\t}\n\n\t@Override\n\tprotected void configure(HttpSecurity http) throws Exception {\n\t\thttp.authorizeRequests().antMatchers(\"/login\").permitAll()\n\t\t\t\t.antMatchers(\"/\", \"/*todo*/**\").access(\"hasRole('USER')\").and()\n\t\t\t\t.formLogin();\n\t}\n}\n```\n##### /src/main/webapp/WEB-INF/web.xml Modified\nNew Lines\n```\n    \n   <filter>\n    \t\t<filter-name>springSecurityFilterChain</filter-name>\n    \t\t<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>\n   </filter>\n \n   <filter-mapping>\n   \t\t<filter-name>springSecurityFilterChain</filter-name>\n    \t\t<url-pattern>/*</url-pattern>\n   </filter-mapping> \n    \n```\n#### What we will do:\n- Get Setup for Spring Security\n\n###  Step 33 : Refactor and add Logout Functionality using Spring Security\n\n##### /src/main/java/com/in28minutes/login/LoginController.java Deleted\n##### /src/main/java/com/in28minutes/login/LoginService.java Deleted\n##### /src/main/java/com/in28minutes/login/LogoutController.java New\n```\npackage com.in28minutes.login;\n\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\n\nimport org.springframework.security.core.Authentication;\nimport org.springframework.security.core.context.SecurityContextHolder;\nimport org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\n\n@Controller\npublic class LogoutController {\n\n\t@RequestMapping(value = \"/logout\", method = RequestMethod.GET)\n\tpublic String logout(HttpServletRequest request,\n\t\t\tHttpServletResponse response) {\n\t\tAuthentication auth = SecurityContextHolder.getContext()\n\t\t\t\t.getAuthentication();\n\t\tif (auth != null) {\n\t\t\tnew SecurityContextLogoutHandler().logout(request, response, auth);\n\t\t}\n\t\treturn \"redirect:/\";\n\t}\n}\n```\n##### /src/main/java/com/in28minutes/login/WelcomeController.java New\n```\npackage com.in28minutes.login;\n\nimport org.springframework.security.core.context.SecurityContextHolder;\nimport org.springframework.security.core.userdetails.UserDetails;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.ui.ModelMap;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\n\n@Controller\npublic class WelcomeController {\n\n\t@RequestMapping(value = \"/\", method = RequestMethod.GET)\n\tpublic String showWelcomePage(ModelMap model) {\n\t\tmodel.put(\"name\", getLoggedInUserName());\n\t\treturn \"welcome\";\n\t}\n\n\tprivate String getLoggedInUserName() {\n\t\tObject principal = SecurityContextHolder.getContext()\n\t\t\t\t.getAuthentication().getPrincipal();\n\n\t\tif (principal instanceof UserDetails)\n\t\t\treturn ((UserDetails) principal).getUsername();\n\n\t\treturn principal.toString();\n\t}\n\n}\n```\n##### /src/main/java/com/in28minutes/todo/TodoController.java Modified\nNew Lines\n```\n\n\tprivate String getLoggedInUserName() {\n\t\tObject principal = SecurityContextHolder.getContext()\n\t\t\t\t.getAuthentication().getPrincipal();\n\n\t\tif (principal instanceof UserDetails)\n\t\t\treturn ((UserDetails) principal).getUsername();\n\n\t\treturn principal.toString();\n\t}\n\n```\n##### /src/main/webapp/WEB-INF/views/common/navigation.jspf Modified\nNew Lines\n```\n\t\t<ul class=\"nav navbar-nav navbar-right\">\n\t\t\t<li><a href=\"/logout\">Logout</a></li>\n```\n#### What we will do:\n- Remove Hardcoding of User Name\n- Remove LoginService\n- Rename LoginController to WelcomeController\n- Add Logout Functionality\n\n\n###  Step 34 : Exception Handling in Spring MVC - @ControllerAdvice, @ExceptionHandler and error-page in web dot xml\n\n##### /src/main/java/com/in28minutes/common/ExceptionController.java New\n```\npackage com.in28minutes.common;\n\nimport javax.servlet.http.HttpServletRequest;\n\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\nimport org.springframework.web.bind.annotation.ControllerAdvice;\nimport org.springframework.web.bind.annotation.ExceptionHandler;\nimport org.springframework.web.servlet.config.annotation.EnableWebMvc;\n\n@ControllerAdvice\n@EnableWebMvc\npublic class ExceptionController {\n\n\tprivate Log logger = LogFactory.getLog(ExceptionController.class);\n\n\t@ExceptionHandler(value = Exception.class)\n\tpublic String handleError(HttpServletRequest req, Exception exception) {\n\t\tlogger.error(\"Request: \" + req.getRequestURL() + \" raised \" + exception);\n\t\treturn \"error\";\n\t}\n}\n```\n##### /src/main/java/com/in28minutes/common/LogoutController.java New\n```\npackage com.in28minutes.common;\n\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\n\nimport org.springframework.security.core.Authentication;\nimport org.springframework.security.core.context.SecurityContextHolder;\nimport org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\n\n@Controller\npublic class LogoutController {\n\n\t@RequestMapping(value = \"/logout\", method = RequestMethod.GET)\n\tpublic String logout(HttpServletRequest request,\n\t\t\tHttpServletResponse response) {\n\t\tAuthentication auth = SecurityContextHolder.getContext()\n\t\t\t\t.getAuthentication();\n\t\tif (auth != null) {\n\t\t\tnew SecurityContextLogoutHandler().logout(request, response, auth);\n\t\t}\n\t\treturn \"redirect:/\";\n\t}\n}\n```\n##### /src/main/java/com/in28minutes/login/LogoutController.java Deleted\n##### /src/main/java/com/in28minutes/login/WelcomeController.java Deleted\n##### /src/main/java/com/in28minutes/welcome/WelcomeController.java New\n```\npackage com.in28minutes.welcome;\n\nimport org.springframework.security.core.context.SecurityContextHolder;\nimport org.springframework.security.core.userdetails.UserDetails;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.ui.ModelMap;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\n\n@Controller\npublic class WelcomeController {\n\n\t@RequestMapping(value = \"/\", method = RequestMethod.GET)\n\tpublic String showWelcomePage(ModelMap model) {\n\t\tmodel.put(\"name\", getLoggedInUserName());\n\t\treturn \"welcome\";\n\t}\n\n\tprivate String getLoggedInUserName() {\n\t\tObject principal = SecurityContextHolder.getContext()\n\t\t\t\t.getAuthentication().getPrincipal();\n\n\t\tif (principal instanceof UserDetails)\n\t\t\treturn ((UserDetails) principal).getUsername();\n\n\t\treturn principal.toString();\n\t}\n\n}\n```\n##### /src/main/webapp/WEB-INF/views/error.jsp New\n```\n<%@ include file=\"common/header.jspf\"%>\n<%@ include file=\"common/navigation.jspf\"%>\n<div class=\"container\">\n\tApplication has encountered an error. Please contact support on ...\n</div>\n\n<%@ include file=\"common/footer.jspf\"%>\n```\n##### /src/main/webapp/WEB-INF/web.xml Modified\nNew Lines\n```\n   \n    <error-page>\n\t    <location>/WEB-INF/views/error.jsp</location>\n\t</error-page>\n```\n#### What we will do:\n- Basic Exception Handling\n- Exception Handling is a cross cutting concern\n- Do not handle exceptions in Controllers or Services, if you cannot add value to them.\n- Bit of refactoring on the controllers\n- @ControllerAdvice and Controller Specific Exception Handling\n- Handling Errors thrown from Views\n\n#### Useful Snippets\n```\n@ControllerAdvice\n@EnableWebMvc\npublic class ExceptionController {\n\n\tprivate Log logger = LogFactory.getLog(ExceptionController.class);\n\n\t@ExceptionHandler(value = Exception.class)\n\tpublic String handleError(HttpServletRequest req, Exception exception) {\n\t\tlogger.error(\"Request: \" + req.getRequestURL() + \" raised \" + exception);\n\t\treturn \"error\";\n\t}\n}\n\n<error-page>\n\t    <location>/WEB-INF/views/jsp/error.jsp</location>\n</error-page>\n```\n\n###  Step 35 : Let's add Internationalization - i18n\n\n##### /src/main/resources/messages_en.properties New\n```\nwelcome.message=Welcome in English\ntodo.caption= Todo Caption in English\n```\n##### /src/main/resources/messages_fr.properties New\n```\nwelcome.message=Welcome in French\ntodo.caption= Todo Caption in French\n```\n##### /src/main/webapp/WEB-INF/todo-servlet.xml Modified\nNew Lines\n```\n\t<bean id=\"messageSource\"\n\t\tclass=\"org.springframework.context.support.ReloadableResourceBundleMessageSource\">\n\t\t<property name=\"basename\" value=\"classpath:messages\" />\n\t\t<property name=\"defaultEncoding\" value=\"UTF-8\" />\n\t</bean>\n\t<bean id=\"localeResolver\"\n\t\tclass=\"org.springframework.web.servlet.i18n.SessionLocaleResolver\">\n\t\t<property name=\"defaultLocale\" value=\"en\" />\n\t</bean>\n\t<mvc:interceptors>\n\t\t<bean id=\"localeChangeInterceptor\"\n\t\t\tclass=\"org.springframework.web.servlet.i18n.LocaleChangeInterceptor\">\n\t\t\t<property name=\"paramName\" value=\"language\" />\n\t\t</bean>\n\t</mvc:interceptors>\n```\n##### /src/main/webapp/WEB-INF/views/common/header.jspf Modified\nNew Lines\n```\n<%@taglib uri=\"http://www.springframework.org/tags\" prefix=\"spring\"%>\n```\n##### /src/main/webapp/WEB-INF/views/list-todos.jsp Modified\nNew Lines\n```\n\t\t<caption><spring:message code=\"todo.caption\" /></caption>\n```\n##### /src/main/webapp/WEB-INF/views/welcome.jsp Modified\nNew Lines\n```\n\t<spring:message code=\"welcome.message\" /> ${name}.\n```\n#### What we will do:\n- Let's i18n.\n- Exercise : Internationalize Rest of the Stuff\n- http://localhost:8080/list-todos?language=en\n\n###  Step 36 : Basic Spring Rest Services - @RestController and jackson-databind\n\n\n##### /pom.xml Modified\nNew Lines\n```\n<dependency>\n\t<groupId>com.fasterxml.jackson.core</groupId>\n\t<artifactId>jackson-databind</artifactId>\n\t<version>2.5.3</version>\n</dependency>\n```\n##### /src/main/java/com/in28minutes/todo/rest/TodoRestController.java New\n```\npackage com.in28minutes.todo.rest;\n\nimport java.util.List;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\nimport org.springframework.web.bind.annotation.RestController;\n\nimport com.in28minutes.model.Todo;\nimport com.in28minutes.todo.service.TodoService;\n\n@RestController\npublic class TodoRestController {\n\t@Autowired\n\tprivate TodoService service;\n\n\t@RequestMapping(value = \"/todo/\", method = RequestMethod.GET)\n\tpublic List<Todo> listAllTodos() {\n\t\tList<Todo> users = service.retrieveTodos(\"in28Minutes\");\n\t\treturn users;\n\t}\n\n}\n```\n##### /src/main/resources/log4j.properties Modified\nNew Lines\n```\nlog4j.rootLogger=DEBUG, Appender1\n```\n#### What we will do:\n- Basic Spring Rest Services.\n\n###  Step 37 : More Rest Services - @PathVariable\n\n##### /src/main/java/com/in28minutes/todo/rest/TodoRestController.java Modified\nNew Lines\n```\n\t@RequestMapping(value = \"/todo/{id}\", method = RequestMethod.GET)\n\tpublic Todo retrieveTodo(@PathVariable(\"id\") int id) {\n\t\treturn service.retrieveTodo(id);\n\t}\n```\n#### What we will do:\n- One More Spring Rest Services.\n- @PathVariable(\"id\") int id\n#### Useful Snippets\n\n```\nproduces = MediaType.APPLICATION_JSON_VALUE\n```\n\n\n\n## Spring MVC Exercises\n\n## Read Documentation\nhttp://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html\n\n## Try a Few Spring Exercises From the Guide\nhttps://spring.io/guides\n\n## Setup Showcase Application\nhttps://github.com/spring-projects/spring-mvc-showcase\n\n## Try using the Spring Initializr\nhttps://start.spring.io\n\n### Some Theory\n\n- Complete Reference\n\t- http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html\n- Architecture Diagram\n\t- http://docs.spring.io/spring/docs/current/spring-framework-reference/html/images/mvc.png\n- Dispatcher Servlet\n\t- Dispatches requests to handlers, with configurable handler mappings\n\t- View Resolution\n\t- Locale, time zone and theme resolution \n\t- Support for uploading files.\n- Flexible Data Binding\n\t- Any POJO can be used as a command or form backing object\n\t- Highly Flexible Data Binding. Databinding Errors do not throw exceptions. They only cause validation errors.\n- Flexible View Resolution\n\t- Controller can either\n\t\t- Return a View\n\t\t- Return a View or Model\n\t\t- Write to response stream directly\n- Flexible Controller Methods\n- Accepting Variety of Parameters\n\t- Request or response objects : ServletRequest or HttpServletRequest.\n\t- Session object (Servlet API): of type HttpSession. \n\t- Other Options: http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-methods\n- Support Multiple Return Types\n\t- A ModelAndView object\n\t- A Model object\n- @ModelAttribute Methods\n\t- Indicates the purpose of that method is to add one or more model attributes.\n\t- Invoked before @RequestMapping methods.\n\t- Used to fill the model with commonly needed attributes \n\t  - Drop down values for form\n\t  - Command or Form Backing Objects\n- Method Argument\n\t- To automatically add/retrieve value from Model\n\t- It can be stored in session as well using @SessionAttributes.\n- Validation\n\t- Automatic\n\t- @Valid annotation\n\n##### Customized\nYou can also invoke validation using your own custom validator \n```\n@RequestMapping(path = \"/something\", method = RequestMethod.POST)\npublic String processSubmit(@ModelAttribute(\"todo\") Pet Todo, BindingResult result) {\n    new TodoValidator().validate(todo, result);\n    if (result.hasErrors()) {\n        return \"todo\";\n    }\n    // ...\n}\n```\n\n##### @ControllerAdvice\n\n- Can contain @ExceptionHandler, @InitBinder, and @ModelAttribute annotated methods\n- These methods will apply to @RequestMapping methods across all controller hierarchies\n\n##### Hibernate Validator : JSR 349 Reference Implementation\nFor more information refer http://docs.jboss.org/hibernate/validator/5.0/reference/en-US/html_single/#validator-defineconstraints-spec\n\n\n"
  },
  {
    "path": "_blog/articles/2017-11-11-eclipse-in-5-steps.md",
    "content": "---\nlayout:     post\ntitle:      Eclipse Tutorial for Beginners in 5 Steps\ndate:       2017-11-11 12:31:19\nsummary:    Eclipse Tutorial for Beginners in 5 Steps\ncategories: SwEclipse\npermalink:  /eclipse-tutorial-for-beginners\nimage: /images/java-category.png\n---\n\n- Git Repository - https://github.com/in28minutes/getting-started-in-5-steps/tree/master/eclipse-in-5-steps\n- Pre-requisites - Java & Eclipse - https://www.youtube.com/playlist?list=PLBBog2r6uMCSmMVTW_QmDLyASBvovyAO3\n\n> If you are using mac, use Cmd instead of Ctrl. \n\n> In Windows, use Window -> Preferences for Preferences.\n\n\n## Step By Step Details\n\n- Step 1 : Create a Java Project \n  - Create and run a Java class\n- Step 2 : Keyboard Shortcuts\n  - Ctrl + Space\n    - BigDecimal - Auto Suggestion\n    - Templates - main, fore, sysout, syserr\n  - Ctrl + 1\n    - File Name and Class Name does not match - Display Errors\n    - Rename a Class - What suggestions are offered?\n    - new Integer() - What suggestions are offered?\n  - Ctrl + Shift + R (and T)\n  - F3 (Goto declaration)\n  - F4 (Type Hierarchy)\n  - Ctrl + Shift + L\n- Step 3 : Views and Perspectives\n- Step 4 : Save Actions\n- Step 5 : Code Generation\n    - Alt + Shift + S\n      - Getters and Setters\n      - toString()\n      - equals()\n      - hashcode()"
  },
  {
    "path": "_blog/articles/2017-11-12-in28minutes-connect.md",
    "content": "---\nlayout:     post\ntitle:      The in28Minutes Connect - connecting experts with the learners\ndate:       2017-11-12 12:31:19\nsummary:    in28Minutes Connect - connecting experts with the learners. \ncategories: TheIn28MinutesWay\npermalink:  /in28minutes-connect\n---\n\n## Aim\n\n- Give Experts a platform to share their expertise\n\t- With this platform, experts get the opportunity to (possibly) share your vision, passion and knowledge with our  43,000 subscribers on YouTube (https://www.youtube.com/rithustutorials) and 100,000 learners on Udemy (https://github.com/in28minutes/learn#best-selling-courses)\n- Create Great Programmers from India\n\t- There are awesome programmers from India doing great work across the world. However, as a percentage of IT professionals, the number of awesome programmers remains miniscule.\n- Promote Online Learning in India\n\t- We think Online Learning is a great socio economic leveller. Online learning has come a long way in the last few years around the world. However, adoption in India remains slow and we want to increase adoption by bringing online learning at an early stage - college and industry entry level. We belive once you start learning online, it will remain your No 1 choice of learning.\n- Give Learners exposure to \n\t- Behind the scenes look at experts - stories, lessons, beliefs and vision!\n\t- What's happening in the industry?\n\t- How can they adapt?\n\n## Our Beliefs\n\n- We believe in continuous learning. Learn every day and adapt. A day you've not learnt something new is a day wasted! And thats the origin for our name in28Minutes.\n- Be passionate about what your do!\n- While we are creating great learning experiences with our courses, we think a real mindset change happens only when a learner gets a chance to interact with experts - who are passionate and doing great work.\n- As an online instructor, we should engage and care for our students.\n\n\n## Logistics\n\n- Only One Step\n\t- You can book a slot using calendly \n\t\t- https://calendly.com/in28minutes/60min\n\t\t- Calendly provides flexibility of rescheduling if needed\n\n## Before We Meet\n\n- This would be a video interview. Ensure that you have a good background (preferably light color - white) and a good internet connection for the video.\n- We would establish initial contact on Skype.  After that we will \n      - go live on facebook - https://www.facebook.com/in28Minutes/. using belive.tv.\n      \t- I will share you a link before the meeting. \n      \t- You would need Google Chrome browser. \n      \t- ~~We can record video using Zoom~~\n- Typical Schedule\n\t- 15 Minutes - Build a Rapport\n\t- 45 Minutes - Do the interview\n- Please share a few links with me ahead of time that you would want me to research.\n\t- Your Assets - Websites/Courses/Videos etc\n\t\t- Things you would want to see in the description of the video (Links etc)\n- Look at it like a conversation (more than an interview) between two folks having similar visions about entrepreneurship and online learning.\n- Tell a Story\n\t- Keep it short :)\n\t- Humanize\n\t- Surprise\n\t- Have a Narrative\n- Research a little bit about in28Minutes\n\t- Udemy - https://github.com/in28minutes/learn#best-selling-courses \n\n## Usually Talked About\n\n- Your Journey\n\t- As a Person\n\t\t- Your goals\n\t\t- What inspires you?\n\t- As an Enterpreneur /IT Professional/Udemy Instructor/etc\n\t\t- What's your vision?\n\t\t- What are your goals?\n\t\t- What are your next steps?\n\t\t- What is your advice to others who want to follow your path\n\t\t- Anything else you wanna add\n- Your Time\n\t- How do you manage to stay connected with your family inspite of being busy?\n- Your Views\n\t- Trends\n\t- IT Products vs Services\n\t- Startups\t\n\t- Technology\n\t\t- The Churn in the Industry\n\t\t\t- AI\n\t\t\t- IOT\n\t\t\t- Machine Learning\n\t\t\t- Big Data\n\t\t\t- DevOps\n\t\t\t- Cloud\n\t\t- Microservices - Node JS/Spring Boot\n\t\t- Frontend Frameworks - Javascript/etc\n\t\t- Automation Testing\n\t\t- Mobile Development - Android/iPhone/Cross Platform\n\t- About Indian IT\n\t\t- Evolution in the last few years\n\t- About Agile\n\t- Anything else you wanna add :)\n- Your Message\n\t- For Students\n\t\t- Engineers, 0-2 Years\n\t\t- 3-6 years\n\t\t- 6+ years\n\t- For Indian IT Professions (if you had an opportunity to work with them) \n\t- For Other Udemy Instructors (If you are one)\n- Our Connection\n\t- Have you heard about in28Minutes - https://github.com/in28minutes/learn#best-selling-courses ?\n\t- Do you connect with our vision and message?\n\t\t- Vision\n\t\t\t- Learn in 28 Minutes everyday - Continuous Learning\n\t\t- Approach\n\t\t\t- Create Great Learning Experiences\n\t\t\t- Promote Online Learning in India\n\t\t\t- Be an expert at what you do.\n\t\t\t- Promote Hands-on Trainings for Programming\n\t- Your recommendations for in28Minutes\n\n## What Next\n\n- We will be live on facebook. \n- We will own the content of the video and when we have a group of related videos, we would release them out to youtube in batches - so, posting on YouTube will take a little while.\n- You can talk about the interview, post the link or embed the video in your platforms\n   - Your YouTube Channel\n   - Udemy Educational Announcement\n   - Website\n   - Blog\n   - etc\n\n## Quick Reference\n- What drives you? What made you a programmer? What made you teach online?\n- First Program? First Video etc...\n- What's the coolest stuff you are working on?\n- What are the problems that will be solved in the future in ABC (the technology you are working on)?\n- How do you think we can promote self learning?\n- How important you think it is to be hands-on while doing a tech course?\n- What is your suggestion for programmers who are starting off?\n- If you have to learn a new concept/tool/framework, how do you do it?\n- How do you keep up with whats happening in the industry?\n- What are your all-time favourite books on technology and learning? Any recent thought-provoking books that you've read recently.\n- Which blogs and podcasts do you follow/listen to keep yourself updated about latest development on technology.\n- What 2-minute advice you'd like to give to your younger self who's just getting started in the IT industry?\n\n## The End\n\nWow! Wasn't it a wonderful read? We would love to hear your thoughts.  \nTo find out more about our courses visit http://www.in28minutes.com\n\nShare on Twitter - https://twitter.com/home?status=Having%20a%20great%20time!%20%0A%20%23in28Minutes%20%23ImLearningIn28Minutes\n\n#in28Minutes #ImLearningIn28Minutes #ImLovingIn28Minutes \n\nGood Luck and Keep Learning in28Minutes\n- Linked In : https://www.linkedin.com/in/rangakaranam/​\n- Facebook  : https://www.facebook.com/in28Minutes​\n- Twitter   : https://twitter.com/in28Minutes​\n- YouTube   : https://www.youtube.com/rithustutorials​\n​"
  },
  {
    "path": "_blog/articles/2017-11-13-jpa-and-hibernate-with-spring-boot.md",
    "content": "---\nlayout:     post\ntitle:      JPA and Hibernate Tutorial for Beginners - with Spring Boot\ndate:       2017-11-13 12:31:19\nsummary:    JPA and Hibernate with Spring Boot - Course Guide with Step by Step Details, Code Examples and the Notes\ncategories: SpringBootJPA\npermalink:  /jpa-and-hibernate-tutorial-with-spring-boot\nimage: /images/spring-data-category.png\n---\n\nMaster JPA using Hibernate as the implementation. Learn the basics of JPA - entities, relationships, entity manager, annotations, JPQL and Criteria API. Take a step into the advanced world of JPA - caching, performance tuning(n + 1 queries), mapping inheritance hierarchies. Get a peek into the magic of Spring Data JPA & Spring Data Rest.\n\n### Introduction\n\nThe Java Persistence API provides Java developers with an api for mapping java objects to relational data. In this course, you will learn about the JPA API, JPQL (Java Persistence query language), Java Persistence Criteria API and how you can perform ORM (Object Relational Mapping) with JPA. \n\nHibernate is the most popular implementation of JPA. It was the most popular ORM framework option before JPA emerged and it provides additional features on top of JPA. We will use Hibernate as the implementation in this course.\n\n### What You will learn\n\n- You will learn the basics of JPA and Hibernate - Entities, Relationships, Inheritance Mappings and Annotations\n- You will understand approaches to querying data using JPA and Hibernate - JPQL, Criteria API and Native Queries\n- You will understand JPA and Hibernate Relationships in depth - One to One, Many to One and Many to Many\n- You will use a variety of Spring Boot Starters - Spring Boot Starter Web, Starter Data Jpa, Starter Test\n- You will learn the basic of performance tuning your JPA application with Hibernate - Solve N+1 Queries Issue. \n- You will learn the basics of caching - First Level Cache and Second Level Cache with EhCache\n- You will understand the basics of Spring Data JPA and Spring Data REST\n\n\n\n## Connecting to My SQL and Other Databases\n\nSpring Boot makes it easy to switch databases! Yeah really simple.\n\n## Steps\n- Install MySQL and Setup Schema\n- Remove H2 dependency from pom.xml\n- Add MySQL (or your database) dependency to pom.xml\n```xml\n<dependency>\n    <groupId>mysql</groupId>\n    <artifactId>mysql-connector-java</artifactId>\n</dependency>\n```\n- Configure application.properties\n\n```properties\nspring.jpa.hibernate.ddl-auto=none\nspring.datasource.url=jdbc:mysql://localhost:3306/person_example\nspring.datasource.username=personuser\nspring.datasource.password=YOUR_PASSWORD\n```\n\n- Restart the app and You are ready!\n\n> Spring Boot can setup the database for you using Hibernate\n\nThings to note:\n- Spring Boot chooses a default value for you based on whether it thinks your database is embedded (default create-drop) or not (default none).\n- ```spring.jpa.hibernate.ddl-auto``` is the setting to perform SchemaManagementTool actions automatically\n   - none : No action will be performed.\n   - create-only : Database creation will be generated.\n   - drop : Database dropping will be generated.\n   - create : Database dropping will be generated followed by database creation.\n   - validate : Validate the database schema\n   - update : Update the database schema\n- Reference : https://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/Hibernate_User_Guide.html#configurations-hbmddl\n\n\napplication.properties\n```\n#none, validate, update, create, create-drop\nspring.jpa.hibernate.ddl-auto=create\n```\n\n## Installing and Setting Up MySQL\n\n- Install MySQL https://dev.mysql.com/doc/en/installing.html\n  - More details - http://www.mysqltutorial.org/install-mysql/\n  - Trouble Shooting - https://dev.mysql.com/doc/refman/en/problems.html\n- Startup the Server (as a service)\n- Go to command prompt (or terminal)\n   - Execute following commands to create a database and a user\n\n```\nmysql --user=user_name --password db_name\ncreate database person_example;\ncreate user 'personuser'@'localhost' identified by 'YOUR_PASSWORD';\ngrant all on person_example.* to 'personuser'@'localhost';\n```\n\n- Execute following sql queries to create the table and insert the data\n\n### JDBC TO JPA\nTable\n\n```sql\ncreate table person\n(\n  id integer not null,\n  birth_date timestamp,\n  location varchar(255),\n  name varchar(255),\n  primary key (id)\n);\n\n```\n\nData\n\n```sql\nINSERT INTO PERSON (ID, NAME, LOCATION, BIRTH_DATE ) VALUES(10001,  'Ranga', 'Hyderabad',sysdate());\nINSERT INTO PERSON (ID, NAME, LOCATION, BIRTH_DATE ) VALUES(10002,  'James', 'New York',sysdate());\nINSERT INTO PERSON (ID, NAME, LOCATION, BIRTH_DATE ) VALUES(10003,  'Pieter', 'Amsterdam',sysdate());\n```\n\n\n### JPA in Depth\nTables\n\n```sql\n    create table course (\n       id bigint not null,\n        created_date timestamp,\n        is_deleted boolean not null,\n        last_updated_date timestamp,\n        name varchar(255) not null,\n        primary key (id)\n    );\n    create table full_time_employee (\n       id bigint not null,\n        name varchar(255) not null,\n        salary decimal(19,2),\n        primary key (id)\n    );\n    create table part_time_employee (\n       id bigint not null,\n        name varchar(255) not null,\n        hourly_wage decimal(19,2),\n        primary key (id)\n    );\n    create table passport (\n       id bigint not null,\n        number varchar(255) not null,\n        primary key (id)\n    );\n    create table review (\n       id bigint not null,\n        description varchar(255),\n        rating varchar(255),\n        course_id bigint,\n        primary key (id)\n    );\n    create table student (\n       id bigint not null,\n        city varchar(255),\n        line1 varchar(255),\n        line2 varchar(255),\n        name varchar(255) not null,\n        passport_id bigint,\n        primary key (id)\n    );\n    create table student_course (\n       student_id bigint not null,\n        course_id bigint not null\n    )\n    alter table review \n       add constraint FKprox8elgnr8u5wrq1983degk \n       foreign key (course_id) \n       references course;\n    alter table student \n       add constraint FK6i2dofwfuu97njtfprqv68pib \n       foreign key (passport_id) \n       references passport;\n    alter table student_course \n       add constraint FKejrkh4gv8iqgmspsanaji90ws \n       foreign key (course_id) \n       references course;\n    alter table student_course \n       add constraint FKq7yw2wg9wlt2cnj480hcdn6dq \n       foreign key (student_id) \n       references student;\n\n```\n\nData\n\n```sql\ninsert into course(id, name, created_date, last_updated_date,is_deleted) \nvalues(10001,'JPA in 50 Steps', sysdate(), sysdate(),false);\ninsert into course(id, name, created_date, last_updated_date,is_deleted) \nvalues(10002,'Spring in 50 Steps', sysdate(), sysdate(),false);\ninsert into course(id, name, created_date, last_updated_date,is_deleted) \nvalues(10003,'Spring Boot in 100 Steps', sysdate(), sysdate(),false);\n\n\ninsert into passport(id,number)\nvalues(40001,'E123456');\ninsert into passport(id,number)\nvalues(40002,'N123457');\ninsert into passport(id,number)\nvalues(40003,'L123890');\n\ninsert into student(id,name,passport_id)\nvalues(20001,'Ranga',40001);\ninsert into student(id,name,passport_id)\nvalues(20002,'Adam',40002);\ninsert into student(id,name,passport_id)\nvalues(20003,'Jane',40003);\n\ninsert into review(id,rating,description,course_id)\nvalues(50001,'FIVE', 'Great Course',10001);\ninsert into review(id,rating,description,course_id)\nvalues(50002,'FOUR', 'Wonderful Course',10001);\ninsert into review(id,rating,description,course_id)\nvalues(50003,'FIVE', 'Awesome Course',10003);\n\ninsert into student_course(student_id,course_id)\nvalues(20001,10001);\ninsert into student_course(student_id,course_id)\nvalues(20002,10001);\ninsert into student_course(student_id,course_id)\nvalues(20003,10001);\ninsert into student_course(student_id,course_id)\nvalues(20001,10003);\n```\n\n\n\n## Installing Tools\n- Installation Video : https://www.youtube.com/playlist?list=PLBBog2r6uMCSmMVTW_QmDLyASBvovyAO3\n- GIT Repository For Installation : https://github.com/in28minutes/getting-started-in-5-steps\n- PDF : https://github.com/in28minutes/SpringIn28Minutes/blob/master/InstallationGuide-JavaEclipseAndMaven_v2.pdf\n\n## Running Examples\n- Download the zip or clone the Git repository.\n- Unzip the zip file (if you downloaded one)\n- Open Command Prompt and Change directory (cd) to folder containing pom.xml\n- Open Eclipse \n   - File -> Import -> Existing Maven Project -> Navigate to the folder where you unzipped the zip\n   - Select the right project\n- Choose the Spring Boot Application file (search for @SpringBootApplication)\n- Right Click on the file and Run as Java Application\n- You are all Set\n- For help : use our installation guide - https://www.youtube.com/playlist?list=PLBBog2r6uMCSmMVTW_QmDLyASBvovyAO3\n\n## Step By Step Details\n\n\n### JPA Introduction\n- 0005 - Quick introduction to JPA\n\n### Spring Boot in 10 Steps\n- Link - Spring Boot in 5 Steps\n- Github Folder -\n\n### Journey from JDBC To JPA\n- Step 01 - Setting up a project with JDBC, JPA, H2 and Web Dependencies\n- Step 02 - Launching up H2 Console\n- Step 03 - Creating a Database Table in H2\n- Step 04 - Populate data into Person Table\n- Step 05 - Implement findAll persons Spring JDBC Query Method\n- Step 06 - Execute the findAll method using CommandLineRunner\n- Step 07 - A Quick Review - JDBC vs Spring JDBC\n- Step 08 - Whats in the background? Understanding Spring Boot Autoconfiguration\n- Step 09 - Implementing findById Spring JDBC Query Method\n- Step 10 - Implementing deleteById Spring JDBC Update Method\n- Step 11 - Implementing insert and update Spring JDBC Update Methods\n- Step 12 - Creating a custom Spring JDBC RowMapper\n- Step 13 - Quick introduction to JPA\n- Step 14 - Defining Person Entity\n- Step 15 - Implementing findById JPA Repository Method\n- Step 16 - Implementing insert and update JPA Repository Methods\n- Step 17 - Implementing deleteById JPA Repository Method\n- Step 18 - Implementing findAll using JPQL Named Query\n\n### JUnit in 5 Steps\n- Link - JUnit in 5 Steps\n- Github Folder -\n\n### JPA/Hibernate in Depth\n- Step 01 - Create a JPA Project with H2 and Spring Boot\n- Step 02 - Create JPA Entity Course\n- Step 03 - Create findById using JPA Entity Manager\n- Step 04 - Configuring application.properties to enable H2 console and logging\n- Step 05 - Writing Unit Test for findById method\n- Step 06 - Writing a deleteByID method to delete an Entity\n- Step 07 - Writing Unit Test for deleteById method\n- Step 08 - Writing a save method to update and insert an Entity\n- Step 09 - Writing Unit Test for save method\n- Step 10 - Quick Review and Debugging Tips\n- Step 11 - Playing with Entity Manager\n- Step 12 - Entity Manager Methods - clear and detach\n- Step 13 - Entity Manager Methods - refresh\n- Step 14 - A Quick Review of Entity Manager\n- Step 15 - JPQL - Basics\n- Step 16 - JPA and Hibernate Annotations - @Table\n- Step 17 - JPA and Hibernate Annotations - @Column\n- Step 18 - JPA and Hibernate Annotations - @UpdateTimestamp and @CreationTimestamp\n- Step 19 - JPA and Hibernate Annotations - @NamedQuery and @NamedQueries\n- Step 20 - Native Queries - Basics\n- Step 21 - Entities and Relationships - An overview\n- Step 22 - Defining Entities - Student, Passport and Review\n- Step 23 - Introduction to One to One Relationship\n- Step 24 - OneToOne Mapping - Insert Student with Passport\n- Step 25 - OneToOne Mapping - Retrieving Student with Passport and Eager Fetch\n- Step 26 - OneToOne Mapping - Lazy Fetch\n- Step 27 - Transaction, Entity Manager and Persistence Context\n- Step 28 - OneToOne Mapping - Bidirectional Relationship - Part 1\n- Step 29 - OneToOne Mapping - Bidirectional Relationship - Part 2\n- Step 30 - ManyToOne Mapping - Designing the database\n- Step 30 - 02 - ManyToOne Mapping - Implementing the Mapping *****\n- Step 31 - ManyToOne Mapping - Retrieving and inserting Reviews for Course\n- Step 32 - ManyToOne Mapping - Generalizing Insert Reviews\n- Step 33 - ManyToOne Mapping - Wrapping up\n- Step 34 - ManyToMany Mapping - Table Design\n- Step 35 - ManyToMany Mapping - Adding Annotations on Entities\n- Step 36 - ManyToMany Mapping - Fixing two join tables problem\n- Step 37 - ManyToMany Mapping - Customizing the Join Table\n- Step 38 - ManyToMany Mapping - Insert Data and Write Join Query\n- Step 39 - ManyToMany Mapping - Retrieve Data using JPA Relationships\n- Step 40 - ManyToMany Mapping - Insert Student and Course\n- Step 41 - Relationships between JPA Entities - A summary\n- Step 42 - Introduction to Inheritance Hierarchies and Mappings\n- Step 43 - JPA Inheritance Hierarchies and Mappings - Setting up entities\n- Step 44 - JPA Inheritance Hierarchies and Mappings - Setting up a Repository\n- Step 45 - JPA Inheritance Hierarchies and Mappings - Single Table\n- Step 46 - JPA Inheritance Hierarchies and Mappings - Table Per Class\n- Step 47 - JPA Inheritance Hierarchies and Mappings - Joined\n- Step 48 - JPA Inheritance Hierarchies and Mappings - Mapped Super Class\n- Step 49 - JPA Inheritance Hierarchies and Mappings - How to Choose?\n- Step 50 - JPQL - Courses without Students\n- Step 51 - JPQL - Courses with atleast 2 Students and order by\n- Step 52 - JPQL - Courses like 100 Steps\n- Step 53 - JPQL - Using Joins\n- Step 54 - Criteria Query - Retrieving all courses\n- Step 55 - Criteria Query - Courses like 100 Steps\n- Step 56 - Criteria Query - Courses without Students\n- Step 57 - Criteria Query - Using Joins\n- Step 58 - Introduction to Transaction Management\n- Step 59 - Transaction Management - ACID Properties\n- Step 60 - Understanding Dirty, Phanthom and Non Repeatable Reads\n- Step 61 - Understand 4 Isolation Levels\n- Step 62 - Choosing between Isolation Levels\n- Step 63 - Implementing Transaction Management - 3 Things to Decide\n- Step 64 - Introduction to Spring Data JPA\n- Step 65 - Testing the Spring Data JPA Repository with findById.\n- Step 66 - Spring Data JPA Repository - CRUD Methods\n- Step 67 - Sorting using Spring Data JPA Repository\n- Step 68 - Pagination using Spring Data JPA Repository \n- Step 69 - Custom Queries using Spring Data JPA Repository \n- Step 70 - Spring Data REST\n- Step 71 - Introduction to Caching\n- Step 72 - Hibernate and JPA Caching - First Level Cache\n- Step 73 - Hibernate and JPA Caching - Basics of Second Level Cache with EhCache\n- Step 74 - Hibernate and JPA Caching - Second Level Cache Part 2\n- Step 75 - Hibernate Tips - Hibernate Soft Deletes - @SQLDelete and @Where\n- Step 76 - Hibernate Soft Deletes - Part 2\n- Step 77 - JPA Entity Life Cycle Methods\n- Step 78 - Using Embedded and Embeddable with JPA\n- Step 79 - Using Enums with JPA\n- Step 80 - JPA Tip - Be cautious with toString method implementations\n- Step 81 - JPA Tip - When do you use JPA?\n- Step 82 - Performance Tuning - Measure before Tuning\n- Step 83 - Performance Tuning - Indexes\n- Step 84 - Performance Tuning - Use Appropriate Caching\n- Step 85 - Performance Tuning - Eager vs Lazy Fetch\n- Step 86 - Performance Tuning - Avoid N+1 Problems\n- FAQ 1 - When does Hibernate send updates to the database?\n- FAQ 2 - When do we need @Transactional in an Unit Test?\n- FAQ 3 - Do read only methods need a transaction?\n- FAQ 4 - Why do we use @DirtiesContext in an Unit Test?\n- FAQ 5 - How to connect to a different database with Spring Boot?\n- FAQ 6 - Approach to design great applications with JPA?\n- FAQ 7 - Good Practices for developing JPA Applications\n\n### Spring Framework in 10 Steps\n- Link - Spring Framework in 10 Steps\n- Github Folder -\n\n\n## Step By Step Notes\n\n### Journey from JDBC To JPA\n\n> TODO \n\n> TODO \n\n### JPA/Hibernate in Depth\n\n####  Step 01 - Create a JPA Project with H2 and Spring Boot\n\nCreating a JPA Project with Spring Initializr is a cake walk. \n\n> Spring Initializr [http://start.spring.io/](http://start.spring.io/){:target=\"_blank\"} is great tool to bootstrap your Spring Boot projects.\n\nNotes\n- Launch Spring Initializr and choose the following\n  - Choose `com.in28minutes.jpa.hibernate` as Group\n  - Choose `demo` as Artifact\n  - Choose the following Dependencies\n    - Web\n    - JPA\n    - H2\n- Click Generate Project.\n- Import the project into Eclipse.\n- If you want to understand all the files that are part of this project, you can go here.\n\n\n\n####  Step 02 - Create JPA Entity Course\n\nDefine an Entity Course with a primary key id.\n\n/src/main/java/com/in28minutes/jpa/hibernate/demo/entity/Course.java\n\n```java\npackage com.in28minutes.jpa.hibernate.demo.entity;\n\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.Id;\n\n@Entity\npublic class Course {\n\n  @Id\n  @GeneratedValue\n  private Long id;\n\n  private String name;\n\n  protected Course() {\n  }\n\n  public Course(String name) {\n    this.name = name;\n  }\n\n  public String getName() {\n    return name;\n  }\n\n  public void setName(String name) {\n    this.name = name;\n  }\n\n  public Long getId() {\n    return id;\n  }\n}\n```\n\nImportant things to note:\n\n- @Entity: Specifies that the class is an entity. This annotation is applied to the entity class.\n- @Id: Specifies the primary key of an entity.\n- @GeneratedValue: Provides for the specification of generation strategies for the values of primary keys.\n- protected Course(): Default constructor to make JPA Happy\n\n\n---\n\n####  Step 03 - Create findById using JPA Entity Manager\n\n/src/main/java/com/in28minutes/jpa/hibernate/demo/repository/CourseRepository.java\n\n```java\npackage com.in28minutes.jpa.hibernate.demo.repository;\n\nimport javax.persistence.EntityManager;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Repository;\n\nimport com.in28minutes.jpa.hibernate.demo.entity.Course;\n\n@Repository\npublic class CourseRepository { \n  \n  @Autowired\n  EntityManager em;\n  \n  public Course findById(Long id){\n    return em.find(Course.class, id);\n  }\n  \n  //public Course save(Course course) -> insert or update\n  \n  //public void deleteById(Long id)\n\n}\n```\n\nEnhance DemoApplication to implement CommandLineRunner and invoke the ```repository.findById(10001L)``` method.\n\n/src/main/java/com/in28minutes/jpa/hibernate/demo/DemoApplication.java\n```java\n@SpringBootApplication\npublic class DemoApplication implements CommandLineRunner{\n  \n  private Logger logger = LoggerFactory.getLogger(this.getClass());\n  \n  @Autowired\n  private CourseRepository repository;\n\n  public static void main(String[] args) {\n    SpringApplication.run(DemoApplication.class, args);\n  }\n\n  @Override\n  public void run(String... arg0) throws Exception {\n    Course course = repository.findById(10001L);\n    \n    logger.info(\"Course 10001 -> {}\", course);\n    \n  }\n}\n```\n\n\n####  Step 04 - Configuring application.properties to enable H2 console and logging\n\nThree important things are configured in application.properties\n- Enable H2 Console spring.h2.console.enabled=true\n  - http://localhost:8080/h2-console\n  - Use db url jdbc:h2:mem:testdb\n- Turn the hibernate statistics on\n- Enable logging of all queries\n\n/src/main/resources/application.properties \n```\n# Enabling H2 Console\nspring.h2.console.enabled=true\n#Turn Statistics on\nspring.jpa.properties.hibernate.generate_statistics=true\nlogging.level.org.hibernate.stat=debug\n# Show all queries\nspring.jpa.show-sql=true\nspring.datasource.url=jdbc:h2:mem:testdb\nspring.data.jpa.repositories.bootstrap-mode=default\nspring.jpa.properties.hibernate.format_sql=true\nlogging.level.org.hibernate.type=trace\n```\n\nInsert a row into the Course table\n\n/src/main/resources/data.sql\n\n```\ninsert into course(id, name) values(10001,'JPA in 50 Steps');\n```\n---\n\n####  Step 05 - Writing Unit Test for findById method\n\n/src/test/java/com/in28minutes/jpa/hibernate/demo/repository/CourseRepositoryTest.java\n\n```java\npackage com.in28minutes.jpa.hibernate.demo.repository;\n\nimport static org.junit.Assert.*;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.test.context.SpringBootTest;\nimport org.springframework.test.context.junit4.SpringRunner;\n\nimport com.in28minutes.jpa.hibernate.demo.DemoApplication;\nimport com.in28minutes.jpa.hibernate.demo.entity.Course;\n\n@RunWith(SpringRunner.class)\n@SpringBootTest(classes=DemoApplication.class)\npublic class CourseRepositoryTest {\n  \n  private Logger logger = LoggerFactory.getLogger(this.getClass());\n  \n  @Autowired\n  CourseRepository repository;\n  \n  @Test\n  public void findById_basic() {\n    Course course = repository.findById(10001L);\n    assertEquals(\"JPA in 50 Steps\", course.getName());\n  }\n\n}\n```\n---\n####  Step 06 - Writing a deleteByID method to delete an Entity\n\nclass DemoApplication\n\nModified Lines\n```\n    repository.deleteById(10001L);\n```\n\n/src/main/java/com/in28minutes/jpa/hibernate/demo/repository/CourseRepository.java \nModified Lines\n```\nimport org.springframework.transaction.annotation.Transactional;\n@Transactional\n```\n\n```\npublic void deleteById(Long id){\n  Course course = findById(id);\n  em.remove(course);\n}\n```\n\n/src/main/resources/data.sql \nModified Lines\n```\ninsert into course(id, name) values(10002,'Spring in 50 Steps');\ninsert into course(id, name) values(10003,'Spring Boot in 100 Steps');\n```\n####  Step 07 - Writing Unit Test for deleteById method\n\n/src/test/java/com/in28minutes/jpa/hibernate/demo/repository/CourseRepositoryTest.java \n```java\n//Imports\nimport org.springframework.test.annotation.DirtiesContext;\nimport org.springframework.transaction.annotation.Transactional;\n\n//New Method\n@DirtiesContext\npublic void deleteById_basic() {\n  repository.deleteById(10002L);\n  assertNull(repository.findById(10002L));\n} \n```\n\n####  Step 08 - Writing a save method to update and insert an Entity\n\n/src/main/java/com/in28minutes/jpa/hibernate/demo/DemoApplication.java\n\nModified Lines\n```\n    repository.save(new Course(\"Microservices in 100 Steps\"));\n  } \n```\n\n/src/main/java/com/in28minutes/jpa/hibernate/demo/repository/CourseRepository.java Modified Lines\n```\n  public Course save(Course course) {\n    \n    if (course.getId() == null) {\n      em.persist(course);\n    } else {\n      em.merge(course);\n    }\n    \n    return course;\n  }\n```\n\n####  Step 09 - Writing Unit Test for save method\n\n\n/src/test/java/com/in28minutes/jpa/hibernate/demo/repository/CourseRepositoryTest.java \nModified Lines\n\n```\n@SpringBootTest(classes = DemoApplication.class)\n```\n\n```java\npublic void save_basic() {\n  // get a course\n  // update details\n  course.setName(\"JPA in 50 Steps - Updated\");\n  repository.save(course);\n  // check the value\n  Course course1 = repository.findById(10001L);\n  assertEquals(\"JPA in 50 Steps - Updated\", course1.getName());\n}\n```\n\n####  Step 10 - Quick Review and Debugging Tips\n\n####  Step 11 - Playing with Entity Manager\n\n/src/main/java/com/in28minutes/jpa/hibernate/demo/DemoApplication.java\nModified Lines\n```\n    repository.playWithEntityManager();\n```\n\n/src/main/java/com/in28minutes/jpa/hibernate/demo/repository/CourseRepository.java \nModified Lines\n```java  \npublic void playWithEntityManager() {\n  Course course = new Course(\"Web Services in 100 Steps\");\n  em.persist(course);\n  course.setName(\"Web Services in 100 Steps - Updated\");\n}\n```\n\n/src/test/java/com/in28minutes/jpa/hibernate/demo/repository/CourseRepositoryTest.java \n\n```\n  @Test\n  @DirtiesContext\n  public void playWithEntityManager() {\n    repository.playWithEntityManager();\n  }\n\n```\n\n####  Step 12 - Entity Manager Methods - clear and detach\n####  Step 13 - Entity Manager Methods - refresh\n####  Step 14 - A Quick Review of Entity Manager\n\n/src/main/java/com/in28minutes/jpa/hibernate/demo/repository/CourseRepository.java Modified Lines\n```java\n  public void playWithEntityManager() {\n    \n    Course course1 = new Course(\"Web Services in 100 Steps\");\n    em.persist(course1);  \n    \n    Course course2 = new Course(\"Angular Js in 100 Steps\");\n    em.persist(course2);\n\n    em.flush();\n\n    course1.setName(\"Web Services in 100 Steps - Updated\");\n    course2.setName(\"Angular Js in 100 Steps - Updated\");\n    \n    em.refresh(course1);\n    \n    em.flush();\n  }\n```\n\n####  Step 15 - JPQL - Basics\n\n/src/test/java/com/in28minutes/jpa/hibernate/demo/repository/JPQLTest.java\n\n```java\n\n@RunWith(SpringRunner.class)\n@SpringBootTest(classes = DemoApplication.class)\npublic class JPQLTest {\n\n  private Logger logger = LoggerFactory.getLogger(this.getClass());\n\n  @Autowired\n  EntityManager em;\n\n  @Test\n  public void jpql_basic() {\n    Query query = em.createQuery(\"Select  c  From Course c\");\n    List resultList = query.getResultList();\n    logger.info(\"Select  c  From Course c -> {}\",resultList);\n  }\n\n  @Test\n  public void jpql_typed() {\n    TypedQuery<Course> query = \n          em.createQuery(\"Select  c  From Course c\", Course.class);\n    \n    List<Course> resultList = query.getResultList();\n    \n    logger.info(\"Select  c  From Course c -> {}\",resultList);\n  }\n\n  @Test\n  public void jpql_where() {\n    TypedQuery<Course> query = \n          em.createQuery(\"Select  c  From Course c where name like '%100 Steps'\", Course.class);\n    \n    List<Course> resultList = query.getResultList();\n    \n    logger.info(\"Select  c  From Course c where name like '%100 Steps'-> {}\",resultList);\n    //[Course[Web Services in 100 Steps], Course[Spring Boot in 100 Steps]]\n  }\n\n}\n```\n---\n\n####  Step 16 - JPA and Hibernate Annotations - @Table\n\n####  Step 17 - JPA and Hibernate Annotations - @Column\n\n/src/main/java/com/in28minutes/jpa/hibernate/demo/entity/Course.java\n\n```java\n@Entity\npublic class Course {\n\n  @Id\n  @GeneratedValue\n  private Long id;\n\n  @Column(nullable = false)\n  private String name;\n\n}\n```\n\nThis method would throw an exception because is name is not nullable.\n```\npublic void playWithEntityManager() {\n  Course course1 = new Course(\"Web Services in 100 Steps\");\n  em.persist(course1);\n\n  course1.setName(null);\n}\n```\n---\n\n####  Step 18 - JPA and Hibernate Annotations - @UpdateTimestamp and @CreationTimestamp\n####  Step 19 - JPA and Hibernate Annotations - @NamedQuery and @NamedQueries\n####  Step 20 - Native Queries - Basics\n####  Step 21 - Entities and Relationships - An overview\n####  Step 22 - Defining Entities - Student, Passport and Review\n####  Step 23 - Introduction to One to One Relationship\n\n/src/main/java/com/in28minutes/jpa/hibernate/demo/entity/Course.java\nModified Lines\n```\nimport java.time.LocalDateTime;\nimport javax.persistence.NamedQueries;\nimport javax.persistence.NamedQuery;\nimport org.hibernate.annotations.CreationTimestamp;\nimport org.hibernate.annotations.UpdateTimestamp;\n\n@NamedQueries(value = { \n    @NamedQuery(name = \"query_get_all_courses\", \n        query = \"Select  c  From Course c\"),\n    @NamedQuery(name = \"query_get_100_Step_courses\", \n    query = \"Select  c  From Course c where name like '%100 Steps'\") })\n\n@UpdateTimestamp\nprivate LocalDateTime lastUpdatedDate;\n\n@CreationTimestamp\nprivate LocalDateTime createdDate;\n```\n\n/src/main/java/com/in28minutes/jpa/hibernate/demo/entity/Passport.java New\n\n```java\npackage com.in28minutes.jpa.hibernate.demo.entity;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.Id;\n\n@Entity\npublic class Passport {\n\n  @Id\n  @GeneratedValue\n  private Long id;\n\n  @Column(nullable = false)\n  private String number;\n\n  protected Passport() {\n  }\n\n  public Passport(String number) {\n    this.number = number;\n  }\n\n  public String getNumber() {\n    return number;\n  }\n\n  public void setNumber(String number) {\n    this.number = number;\n  }\n\n  public Long getId() {\n    return id;\n  }\n\n  @Override\n  public String toString() {\n    return String.format(\"Passport[%s]\", number);\n  }\n}\n```\n---\n\n/src/main/java/com/in28minutes/jpa/hibernate/demo/entity/Review.java New\n\n```java\npackage com.in28minutes.jpa.hibernate.demo.entity;\n\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.Id;\n\n@Entity\npublic class Review {\n\n  @Id\n  @GeneratedValue\n  private Long id;\n\n  private String rating;\n\n  private String description;\n\n  protected Review() {\n  }\n\n  public Review(String rating, String description) {\n    this.rating = rating;\n    this.description = description;\n  }\n\n  public String getDescription() {\n    return description;\n  }\n\n  public void setDescription(String description) {\n    this.description = description;\n  }\n\n  public String getRating() {\n    return rating;\n  }\n\n  public void setRating(String rating) {\n    this.rating = rating;\n  }\n\n  public Long getId() {\n    return id;\n  }\n\n  @Override\n  public String toString() {\n    return String.format(\"Review[%s %s]\", rating, description);\n  }\n\n}\n```\n---\n\n/src/main/java/com/in28minutes/jpa/hibernate/demo/entity/Student.java New\n\n```java\npackage com.in28minutes.jpa.hibernate.demo.entity;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.Id;\nimport javax.persistence.OneToOne;\n\n@Entity\npublic class Student {\n\n  @Id\n  @GeneratedValue\n  private Long id;\n\n  @Column(nullable = false)\n  private String name;\n  \n  @OneToOne\n  private Passport passport;\n\n  protected Student() {\n  }\n\n  public Student(String name) {\n    this.name = name;\n  }\n\n  public String getName() {\n    return name;\n  }\n\n  public void setName(String name) {\n    this.name = name;\n  }\n\n  public Long getId() {\n    return id;\n  }\n\n  @Override\n  public String toString() {\n    return String.format(\"Student[%s]\", name);\n  }\n}\n```\n---\n\n/src/main/java/com/in28minutes/jpa/hibernate/demo/repository/CourseRepository.java \n```java\n\n  public void playWithEntityManager() {\n    Course course1 = new Course(\"Web Services in 100 Steps\");\n    em.persist(course1);\n    \n    Course course2 = findById(10001L);\n    \n    course2.setName(\"JPA in 50 Steps - Updated\");\n    \n  }\n\n```\n\n/src/main/resources/data.sql \nModified Lines\n```\ninsert into course(id, name, created_date, last_updated_date) \nvalues(10001,'JPA in 50 Steps', sysdate(), sysdate());\ninsert into course(id, name, created_date, last_updated_date) \nvalues(10002,'Spring in 50 Steps', sysdate(), sysdate());\ninsert into course(id, name, created_date, last_updated_date) \nvalues(10003,'Spring Boot in 100 Steps', sysdate(), sysdate());\ninsert into passport(id,number)\nvalues(40001,'E123456');\ninsert into passport(id,number)\nvalues(40002,'N123457');\ninsert into passport(id,number)\nvalues(40003,'L123890');\ninsert into student(id,name,passport_id)\nvalues(20001,'Ranga',40001);\ninsert into student(id,name,passport_id)\nvalues(20002,'Adam',40002);\ninsert into student(id,name,passport_id)\nvalues(20003,'Jane',40003);\ninsert into review(id,rating,description)\nvalues(50001,'5', 'Great Course');\ninsert into review(id,rating,description)\nvalues(50002,'4', 'Wonderful Course');\ninsert into review(id,rating,description)\nvalues(50003,'5', 'Awesome Course');\n```\n\n/src/test/java/com/in28minutes/jpa/hibernate/demo/repository/JPQLTest.java Modified\n#### Full File\n\n```java\n\n  @Test\n  public void jpql_typed() {\n    TypedQuery<Course> query = em.createNamedQuery(\"query_get_all_courses\", Course.class);\n\n    List<Course> resultList = query.getResultList();\n\n    logger.info(\"Select  c  From Course c -> {}\", resultList);\n  }\n\n  @Test\n  public void jpql_where() {\n    TypedQuery<Course> query = em.createNamedQuery(\"query_get_100_Step_courses\", Course.class);\n\n    List<Course> resultList = query.getResultList();\n\n    logger.info(\"Select  c  From Course c where name like '%100 Steps'-> {}\", resultList);\n    // [Course[Web Services in 100 Steps], Course[Spring Boot in 100 Steps]]\n  }\n\n```\n\n/src/test/java/com/in28minutes/jpa/hibernate/demo/repository/NativeQueriesTest.java New\n```java\n\n@RunWith(SpringRunner.class)\n@SpringBootTest(classes = DemoApplication.class)\npublic class NativeQueriesTest {\n\n  private Logger logger = LoggerFactory.getLogger(this.getClass());\n\n  @Autowired\n  EntityManager em;\n\n  @Test\n  public void native_queries_basic() {\n    Query query = em.createNativeQuery(\"SELECT * FROM COURSE\", Course.class);\n    List resultList = query.getResultList();\n    logger.info(\"SELECT * FROM COURSE  -> {}\", resultList);\n    //SELECT * FROM COURSE  -> [Course[Web Services in 100 Steps], Course[JPA in 50 Steps - Updated], Course[Spring in 50 Steps], Course[Spring Boot in 100 Steps]]\n  }\n\n  @Test\n  public void native_queries_with_parameter() {\n    Query query = em.createNativeQuery(\"SELECT * FROM COURSE where id = ?\", Course.class);\n    query.setParameter(1, 10001L);\n    List resultList = query.getResultList();\n    logger.info(\"SELECT * FROM COURSE  where id = ? -> {}\", resultList);\n    //[Course[JPA in 50 Steps - Updated]]\n  }\n\n  @Test\n  public void native_queries_with_named_parameter() {\n    Query query = em.createNativeQuery(\"SELECT * FROM COURSE where id = :id\", Course.class);\n    query.setParameter(\"id\", 10001L);\n    List resultList = query.getResultList();\n    logger.info(\"SELECT * FROM COURSE  where id = :id -> {}\", resultList);\n    //[Course[JPA in 50 Steps - Updated]]\n  }\n  \n  @Test\n  @Transactional\n  public void native_queries_to_update() {\n    Query query = em.createNativeQuery(\"Update COURSE set last_updated_date=sysdate()\");\n    int noOfRowsUpdated = query.executeUpdate();\n    logger.info(\"noOfRowsUpdated  -> {}\", noOfRowsUpdated);\n    //SELECT * FROM COURSE  -> [Course[Web Services in 100 Steps], Course[JPA in 50 Steps - Updated], Course[Spring in 50 Steps], Course[Spring Boot in 100 Steps]]\n  }\n\n\n}\n```\n---\n\n####  Step 24 - OneToOne Mapping - Insert Student with Passport\n####  Step 25 - OneToOne Mapping - Retrieving Student with Passport and Eager Fetch\n####  Step 26 - OneToOne Mapping - Lazy Fetch\n####  Step 27 - Transaction, Entity Manager and Persistence Context\n\n/src/main/java/com/in28minutes/jpa/hibernate/demo/entity/Student.java Modified\n#### Full File\n\n```java\n\n@Entity\npublic class Student {\n\n  @Id\n  @GeneratedValue\n  private Long id;\n\n  @Column(nullable = false)\n  private String name;\n  \n  @OneToOne(fetch=FetchType.LAZY)\n  private Passport passport;\n\n}\n```\n\n/src/main/java/com/in28minutes/jpa/hibernate/demo/repository/StudentRepository.java New\n\n```java\n\n@Repository\n@Transactional\npublic class StudentRepository {\n\n  private Logger logger = LoggerFactory.getLogger(this.getClass());\n  \n  @Autowired\n  EntityManager em;\n\n  public Student findById(Long id) {\n    return em.find(Student.class, id);\n  }\n\n  public Student save(Student student) {\n\n    if (student.getId() == null) {\n      em.persist(student);\n    } else {\n      em.merge(student);\n    }\n\n    return student;\n  }\n\n  public void deleteById(Long id) {\n    Student student = findById(id);\n    em.remove(student);\n  }\n\n  public void saveStudentWithPassport() {\n    Passport passport = new Passport(\"Z123456\");\n    em.persist(passport);\n\n    Student student = new Student(\"Mike\");\n\n    student.setPassport(passport);\n    em.persist(student);  \n  }\n  \n  public void someOperationToUnderstandPersistenceContext() {\n    //Database Operation 1 - Retrieve student\n    Student student = em.find(Student.class, 20001L);\n    //Persistence Context (student)\n    \n    \n    //Database Operation 2 - Retrieve passport\n    Passport passport = student.getPassport();\n    //Persistence Context (student, passport)\n\n    //Database Operation 3 - update passport\n    passport.setNumber(\"E123457\");\n    //Persistence Context (student, passport++)\n    \n    //Database Operation 4 - update student\n    student.setName(\"Ranga - updated\");\n    //Persistence Context (student++ , passport++)\n  }\n\n}\n```\n---\n/src/test/java/com/in28minutes/jpa/hibernate/demo/repository/StudentRepositoryTest.java New\n\n```java\npackage com.in28minutes.jpa.hibernate.demo.repository;\n\nimport javax.persistence.EntityManager;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.test.context.SpringBootTest;\nimport org.springframework.test.context.junit4.SpringRunner;\nimport org.springframework.transaction.annotation.Transactional;\n\nimport com.in28minutes.jpa.hibernate.demo.DemoApplication;\nimport com.in28minutes.jpa.hibernate.demo.entity.Student;\n\n@RunWith(SpringRunner.class)\n@SpringBootTest(classes = DemoApplication.class)\npublic class StudentRepositoryTest {\n\n  private Logger logger = LoggerFactory.getLogger(this.getClass());\n\n  @Autowired\n  StudentRepository repository;\n  \n  @Autowired\n  EntityManager em;\n\n  //Session & Session Factory\n\n  \n  //EntityManager & Persistence Context\n  //Transaction\n  \n  @Test\n  public void someTest() {\n    repository.someOperationToUnderstandPersistenceContext();\n  }\n\n\n  @Test\n  @Transactional\n  public void retrieveStudentAndPassportDetails() {\n    Student student = em.find(Student.class, 20001L);\n    logger.info(\"student -> {}\", student);\n    logger.info(\"passport -> {}\",student.getPassport());\n  }\n}\n```\n---\n####  TODO CONFUSION Step 27 - Transaction, Entity Manager and Persistence Context\n\n/src/test/java/com/in28minutes/jpa/hibernate/demo/repository/StudentRepositoryTest.java \n\n```java\n  \n  @Test\n  @Transactional\n  public void someTest() {\n    //Database Operation 1 - Retrieve student\n    //Database Operation 2 - Retrieve passport\n    //Database Operation 3 - update passport\n  }\n\n```\n\n####  Step 28 - OneToOne Mapping - Bidirectional Relationship - Part 1\n\n####  Step 29 - OneToOne Mapping - Bidirectional Relationship - Part 2\n\n/src/main/java/com/in28minutes/jpa/hibernate/demo/entity/Passport.java Modified\nModified Lines\n```\nimport javax.persistence.FetchType;\nimport javax.persistence.OneToOne;\n  \n@OneToOne(fetch=FetchType.LAZY, mappedBy=\"passport\")\nprivate Student student;\n\n```\n/src/main/java/com/in28minutes/jpa/hibernate/demo/repository/StudentRepository.java Modified\n```java\n  \n  public void someOperationToUnderstandPersistenceContext() {\n    //Database Operation 1 - Retrieve student\n    Student student = em.find(Student.class, 20001L);\n    //Persistence Context (student)\n    \n    \n    //Database Operation 2 - Retrieve passport\n    Passport passport = student.getPassport();\n    //Persistence Context (student, passport)\n\n    //Database Operation 3 - update passport\n    passport.setNumber(\"E123457\");\n    //Persistence Context (student, passport++)\n    \n    //Database Operation 4 - update student\n    student.setName(\"Ranga - updated\");\n    //Persistence Context (student++ , passport++)\n  }\n\n```\n\n/src/test/java/com/in28minutes/jpa/hibernate/demo/repository/StudentRepositoryTest.java \n\n```java\n\n  @Test\n  public void someTest() {\n    repository.someOperationToUnderstandPersistenceContext();\n  }\n  \n  @Test\n  @Transactional\n  public void retrievePassportAndAssociatedStudent() {\n    Passport passport = em.find(Passport.class, 40001L);\n    logger.info(\"passport -> {}\", passport);\n    logger.info(\"student -> {}\", passport.getStudent());\n  }\n```\n\n####  Step 30 - ManyToOne Mapping - Designing the database\n####  Step 30 - 02 - ManyToOne Mapping - Implementing the Mapping *****\n####  Step 31 - ManyToOne Mapping - Retrieving and inserting Reviews for Course\n\n/src/main/java/com/in28minutes/jpa/hibernate/demo/entity/Course.java Modified\n```java\n\n  @OneToMany(mappedBy=\"course\")\n  private List<Review> reviews = new ArrayList<>();\n  \n```\n/src/main/java/com/in28minutes/jpa/hibernate/demo/repository/CourseRepository.java \n\n#### Full File\n\n```java\n\n  public void addReviewsForCourse() {\n    //get the course 10003\n    Course course = findById(10003L);\n    logger.info(\"course.getReviews() -> {}\", course.getReviews());\n    \n    //add 2 reviews to it\n    Review review1 = new Review(\"5\", \"Great Hands-on Stuff.\");  \n    Review review2 = new Review(\"5\", \"Hatsoff.\");\n    \n    //setting the relationship\n    course.addReview(review1);\n    review1.setCourse(course);\n    \n    course.addReview(review2);\n    review2.setCourse(course);\n    \n    //save it to the database\n    em.persist(review1);\n    em.persist(review2);\n  }\n```\n\n/src/main/resources/data.sql \nModified Lines\n```\ninsert into review(id,rating,description,course_id)\nvalues(50001,'5', 'Great Course',10001);\ninsert into review(id,rating,description,course_id)\nvalues(50002,'4', 'Wonderful Course',10001);\ninsert into review(id,rating,description,course_id)\nvalues(50003,'5', 'Awesome Course',10003);\n```\n\n####  Step 32 - ManyToOne Mapping - Generalizing Insert Reviews\n\n/src/main/java/com/in28minutes/jpa/hibernate/demo/DemoApplication.java Modified\nModified Lines\n```\n    List<Review> reviews = new ArrayList<>();\n    reviews.add(new Review(\"5\", \"Great Hands-on Stuff.\"));  \n    reviews.add(new Review(\"5\", \"Hatsoff.\"));\n    courseRepository.addReviewsForCourse(10003L, reviews );   \n```\n\n/src/main/java/com/in28minutes/jpa/hibernate/demo/repository/CourseRepository.java Modified\n\n```java\n\n  public void addHardcodedReviewsForCourse() {\n    //get the course 10003\n    Course course = findById(10003L);\n    logger.info(\"course.getReviews() -> {}\", course.getReviews());\n    \n    //add 2 reviews to it\n    Review review1 = new Review(\"5\", \"Great Hands-on Stuff.\");  \n    Review review2 = new Review(\"5\", \"Hatsoff.\");\n    \n    //setting the relationship\n    course.addReview(review1);\n    review1.setCourse(course);\n    \n    course.addReview(review2);\n    review2.setCourse(course);\n    \n    //save it to the database\n    em.persist(review1);\n    em.persist(review2);\n  }\n  \n  public void addReviewsForCourse(Long courseId, List<Review> reviews) {    \n    Course course = findById(courseId);\n    logger.info(\"course.getReviews() -> {}\", course.getReviews());\n    for(Review review:reviews)\n    {     \n      //setting the relationship\n      course.addReview(review);\n      review.setCourse(course);\n      em.persist(review);\n    }\n  }\n```\n\n####  Step 33 - ManyToOne Mapping - Wrapping up\n\n/src/test/java/com/in28minutes/jpa/hibernate/demo/repository/CourseRepositoryTest.java Modified\n```java\n  \n  @Test\n  @Transactional\n  public void retrieveReviewsForCourse() {\n    Course course = repository.findById(10001L);\n    logger.info(\"{}\",course.getReviews());\n  }\n\n  @Test\n  @Transactional\n  public void retrieveCourseForReview() {\n    Review review = em.find(Review.class, 50001L);\n    logger.info(\"{}\",review.getCourse());\n  }\n\n```\n####  Step 34 - ManyToMany Mapping - Table Design\n####  Step 35 - ManyToMany Mapping - Adding Annotations on Entities\n\n\n/src/main/java/com/in28minutes/jpa/hibernate/demo/entity/Course.java\n\n```java  \n  @ManyToMany\n  private List<Student> students = new ArrayList<>();\n```\n\n/src/main/java/com/in28minutes/jpa/hibernate/demo/entity/Student.java\n\n```java\n  \n  @ManyToMany\n  private List<Course> courses = new ArrayList<>();\n```\n\n####  Step 36 - ManyToMany Mapping - Fixing two join tables problem\n\n\n/src/main/java/com/in28minutes/jpa/hibernate/demo/entity/Course.java Modified\n\n```java\n  \n  @ManyToMany(mappedBy=\"courses\")\n  private List<Student> students = new ArrayList<>();\n```\n####  Step 37 - ManyToMany Mapping - Customizing the Join Table\n\n/src/main/java/com/in28minutes/jpa/hibernate/demo/entity/Student.java Modified\n```java\n\n  @ManyToMany\n  @JoinTable(name = \"STUDENT_COURSE\", \n  joinColumns = @JoinColumn(name = \"STUDENT_ID\"), \n  inverseJoinColumns = @JoinColumn(name = \"COURSE_ID\"))\n  private List<Course> courses = new ArrayList<>();\n\n```\n\n####  Step 38 - ManyToMany Mapping - Insert Data and Write Join Query\n####  Step 39 - ManyToMany Mapping - Retrieve Data using JPA Relationships\n\n\n/src/main/resources/data.sql \nModified Lines\n```\ninsert into student_course(student_id,course_id)\nvalues(20001,10001);\ninsert into student_course(student_id,course_id)\nvalues(20002,10001);\ninsert into student_course(student_id,course_id)\nvalues(20003,10001);\ninsert into student_course(student_id,course_id)\nvalues(20001,10003);\n```\n/src/test/java/com/in28minutes/jpa/hibernate/demo/repository/StudentRepositoryTest.java Modified\n```java  \n@Test\n@Transactional\npublic void retrieveStudentAndCourses() {\n  Student student = em.find(Student.class, 20001L);\n  \n  logger.info(\"student -> {}\", student);\n  logger.info(\"courses -> {}\", student.getCourses());\n}\n```\n\n####  Step 40 - ManyToMany Mapping - Insert Student and Course\n####  Step 41 - Relationships between JPA Entities - A summary\n\n/src/main/java/com/in28minutes/jpa/hibernate/demo/DemoApplication.java Modified\n```\n\n    studentRepository.insertStudentAndCourse(new Student(\"Jack\"), \n        new Course(\"Microservices in 100 Steps\"));\n```\n\n/src/main/java/com/in28minutes/jpa/hibernate/demo/repository/StudentRepository.java Modified\n\n```java\n  \n  public void insertHardcodedStudentAndCourse(){\n    Student student = new Student(\"Jack\");\n    Course course = new Course(\"Microservices in 100 Steps\");\n    em.persist(student);\n    em.persist(course);\n    \n    student.addCourse(course);\n    course.addStudent(student);\n    em.persist(student);\n  }\n\n  public void insertStudentAndCourse(Student student, Course course){\n    //Student student = new Student(\"Jack\");\n    //Course course = new Course(\"Microservices in 100 Steps\");\n    student.addCourse(course);\n    course.addStudent(student);\n\n    em.persist(student);\n    em.persist(course);\n  }\n\n```\n\n####  Step 42 - Introduction to Inheritance Hierarchies and Mappings\n####  Step 43 - JPA Inheritance Hierarchies and Mappings - Setting up entities\n####  Step 44 - JPA Inheritance Hierarchies and Mappings - Setting up a Repository\n\n\n/src/main/java/com/in28minutes/jpa/hibernate/demo/DemoApplication.java\nModified Lines\n```\n\n    employeeRepository.insert(new PartTimeEmployee(\"Jill\", new BigDecimal(\"50\")));\n    employeeRepository.insert(new FullTimeEmployee(\"Jack\", new BigDecimal(\"10000\")));\n    logger.info(\"All Employees -> {}\", employeeRepository.retrieveAllEmployees());\n```\n/src/main/java/com/in28minutes/jpa/hibernate/demo/entity/Employee.java New\n\n```java\npackage com.in28minutes.jpa.hibernate.demo.entity;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.Id;\n\n@Entity\npublic abstract class Employee {\n\n  @Id\n  @GeneratedValue\n  private Long id;\n\n  @Column(nullable = false)\n  private String name;\n\n  protected Employee() {\n  }\n\n  public Employee(String name) {\n    this.name = name;\n  }\n\n  public String getName() {\n    return name;\n  }\n\n  public void setName(String name) {\n    this.name = name;\n  }\n\n  public Long getId() {\n    return id;\n  }\n\n  @Override\n  public String toString() {\n    return String.format(\"Employee[%s]\", name);\n  }\n}\n```\n---\n\n/src/main/java/com/in28minutes/jpa/hibernate/demo/entity/FullTimeEmployee.java New\n\n```java\npackage com.in28minutes.jpa.hibernate.demo.entity;\n\nimport java.math.BigDecimal;\n\nimport javax.persistence.Entity;\n\n@Entity\npublic class FullTimeEmployee extends Employee {\n  protected FullTimeEmployee() {\n  }\n\n  public FullTimeEmployee(String name, BigDecimal salary) {\n    super(name);\n    this.salary = salary;\n  }\n\n  private BigDecimal salary;\n\n}\n```\n---\n\n/src/main/java/com/in28minutes/jpa/hibernate/demo/entity/PartTimeEmployee.java New\n\n```java\npackage com.in28minutes.jpa.hibernate.demo.entity;\n\nimport java.math.BigDecimal;\n\nimport javax.persistence.Entity;\n\n@Entity\npublic class PartTimeEmployee extends Employee {\n\n  protected PartTimeEmployee() {\n  }\n\n  public PartTimeEmployee(String name, BigDecimal hourlyWage) {\n    super(name);\n    this.hourlyWage = hourlyWage;\n  }\n\n  private BigDecimal hourlyWage;\n\n}\n```\n---\n\n/src/main/java/com/in28minutes/jpa/hibernate/demo/repository/EmployeeRepository.java New\n\n```java\npackage com.in28minutes.jpa.hibernate.demo.repository;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Repository;\nimport org.springframework.transaction.annotation.Transactional;\n\nimport com.in28minutes.jpa.hibernate.demo.entity.Employee;\n\n@Repository\n@Transactional\npublic class EmployeeRepository {\n\n  private Logger logger = LoggerFactory.getLogger(this.getClass());\n\n  @Autowired\n  EntityManager em;\n\n  public void insert(Employee employee) {\n    em.persist(employee);\n  }\n\n  public List<Employee> retrieveAllEmployees() {\n    return em.createQuery(\"select e from Employee e\", Employee.class).getResultList();\n  }\n}\n```\n---\n\n####  Step 45 - JPA Inheritance Hierarchies and Mappings - Single Table\n\n/src/main/java/com/in28minutes/jpa/hibernate/demo/entity/Employee.java Modified\n```java\n\n@Entity\n@Inheritance(strategy=InheritanceType.SINGLE_TABLE)\n@DiscriminatorColumn(name=\"EmployeeType\")\npublic abstract class Employee {\n```\n\n####  Step 46 - JPA Inheritance Hierarchies and Mappings - Table Per Class\n\n/src/main/java/com/in28minutes/jpa/hibernate/demo/entity/Employee.java\n\n```java\n@Entity\n@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)\npublic abstract class Employee {\n\n```\n\n####  Step 47 - JPA Inheritance Hierarchies and Mappings - Joined\n\n/src/main/java/com/in28minutes/jpa/hibernate/demo/entity/Employee.java\n\n```java\n//@Entity\n@Inheritance(strategy=InheritanceType.JOINED)\npublic abstract class Employee {\n```\n- Step 48 - JPA Inheritance Hierarchies and Mappings - Mapped Super Class\n- Step 49 - JPA Inheritance Hierarchies and Mappings - How to Choose?\n\n\n/src/main/java/com/in28minutes/jpa/hibernate/demo/DemoApplication.java Modified\nModified Lines\n```\n    logger.info(\"Full Time Employees -> {}\", \n        employeeRepository.retrieveAllFullTimeEmployees());\n    \n    logger.info(\"Part Time Employees -> {}\", \n        employeeRepository.retrieveAllPartTimeEmployees());\n```\n/src/main/java/com/in28minutes/jpa/hibernate/demo/entity/Employee.java Modified\n\n```java\n@MappedSuperclass\n//@Entity\n//@Inheritance(strategy=InheritanceType.JOINED)\npublic abstract class Employee {\n\n```\n\n/src/main/java/com/in28minutes/jpa/hibernate/demo/repository/EmployeeRepository.java Modified\n\n```java\n\n  public List<PartTimeEmployee> retrieveAllPartTimeEmployees() {\n    return em.createQuery(\"select e from PartTimeEmployee e\", PartTimeEmployee.class).getResultList();\n  }\n\n  public List<FullTimeEmployee> retrieveAllFullTimeEmployees() {\n    return em.createQuery(\"select e from FullTimeEmployee e\", FullTimeEmployee.class).getResultList();\n  }\n\n```\n####  Step 50 - JPQL - Courses without Students\n####  Step 51 - JPQL - Courses with atleast 2 Students and order by\n\n/src/test/java/com/in28minutes/jpa/hibernate/demo/repository/JPQLTest.java Modified\n```java\n\n  @Test\n  public void jpql_courses_without_students() {\n    TypedQuery<Course> query = em.createQuery(\"Select c from Course c where c.students is empty\", Course.class);\n    List<Course> resultList = query.getResultList();\n    logger.info(\"Results -> {}\", resultList);\n    // [Course[Spring in 50 Steps]]\n  }\n\n  \n  @Test\n  public void jpql_courses_with_atleast_2_students() {\n    TypedQuery<Course> query = em.createQuery(\"Select c from Course c where size(c.students) >= 2\", Course.class);\n    List<Course> resultList = query.getResultList();\n    logger.info(\"Results -> {}\", resultList);\n    //[Course[JPA in 50 Steps]]\n  }\n\n  @Test\n  public void jpql_courses_ordered_by_students() {\n    TypedQuery<Course> query = em.createQuery(\"Select c from Course c order by size(c.students) desc\", Course.class);\n    List<Course> resultList = query.getResultList();\n    logger.info(\"Results -> {}\", resultList);\n  }\n\n```\n\n####  Step 52 - JPQL - Courses like 100 Steps\n####  Step 53 - JPQL - Using Joins\n####  Step 54 - Criteria Query - Retrieving all courses\n####  Step 55 - Criteria Query - Courses like 100 Steps\n####  Step 56 - Criteria Query - Courses without Students\n####  Step 57 - Criteria Query - Using Joins\n\n/src/test/java/com/in28minutes/jpa/hibernate/demo/repository/CriteriaQueryTest.java New\n\n```java\npackage com.in28minutes.jpa.hibernate.demo.repository;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.TypedQuery;\nimport javax.persistence.criteria.CriteriaBuilder;\nimport javax.persistence.criteria.CriteriaQuery;\nimport javax.persistence.criteria.Join;\nimport javax.persistence.criteria.JoinType;\nimport javax.persistence.criteria.Predicate;\nimport javax.persistence.criteria.Root;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.test.context.SpringBootTest;\nimport org.springframework.test.context.junit4.SpringRunner;\n\nimport com.in28minutes.jpa.hibernate.demo.DemoApplication;\nimport com.in28minutes.jpa.hibernate.demo.entity.Course;\n\n@RunWith(SpringRunner.class)\n@SpringBootTest(classes = DemoApplication.class)\npublic class CriteriaQueryTest {\n\n  private Logger logger = LoggerFactory.getLogger(this.getClass());\n\n  @Autowired\n  EntityManager em;\n\n  @Test\n  public void all_courses() {\n    // \"Select c From Course c\"\n\n    // 1. Use Criteria Builder to create a Criteria Query returning the\n    // expected result object\n    CriteriaBuilder cb = em.getCriteriaBuilder();\n    CriteriaQuery<Course> cq = cb.createQuery(Course.class);\n\n    // 2. Define roots for tables which are involved in the query\n    Root<Course> courseRoot = cq.from(Course.class);\n\n    // 3. Define Predicates etc using Criteria Builder\n\n    // 4. Add Predicates etc to the Criteria Query\n\n    // 5. Build the TypedQuery using the entity manager and criteria query\n    TypedQuery<Course> query = em.createQuery(cq.select(courseRoot));\n\n    List<Course> resultList = query.getResultList();\n\n    logger.info(\"Typed Query -> {}\", resultList);\n    // [Course[JPA in 50 Steps], Course[Spring in 50 Steps], Course[Spring\n    // Boot in 100 Steps]]\n  }\n\n  @Test\n  public void all_courses_having_100Steps() {\n    // \"Select c From Course c where name like '%100 Steps' \"\n\n    // 1. Use Criteria Builder to create a Criteria Query returning the\n    // expected result object\n    CriteriaBuilder cb = em.getCriteriaBuilder();\n    CriteriaQuery<Course> cq = cb.createQuery(Course.class);\n\n    // 2. Define roots for tables which are involved in the query\n    Root<Course> courseRoot = cq.from(Course.class);\n\n    // 3. Define Predicates etc using Criteria Builder\n    Predicate like100Steps = cb.like(courseRoot.get(\"name\"), \"%100 Steps\");\n\n    // 4. Add Predicates etc to the Criteria Query\n    cq.where(like100Steps);\n\n    // 5. Build the TypedQuery using the entity manager and criteria query\n    TypedQuery<Course> query = em.createQuery(cq.select(courseRoot));\n\n    List<Course> resultList = query.getResultList();\n\n    logger.info(\"Typed Query -> {}\", resultList);\n    // [Course[Spring Boot in 100 Steps]]\n  }\n\n  @Test\n  public void all_courses_without_students() {\n    // \"Select c From Course c where c.students is empty\"\n\n    // 1. Use Criteria Builder to create a Criteria Query returning the\n    // expected result object\n    CriteriaBuilder cb = em.getCriteriaBuilder();\n    CriteriaQuery<Course> cq = cb.createQuery(Course.class);\n\n    // 2. Define roots for tables which are involved in the query\n    Root<Course> courseRoot = cq.from(Course.class);\n\n    // 3. Define Predicates etc using Criteria Builder\n    Predicate studentsIsEmpty = cb.isEmpty(courseRoot.get(\"students\"));\n\n    // 4. Add Predicates etc to the Criteria Query\n    cq.where(studentsIsEmpty);\n\n    // 5. Build the TypedQuery using the entity manager and criteria query\n    TypedQuery<Course> query = em.createQuery(cq.select(courseRoot));\n\n    List<Course> resultList = query.getResultList();\n\n    logger.info(\"Typed Query -> {}\", resultList);\n    // [Course[Spring in 50 Steps]]\n  }\n\n  @Test\n  public void join() {\n    // \"Select c From Course c join c.students s\"\n\n    // 1. Use Criteria Builder to create a Criteria Query returning the\n    // expected result object\n    CriteriaBuilder cb = em.getCriteriaBuilder();\n    CriteriaQuery<Course> cq = cb.createQuery(Course.class);\n\n    // 2. Define roots for tables which are involved in the query\n    Root<Course> courseRoot = cq.from(Course.class);\n\n    // 3. Define Predicates etc using Criteria Builder\n    Join<Object, Object> join = courseRoot.join(\"students\");\n\n    // 4. Add Predicates etc to the Criteria Query\n\n    // 5. Build the TypedQuery using the entity manager and criteria query\n    TypedQuery<Course> query = em.createQuery(cq.select(courseRoot));\n\n    List<Course> resultList = query.getResultList();\n\n    logger.info(\"Typed Query -> {}\", resultList);\n    // [Course[JPA in 50 Steps], Course[JPA in 50 Steps], Course[JPA in 50\n    // Steps], Course[Spring Boot in 100 Steps]]\n  }\n\n  @Test\n  public void left_join() {\n    // \"Select c From Course c left join c.students s\"\n\n    // 1. Use Criteria Builder to create a Criteria Query returning the\n    // expected result object\n    CriteriaBuilder cb = em.getCriteriaBuilder();\n    CriteriaQuery<Course> cq = cb.createQuery(Course.class);\n\n    // 2. Define roots for tables which are involved in the query\n    Root<Course> courseRoot = cq.from(Course.class);\n\n    // 3. Define Predicates etc using Criteria Builder\n    Join<Object, Object> join = courseRoot.join(\"students\", JoinType.LEFT);\n\n    // 4. Add Predicates etc to the Criteria Query\n\n    // 5. Build the TypedQuery using the entity manager and criteria query\n    TypedQuery<Course> query = em.createQuery(cq.select(courseRoot));\n\n    List<Course> resultList = query.getResultList();\n\n    logger.info(\"Typed Query -> {}\", resultList);\n    // [Course[JPA in 50 Steps], Course[JPA in 50 Steps], Course[JPA in 50\n    // Steps], Course[Spring in 50 Steps], Course[Spring Boot in 100 Steps]]\n  }\n\n}\n```\n---\n\n/src/test/java/com/in28minutes/jpa/hibernate/demo/repository/JPQLTest.java Modified\n```java\n  //like\n  //BETWEEN 100 and 1000\n  //IS NULL\n  //upper, lower, trim, length\n  \n  //JOIN => Select c, s from Course c JOIN c.students s\n  //LEFT JOIN => Select c, s from Course c LEFT JOIN c.students s\n  //CROSS JOIN => Select c, s from Course c, Student s\n  //3 and 4 =>3 * 4 = 12 Rows\n  @Test\n  public void join(){\n    Query query = em.createQuery(\"Select c, s from Course c JOIN c.students s\");\n    List<Object[]> resultList = query.getResultList();\n    logger.info(\"Results Size -> {}\", resultList.size());\n    for(Object[] result:resultList){\n      logger.info(\"Course{} Student{}\", result[0], result[1]);\n    }\n  }\n\n  @Test\n  public void left_join(){\n    Query query = em.createQuery(\"Select c, s from Course c LEFT JOIN c.students s\");\n    List<Object[]> resultList = query.getResultList();\n    logger.info(\"Results Size -> {}\", resultList.size());\n    for(Object[] result:resultList){\n      logger.info(\"Course{} Student{}\", result[0], result[1]);\n    }\n  }\n\n  @Test\n  public void cross_join(){\n    Query query = em.createQuery(\"Select c, s from Course c, Student s\");\n    List<Object[]> resultList = query.getResultList();\n    logger.info(\"Results Size -> {}\", resultList.size());\n    for(Object[] result:resultList){\n      logger.info(\"Course{} Student{}\", result[0], result[1]);\n    }\n  }\n\n```\n####  Step 58 - Introduction to Transaction Management\n####  Step 59 - Transaction Management - ACID Properties\n####  Step 60 - Understanding Dirty, Phanthom and Non Repeatable Reads\n####  Step 61 - Understand 4 Isolation Levels\n####  Step 62 - Choosing between Isolation Levels\n####  Step 63 - Implementing Transaction Management - 3 Things to Decide\n####  Step 64 - Introduction to Spring Data JPA\n####  Step 65 - Testing the Spring Data JPA Repository with findById.\n####  Step 66 - Spring Data JPA Repository - CRUD Methods\n####  Step 67 - Sorting using Spring Data JPA Repository\n####  Step 68 - Pagination using Spring Data JPA Repository \n\n/src/main/java/com/in28minutes/jpa/hibernate/demo/repository/CourseSpringDataRepository.java New\n\n```java\npackage com.in28minutes.jpa.hibernate.demo.repository;\n\nimport org.springframework.data.jpa.repository.JpaRepository;\n\nimport com.in28minutes.jpa.hibernate.demo.entity.Course;\n\npublic interface CourseSpringDataRepository extends JpaRepository<Course, Long> {\n\n}\n```\n---\n\n/src/main/resources/application.properties \nModified Lines\n```\nspring.jpa.properties.hibernate.connection.isolation=2\n# Performance\nspring.jpa.properties.hibernate.jdbc.batch_size=10\n```\n/src/main/resources/data.sql \nModified Lines\n```\nvalues(10004,'Dummy1', sysdate(), sysdate());\nvalues(10005,'Dummy2', sysdate(), sysdate());\nvalues(10006,'Dummy3', sysdate(), sysdate());\nvalues(10007,'Dummy4', sysdate(), sysdate());\nvalues(10008,'Dummy5', sysdate(), sysdate());\n```\n\n/src/test/java/com/in28minutes/jpa/hibernate/demo/repository/CourseRepositoryTest.java \n\n```java\n\n  @Test\n  @Transactional\n  @DirtiesContext\n  public void performance() {\n    //for (int i = 0; i < 20; i++)\n      //em.persist(new Course(\"Something\" + i));\n    //em.flush();\n    \n    //EntityGraph graph = em.getEntityGraph(\"graph.CourseAndStudents\");\n    \n    EntityGraph<Course> graph = em.createEntityGraph(Course.class);\n      Subgraph<List<Student>> bookSubGraph = graph.addSubgraph(\"students\");\n      \n      List<Course> courses = em.createQuery(\"Select c from Course c\", Course.class)\n          .setHint(\"javax.persistence.loadgraph\", graph)\n          .getResultList();\n      for (Course course : courses) {\n        System.out.println(course + \" \" + course.getStudents());\n      }\n  }\n\n  @Test\n  @Transactional\n  @DirtiesContext\n  public void performance_without_hint() {      \n      List<Course> courses = em.createQuery(\"Select c from Course c\", Course.class)\n          //.setHint(\"javax.persistence.loadgraph\", graph)\n          .getResultList();\n      for (Course course : courses) {\n        System.out.println(course + \" \" + course.getStudents());\n      }\n  }\n\n```\n\n/src/test/java/com/in28minutes/jpa/hibernate/demo/repository/CourseSpringDataRepositoryTest.java New\n\n```java\npackage com.in28minutes.jpa.hibernate.demo.repository;\n\nimport static org.junit.Assert.assertFalse;\nimport static org.junit.Assert.assertTrue;\n\nimport java.util.Optional;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.test.context.SpringBootTest;\nimport org.springframework.data.domain.Page;\nimport org.springframework.data.domain.PageRequest;\nimport org.springframework.data.domain.Sort;\nimport org.springframework.test.context.junit4.SpringRunner;\n\nimport com.in28minutes.jpa.hibernate.demo.DemoApplication;\nimport com.in28minutes.jpa.hibernate.demo.entity.Course;\n\n@RunWith(SpringRunner.class)\n@SpringBootTest(classes = DemoApplication.class)\npublic class CourseSpringDataRepositoryTest {\n\n  private Logger logger = LoggerFactory.getLogger(this.getClass());\n\n  @Autowired\n  CourseSpringDataRepository repository;\n\n  @Test\n  public void findById_CoursePresent() {\n    Optional<Course> courseOptional = repository.findById(10001L);\n    assertTrue(courseOptional.isPresent());\n  }\n\n  @Test\n  public void findById_CourseNotPresent() {\n    Optional<Course> courseOptional = repository.findById(20001L);\n    assertFalse(courseOptional.isPresent());\n  }\n\n  @Test\n  public void playingAroundWithSpringDataRepository() {\n    //Course course = new Course(\"Microservices in 100 Steps\");\n    //repository.save(course);\n\n    //course.setName(\"Microservices in 100 Steps - Updated\");\n    //repository.save(course);\n    logger.info(\"Courses -> {} \", repository.findAll());\n    logger.info(\"Count -> {} \", repository.count());\n  }\n\n  @Test\n  public void sort() {\n    Sort sort = new Sort(Sort.Direction.ASC, \"name\");\n    logger.info(\"Sorted Courses -> {} \", repository.findAll(sort));\n    //Courses -> [Course[JPA in 50 Steps], Course[Spring in 50 Steps], Course[Spring Boot in 100 Steps]] \n  }\n\n  @Test\n  public void pagination() {\n    PageRequest pageRequest = PageRequest.of(0, 3);\n    \n    Page<Course> firstPage = repository.findAll(pageRequest);\n    logger.info(\"First Page -> {} \", firstPage);\n  }\n\n}\n```\n---\n\n####  Step 69 - Custom Queries using Spring Data JPA Repository\n####  Step 70 - Spring Data REST\n\n\n### /pom.xml \nModified Lines\n```\n<groupId>org.springframework.boot</groupId>\n<artifactId>spring-boot-starter-data-rest</artifactId>\n```\n/src/main/java/com/in28minutes/jpa/hibernate/demo/entity/Course.java Modified\n```java\n  \n  @ManyToMany(mappedBy=\"courses\")\n  @JsonIgnore\n  private List<Student> students = new ArrayList<>();\n  \n```\n\n/src/main/java/com/in28minutes/jpa/hibernate/demo/repository/CourseSpringDataRepository.java Modified\n#### Full File\n\n```java\n\n@RepositoryRestResource(path=\"courses\")\npublic interface CourseSpringDataRepository extends JpaRepository<Course, Long> {\n  List<Course> findByNameAndId(String name, Long id);\n\n  List<Course> findByName(String name);\n\n  List<Course> countByName(String name);\n\n  List<Course> findByNameOrderByIdDesc(String name);\n\n  List<Course> deleteByName(String name);\n\n  @Query(\"Select  c  From Course c where name like '%100 Steps'\")\n  List<Course> courseWith100StepsInName();\n\n  @Query(value = \"Select  *  From Course c where name like '%100 Steps'\", nativeQuery = true)\n  List<Course> courseWith100StepsInNameUsingNativeQuery();\n\n  @Query(name = \"query_get_100_Step_courses\")\n  List<Course> courseWith100StepsInNameUsingNamedQuery();\n}\n```\n\n/src/test/java/com/in28minutes/jpa/hibernate/demo/repository/CourseSpringDataRepositoryTest.java\n```java\n\n  @Test\n  public void pagination() {\n    PageRequest pageRequest = PageRequest.of(0, 3);\n    Page<Course> firstPage = repository.findAll(pageRequest);\n    logger.info(\"First Page -> {} \", firstPage.getContent());\n    \n    Pageable secondPageable = firstPage.nextPageable();\n    Page<Course> secondPage = repository.findAll(secondPageable);\n    logger.info(\"Second Page -> {} \", secondPage.getContent());\n  }\n  \n  @Test\n  public void findUsingName() {\n    logger.info(\"FindByName -> {} \", repository.findByName(\"JPA in 50 Steps\"));\n  }\n\n  @Test\n  public void findUsingStudentsName() {\n    logger.info(\"findUsingStudentsName -> {} \", repository.findByName(\"Ranga\"));\n  }\n\n```\n\n####  Step 71 - Introduction to Caching\n####  Step 72 - Hibernate and JPA Caching - First Level Cache\n####  Step 73 - Hibernate and JPA Caching - Basics of Second Level Cache with EhCache\n####  Step 74 - Hibernate and JPA Caching - Second Level Cache Part 2\n\n\n### /pom.xml \nModified Lines\n```\n      <groupId>org.hibernate</groupId>\n      <artifactId>hibernate-ehcache</artifactId>\n```\n\n/src/main/java/com/in28minutes/jpa/hibernate/demo/entity/Course.java Modified\n\n```java\n\n@Entity\n@NamedQueries(value = { \n    @NamedQuery(name = \"query_get_all_courses\", \n        query = \"Select  c  From Course c\"),\n    @NamedQuery(name = \"query_get_100_Step_courses\", \n    query = \"Select  c  From Course c where name like '%100 Steps'\") })\n@Cacheable\npublic class Course {\n```\n\n/src/main/resources/application.properties \nModified Lines\n```\n# Second Level Cache - Ehcache\n#1. enable second level cache\nspring.jpa.properties.hibernate.cache.use_second_level_cache=true\n#2. specify the caching framework - EhCache\nspring.jpa.properties.hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory\n#3. Only cache what I tell to cache.\nspring.jpa.properties.javax.persistence.sharedCache.mode=ENABLE_SELECTIVE\nlogging.level.net.sf.ehcache=debug\n#4. What data to cache?\n```\n/src/test/java/com/in28minutes/jpa/hibernate/demo/repository/CourseRepositoryTest.java Modified\n```java\n  @Test\n  public void findById_firstLevelCacheDemo() {\n    \n    Course course = repository.findById(10001L);\n    logger.info(\"First Course Retrieved {}\", course);\n\n    Course course1 = repository.findById(10001L);\n    logger.info(\"First Course Retrieved again {}\", course1);\n\n    assertEquals(\"JPA in 50 Steps\", course.getName());\n    \n    assertEquals(\"JPA in 50 Steps\", course1.getName());\n  }\n\n```\n\n####  Step 75 - Hibernate Tips - Hibernate Soft Deletes - @SQLDelete and @Where\n\n\n/src/main/java/com/in28minutes/jpa/hibernate/demo/entity/Course.java Modified\n```java\n\n@Entity\n@NamedQueries(value = { \n    @NamedQuery(name = \"query_get_all_courses\", \n        query = \"Select  c  From Course c\"),\n    @NamedQuery(name = \"query_get_100_Step_courses\", \n    query = \"Select  c  From Course c where name like '%100 Steps'\") })\n@Cacheable\n@SQLDelete(sql=\"update course set is_deleted=true where id=?\")\n@Where(clause=\"is_deleted = false\")\npublic class Course {\n\n  //Other Fields  \n  \n  private boolean isDeleted;\n\n```\n\n/src/main/resources/data.sql \nModified Lines\n```\ninsert into course(id, name, created_date, last_updated_date,is_deleted) \nvalues(10001,'JPA in 50 Steps', sysdate(), sysdate(),false);\ninsert into course(id, name, created_date, last_updated_date,is_deleted) \nvalues(10002,'Spring in 50 Steps', sysdate(), sysdate(),false);\ninsert into course(id, name, created_date, last_updated_date,is_deleted) \nvalues(10003,'Spring Boot in 100 Steps', sysdate(), sysdate(),false);\n```\n\n####  Step 76 - Hibernate Soft Deletes - Part 2\n\n/src/main/java/com/in28minutes/jpa/hibernate/demo/entity/Course.java Modified\n\n```java\n  \n  @PreRemove\n  private void preRemove(){\n    LOGGER.info(\"Setting isDeleted to True\");\n    this.isDeleted = true;\n  }\n\n```\n####  Step 77 - JPA Entity Life Cycle Methods\n####  Step 78 - Using Embedded and Embeddable with JPA\n\n/src/main/java/com/in28minutes/jpa/hibernate/demo/entity/Address.java New\n\n```java\npackage com.in28minutes.jpa.hibernate.demo.entity;\n\nimport javax.persistence.Embeddable;\n\n@Embeddable\npublic class Address {\n  protected Address() {}\n  \n  public Address(String line1, String line2, String city) {\n    super();\n    this.line1 = line1;\n    this.line2 = line2;\n    this.city = city;\n  }\n\n  private String line1;\n  private String line2;\n  private String city;\n\n  \n}\n```\n---\n\n/src/main/java/com/in28minutes/jpa/hibernate/demo/entity/Student.java Modified\n\n```java\n\n  @Embedded\n  private Address address;\n\n  @ManyToMany\n  @JoinTable(name = \"STUDENT_COURSE\", joinColumns = @JoinColumn(name = \"STUDENT_ID\"), inverseJoinColumns = @JoinColumn(name = \"COURSE_ID\"))\n  private List<Course> courses = new ArrayList<>();\n```\n\n/src/test/java/com/in28minutes/jpa/hibernate/demo/repository/StudentRepositoryTest.java Modified\n\n```java\n\n  @Test\n  @Transactional\n  public void setAddressDetails() {\n    Student student = em.find(Student.class, 20001L);\n    student.setAddress(new Address(\"No 101\", \"Some Street\", \"Hyderabad\"));\n    em.flush();\n  }\n\n```\n\n####  Step 79 - Using Enums with JPA\n\n\n/src/main/java/com/in28minutes/jpa/hibernate/demo/entity/Review.java Modified\n\n```java\n\n  @Enumerated(EnumType.STRING)\n  private ReviewRating rating;\n\n  protected Review() {\n  }\n\n  public Review(ReviewRating rating, String description) {\n    this.rating = rating;\n    this.description = description;\n  }\n\n/src/main/java/com/in28minutes/jpa/hibernate/demo/entity/ReviewRating.java\n\n```java\npackage com.in28minutes.jpa.hibernate.demo.entity;\n\npublic enum ReviewRating {\n  ZERO, ONE, TWO, THREE, FOUR, FIVE\n}\n```\n---\n\n/src/main/java/com/in28minutes/jpa/hibernate/demo/repository/CourseRepository.java Modified\n```java\n\n  public void addHardcodedReviewsForCourse() {\n    //get the course 10003\n    Course course = findById(10003L);\n    logger.info(\"course.getReviews() -> {}\", course.getReviews());\n    \n    //add 2 reviews to it\n    Review review1 = new Review(ReviewRating.FIVE, \"Great Hands-on Stuff.\");  \n    Review review2 = new Review(ReviewRating.FIVE, \"Hatsoff.\");\n    \n    //setting the relationship\n    course.addReview(review1);\n    review1.setCourse(course);\n    \n    course.addReview(review2);\n    review2.setCourse(course);\n    \n    //save it to the database\n    em.persist(review1);\n    em.persist(review2);\n  }\n  \n```\n/src/main/resources/data.sql \nModified Lines\n```\ninsert into review(id,rating,description,course_id)\nvalues(50001,'FIVE', 'Great Course',10001);\ninsert into review(id,rating,description,course_id)\nvalues(50002,'FOUR', 'Wonderful Course',10001);\ninsert into review(id,rating,description,course_id)\nvalues(50003,'FIVE', 'Awesome Course',10003);\n```\n\n####  Step 80 - JPA Tip - Be cautious with toString method implementations\n####  Step 81 - JPA Tip - When do you use JPA?\n####  Step 82 - Performance Tuning - Measure before Tuning\n####  Step 83 - Performance Tuning - Indexes\n####  Step 84 - Performance Tuning - Use Appropriate Caching\n####  Step 85 - Performance Tuning - Eager vs Lazy Fetch\n####  Step 86 - Performance Tuning - Avoid N+1 Problems\n\n/src/main/java/com/in28minutes/jpa/hibernate/demo/entity/Course.java Modified\n```java\n\n@Entity\n@NamedQueries(value = { \n    @NamedQuery(name = \"query_get_all_courses\", \n        query = \"Select  c  From Course c\"),    \n    @NamedQuery(name = \"query_get_all_courses_join_fetch\", \n    query = \"Select  c  From Course c JOIN FETCH c.students s\"),    \n    @NamedQuery(name = \"query_get_100_Step_courses\", \n    query = \"Select  c  From Course c where name like '%100 Steps'\") })\n@Cacheable\n@SQLDelete(sql=\"update course set is_deleted=true where id=?\")\n@Where(clause=\"is_deleted = false\")\npublic class Course {\n```\n\n\n/src/test/java/com/in28minutes/jpa/hibernate/demo/repository/PerformanceTuningTest.java New\n\n```java\npackage com.in28minutes.jpa.hibernate.demo.repository;\n\nimport java.util.List;\n\nimport javax.persistence.EntityGraph;\nimport javax.persistence.EntityManager;\nimport javax.persistence.Subgraph;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.test.context.SpringBootTest;\nimport org.springframework.test.context.junit4.SpringRunner;\nimport org.springframework.transaction.annotation.Transactional;\n\nimport com.in28minutes.jpa.hibernate.demo.DemoApplication;\nimport com.in28minutes.jpa.hibernate.demo.entity.Course;\n\n@RunWith(SpringRunner.class)\n@SpringBootTest(classes = DemoApplication.class)\npublic class PerformanceTuningTest {\n\n  private Logger logger = LoggerFactory.getLogger(this.getClass());\n\n  @Autowired\n  EntityManager em;\n\n  @Test\n  @Transactional\n  public void creatingNPlusOneProblem() {\n    List<Course> courses = em\n        .createNamedQuery(\"query_get_all_courses\", Course.class)\n        .getResultList();\n    for(Course course:courses){\n      logger.info(\"Course -> {} Students -> {}\",course, course.getStudents());\n    }\n  }\n  \n  @Test\n  @Transactional\n  public void solvingNPlusOneProblem_EntityGraph() {\n\n    EntityGraph<Course> entityGraph = em.createEntityGraph(Course.class);\n    Subgraph<Object> subGraph = entityGraph.addSubgraph(\"students\");\n    \n    List<Course> courses = em\n        .createNamedQuery(\"query_get_all_courses\", Course.class)\n        .setHint(\"javax.persistence.loadgraph\", entityGraph)\n        .getResultList();\n    \n    for(Course course:courses){\n      logger.info(\"Course -> {} Students -> {}\",course, course.getStudents());\n    }\n  }\n\n  @Test\n  @Transactional\n  public void solvingNPlusOneProblem_JoinFetch() {\n    List<Course> courses = em\n        .createNamedQuery(\"query_get_all_courses_join_fetch\", Course.class)\n        .getResultList();\n    for(Course course:courses){\n      logger.info(\"Course -> {} Students -> {}\",course, course.getStudents());\n    }\n  }\n\n}\n```\n\n####  FAQ 1 - When does Hibernate send updates to the database?\n####  FAQ 2 - When do we need @Transactional in an Unit Test?\n####  FAQ 3 - Do read only methods need a transaction?\n####  FAQ 4 - Why do we use @DirtiesContext in an Unit Test?\n####  FAQ 5 - How to connect to a different database with Spring Boot?\n####  FAQ 6 - Approach to design great applications with JPA?\n####  FAQ 7 - Good Practices for developing JPA Applications\n\n\n\n### FAQ \n\n- Do Read Only methods need a transaction?\n   - Entities - User, Comment\n```\n@Transactional\nList<Comment> someReadOnlyMethod() {\n  \n  User user = em.find(User.class, 1L);\n\n  List<Comment> comments = user.getComments();//\n\n  return comments;\n}\n```\n- Why do we need @Transactional in Unit Tests some times? \n   - Unit Test -> Repository -> EntityManager\n   - Unit Test -> EntityManager\n- When does Hibernate fire queries down to database?\n```\n@Transactional\nvoid someMethodWithChange() {\n   \n    //Create Objects\n  em.persist(user1);\n  em.persist(user2);\n  \n  em.flush();\n  \n  //Change user1\n  //Change user2\n}\n//all changes are saved down to the database!\n\n```\n\n## Hibernate Mapping\n\n```\n<hibernate-mapping>\n   <class name=\"Person\" table=\"person\">\n      <id name=\"id\" type=\"int\" column=\"id\">\n         <generator class=\"native\"/>\n      </id>\n      <property name=\"firstName\" column=\"first_name\" type=\"string\"/>\n      <property name=\"lastName\" column=\"last_name\" type=\"string\"/>\n      <property name=\"role\" column=\"role \" type=\"integer\"/>\n   </class>\n</hibernate-mapping>\n```\n\n#### Entity Manager\n- detach method\n- clear method\n- flush method\n\n#### Play with Annotations\n- @Table : Indicates table name.\n- @Column : Defining Constraints on Columns.\n- @NamedQueries Indicates list of named queries.\n- @NamedQuery Indicates a Query using static name.\n- @CreationTimestamp \n- @UpdateTimestamp\n- @Transient : Column will not be persisted.\n- @PostLoad\n\n## Basics of JPQL\n- Discuss the basics here\n```\n@NamedQueries({\n    @NamedQuery(name=\"name1\",\n                query=\"Query1\"),\n    @NamedQuery(name=\"name2\",\n                query=\"Query2\"),\n})\n```\n- We can discuss the stuff needing Join after discussing relationships\n\n#### Native Queries\n- Database specific feature\n\n#### Relationships\n- Three types of relationships\n\n#### Inheritance\n- best performance - single table strategy\n- best data integrity - joined \n\n- JPQL queries with Joins\n  - basic_empty_courses\n  - basic_courses_with_min_three_students\n\n#### Criteria API\n\n```\n    // 1. Use Criteria Builder to create a Criteria Query returning the\n    // expected result object\n    // 2. Define roots for tables which are involved in the query\n    // 3. Define Predicates etc using Criteria Builder\n    // 4. Add Predicates etc to the Criteria Query\n    // 5. Build the TypedQuery using the entity manager and criteria query\n```\n\n#### Transaction Management\n- Spring vs JPA @Transactional\n- Isolation Levels\n- Transactions have importance even within read-only context - like specifying a database isolation-level. We strongly recommend that all database operations occur within the scope of some transaction.\n\n#### Advanced JPQL\n- basic_courses_order_by\n- join\n- left_outer_join\n- cross_join\n\n#### Advanced Criterial Query\n- join\n- left_outer_join\n\n#### Spring Data JPA\n- Spring Data REST\n\n#### Caching\n- First Level Cache Demo\n- Second Level Cache Demo\n\n#### Hibernate Tips\n- Implementing Soft Deletes - @Where and @SQLDelete\n- Embedded Entities\n- Using Enumerations With JPA\n- Be cautious about toString\n- Be cautious about Eager fetching on both sides of a relationship\n- When do you use JPA? \n    - SQL Database + Static Domain Model + Mostly CRUD + Mostly Simple Queries/Mappings and Updates with few Stored Procedures\n\n#### Performance Tuning\n- Zero Performance Tuning without Statistics. Check Stats in atleast one environment.\n- Do not use JPA/Hibernate for Database intensive Batch Operations - Use Stored Procedures  \n- Add the right indexes on the database - Execution Plan\n- Use Appropriate Caching\n  - Be careful about the size of First Level Cache\n- Eager vs Lazy Fetch - Use Lazy fetching mostly\n  - Remember that all mapping *ToOne (@ManyToOne and @OneToOne) are EAGER by default.\n- Avoid N+1\n  - Entity Graph & Named Entity Graphs & Dynamic Entity Graphs\n  - Join Fetch Clause\n- Use Pagination & Batch Updates\n\n```\nquery.setFirstResult(0);\nquery.setMaxResults(10);\n```\n- @Immutable - zero dirty checks!\n- Read only transactions\n\n\n\n## Complete Code Example\n\n### Hibernate/JPA in Depth\n\n### /pom.xml\n\n```xml\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n  xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n\n  <groupId>com.in28minutes.jpa</groupId>\n  <artifactId>jpa-demo</artifactId>\n  <version>0.0.1-SNAPSHOT</version>\n  <packaging>jar</packaging>\n\n  <name>jpa-demo</name>\n  <description>Demo project for Spring Boot</description>\n\n  <parent>\n    <groupId>org.springframework.boot</groupId>\n    <artifactId>spring-boot-starter-parent</artifactId>\n    <version>2.3.1.RELEASE</version>\n    <relativePath /> <!-- lookup parent from repository -->\n  </parent>\n\n  <properties>\n    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>\n    <java.version>1.8</java.version>\n<maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.springframework.boot</groupId>\n      <artifactId>spring-boot-starter-data-jpa</artifactId>\n    </dependency>\n    <dependency>\n      <groupId>org.springframework.boot</groupId>\n      <artifactId>spring-boot-starter-web</artifactId>\n    </dependency>\n\n    <dependency>\n      <groupId>com.h2database</groupId>\n      <artifactId>h2</artifactId>\n      <scope>runtime</scope>\n    </dependency>\n\n    <dependency>\n      <groupId>org.hibernate</groupId>\n      <artifactId>hibernate-jpamodelgen</artifactId>\n    </dependency>\n\n    <dependency>\n      <groupId>org.hibernate</groupId>\n      <artifactId>hibernate-ehcache</artifactId>\n    </dependency>\n\n    <dependency>\n      <groupId>org.springframework.boot</groupId>\n      <artifactId>spring-boot-starter-test</artifactId>\n      <scope>test</scope>\n    </dependency>\n  </dependencies>\n\n  <build>\n    <plugins>\n      <plugin>\n        <groupId>org.springframework.boot</groupId>\n        <artifactId>spring-boot-maven-plugin</artifactId>\n      </plugin>\n\n      <plugin>\n        <groupId>org.apache.maven.plugins</groupId>\n        <artifactId>maven-compiler-plugin</artifactId>\n        <configuration>\n          <source>1.8</source>\n          <target>1.8</target>\n          <compilerArguments>\n            <processor>org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor</processor>\n          </compilerArguments>\n        </configuration>\n      </plugin>\n\n      <plugin>\n        <groupId>org.codehaus.mojo</groupId>\n        <artifactId>build-helper-maven-plugin</artifactId>\n        <executions>\n          <execution>\n            <phase>process-sources</phase>\n            <configuration>\n              <sources>\n                <source>${project.build.directory}/generated-sources/annotations</source>\n              </sources>\n            </configuration>\n            <goals>\n              <goal>add-source</goal>\n            </goals>\n          </execution>\n        </executions>\n      </plugin>\n    </plugins>\n  </build>\n\n  <repositories>\n    <repository>\n      <id>spring-snapshots</id>\n      <name>Spring Snapshots</name>\n      <url>https://repo.spring.io/snapshot</url>\n      <snapshots>\n        <enabled>true</enabled>\n      </snapshots>\n    </repository>\n    <repository>\n      <id>spring-milestones</id>\n      <name>Spring Milestones</name>\n      <url>https://repo.spring.io/milestone</url>\n      <snapshots>\n        <enabled>false</enabled>\n      </snapshots>\n    </repository>\n  </repositories>\n\n  <pluginRepositories>\n    <pluginRepository>\n      <id>spring-snapshots</id>\n      <name>Spring Snapshots</name>\n      <url>https://repo.spring.io/snapshot</url>\n      <snapshots>\n        <enabled>true</enabled>\n      </snapshots>\n    </pluginRepository>\n    <pluginRepository>\n      <id>spring-milestones</id>\n      <name>Spring Milestones</name>\n      <url>https://repo.spring.io/milestone</url>\n      <snapshots>\n        <enabled>false</enabled>\n      </snapshots>\n    </pluginRepository>\n    <pluginRepository>\n      <id>maven-annotation</id>\n      <url>http://maven-annotation-plugin.googlecode.com/svn/trunk/mavenrepo</url>\n    </pluginRepository>\n  </pluginRepositories>\n\n\n</project>\n```\n---\n\n### /src/main/java/com/in28minutes/jpa/jpademo/controller/CourseController.java\n\n```java\npackage com.in28minutes.jpa.jpademo.controller;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.RestController;\n\nimport com.in28minutes.jpa.jpademo.relationships.entity.Course;\nimport com.in28minutes.jpa.jpademo.relationships.repository.CourseRepository;\n\n@RestController\npublic class CourseController {\n  \n  @Autowired\n  CourseRepository repository;\n  \n  @GetMapping(\"/courses/{id}\")\n  public  Course retrieveCourse(@PathVariable long id){\n    return repository.retrieveCourse(id);\n  }\n}\n```\n---\n\n### /src/main/java/com/in28minutes/jpa/jpademo/embedded/entity/Name.java\n\n```java\npackage com.in28minutes.jpa.jpademo.embedded.entity;\n\nimport javax.persistence.Embeddable;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.Id;\n\n@Entity\n//@Embeddable\npublic class Name {\n  \n  @Id\n  @GeneratedValue\n  protected Long id;\n  protected String firstName;\n  protected String middleName;\n  protected String lastName;\n}\n```\n---\n\n### /src/main/java/com/in28minutes/jpa/jpademo/embedded/entity/Person.java\n\n```java\n\npackage com.in28minutes.jpa.jpademo.embedded.entity;\n\nimport javax.persistence.Embedded;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.Id;\nimport javax.persistence.OneToOne;\n\n@Entity\npublic class Person {\n  @Id\n  @GeneratedValue\n  protected Long id;\n  \n  @OneToOne\n  //@Embedded\n  protected Name name;\n\n}\n```\n---\n\n### /src/main/java/com/in28minutes/jpa/jpademo/inheritence/entity/Employee.java\n\n```java\npackage com.in28minutes.jpa.jpademo.inheritence.entity;\n\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.Id;\nimport javax.persistence.Inheritance;\nimport javax.persistence.InheritanceType;\nimport javax.persistence.MappedSuperclass;\n\n//@MappedSuperclass\n@Entity\n@Inheritance(strategy = InheritanceType.SINGLE_TABLE)\n// @DiscriminatorColumn(name = \"disc_type\")\npublic abstract class Employee {\n\n  public Employee() {\n  }\n\n  public Employee(String name) {\n    this.name = name;\n  }\n\n  @GeneratedValue\n  @Id\n  protected Integer id;\n\n  private String name;\n\n}\n```\n---\n\n### /src/main/java/com/in28minutes/jpa/jpademo/inheritence/entity/FullTimeEmployee.java\n\n```java\npackage com.in28minutes.jpa.jpademo.inheritence.entity;\n\nimport java.math.BigDecimal;\n\nimport javax.persistence.Entity;\n\n@Entity\npublic class FullTimeEmployee extends Employee {\n  public FullTimeEmployee(){}\n  \n  public FullTimeEmployee(String name, BigDecimal salary) {\n    super(name);\n    this.salary = salary;\n  }\n\n  protected BigDecimal salary;\n}\n```\n---\n\n### /src/main/java/com/in28minutes/jpa/jpademo/inheritence/entity/PartTimeEmployee.java\n\n```java\npackage com.in28minutes.jpa.jpademo.inheritence.entity;\n\nimport java.math.BigDecimal;\n\nimport javax.persistence.Entity;\n\n@Entity\npublic class PartTimeEmployee extends Employee {\n  \n  public PartTimeEmployee(){}\n  \n  public PartTimeEmployee(String name, BigDecimal hourlyWage) {\n    super(name);\n    this.hourlyWage = hourlyWage;\n  }\n\n  protected BigDecimal hourlyWage;\n}\n```\n---\n\n### /src/main/java/com/in28minutes/jpa/jpademo/inheritence/repository/EmployeeRepository.java\n\n```java\npackage com.in28minutes.jpa.jpademo.inheritence.repository;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.transaction.Transactional;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Repository;\n\nimport com.in28minutes.jpa.jpademo.inheritence.entity.Employee;\n\n@Transactional\n@Repository\npublic class EmployeeRepository {\n  \n  @Autowired\n  EntityManager entityManager;\n  \n  public void insertEmployee(Employee employee) {\n    entityManager.persist(employee);\n  }\n  \n  public List<Employee> allEmployees() {\n    return entityManager.createQuery(\"Select e from Employee e\", Employee.class).getResultList();\n  }\n  \n  \n\n}\n```\n---\n\n### /src/main/java/com/in28minutes/jpa/jpademo/JpaDemoApplication.java\n\n```java\npackage com.in28minutes.jpa.jpademo;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.CommandLineRunner;\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\nimport com.in28minutes.jpa.jpademo.inheritence.repository.EmployeeRepository;\nimport com.in28minutes.jpa.jpademo.relationships.repository.StudentRepository;\n\n@SpringBootApplication\npublic class JpaDemoApplication implements CommandLineRunner {\n  \n  @Autowired\n  StudentRepository studentRepository;\n  \n  @Autowired \n  EmployeeRepository employeeRepository;\n\n  public static void main(String[] args) {\n    SpringApplication.run(JpaDemoApplication.class, args);\n  }\n\n  @Override\n  public void run(String... args) throws Exception {\n  }\n\n}\n```\n---\n\n### /src/main/java/com/in28minutes/jpa/jpademo/relationships/entity/Course.java\n\n```java\npackage com.in28minutes.jpa.jpademo.relationships.entity;\n\nimport java.time.LocalDate;\nimport java.time.LocalDateTime;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.Cacheable;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.Id;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.NamedAttributeNode;\nimport javax.persistence.NamedEntityGraph;\nimport javax.persistence.NamedQuery;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\nimport org.hibernate.annotations.CreationTimestamp;\nimport org.hibernate.annotations.UpdateTimestamp;\n\n@Entity\n@Table(name = \"Course\")\n@NamedQuery(query = \"select c from Course c\", name = \"QUERY_ALL_COURSES\")\n@NamedEntityGraph(name = \"graph.CourseAndStudents\", \nattributeNodes = @NamedAttributeNode(value = \"students\"/*, subgraph = \"students\"),*/)\n/*subgraphs = @NamedSubgraph(name = \"students\", attributeNodes = @NamedAttributeNode(\"passport\"))*/)\n@Cacheable\npublic class Course {\n\n  public Course() {\n  }\n\n  public Course(String name) {\n    super();\n    this.name = name;\n  }\n\n  @Id\n  @GeneratedValue\n  protected Long id;\n\n  protected String name;\n\n  // @OneToMany\n  @OneToMany(mappedBy = \"course\")\n  protected List<Review> reviews = new ArrayList<>();\n\n  @ManyToMany\n  // @JoinTable(name = \"COURSE_STUDENT\",\n  // joinColumns = @JoinColumn(name = \"COURSE_ID\"),\n  // inverseJoinColumns = @JoinColumn(name = \"STUDENT_ID\"))\n  protected List<Student> students = new ArrayList<>();\n\n  @CreationTimestamp\n  private LocalDateTime createDateTime;\n\n  private LocalDate activeFrom;\n\n  @UpdateTimestamp\n  private LocalDateTime updateDateTime;\n\n  public Long getId() {\n    return id;\n  }\n\n  public String getName() {\n    return name;\n  }\n\n  public void setName(String name) {\n    this.name = name;\n  }\n\n  public List<Review> getReviews() {\n    return reviews;\n  }\n\n  public void addReview(Review review) {\n    this.reviews.add(review);\n  }\n\n  public List<Student> getStudents() {\n    return students;\n  }\n\n  public void addStudent(Student student) {\n    this.students.add(student);\n  }\n\n  public LocalDate getActiveFrom() {\n    return activeFrom;\n  }\n\n  public void setActiveFrom(LocalDate activeFrom) {\n    this.activeFrom = activeFrom;\n  }\n\n  @Override\n  public String toString() {\n    return String.format(\"Course[%s]\", name);\n  }\n\n}\n```\n---\n\n### /src/main/java/com/in28minutes/jpa/jpademo/relationships/entity/Passport.java\n\n```java\npackage com.in28minutes.jpa.jpademo.relationships.entity;\n\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.Id;\nimport javax.persistence.OneToOne;\nimport javax.validation.constraints.NotNull;\n\nimport org.hibernate.annotations.Where;\n\n@Entity\n@Where(clause = \"1=1\")\npublic class Passport {\n\n  protected Passport() {\n  }\n\n  public Passport(String number) {\n    super();\n    this.number = number;\n  }\n\n  @Id\n  @GeneratedValue\n  protected Long id;\n\n  @NotNull\n  protected String number;\n\n  // Inverse Relationship\n  // bi-directional OneToOne relationship\n  // Column will not be created in the table\n  // Try removing mappedBy = \"passport\" => You will see a student_id column\n  // will be created in passport\n  // @OneToOne\n  @OneToOne(fetch = FetchType.LAZY, mappedBy = \"passport\")\n  protected Student student;\n\n  public Long getId() {\n    return id;\n  }\n\n  public String getNumber() {\n    return number;\n  }\n\n  public void setNumber(String number) {\n    this.number = number;\n  }\n\n  public Student getStudent() {\n    return student;\n  }\n\n  public void setStudent(Student student) {\n    this.student = student;\n  }\n}\n```\n---\n\n### /src/main/java/com/in28minutes/jpa/jpademo/relationships/entity/Review.java\n\n```java\npackage com.in28minutes.jpa.jpademo.relationships.entity;\n\nimport javax.persistence.Entity;\nimport javax.persistence.Enumerated;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.Id;\nimport javax.persistence.ManyToOne;\n\n@Entity\npublic class Review {\n  \n  private Review() {}\n\n  public Review(ReviewRating rating, String description) {\n    super();\n    this.rating = rating;\n    this.description = description;\n  }\n\n  @Id\n  @GeneratedValue\n  protected Long id;\n  \n  @Enumerated\n  protected ReviewRating rating;\n    \n  protected String description;\n\n  @ManyToOne\n  // @JoinColumn(name=\"COURSE_ID\")\n  protected Course course;\n\n  public Long getId() {\n    return id;\n  }\n\n  public ReviewRating getRating() {\n    return rating;\n  }\n\n  public void setRating(ReviewRating rating) {\n    this.rating = rating;\n  }\n\n  public String getDescription() {\n    return description;\n  }\n\n  public void setDescription(String description) {\n    this.description = description;\n  }\n\n  public Course getCourse() {\n    return course;\n  }\n\n  public void setCourse(Course course) {\n    this.course = course;\n  }\n  \n  \n}\n```\n---\n\n### /src/main/java/com/in28minutes/jpa/jpademo/relationships/entity/ReviewRating.java\n\n```java\npackage com.in28minutes.jpa.jpademo.relationships.entity;\npublic enum ReviewRating {\n  ONE,TWO,THREE,FOUR,FIVE\n}\n```\n---\n\n### /src/main/java/com/in28minutes/jpa/jpademo/relationships/entity/Student.java\n\n```java\npackage com.in28minutes.jpa.jpademo.relationships.entity;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.CollectionTable;\nimport javax.persistence.Column;\nimport javax.persistence.ElementCollection;\nimport javax.persistence.Entity;\nimport javax.persistence.EnumType;\nimport javax.persistence.Enumerated;\nimport javax.persistence.FetchType;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.Id;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.MapKeyColumn;\nimport javax.persistence.MapKeyEnumerated;\nimport javax.persistence.OneToOne;\n\nimport org.hibernate.annotations.SQLDelete;\n\n@Entity\n@SQLDelete(sql = \"UPDATE student SET state = 'DELETED' WHERE id = ?\")\npublic class Student {\n\n  private Student() {\n  }\n\n  public Student(String name, StudentType studentType) {\n    super();\n    this.name = name;\n    this.studentType = studentType;\n  }\n\n  @Id\n  @GeneratedValue\n  protected Long id;\n\n  protected String name;\n\n  @OneToOne(fetch = FetchType.LAZY)\n  protected Passport passport;\n\n  // @ManyToMany\n  @ManyToMany(mappedBy = \"students\")\n  protected List<Course> courses = new ArrayList<>();\n\n  // @Enumerated\n  @Enumerated(EnumType.STRING)\n  private StudentType studentType;\n\n  @ElementCollection\n  @CollectionTable(name = \"STUDENT_PHONE\")\n  @MapKeyEnumerated(EnumType.STRING)\n  @MapKeyColumn(name = \"PHONE_TYPE\")\n  @Column(name = \"PHONE_NUM\")\n  private Map<PhoneType, String> phoneNumbers;\n\n  enum PhoneType {\n    Home, Mobile, Work\n  }\n\n  public Long getId() {\n    return id;\n  }\n\n  public String getName() {\n    return name;\n  }\n\n  public void setName(String name) {\n    this.name = name;\n  }\n\n  public Passport getPassport() {\n    return passport;\n  }\n\n  public void setPassport(Passport passport) {\n    this.passport = passport;\n  }\n\n  public List<Course> getCourses() {\n    return courses;\n  }\n\n  public void addCourse(Course course) {\n    courses.add(course);\n  }\n\n  public StudentType getStudentType() {\n    return studentType;\n  }\n\n  public void setStudentType(StudentType studentType) {\n    this.studentType = studentType;\n  }\n\n  public Map<PhoneType, String> getPhoneNumbers() {\n    return phoneNumbers;\n  }\n\n  public void addPhoneNumber(PhoneType phoneType, String number) {\n    phoneNumbers.put(phoneType, number);\n  }\n\n  @Override\n  public String toString() {\n    return String.format(\"Student[%s]\", name);\n  }\n\n}\n```\n---\n\n### /src/main/java/com/in28minutes/jpa/jpademo/relationships/entity/StudentType.java\n\n```java\npackage com.in28minutes.jpa.jpademo.relationships.entity;\npublic enum StudentType {\n  FullTime, PartTime\n}\n```\n---\n\n### /src/main/java/com/in28minutes/jpa/jpademo/relationships/repository/CourseRepository.java\n\n```java\npackage com.in28minutes.jpa.jpademo.relationships.repository;\n\nimport java.util.List;\n\nimport javax.persistence.EntityGraph;\nimport javax.persistence.EntityManager;\nimport javax.persistence.Subgraph;\nimport javax.transaction.Transactional;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Repository;\n\nimport com.in28minutes.jpa.jpademo.relationships.entity.Course;\nimport com.in28minutes.jpa.jpademo.relationships.entity.Course_;\nimport com.in28minutes.jpa.jpademo.relationships.entity.Review;\nimport com.in28minutes.jpa.jpademo.relationships.entity.Student;\n\n@Repository\n@Transactional\npublic class CourseRepository {\n\n  @Autowired\n  EntityManager entityManager;\n\n  public void createCourse(Course course) {\n    entityManager.persist(course);\n  }\n\n  public Course retrieveCourse(Long id) {\n    return entityManager.find(Course.class, id);\n  }\n\n  public void printAllCourseAndStudents() {\n    EntityGraph graph = entityManager.getEntityGraph(\"graph.CourseAndStudents\");\n    List<Course> courses = entityManager.createQuery(\"Select c from Course c\", Course.class)\n        .setHint(\"javax.persistence.loadgraph\", graph).getResultList();\n    for (Course course : courses) {\n      System.out.println(course + \" \" + course.getStudents());\n    }\n  }\n\n  public void printAllCourseAndStudentsDynamicSubgraph() {\n    EntityGraph<Course> graph = entityManager.createEntityGraph(Course.class);\n    Subgraph<List<Student>> bookSubGraph = graph.addSubgraph(Course_.students);\n\n    List<Course> courses = entityManager.createQuery(\"Select c from Course c\", Course.class)\n        .setHint(\"javax.persistence.loadgraph\", graph).getResultList();\n\n    for (Course course : courses) {\n      System.out.println(course + \" \" + course.getStudents());\n    }\n  }\n\n  public void printAllCourseAndStudentsJoinFetch() {\n    List<Course> courses = entityManager.createQuery(\"Select c from Course c JOIN FETCH c.students s\", Course.class)\n        .getResultList();\n    for (Course course : courses) {\n      System.out.println(course + \" \" + course.getStudents());\n    }\n  }\n\n  public void updateCourse(Course course) {\n    entityManager.merge(course);\n  }\n\n  public void createCourseWithStudents(Course course, Student... students) {\n\n    for (Student student : students) {\n      course.addStudent(student);\n      student.addCourse(course);\n      if (student.getId() == null) {\n        entityManager.persist(student);\n      }\n    }\n\n    createCourse(course);\n\n  }\n\n  public void createReviewsForCourse(Course course, Review... reviews) {\n    for (Review review : reviews) {\n      course.addReview(review);\n      review.setCourse(course);\n      if (review.getId() == null) {\n        entityManager.persist(review);\n      }\n    }\n  }\n\n}\n```\n---\n\n### /src/main/java/com/in28minutes/jpa/jpademo/relationships/repository/EntityManagerRepository.java\n\n```java\npackage com.in28minutes.jpa.jpademo.relationships.repository;\n\nimport javax.persistence.EntityManager;\nimport javax.transaction.Transactional;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Repository;\n\nimport com.in28minutes.jpa.jpademo.relationships.entity.Passport;\n\n@Repository\n@Transactional\npublic class EntityManagerRepository {\n\n  @Autowired\n  EntityManager entityManager;\n\n  public void doSomething() {\n    Passport passport = new Passport(\"E123456\");\n    entityManager.persist(passport);\n    entityManager.flush();\n    passport.setNumber(\"E123457\");\n    // entityManager.clear();\n    // entityManager.detach(passport);\n    // entityManager.refresh(passport);\n    // entityManager.remove(passport);\n    // entityManager.merge(passport);\n    // Queries\n    // Entity Graphs\n  }\n}\n```\n---\n\n### /src/main/java/com/in28minutes/jpa/jpademo/relationships/repository/StudentRepository.java\n\n```java\npackage com.in28minutes.jpa.jpademo.relationships.repository;\n\nimport javax.persistence.EntityManager;\nimport javax.transaction.Transactional;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Repository;\n\nimport com.in28minutes.jpa.jpademo.relationships.entity.Course;\nimport com.in28minutes.jpa.jpademo.relationships.entity.Passport;\nimport com.in28minutes.jpa.jpademo.relationships.entity.Review;\nimport com.in28minutes.jpa.jpademo.relationships.entity.Student;\n\n@Repository\n@Transactional\npublic class StudentRepository {\n\n  @Autowired\n  EntityManager entityManager;\n\n  public void createStudentWithPassport(Student student, Passport passport) {\n    student.setPassport(passport);\n    //passport.setStudent(student);\n    entityManager.persist(passport);\n    entityManager.persist(student);\n        \n  }\n}\n```\n---\n\n### /src/main/java/com/in28minutes/jpa/jpademo/relationships/repository/TransactionManagementRepository.java\n\n```java\npackage com.in28minutes.jpa.jpademo.relationships.repository;\n\nimport javax.persistence.EntityManager;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Repository;\nimport org.springframework.transaction.annotation.Transactional;\n\nimport com.in28minutes.jpa.jpademo.relationships.entity.Passport;\n\n@Repository\n@Transactional\npublic class TransactionManagementRepository {\n\n  @Autowired\n  EntityManager entityManager;\n\n  public void doSomething() {\n    Passport passport1 = new Passport(\"E123456\");\n    entityManager.persist(passport1);\n    Passport passport2 = new Passport(null);\n    entityManager.persist(passport2);\n  }\n}\n```\n---\n\n### /src/main/resources/application.properties\n\n```properties\nspring.h2.console.enabled=true\nspring.jpa.properties.hibernate.generate_statistics=true\nlogging.level.org.hibernate.stat=debug\nspring.jpa.show-sql=true\nspring.datasource.url=jdbc:h2:mem:testdb\nspring.data.jpa.repositories.bootstrap-mode=default\nspring.jpa.properties.hibernate.format_sql=true\n#logging.level.org.hibernate.type=TRACE\nspring.jpa.properties.hibernate.cache.use_second_level_cache=true\nspring.jpa.properties.hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory\nspring.jpa.properties.javax.persistence.sharedCache.mode=ENABLE_SELECTIVE\nlogging.level.net.sf.ehcache=debug\n```\n---\n\n### /src/main/resources/data.sql\n\n```\ninsert into course(id, name)\nvalues(10101,'Caching in 100 Steps');\n```\n---\n\n### /src/test/java/com/in28minutes/jpa/jpademo/CriteriaQueryDemoApplicationTest.java\n\n```java\npackage com.in28minutes.jpa.jpademo;\n\nimport static org.junit.Assert.assertEquals;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.TypedQuery;\nimport javax.persistence.criteria.CriteriaBuilder;\nimport javax.persistence.criteria.CriteriaQuery;\nimport javax.persistence.criteria.Join;\nimport javax.persistence.criteria.JoinType;\nimport javax.persistence.criteria.Predicate;\nimport javax.persistence.criteria.Root;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.test.context.SpringBootTest;\nimport org.springframework.test.context.junit4.SpringRunner;\n\nimport com.in28minutes.jpa.jpademo.relationships.entity.Course;\nimport com.in28minutes.jpa.jpademo.relationships.entity.Course_;\nimport com.in28minutes.jpa.jpademo.relationships.entity.Student;\n\n@RunWith(SpringRunner.class)\n@SpringBootTest // (webEnvironment = WebEnvironment.RANDOM_PORT)\npublic class CriteriaQueryDemoApplicationTest {\n\n  // @LocalServerPort\n  // String port;\n\n  @Autowired\n  EntityManager entityManager;\n\n  @Test\n  public void basic() {\n\n    CriteriaBuilder cb = entityManager.getCriteriaBuilder();\n\n    CriteriaQuery<Course> cq = cb.createQuery(Course.class);\n    Root<Course> root = cq.from(Course.class);\n\n    TypedQuery<Course> query = entityManager.createQuery(cq.select(root));\n\n    List<Course> courses = query.getResultList();\n    System.out.println(courses);\n  }\n\n  @Test\n  public void basic2() {\n    CriteriaBuilder cb = entityManager.getCriteriaBuilder();\n    CriteriaQuery<Course> cq = cb.createQuery(Course.class);\n\n    Root<Course> course = cq.from(Course.class);\n    Predicate condition = cb.like(course.get(Course_.name), \"%100 Steps\");\n    cq.where(condition);\n\n    TypedQuery<Course> query = entityManager.createQuery(cq.select(course));\n\n    List<Course> courses = query.getResultList();\n    System.out.println(courses);\n\n    assertEquals(2, courses.size());\n    System.out.println(courses);\n  }\n\n  @Test\n  public void basic_empty_courses() {\n\n    CriteriaBuilder cb = entityManager.getCriteriaBuilder();\n    CriteriaQuery<Course> cq = cb.createQuery(Course.class);\n\n    Root<Course> course = cq.from(Course.class);\n    Predicate condition = cb.isEmpty(course.get(Course_.students));\n    cq.where(condition);\n\n    TypedQuery<Course> query = entityManager.createQuery(cq.select(course));\n\n    List<Course> courses = query.getResultList();\n    System.out.println(courses);\n\n    assertEquals(1, courses.size());\n    System.out.println(courses);\n  }\n\n  @Test\n  public void basic_courses_order_by() {\n    CriteriaBuilder cb = entityManager.getCriteriaBuilder();\n\n    CriteriaQuery<Course> cq = cb.createQuery(Course.class);\n    Root<Course> course = cq.from(Course.class);\n    cq.orderBy(cb.desc(course.get(Course_.name)));\n    TypedQuery<Course> query = entityManager.createQuery(cq.select(course));\n\n    List<Course> courses = query.getResultList();\n    System.out.println(courses);\n\n  }\n\n  @Test\n  public void join() {\n    CriteriaBuilder cb = entityManager.getCriteriaBuilder();\n\n    CriteriaQuery<Course> cq = cb.createQuery(Course.class);\n    Root<Course> course = cq.from(Course.class);\n    Join<Course, Student> student = course.join(Course_.students);\n\n    TypedQuery<Course> query = entityManager.createQuery(cq.select(course));\n\n    List<Course> courses = query.getResultList();\n    System.out.println(courses);\n    assertEquals(5, courses.size());\n  }\n\n  @Test\n  public void left_outer_join() {\n    CriteriaBuilder cb = entityManager.getCriteriaBuilder();\n\n    CriteriaQuery<Course> cq = cb.createQuery(Course.class);\n    Root<Course> course = cq.from(Course.class);\n    Join<Course, Student> student = course.join(Course_.students, JoinType.LEFT);\n\n    TypedQuery<Course> query = entityManager.createQuery(cq.select(course));\n\n    List<Course> courses = query.getResultList();\n    System.out.println(courses);\n    assertEquals(6, courses.size());\n  }\n}\n```\n---\n\n### /src/test/java/com/in28minutes/jpa/jpademo/EntityManagerDemoApplicationTests.java\n\n```java\npackage com.in28minutes.jpa.jpademo;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.test.context.SpringBootTest;\nimport org.springframework.test.context.junit4.SpringRunner;\n\nimport com.in28minutes.jpa.jpademo.relationships.repository.EntityManagerRepository;\n\n@RunWith(SpringRunner.class)\n@SpringBootTest // (webEnvironment = WebEnvironment.RANDOM_PORT)\npublic class EntityManagerDemoApplicationTests {\n\n  @Autowired\n  EntityManagerRepository entityManagerRepository;\n\n  @Test\n  public void someTest() {\n    entityManagerRepository.doSomething();\n  }\n}\n```\n---\n\n### /src/test/java/com/in28minutes/jpa/jpademo/InheritanceDemoApplicationTest.java\n\n```java\npackage com.in28minutes.jpa.jpademo;\n\nimport java.math.BigDecimal;\n\nimport javax.persistence.EntityManager;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.test.context.SpringBootTest;\nimport org.springframework.test.context.junit4.SpringRunner;\n\nimport com.in28minutes.jpa.jpademo.inheritence.entity.FullTimeEmployee;\nimport com.in28minutes.jpa.jpademo.inheritence.entity.PartTimeEmployee;\nimport com.in28minutes.jpa.jpademo.inheritence.repository.EmployeeRepository;\n\n@RunWith(SpringRunner.class)\n@SpringBootTest // (webEnvironment = WebEnvironment.RANDOM_PORT)\npublic class InheritanceDemoApplicationTest {\n\n  // @LocalServerPort\n  // String port;\n\n  @Autowired\n  EntityManager entityManager;\n\n  @Autowired\n  EmployeeRepository employeeRepository;\n\n  @Test\n  public void basic() {\n    employeeRepository.insertEmployee(new PartTimeEmployee(\"PartTimeEE\", new BigDecimal(100)));\n    employeeRepository.insertEmployee(new FullTimeEmployee(\"FullTimeEE\", new BigDecimal(10)));\n    System.out.println(employeeRepository.allEmployees());\n  }\n}\n```\n---\n\n### /src/test/java/com/in28minutes/jpa/jpademo/JpaDemoApplicationTests.java\n\n```java\npackage com.in28minutes.jpa.jpademo;\n\nimport java.time.LocalDate;\nimport java.time.Month;\n\nimport javax.persistence.EntityManager;\nimport javax.transaction.Transactional;\n\nimport org.junit.After;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.test.context.SpringBootTest;\nimport org.springframework.test.context.junit4.SpringRunner;\n\nimport com.in28minutes.jpa.jpademo.relationships.entity.Course;\nimport com.in28minutes.jpa.jpademo.relationships.entity.Passport;\nimport com.in28minutes.jpa.jpademo.relationships.entity.Review;\nimport com.in28minutes.jpa.jpademo.relationships.entity.ReviewRating;\nimport com.in28minutes.jpa.jpademo.relationships.entity.Student;\nimport com.in28minutes.jpa.jpademo.relationships.entity.StudentType;\nimport com.in28minutes.jpa.jpademo.relationships.repository.CourseRepository;\nimport com.in28minutes.jpa.jpademo.relationships.repository.StudentRepository;\n\n@RunWith(SpringRunner.class)\n@SpringBootTest // (webEnvironment = WebEnvironment.RANDOM_PORT)\npublic class JpaDemoApplicationTests {\n\n  // @LocalServerPort\n  // String port;\n\n  @Autowired\n  EntityManager entityManager;\n\n  @Autowired\n  CourseRepository courseRepository;\n\n  @Autowired\n  StudentRepository studentRepository;\n\n  @Test\n  public void createCourseWithStudents() {\n    Student student = new Student(\"Ranga\", StudentType.FullTime);\n    courseRepository.createCourseWithStudents(new Course(\"Spring in 100 Steps\"), student);\n    courseRepository.createCourseWithStudents(new Course(\"Spring Boot in 100 Steps\"), student);\n  }\n\n  @Test\n  public void createReviewsForCourse() {\n    Course course = new Course(\"JPA in 100 Steps\");\n    courseRepository.createCourse(course);\n    courseRepository.createReviewsForCourse(course, new Review(ReviewRating.FIVE, \"Awesome Course\"),\n        new Review(ReviewRating.FIVE, \"Wow!\"));\n    \n  }\n\n  @Test\n  public void createCourse() {\n    courseRepository.createCourse(new Course(\"JPA in 100 Steps\"));\n  }\n\n  @Test\n  @Transactional\n  public void createStudentWithPassport() {\n    Student student = new Student(\"Ranga\", StudentType.FullTime);\n    Passport passport = new Passport(\"A12345678\");\n    studentRepository.createStudentWithPassport(student, passport);\n  }\n\n  @Test\n  public void updateCourse() {\n    Course course = courseRepository.retrieveCourse(10001L);\n    course.setName(\"JPA in 100 Steps - updated\");\n    course.setActiveFrom(LocalDate.of(2018, Month.APRIL, 10));\n    courseRepository.updateCourse(course);\n  }\n\n  @After\n  public void printAllData() {\n    System.out.println(\"Dummy\");\n  }\n}\n```\n---\n\n### /src/test/java/com/in28minutes/jpa/jpademo/JPQLDemoApplicationTest.java\n\n```java\npackage com.in28minutes.jpa.jpademo;\n\nimport static org.junit.Assert.assertEquals;\n\nimport java.util.Arrays;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\nimport javax.persistence.TypedQuery;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.test.context.SpringBootTest;\nimport org.springframework.test.context.junit4.SpringRunner;\n\nimport com.in28minutes.jpa.jpademo.relationships.entity.Course;\nimport com.in28minutes.jpa.jpademo.relationships.entity.Student;\n\n@RunWith(SpringRunner.class)\n@SpringBootTest // (webEnvironment = WebEnvironment.RANDOM_PORT)\npublic class JPQLDemoApplicationTest {\n\n  // @LocalServerPort\n  // String port;\n\n  @Autowired\n  EntityManager entityManager;\n\n  @Test\n  public void basic() {\n    Query query = entityManager.createQuery(\"SELECT c FROM Course c\");\n    System.out.println(query.getResultList());\n  }\n\n  @Test\n  public void basic_typed() {\n    TypedQuery<Course> query = entityManager.createQuery(\"SELECT c FROM Course c\", Course.class);\n    List<Course> resultList = query.getResultList();\n    System.out.println(resultList);\n  }\n\n  @Test\n  public void basic2() {\n    Query query = entityManager.createQuery(\"SELECT c FROM Course c WHERE c.name like '%100 Steps'\");\n    List resultList = query.getResultList();\n    assertEquals(2, resultList.size());\n    System.out.println(resultList);\n  }\n\n  @Test\n  public void basic_empty_courses() {\n    Query query = entityManager.createQuery(\"SELECT c FROM Course c WHERE c.students IS EMPTY\");\n    List resultList = query.getResultList();\n    assertEquals(1, resultList.size());\n    System.out.println(resultList);\n  }\n\n  @Test\n  public void basic_courses_with_min_three_students() {\n    Query query = entityManager.createQuery(\"SELECT c FROM Course c WHERE size(c.students) >= 3\");\n    List resultList = query.getResultList();\n    assertEquals(1, resultList.size());\n    System.out.println(resultList);\n  }\n\n  @Test\n  public void basic_courses_order_by() {\n    Query query = entityManager.createQuery(\"SELECT c FROM Course c ORDER BY size(c.students) DESC\");\n    List resultList = query.getResultList();\n    assertEquals(3, resultList.size());\n    System.out.println(resultList);\n  }\n\n  @Test\n  public void basic3() {\n    Query query = entityManager.createQuery(\"SELECT s FROM Student s WHERE s.passport.number like 'N%'\");\n    List resultList = query.getResultList();\n    assertEquals(1, resultList.size());\n    System.out.println(resultList);\n  }\n\n  @Test\n  public void basic4() {\n    Query query = entityManager.createQuery(\"SELECT s FROM Student s WHERE s.passport.number like 'N%'\");\n    List resultList = query.getResultList();\n    assertEquals(1, resultList.size());\n    System.out.println(resultList);\n  }\n\n  // BETWEEN 100 and 1000\n  // IS NULL\n  // upper, lower, trim, length\n  // Group by, having\n  \n  \n  @Test\n  public void join() {\n    Query query = entityManager.createQuery(\"SELECT c, s FROM Course c JOIN c.students s\");\n    List resultList = query.getResultList();\n    System.out.println(resultList.get(1).getClass());\n    assertEquals(5, resultList.size());\n    System.out.println(resultList);\n  }\n\n  @Test\n  public void left_outer_join() {\n    Query query = entityManager.createQuery(\"SELECT c, s FROM Course c LEFT JOIN c.students s\");\n    List<Object[]> resultList = query.getResultList();\n    assertEquals(6, resultList.size());\n    for (Object[] result : resultList) {\n      Course course = (Course) result[0];\n      Student student = (Student) result[1];\n      System.out.println(course + \" \" + student);\n    }\n  }\n\n  @Test\n  public void cross_join() {\n    Query query = entityManager.createQuery(\"SELECT c, s FROM Course c, Student s\");\n    List resultList = query.getResultList();\n    assertEquals(12, resultList.size());\n    System.out.println(resultList);\n  }\n\n}\n```\n---\n\n### /src/test/java/com/in28minutes/jpa/jpademo/NativeQueriesDemoApplicationTest.java\n\n```java\npackage com.in28minutes.jpa.jpademo;\n\nimport static org.junit.Assert.assertEquals;\n\nimport java.util.Arrays;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\nimport javax.persistence.TypedQuery;\nimport javax.transaction.Transactional;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.test.context.SpringBootTest;\nimport org.springframework.test.context.junit4.SpringRunner;\n\nimport com.in28minutes.jpa.jpademo.relationships.entity.Course;\nimport com.in28minutes.jpa.jpademo.relationships.entity.Student;\n\n@RunWith(SpringRunner.class)\n@SpringBootTest // (webEnvironment = WebEnvironment.RANDOM_PORT)\npublic class NativeQueriesDemoApplicationTest {\n\n  // @LocalServerPort\n  // String port;\n\n  @Autowired\n  EntityManager entityManager;\n\n  @Test\n  public void basic() {\n    Query query = entityManager.createNativeQuery(\"SELECT * FROM Course c\");\n    System.out.println(query.getResultList());\n  }\n\n  @Test\n  public void basic_with_parameter() {\n    Query query = entityManager.createNativeQuery(\"SELECT * FROM Course c where c.id = ?\");\n    query.setParameter(1  , 10001L);\n    \n    List resultList = query.getResultList();\n    assertEquals(1,resultList.size());\n\n    System.out.println(resultList);\n  }\n\n  @Test\n  public void basic_with_named_parameter() {\n    Query query = entityManager.createNativeQuery(\"SELECT * FROM Course c where c.id = :id\");\n    query.setParameter(\"id\", 10001L);\n    \n    List resultList = query.getResultList();\n    assertEquals(1,resultList.size());\n\n    System.out.println(resultList);\n  }\n  \n  @Test\n  public void basic_with_named_native_query() {\n  }\n\n  @Test\n  @Transactional\n  public void updating_a_number_of_rows() {\n    Query query = entityManager.createNativeQuery(\"Update Course Set create_date_time=sysdate()\");\n    int executeUpdate = query.executeUpdate();\n    System.out.println(executeUpdate);\n  }\n\n\n  @Test\n  public void basic_typed() {\n    TypedQuery<Course> query = entityManager.createQuery(\"SELECT c FROM Course c\", Course.class);\n    List<Course> resultList = query.getResultList();\n    System.out.println(resultList);\n  }\n\n  @Test\n  public void basic2() {\n    Query query = entityManager.createQuery(\"SELECT c FROM Course c WHERE c.name like '%100 Steps'\");\n    List resultList = query.getResultList();\n    assertEquals(2, resultList.size());\n    System.out.println(resultList);\n  }\n\n  @Test\n  public void basic_empty_courses() {\n    Query query = entityManager.createQuery(\"SELECT c FROM Course c WHERE c.students IS EMPTY\");\n    List resultList = query.getResultList();\n    assertEquals(1, resultList.size());\n    System.out.println(resultList);\n  }\n\n  @Test\n  public void basic_courses_with_min_three_students() {\n    Query query = entityManager.createQuery(\"SELECT c FROM Course c WHERE size(c.students) >= 3\");\n    List resultList = query.getResultList();\n    assertEquals(1, resultList.size());\n    System.out.println(resultList);\n  }\n\n  @Test\n  public void basic_courses_order_by() {\n    Query query = entityManager.createQuery(\"SELECT c FROM Course c ORDER BY size(c.students) DESC\");\n    List resultList = query.getResultList();\n    assertEquals(3, resultList.size());\n    System.out.println(resultList);\n  }\n\n  @Test\n  public void basic3() {\n    Query query = entityManager.createQuery(\"SELECT s FROM Student s WHERE s.passport.number like 'N%'\");\n    List resultList = query.getResultList();\n    assertEquals(1, resultList.size());\n    System.out.println(resultList);\n  }\n\n  @Test\n  public void basic4() {\n    Query query = entityManager.createQuery(\"SELECT s FROM Student s WHERE s.passport.number like 'N%'\");\n    List resultList = query.getResultList();\n    assertEquals(1, resultList.size());\n    System.out.println(resultList);\n  }\n\n  // BETWEEN 100 and 1000\n  // IS NULL\n  // upper, lower, trim, length\n  // Group by, having\n  \n  \n  @Test\n  public void join() {\n    Query query = entityManager.createQuery(\"SELECT c, s FROM Course c JOIN c.students s\");\n    List resultList = query.getResultList();\n    System.out.println(resultList.get(1).getClass());\n    assertEquals(5, resultList.size());\n    System.out.println(resultList);\n  }\n\n  @Test\n  public void left_outer_join() {\n    Query query = entityManager.createQuery(\"SELECT c, s FROM Course c LEFT JOIN c.students s\");\n    List<Object[]> resultList = query.getResultList();\n    assertEquals(6, resultList.size());\n    for (Object[] result : resultList) {\n      Course course = (Course) result[0];\n      Student student = (Student) result[1];\n      System.out.println(course + \" \" + student);\n    }\n  }\n\n  @Test\n  public void cross_join() {\n    Query query = entityManager.createQuery(\"SELECT c, s FROM Course c, Student s\");\n    List resultList = query.getResultList();\n    assertEquals(12, resultList.size());\n    System.out.println(resultList);\n  }\n\n}\n```\n---\n\n### /src/test/java/com/in28minutes/jpa/jpademo/PerformanceDemoApplicationTest.java\n\n```java\npackage com.in28minutes.jpa.jpademo;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.test.context.SpringBootTest;\nimport org.springframework.test.context.junit4.SpringRunner;\n\nimport com.in28minutes.jpa.jpademo.relationships.repository.CourseRepository;\n\n@RunWith(SpringRunner.class)\n@SpringBootTest\npublic class PerformanceDemoApplicationTest {\n\n  @Autowired\n  CourseRepository courseRepository;\n  \n  @Test\n  public void testNplus1(){\n    courseRepository.printAllCourseAndStudents();\n    //courseRepository.printAllCourseAndStudentsDynamicSubgraph();\n    //courseRepository.printAllCourseAndStudentsJoinFetch();\n  }\n\n\n}\n```\n---\n\n### /src/test/java/com/in28minutes/jpa/jpademo/TransactionManagementDemoApplicationTests.java\n\n```java\npackage com.in28minutes.jpa.jpademo;\n\nimport static org.junit.Assert.assertNull;\n\nimport javax.persistence.EntityManager;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.test.context.SpringBootTest;\nimport org.springframework.test.context.junit4.SpringRunner;\n\nimport com.in28minutes.jpa.jpademo.relationships.entity.Passport;\nimport com.in28minutes.jpa.jpademo.relationships.repository.TransactionManagementRepository;\n\n@RunWith(SpringRunner.class)\n@SpringBootTest // (webEnvironment = WebEnvironment.RANDOM_PORT)\npublic class TransactionManagementDemoApplicationTests {\n\n  @Autowired\n  TransactionManagementRepository transactionManagementRepository;\n\n  @Autowired\n  EntityManager entityManager;\n\n  @Test\n  public void someTest() {\n    \n    try {\n      transactionManagementRepository.doSomething();\n    } catch (Exception e) { }\n    \n    assertNull(entityManager.find(Passport.class, 1L));\n  }\n}\n```\n---\n\n### /src/test/resources/data.sql\n\n```\ninsert into passport(id, number)\nvalues(40001, 'L123456');\n\ninsert into passport(id, number)\nvalues(40002, 'M123456');\n\ninsert into passport(id, number)\nvalues(40003, 'N123456');\n\ninsert into passport(id, number)\nvalues(40004, 'O123456');\n\n\ninsert into course(id, name)\nvalues(10001,'Spring in 100 Steps');\n\ninsert into course(id, name)\nvalues(10002,'Spring Boot in 100 Steps');\n\ninsert into course(id, name)\nvalues(10003,'JPA in 50 Steps');\n\ninsert into student(id, name,passport_id)\nvalues(20001, 'Adam',40001);\n\ninsert into student(id, name,passport_id)\nvalues(20002, 'Buck',40002);\n\ninsert into student(id, name,passport_id)\nvalues(20003, 'Chris',40003);\n\ninsert into student(id, name,passport_id)\nvalues(20004, 'Dennis',40004);\n\n\ninsert into course_students(courses_id,students_id)\nvalues(10001,20001);\n\ninsert into course_students(courses_id,students_id)\nvalues(10001,20002);\n\ninsert into course_students(courses_id,students_id)\nvalues(10001,20003);\n\ninsert into course_students(courses_id,students_id)\nvalues(10002,20001);\n\ninsert into course_students(courses_id,students_id)\nvalues(10002,20002);\n```\n---\n\n"
  },
  {
    "path": "_blog/articles/2017-11-14-jpa-in-10-steps.md",
    "content": "---\nlayout:     post\ntitle:      JPA and Hibernate Tutorial For Beginners - 10 Steps with Spring Boot and H2\ndate:       2023-03-15 12:31:19\nsummary:    JPA and Hibernate in 10 Steps with H2 - Creating a simple project using Spring Boot and an in-memory database H2. It's a piece of cake. \ncategories: SpringBootJPA\npermalink:  /jpa-hibernate-tutorial-for-beginners\nimage: /images/spring-data-category.png\n---\n\n![Image](http://www.springboottutorial.com/images/JPA_02_Architecture.png \"Basics of JPA\")   \n\nIn this part, we will cover the fundamentals of JPA and compare it to previous attempts at persistence frameworks used to store data in databases.\n- How does it compare to JDBC?\n- How does it compare to Spring JDBC?\n\nWe will understand the basic concepts of JPA\n- Entities\n- Mappings\n- Relationships \n\nWe will create a Spring Boot project with Spring Initializr and create an Entity and Repository to get a big picture of JPA, Spring Data and Spring Data JPA.\n\n\n\n### JPA and Hibernate in 10 Steps with H2\n\nSteps\n- Step 1 : Object Relational Impedence Mismatch - Understanding the problem that JPA solves\n- Step 2 : World before JPA - JDBC, Spring JDBC and myBatis\n- Step 3 : Introduction to JPA\n- Step 4 : Creating a JPA Project using Spring Initializr\n- Step 5 : Defining a JPA Entity - User\n- Step 6 : Defining a Service to manage the Entity - UserService and EntityManager\n- Step 7 : Using a Command Line Runner to save the User to Database\n- Step 8 : Magic of Spring Boot and In Memory Database H2\n- Step 9 : Introduction to Spring Data JPA\n- Step 10 : More JPA Repository : findById and findAll\n\n\n#### Step 1 : Object Relational Impedence Mismatch - Understanding the problem that JPA solves\n\n> What problem does JPA solve?\n\n\nJava is an object oriented programming language & Relational databases are used to store data.The way we design objects is different from the way the relational databases are designed.\n- Mismatch in Design - Object Oriented vs Normal Forms\n- Mismatches in naming - Java Fields vs Table Columns\n- Relationships between objects are expressed in a different way compared with relationship between tables.\n\n> Must Read - http://www.springboottutorial.com/introduction-to-jpa-with-spring-boot-data-jpa\n\n#### Step 2 : World before JPA - JDBC, Spring JDBC and myBatis\n\nBefore the emergence of JPA and Hibernate, we relied on JDBC, Spring JDBC and myBatis to interact with Relational Databases. \n- JDBC, Spring JDBC and myBatis involve writing queries.\n- In big application, queries can become complex. Especially when we retrieve data from multiple tables.\n- This creates a problem whenever there are changes in the structure of the database.\n\n##### JDBC \nLot of code\n\n```java\nConnection connection = datasource.getConnection();\n\nPreparedStatement st = connection.prepareStatement(\n\t\t\"Update todo set user=?, desc=?, target_date=?, is_done=? where id=?\");\n\nst.setString(1, todo.getUser());\nst.setString(2, todo.getDesc());\nst.setTimestamp(3, new Timestamp(\n\t\ttodo.getTargetDate().getTime()));\nst.setBoolean(4, todo.isDone());\nst.setInt(5, todo.getId());\n\nst.execute();\n\nst.close();\n\nconnection.close();\n```\n\n##### Spring JDBC\n\nSimpler than JDBC but still queries\n\n```java\njdbcTemplate\n.update(\"Update todo set user=?, desc=?, target_date=?, is_done=? where id=?\",\n\ttodo.getUser(), \n\ttodo.getDesc(),\n\tnew Timestamp(todo.getTargetDate().getTime()),\n\ttodo.isDone(), \n\ttodo.getId());\n```\n\n##### myBatis\nMyBatis removes the need for manually writing code to set parameters and retrieve results. It provides simple XML or Annotation based configuration to map Java POJOs to database.\n\n```\n@Override\n@Update(\"Update todo set user=#{user}, desc=#{desc}, target_date=#{targetDate}, is_done=#{isDone} where id=#{id}\")\npublic void updateTodo(Todo todo) throws SQLException;\n```\n\n#### Step 03 : Introduction to JPA\n\nHibernate (and ORM - Object Relational Mapping) emerged as a result of this big idea:\n\n> Instead of writing queries by hand, what if we can map tables(relations) to java objects and generate queries \n\nJPA came in later when Java EE attempted to standize ORM frameworks. \n\nHibernate went on to become the preferred implementation for JPA (in addition to offering excellent additional features)\n\n![Image](https://www.springboottutorial.com/images/JPA_02_Architecture.png \"Basics of JPA\")   \n\n### Step 4 : Creating a JPA Project using Spring Initializr\n\nCreating a Spring Project with Spring Initializr is a cake walk. \n\n> Spring Initializr [http://start.spring.io/](http://start.spring.io/){:target=\"_blank\"} is great tool to bootstrap your Spring Boot projects.\n\n![Image](/images/spring-initializr-spring-in-10-steps.png \"Spring Initializr\")   \n\nAs shown in the image above, following steps have to be done\n\n- Launch Spring Initializr and choose the following\n  - Choose `com.in28minutes.learning.jpa` as Group\n  - Choose `jpa-in-10-steps` as Artifact\n  - Choose Following Dependencies\n    - Web\n    - JPA\n    - H2\n- Click Generate Project.\n- Import the project into Eclipse.\n- If you want to understand all the files that are part of this project, you can go here.\n\n##### JPA vs Hibernate\n\nHibernate is one of the most popular ORM frameworks.\n\nJPA defines the specification. It is an API.\n- How do you define entities?\n- How do you map attributes?\n- How do you map relationships between entities?\n- Who manages the entities?\n- Hibernate is one of the popular implementations of JPA.\n\nHibernate recognises the mappings we create between objects and tables. It guarantees that data is stored and retrieved from the database in accordance with the mappings.\n\nHibernate extends JPA with extra functionality. But, relying on them would bind you to Hibernate. You cannot switch to another JPA implementation, such as Toplink.\n\n#### Step 5 : Defining a JPA Entity - User\n\nLet's define a User Entity with a primary key.\n\n```java\npackage com.in28minutes.learning.jpa.jpain10steps.entity;\n\nimport jakarta.persistence.Entity;\nimport jakarta.persistence.GeneratedValue;\nimport jakarta.persistence.Id;\n\n//Table - User\n@Entity\npublic class User {\n\n\t@Id\n\t@GeneratedValue\n\tprivate long id;\n\n\tprivate String name;\n\n\tprivate String role;\n\n\tprotected User() {\n\n\t}\n\n\tpublic User(String name, String role) {\n\t\tsuper();\n\t\tthis.name = name;\n\t\tthis.role = role;\n\t}\n\n\tpublic long getId() {\n\t\treturn id;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic String getRole() {\n\t\treturn role;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn String.format(\"User [id=%s, name=%s, role=%s]\", id, name, role);\n\t}\n}\n```\n \n#### Step 6 : Defining a Service to manage the Entity - UserService and EntityManager\n\nLets define a repository to manage the User entity.\n\n```java\npackage com.in28minutes.learning.jpa.jpain10steps.service;\n\nimport jakarta.persistence.EntityManager;\nimport jakarta.persistence.PersistenceContext;\nimport jakarta.transaction.Transactional;\n\nimport org.springframework.stereotype.Repository;\n\nimport com.in28minutes.learning.jpa.jpain10steps.entity.User;\n\n@Repository\n@Transactional\npublic class UserDAOService {\n\t\t\n\t@PersistenceContext\n\tprivate EntityManager entityManager;\n\t\n\tpublic long insert(User user){\n\t\tentityManager.persist(user);\n\t\treturn user.getId();\n\t}\n}\n```\nImportant things to note\n- @Repository: Spring Annotation to indicate that this component handles storing data to a data store.\n- @Transactional: Spring annotation used to simplify transaction management\n- @PersistenceContext: A persistence context handles a set of entities which hold data to be persisted in some persistence store (e.g. a database). In particular, the context is aware of the different states an entity can have (e.g. managed, detached) in relation to both the context and the underlying persistence store.\n- EntityManager : Interface used to interact with the persistence context.\n- entityManager.persist(user): Make user entity instance managed and persistent i.e. saved to database.\n\nNotes from http://docs.oracle.com/javaee/6/api/javax/persistence/EntityManager.html#createNamedQuery(java.lang.String)\n\n> An EntityManager instance is associated with a persistence context. A persistence context is a set of entity instances in which for any persistent entity identity there is a unique entity instance. Within the persistence context, the entity instances and their lifecycle are managed. The EntityManager API is used to create and remove persistent entity instances, to find entities by their primary key, and to query over entities.\n\n> The set of entities that can be managed by a given EntityManager instance is defined by a persistence unit. A persistence unit defines the set of all classes that are related or grouped by the application, and which must be colocated in their mapping to a single database.\n \n#### Step 7 : Using a Command Line Runner to save the User to Database\n\nCommandLineRunner interface is used to indicate that this bean has to be run as soon as the Spring application context is initialized.\n\n\n```java\npackage com.in28minutes.learning.jpa.jpain10steps;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.CommandLineRunner;\nimport org.springframework.stereotype.Component;\n\nimport com.in28minutes.learning.jpa.jpain10steps.entity.User;\nimport com.in28minutes.learning.jpa.jpain10steps.service.UserDAOService;\n\n@Component\npublic class UserDaoServiceCommandLineRunner implements CommandLineRunner{\n\n\tprivate static final Logger log = \n\t\t\tLoggerFactory.getLogger(UserDaoServiceCommandLineRunner.class);\n\t\n\t@Autowired\n\tprivate UserDAOService userDaoService;\n\t\n\t@Override\n\tpublic void run(String... arg0) throws Exception {\n\t\tvar user = new User(\"Jack\", \"Admin\");\n\t\t//New User is created : User [id=1, name=Jack, role=Admin]\n\t\tlong insert = userDaoService.insert(user);\n\t\tlog.info(\"New User is created : \" + user);\n\t}\n}\n```\n\n### Step 8 : Magic of Spring Boot and In Memory Database H2\n\n The simple answer is all the magic is happening because of Spring Boot and Starter Projects. \n\n Recommended Reading\n - Spring Boot Auto Configuration - http://www.springboottutorial.com/spring-boot-auto-configuration\n - Spring Boot Starter Project - http://www.springboottutorial.com/spring-boot-starter-projects\n - Spring Boot Starter Parent - http://www.springboottutorial.com/spring-boot-starter-parent \n\nH2 Console - We will enable h2 console in /src/main/resources/application.properties\n\n```\nspring.h2.console.enabled=true\nspring.datasource.url=jdbc:h2:mem:testdb\nspring.data.jpa.repositories.bootstrap-mode=default\n```\n##### FAQ\n- Where is the database created?\n\t- In Memory - Using H2\n- What schema is used to create the tables?\n\t- Created based on the entities defined\n- Where are the tables created?\n\t- Created based on the entities defined\n\t- In Memory - Using H2\n- Can I see the data in the database?\n\t- http://localhost:8080/h2-console\n\t- Use db url jdbc:h2:mem:testdb\n- Where is Hibernate coming in from?\n\t- Through Spring Data JPA Starter\n- How is a datasource created?\n\t- Through Spring Boot Auto Configuration\n\n##### Magic of Spring Boot and in Memory Database\n- Zero project setup or infrastructure\n- Zero Configuration\n- Zero Maintainance\n- Easy to use for Learning and Unit Tests\n- Simple Configuration to switch to a real database\n\n### Step 9 : Introduction to Spring Data JPA\nSpring Data aims to provide a consistent model for accessing data from different kinds of data stores.\n\nUserService (which we created earlier) contains a lot of redundant code which can be easily generalized. Spring Data aims to simplify the code below.\n\n```java\npackage com.in28minutes.learning.jpa.jpain10steps.service;\n\nimport org.springframework.data.jpa.repository.JpaRepository;\n\nimport com.in28minutes.learning.jpa.jpain10steps.entity.User;\n\npublic interface UserRepository extends JpaRepository<User, Long>{\n\n}\n```\n\n```\npackage com.in28minutes.learning.jpa.jpain10steps;\n\nimport java.util.List;\nimport java.util.Optional;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.CommandLineRunner;\nimport org.springframework.stereotype.Component;\n\nimport com.in28minutes.learning.jpa.jpain10steps.entity.User;\nimport com.in28minutes.learning.jpa.jpain10steps.service.UserRepository;\n\n@Component\npublic class UserRepositoryCommandLineRunner implements CommandLineRunner{\n\n\tprivate static final Logger log = \n\t\t\tLoggerFactory.getLogger(UserRepositoryCommandLineRunner.class);\n\t\n\t@Autowired\n\tprivate UserRepository userRepository;\n\t\n\t@Override\n\tpublic void run(String... arg0) throws Exception {\n\t\tvar user = new User(\"Jill\", \"Admin\");\n\t\tuserRepository.save(user);\n\t\tlog.info(\"New User is created : \" + user);\n\t\t\n\t}\n\t\n}\n```\n \n#### Step 10 : More JPA Repository : findById and findAll\n\n```\npackage com.in28minutes.learning.jpa.jpain10steps;\n\nimport java.util.List;\nimport java.util.Optional;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.CommandLineRunner;\nimport org.springframework.stereotype.Component;\n\nimport com.in28minutes.learning.jpa.jpain10steps.entity.User;\nimport com.in28minutes.learning.jpa.jpain10steps.service.UserRepository;\n\n@Component\npublic class UserRepositoryCommandLineRunner implements CommandLineRunner{\n\n\tprivate static final Logger log = \n\t\t\tLoggerFactory.getLogger(UserRepositoryCommandLineRunner.class);\n\t\n\t@Autowired\n\tprivate UserRepository userRepository;\n\t\n\t@Override\n\tpublic void run(String... arg0) throws Exception {\n\t\tvar user = new User(\"Jill\", \"Admin\");\n\t\tuserRepository.save(user);\n\t\tlog.info(\"New User is created : \" + user);\n\t\t\n\t\tOptional<User> userWithIdOne = userRepository.findById(1L);\n\t\tlog.info(\"User is retrived : \" + userWithIdOne);\n\n\t\tList<User> users = userRepository.findAll();\n\t\tlog.info(\"All Users : \" + users);\t\t\t\n\t}\n\t\n}\n```\n\nlog\n```\nHibernateJpaAutoConfiguration matched:\n - @ConditionalOnClass found required classes 'org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean', 'jakarta.persistence.EntityManager'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition)\n - HibernateEntityManager found class 'org.hibernate.ejb.HibernateEntityManager' (HibernateJpaAutoConfiguration.HibernateEntityManagerCondition)\n\nDataSourceAutoConfiguration matched:\n - @ConditionalOnClass found required classes 'jakarta.sql.DataSource', 'org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition)\n\nJpaBaseConfiguration#entityManagerFactory matched:\n - @ConditionalOnMissingBean (types: org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean,jakarta.persistence.EntityManagerFactory; SearchStrategy: all) did not find any beans (OnBeanCondition)\n\nJpaBaseConfiguration#transactionManager matched:\n - @ConditionalOnMissingBean (types: org.springframework.transaction.PlatformTransactionManager; SearchStrategy: all) did not find any beans (OnBeanCondition)\n```\n\n---\n"
  },
  {
    "path": "_blog/articles/2017-11-15-junit-in-5-steps.md",
    "content": "---\nlayout:     post\ntitle:      JUnit Tutorial for Beginners in 5 Steps\ndate:       2023-03-15 12:31:19\nsummary:    JUnit Tutorial for Beginners in 5 Steps. Setting up a basic JUnit example and understanding the basics of junit. \ncategories: SpringBootUnitTesting\npermalink:  /junit-tutorial-for-beginners\nimage: /images/unit-test-category.png\n---\n\n- Git Repository - https://github.com/in28minutes/getting-started-in-5-steps/tree/master/junit-in-5-steps\n- Pre-requisites \n\t- Java & Eclipse - https://www.youtube.com/playlist?list=PLBBog2r6uMCSmMVTW_QmDLyASBvovyAO3\n- We will use embedded maven in Eclipse\n\nJUnit is the most popular Java Unit testing framework\n\nHere is an overview of what we would learn in this section\n- Step 1 : What is JUnit and Unit Testing?\n- Step 2 : First JUnit Project and Green Bar\n- Step 3 : First Code and First Unit Test\n- Step 4 : Other assert methods\n- Step 5 : Important annotations\n\n### Step 1 : What is JUnit and Unit Testing?\n - What is JUnit?\n - What is Unit Testing?\n - Advantages of Unit Testing\n\nWe often work on huge projects, which may have more than 2000 source files or as many as 10,000 files with one million lines of code.\n\nPrior to unit testing, we rely on deploying the full programme and verifying that the displays look nice. Yet, this is inefficient. It is also manual.\n\nUnit testing is concerned with creating automated tests for specific classes and functions.\n\nJUnit is a framework that allows you to call a method and verify (or assert) that the result is as anticipated.\n\nThe crucial aspect of automated testing is that it can be executed with continuous integration - that is, as soon as some code changes.\n\n### Step 2 : First JUnit Project and Green Bar\n - What is JUnit?\n - First Project with JUnit\n - First JUnit Class\n - No Failure is Success\n - MyMath class with sum method\n\n\n```java\npackage com.in28minutes.junit;\n\npublic class MyMath {\n\tint sum(int[] numbers) {\n\t\tint sum = 0;\n\t\tfor (int i : numbers) {\n\t\t\tsum += i;\n\t\t}\n\t\treturn sum;\n\t}\n}\n```\n\n### Step 3 : First Code and First Unit Test\n - Unit test for the sum method\n\n```java\npackage com.in28minutes.junit;\n\nimport static org.junit.Assert.assertEquals;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\npublic class MyMathTest {\n\tMyMath myMath = new MyMath();\n\n\t// MyMath.sum\n\t// 1,2,3 => 6\n\t@Test\n\tpublic void sum_with3numbers() {\n\t\tSystem.out.println(\"Test1\");\n\t\tassertEquals(6, myMath.sum(new int[] { 1, 2, 3 }));\n\t}\n\n\t@Test\n\tpublic void sum_with1number() {\n\t\tSystem.out.println(\"Test2\");\n\t\tassertEquals(3, myMath.sum(new int[] { 3 }));\n\t}\n}\n```\n### Step 4 : Other assert methods\n - assertTrue and assertFalse methods\n\n\n```java\npackage com.in28minutes.junit;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertTrue;\n\nimport org.junit.Test;\n\npublic class AssertTest {\n\n\t@Test\n\tpublic void test() {\n\t\tboolean condn = true;\n\t\tassertEquals(true, condn);\n\t\tassertTrue(condn);\n\t\t// assertFalse(condn);\n\t}\n\n}\n```\n\n### Step 5 : Important annotations\n- @Before @After annotations\n\t- Run before and after every test method in the class\n- @BeforeClass @AfterClass annotations\n\t- Static methods which are executed once before and after a test class\n\n\n```java\npackage com.in28minutes.junit;\n\nimport static org.junit.Assert.assertEquals;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\npublic class MyMathTest {\n\tMyMath myMath = new MyMath();\n\n\t@Before\n\tpublic void before() {\n\t\tSystem.out.println(\"Before\");\n\t}\n\n\t@After\n\tpublic void after() {\n\t\tSystem.out.println(\"After\");\n\t}\n\n\t@BeforeClass\n\tpublic static void beforeClass() {\n\t\tSystem.out.println(\"Before Class\");\n\t}\n\n\t@AfterClass\n\tpublic static void afterClass() {\n\t\tSystem.out.println(\"After Class\");\n\t}\n\n\t// MyMath.sum\n\t// 1,2,3 => 6\n\t@Test\n\tpublic void sum_with3numbers() {\n\t\tSystem.out.println(\"Test1\");\n\t\tassertEquals(6, myMath.sum(new int[] { 1, 2, 3 }));\n\t}\n\n\t@Test\n\tpublic void sum_with1number() {\n\t\tSystem.out.println(\"Test2\");\n\t\tassertEquals(3, myMath.sum(new int[] { 3 }));\n\t}\n}\n```"
  },
  {
    "path": "_blog/articles/2017-11-15-spring-boot-and-spring-jdbc-with-h2.md",
    "content": "---\nlayout:     post\ntitle:      Integrating Spring Boot and Spring JDBC with H2 and Starter JDBC\ndate:       2023-03-17 01:12:27\nsummary:    Discover how to utilise Spring Boot Starter JDBC to connect Spring Boot to H2 (in-memory database). You will use Spring Boot to develop a basic project. You will add code to the project that will allow you to connect to a database using Spring JDBC. You will learn how to use the fundamental CRUD techniques.\ncategories:  SpringBootJPA\npermalink:  /spring-boot-and-spring-jdbc-with-h2\nimage: /images/spring-data-category.png\n---\n\n![Image](/images/spring-initializer-web-h2-devtools-jdbc.png \"Web, JDBC,H2 and Developer Tools\")\n\nThis article will assist you in creating a basic Spring Boot project. You will add code to the project that will allow you to connect to a database using Spring JDBC. You will learn how to code all of the CRUD procedures.\n \n![Image](/images/H2-Console-Login-Page.png \"H2 Console Login PAge\") \n\n## You will learn\n- How does Spring Boot Started JDBC work? \n- How to connect a Spring Boot project to a database using Spring JDBC?\n- How to write a simple repository class with all the CRUD methods?\n- How to execute basic queries using Spring JDBC?\n- How to create a project using Spring Boot, Spring JDBC, and H2?\n- What are the basics of an in-memory database?\n\n## Project Code Structure\n\nThe framework of the project we will construct is seen in the screenshot below.\n\n![Image](/images/SpringBootwithJDBC-ProjectStructure.png \"Spring Boot with JDBC - Project Structure\") \n\nA few details\n\n- `Student.java` - The bean to store student details.\n- `StudentJdbcRepository.java` - The H2 database contains all the methods to store and retrieve student details.\n- `schema.sql` - Since we are using an in-memory database, we define the tables as part of our application code in this file.\n- `data.sql` - We use `data.sql` to populate the initial student data.\n- `SpringBoot2JdbcWithH2Application.java` - The main Spring Boot application class which is used to launch the application. We will extend the `CommandLineRunner` interface and implement the `public void run(String... args)` method to launch the spring JDBC code when the server launches.\n- `pom.xml` - This contains all the dependencies needed to build this project. In addition to Developer Tools and H2, we will use Spring Boot Starter JDBC and Web. \n\n## Prerequisites:\n- Maven 3.0+ is your build tool\n- Your favorite IDE. We use Eclipse or IntelliJ.\n- JDK 17\n\n## Maven Project Completion using Code Samples\n> Our Github repository has all the code examples. - https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-2-jdbc-with-h2\n\n## A Little Theoretical\n\nJDBC\n- JDBC is an abbreviation for Java Database Connectivity.\n- It made use of terms such as Statement, PreparedStatement, and ResultSet.\n- The query used in the sample below is ```Update todo set user=?, desc=?, target_date=?, is_done=? where id=?```\n- The values required to run the query are entered into the query using various set methods on the PreparedStatement.\n- The query's results are added to the ResultSet. To convert the ResultSet into objects, we had to create code.\n\n#### Update Todo\n```java\nConnection connection = datasource.getConnection();\n\nPreparedStatement st = connection.prepareStatement(\"Update todo set user=?, desc=?, target_date=?, is_done=? where id=?\");\n\nst.setString(1, todo.getUser());\nst.setString(2, todo.getDesc());\nst.setTimestamp(3, new Timestamp(todo.getTargetDate().getTime()));\nst.setBoolean(4, todo.isDone());\nst.setInt(5, todo.getId());\n\nst.execute();\n\nst.close();\n\nconnection.close();\n```\n\n### Spring JDBC\n\n- Spring JDBC is a layer that sits on top of JDBC.\n- It made use of ideas such as JDBCTemplate.\n- Although the following are simplified, it usually requires fewer lines than JDBC.\n   - The mapping of parameters to queries.\n   - liquidating yields beans\n   - Because all exceptions are transformed to RuntimeExceptions, no exception handling is required.\n\n## Creating the Project with Spring Initializr\n\nUsing Spring Initializr to create a REST service is a piece of cake. Our web framework will be Spring Web MVC. \n\nSpring Initializr [http://start.spring.io/](http://start.spring.io/){:target=\"_blank\"} is great tool to bootstrap your Spring Boot projects.\n\n![Image](/images/spring-initializer-web-h2-devtools-jdbc.png \"Web, JDBC,H2 and Developer Tools\")\n\nAs shown in the image above, following steps have to be done\n\n- Launch Spring Initializr and choose the following\n  - Choose `com.in28minutes.springboot.jdbc.h2.example` as Group\n  - Choose `spring-boot-2-jdbc-with-h2` as Artifact\n  - Choose following dependencies\n    - Web\n    - JDBC\n    - H2\n    - DevTools\n- Click \"Generate\"\n- Import the project into Eclipse. File -> Import -> Existing Maven Project.\n- If you want to understand all the files that are part of this project, you can go here TODO.\n\n## Starter Projects in pom.xml\n\nBelow is the list of starter projects in pom.xml. \n\n```\n<dependency>\n\t<groupId>org.springframework.boot</groupId>\n\t<artifactId>spring-boot-starter-jdbc</artifactId>\n</dependency>\n<dependency>\n\t<groupId>org.springframework.boot</groupId>\n\t<artifactId>spring-boot-starter-web</artifactId>\n</dependency>\n\n<dependency>\n\t<groupId>org.springframework.boot</groupId>\n\t<artifactId>spring-boot-devtools</artifactId>\n\t<scope>runtime</scope>\n</dependency>\n\n<dependency>\n\t<groupId>com.h2database</groupId>\n\t<artifactId>h2</artifactId>\n\t<scope>runtime</scope>\n</dependency>\n<dependency>\n\t<groupId>org.springframework.boot</groupId>\n\t<artifactId>spring-boot-starter-test</artifactId>\n\t<scope>test</scope>\n</dependency>\n```\n\n## Set up the H2 in-memory database using the schema.\n\nH2 will be used as the database.\n\nTo see the data, H2 provides a web interface called H2 Console. Allow the H2 console to be enabled in the 'application.properties' file.\n\n/src/main/resources/application.properties\n```properties\n# Enabling H2 Console\nspring.h2.console.enabled=true\n#Turn Statistics on\nspring.jpa.properties.hibernate.generate_statistics=true\nlogging.level.org.hibernate.stat=debug\n# Show all queries\nspring.jpa.show-sql=true\nspring.jpa.properties.hibernate.format_sql=true\nlogging.level.org.hibernate.type=trace\n\nspring.datasource.url=jdbc:h2:mem:testdb\nspring.data.jpa.repositories.bootstrap-mode=default\n```\nYou may access H2 Console by reloading the application http://localhost:8080/h2-console\n\n![Image](/images/H2-Console-Login-Page.png \"H2 Console Login PAge\") \n\n> Tip - Make sure that you use `jdbc:h2:mem:testdb` as JDBC URL.\n\nWhen you provide the correct JDBC URL, you should see an empty schema when you click the 'Connect' button.\n\n![Image](/images/H2-Console-Empty-Schema.png \"H2 Console Empty Page\") \n\n### Build a schema using `schema.sql` and a data set with `data.sql`.\n\nWe'll make a \"student\" table with a few simple columns. We may start a schema by generating a `schema.sql` file in the resources folder.\n\n/src/main/resources/schema.sql\n\n```\ncreate table student\n(\n   id integer not null,\n   name varchar(255) not null,\n   passport_number varchar(255) not null,\n   primary key(id)\n);\n```\n\nLet's additionally add some information to the student table.\n\n/src/main/resources/data.sql\n\n```\ninsert into student values(10001,'Ranga', 'E1234567');\ninsert into student values(10002,'Ravi', 'A1234568');\n```\n\nAfter you refresh the application, you should see the following messages in the log showing that the sql files have been picked up.\n```\nExecuting SQL script from URL [file:/in28Minutes/git/spring-boot-examples/spring-boot-2-jdbc-with-h2/target/classes/schema.sql]\nExecuting SQL script from URL [file:/in28Minutes/git/spring-boot-examples/spring-boot-2-jdbc-with-h2/target/classes/data.sql]\n```\n\nWhen you access H2 Console (http://localhost:8080/h2-console), you'll notice that the student table has been created and the data has been loaded.\n\n\n![Image](/images/H2-Console-With-Student.png \"H2 Console With Student\")\n\n## Creating Student Bean\n\nLet's make a simple Student bean that has basic student information as well as getters, setters, and a function toString() function.\n\n```java\nppackage com.in28minutes.springboot.jdbc.h2.example.student;\n\npublic class Student {\n    private Long id;\n    private String name;\n    private String passportNumber;\n\n    public Student() {\n        super();\n    }\n\n    public Student(Long id, String name, String passportNumber) {\n        super();\n        this.id = id;\n        this.name = name;\n        this.passportNumber = passportNumber;\n    }\n\n    public Student(String name, String passportNumber) {\n        super();\n        this.name = name;\n        this.passportNumber = passportNumber;\n    }\n\n    public Long getId() {\n        return id;\n    }\n\n    public void setId(Long id) {\n        this.id = id;\n    }\n\n    public String getName() {\n        return name;\n    }\n\n    public void setName(String name) {\n        this.name = name;\n    }\n\n    public String getPassportNumber() {\n        return passportNumber;\n    }\n\n    public void setPassportNumber(String passportNumber) {\n        this.passportNumber = passportNumber;\n    }\n\n    @Override\n    public String toString() {\n        return String.format(\"Student [id=%s, name=%s, passportNumber=%s]\", id, name, passportNumber);\n    }\n\n}\n\n```\n## Build a repository way for reading student data.\n\nWe'd want to start by making a basic repository. A JDBCTemplate will be used to communicate with the database.\n```java\n@Repository\npublic class StudentJdbcRepository {\n\t@Autowired\n\tJdbcTemplate jdbcTemplate;\n\n```\n> Spring Boot Auto Configuration detects H2 on the classpath. It recognises that we wish to communicate with an in-memory database. It creates a datasource as well as a JDBCTemplate that connects to that datasource.\n\nCreate the findById method in StudentJDBCRepository to obtain a student by ID.\n```java\n\tpublic Student findById(long id) {\n\t\treturn jdbcTemplate.queryForObject(\"select * from student where id=?\", new BeanPropertyRowMapper<>(Student.class), id);\n\t}\n```\n\nNotes\n- `JdbcTemplate` has a number of methods to execute queries. In this example, we are using the `queryForObject` method.\n- `new BeanPropertyRowMapper<Student>(Student.class)` - We are using a BeanPropertyRowMapper to map the results from ResultSet to the Student bean.\n- `id` - We are passing id as a parameter to the query\n\nWe'd want to use the findById function. To keep things simple, we'll create the SpringBoot2JdbcWithH2Application class implement CommandLineRunner and include a run function that calls the repository's findById method.\n\n/src/main/java/com/in28minutes/springboot/jdbc/h2/example/SpringBoot2JdbcWithH2Application.java\n\n```java\n@SpringBootApplication\npublic class SpringBoot2JdbcWithH2Application implements CommandLineRunner {\n\n\tprivate final Logger logger = LoggerFactory.getLogger(this.getClass());\n\n\t@Autowired\n\tStudentJdbcRepository repository;\n\n\tpublic static void main(String[] args) {\n\t\tSpringApplication.run(SpringBoot2JdbcWithH2Application.class, args);\n\t}\n\n\t@Override\n\tpublic void run(String... args) throws Exception {\n\n\t\tlogger.info(\"Student id 10001 -> {}\", repository.findById(10001L));\n\t}\n}\n```\nNotes\n- `@Autowired StudentJdbcRepository repository;` - We will autowire the StudentJdbcRepository that we previously constructed.\n- `public void run(String... args) throws Exception {` - Implement the commandLineRunner interface's run function. When the application is launched, this method is called.\n- `logger.info(\"Student id 10001 -> {}\", repository.findById(10001L))` - Log all the information about student id 10001.\n\nThis will be shown in the log when the application reloads.\n```\nStudent id 10001 -> Student [id=10001, name=Ranga, passportNumber=E1234567]\n```\n> Congrats for successfully running the first Spring JDBC method! Spring Boot demonstrates how simple it is.\n\nLet's now add another method to get information about all of the students from the StudentJdbcRepository.\n\n```java\n\tstatic class StudentRowMapper implements RowMapper<Student> {\n        @Override\n        public Student mapRow(ResultSet rs, int rowNum) throws SQLException {\n            Student student = new Student();\n            student.setId(rs.getLong(\"id\"));\n            student.setName(rs.getString(\"name\"));\n            student.setPassportNumber(rs.getString(\"passport_number\"));\n            return student;\n        }\n\n    }\n\n\tpublic List<Student> findAll() {\n\t\treturn jdbcTemplate.query(\"select * from student\", new StudentRowMapper());\n\t}\n```\nNotes\n- `class StudentRowMapper implements RowMapper<Student>` - To map the result set to a student bean, we define a custom row mapper.\n- `jdbcTemplate.query(\"select * from student\", new StudentRowMapper())` - We utilise the 'query' method in JdbcTemplate to retrieve a list of students.\n\nIn the run method, we may include a call to the find all function.`SpringBoot2JdbcWithH2Application.java`\n\n```java\n\nlogger.info(\"All users 1 -> {}\", repository.findAll());\n\n```\n\nAfter you restart the project, you should see the following output in the log.\n```\nAll users 1 -> [Student [id=10001, name=Ranga, passportNumber=E1234567], Student [id=10002, name=Ravi, passportNumber=A1234568]]\n```\n\n## Implementing Spring JDBC delete, insert, and update methods\n\nThe following code demonstrates the delete, insert, and update methods.\n\n```java\n\tpublic void deleteById(long id) {\n        jdbcTemplate.update(\"delete from student where id=?\", id);\n    }\n\n\tpublic int insert(Student student) {\n        return jdbcTemplate.update(\"insert into student (id, name, passport_number) \" + \"values(?,  ?, ?)\",\n                student.getId(), student.getName(), student.getPassportNumber());\n    }\n\n\tpublic int update(Student student) {\n        return jdbcTemplate.update(\"update student \" + \" set name = ?, passport_number = ? \" + \" where id = ?\",\n                student.getName(), student.getPassportNumber(), student.getId());\n    }\n\n```\n\nNotes \n- These procedures are pretty simple.\n-All methods make use of the JdbcTemplate class's `update` function to specify the appropriate query and parameters.\n\nAll of the aforementioned methods can be called in the run method of `SpringBoot2JdbcWithH2Application.java`\n\n```java\nlogger.info(\"Inserting -> {}\", repository.insert(new Student(10010L, \"John\", \"A1234657\")));\n\nlogger.info(\"Update 10001 -> {}\", repository.update(new Student(10001L, \"Name-Updated\", \"New-Passport\")));\n\nrepository.deleteById(10002L);\n\nlogger.info(\"All users 2 -> {}\", repository.findAll());\n\n```\n\nAfter you restart the project, you should see the following output in the log.\n```\nInserting -> 1\nUpdate 10003 -> 1\nAll users -> [Student [id=10001, name=Name-Updated, passportNumber=New-Passport], Student [id=10010, name=John, passportNumber=A1234657]]\n```\n> That's fantastic! You've used Spring JDBC and Spring Boot to implement all of the CRUD functions.\n"
  },
  {
    "path": "_blog/articles/2017-11-16-maven-in-5-steps.md",
    "content": "---\nlayout:     post\ntitle:      Maven Tutorial for Beginners in 5 Steps\ndate:       2023-03-17 12:31:19\nsummary:    Maven 5 Step Tutorial for Beginners. Understand the fundamentals of Maven by creating a simple example with Spring Initializr. \ncategories: SpringBoot\npermalink:  /maven-tutorial-for-beginners\nimage: /images/java-category.png\n---\n\nIt is tough to define what Maven accomplishes.\n\nEvery day, Developer undertakes a variety of tasks.\n- Manages Dependencies \n\t- Web Layer (Spring MVC)\n\t- Data Layer (JPA - Hibernate) etc..                  \n- Build a jar or a war or an ear\n- Run the application locally \n\t- Tomcat or Jetty\n- Deploy to a T environment\n- Add new dependencies to a project\n- Run Unit Tests\n- Generate Projects\n- Create Eclipse Workspace\n\n > All of this and more is made possible by Maven...\n\n\n\n### Getting Started \n- Git Repository - https://github.com/in28minutes/getting-started-in-5-steps/tree/master/maven-in-5-steps\n- Pre-requisites \n\t- Java & Eclipse - https://www.youtube.com/playlist?list=PLBBog2r6uMCSmMVTW_QmDLyASBvovyAO3\n- We will use embedded maven in Eclipse\n\n### Overview\n- Step 1 : Creating and importing a Maven Project\n- Step 2 : Understanding Project Object Model - pom.xml\n- Step 3 : Maven Build Life Cycle\n- Step 4 : How does Maven Work?\n- Step 5 : Important Maven Commands\n\n### Step 1 : Creating and importing a Maven Project\nCreating a Spring Project with Spring Initializr is a cake walk. \n\n> Spring Initializr [http://start.spring.io/](http://start.spring.io/){:target=\"_blank\"} is great tool to bootstrap your Spring Boot projects.\n\n![Image](/images/spring-initializr-spring-in-10-steps.png \"Spring Initializr\")   \n\nAs shown in the image above, following steps have to be done\n\n- Launch Spring Initializr and choose the following\n  - Choose `com.in28minutes.learning.maven` as Group\n  - Choose `maven-in-few-steps` as Artifact\n  - Choose Dependency\n    - Web\n- Click Generate Project.\n- Import the project into Eclipse.\n- If you want to understand all the files that are part of this project, you can go here.\n\n### Step 2 : Understanding the `pom.xml` Project Object Model\n\n#### Naming a project\n\nHow can other projects benefit from our project? Using the `groupId` and `artifactId` from our project\n```\n\t<groupId>com.in28minutes.learning.maven</groupId>\n\t<artifactId>maven-in-few-steps</artifactId>\n```\n\n#### Parent Pom\n\nThe same as Java Inheritance. We get a lot of things from our parents.\n\n```\n\t<parent>\n\t\t<groupId>org.springframework.boot</groupId>\n\t\t<artifactId>spring-boot-starter-parent</artifactId>\n\t\t<version>3.0.4/version>\n\t\t<relativePath/> <!-- lookup parent from repository -->\n\t</parent>\n\n```\n#### Declaration of Dependencies\n\nDependencies are frameworks required to construct your project.\n\nIn the following example, we will add two dependencies.\n```\n<dependency>\n\t<groupId>org.springframework.boot</groupId>\n\t<artifactId>spring-boot-starter-web</artifactId>\n</dependency>\n\n<dependency>\n\t<groupId>org.springframework.boot</groupId>\n\t<artifactId>spring-boot-starter-test</artifactId>\n\t<scope>test</scope>\n</dependency>\n```\n\n### Step 3 : Life Cycle Maven Build\nWhen we execute `mvn clean install` we finish the whole maven build life cycle.\n\nLifeCycle construction is a series of phases.\n - Validate\n - Compile\n - Test\n - Package\n - Integration Test\n - Verify\n - Install\n - Deploy\n\n> Maven prefers convention to configuration.\n\nPre defined folder structure\n- Source Code\n\t- ${basedir}/src/main/java\n\t- ${basedir}/src/main/resources\n- Test Code\n\t- ${basedir}/src/test\n\n### Step 4 : How does Maven Work?\n\nAll jars in the Maven Repository are indexed by `artifactid` and `group id`. \n\nWhen we add a dependence to our pom.xml, maven queries the maven repository for jar dependencies, using the group id and artefact id as input. \n- Maven repository stores all the versions of all dependencies. JUnit 4.2,4.3,4.4\n \nThe jar dependencies are saved on your system in the maven local repository folder. All of our projects would make use of the jars in the maven local repository.\n\n> Local Repository: a temporary folder on your workstation in which Maven keeps jar and dependent files obtained from the Maven Repository.\n\n### Step 5 : Important Maven Commands\n - `mvn --version`\n - `mvn compile` (compiles source files)\n - `mvn test-compile` (compiles test files) - one thing to observe is this also compiles source files\n - `mvn clean` - deletes target directory\n - `mvn test` - run unit tests\n - `mvn package` - creates the jar\n- `help:effective-settings`\n- `help:effective-pom`\n- `dependency:tree`\n- `dependency:sources`\n- `--debug`\n"
  },
  {
    "path": "_blog/articles/2017-11-17-mockito-in-5-steps.md",
    "content": "---\nlayout:     post\ntitle:      Mockito Tutorial for Beginner in 5 Steps\ndate:       2023-03-19 12:31:19\nsummary:    Mockito lesson in 5 steps for beginners. In 5 simple stages, learn the fundamentals of mocking with the most popular Java mocking framework using a simple mock example. \ncategories: SpringBootUnitTesting\npermalink:  /mockito-tutorial-for-beginners\nimage: /images/unit-test-category.png\n---\n\nMockito is the most popular Java mocking framework.\n\n\n### Git Repository \n- https://github.com/in28minutes/getting-started-in-5-steps/tree/master/mockito-in-5-steps\n\n### Pre-requisites \n- Java & Eclipse - https://www.youtube.com/playlist?list=PLBBog2r6uMCSmMVTW_QmDLyASBvovyAO3\n- JUnit - https://courses.in28minutes.com/p/junit-tutorial-for-beginners\n\n### IDE Configuration\n\nEasier Static Imports\n- Window > Preferences > Java > Editor > Content Assist > Favorites\n\t- org.junit.Assert\n\t- org.mockito.BDDMockito\n\t- org.mockito.Mockito\n\t- org.hamcrest.Matchers\n\t- org.hamcrest.CoreMatchers\n\n### Reference\n- Visit Mockito Official Documentation - http://site.mockito.org/mockito/docs/current/org/mockito/Mockito.html\n\n### Overview\n- Step 1 : Setting up an example using http://start.spring.io.\n- Step 2 : Using a Stubs - Disadvantages\n- Step 3 : Your first mock. \n- Step 4 : Using Mockito Annotations - @Mock, @InjectMocks, @RunWith(MockitoJUnitRunner.class)\n- Step 5 : Mocking List interface\n\n### Step 1 : Setting up an example using http://start.spring.io.\nCreating a Spring Project with Spring Initializr is a cake walk. \n\n> Spring Initializr [http://start.spring.io/](http://start.spring.io/){:target=\"_blank\"} is great tool to bootstrap your Spring Boot projects.\n\n![Image](/images/spring-initializr-spring-in-10-steps.png \"Spring Initializr\")   \n\nAs shown in the image above, following steps have to be done\n\n- Launch Spring Initializr and choose the following\n  - Choose `com.in28minutes.mockito` as Group\n  - Choose `mockito-demo` as Artifact\n  - Choose Dependency\n    - Web\n- Click Generate Project.\n- Import the project into Eclipse.\n- If you want to understand all the files that are part of this project, you can go here.\n\nLet's also set up a simple business class with a dependency.\n- SomeBusinessImpl depends on DataService for the data\n- findTheGreatestFromAllData has some business logic to find the greatest\n\n```java\npackage com.in28minutes.mockito.mockitodemo;\n\npublic class SomeBusinessImpl {\n\tprivate DataService dataService;\n\n\tpublic SomeBusinessImpl(DataService dataService) {\n\t\tsuper();\n\t\tthis.dataService = dataService;\n\t}\n\n\tint findTheGreatestFromAllData() {\n\t\tint[] data = dataService.retrieveAllData();\n\t\tint greatest = Integer.MIN_VALUE;\n\n\t\tfor (int value : data) {\n\t\t\tif (value > greatest) {\n\t\t\t\tgreatest = value;\n\t\t\t}\n\t\t}\n\t\treturn greatest;\n\t}\n}\n```\n\n```java\npackage com.in28minutes.mockito.mockitodemo;\n\npublic interface DataService {\n\tint[] retrieveAllData();\n}\n```\n### Step 2 : Using a Stubs - Disadvantages\n\nLet's construct a unit test for SomeBusinessImpl using a stub.\n\n```java\npackage com.in28minutes.mockito.mockitodemo;\n\nimport static org.junit.Assert.assertEquals;\n\nimport org.junit.Test;\n\npublic class SomeBusinessStubTest {\n\t@Test\n\tpublic void testFindTheGreatestFromAllData() {\n\t\tvar businessImpl = new SomeBusinessImpl(new DataServiceStub());\n\t\tint result = businessImpl.findTheGreatestFromAllData();\n\t\tassertEquals(24, result);\n\n\t}\n\n}\n\nclass DataServiceStub implements DataService {\n\t@Override\n\tpublic int[] retrieveAllData() {\n\t\treturn new int[] { 24, 6, 15 };\n\t}\n}\n```\n\nIssues with Stub\n- How can I get DataServiceStub to return various data depending on the situation?\n- The DataServiceStub implementations should be updated whenever the DataService interface is changed with new methods.\n\n### Step 3 : This is your first mock. \n\n```java\npackage com.in28minutes.mockito.mockitodemo;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.mockito.Mockito.mock;\nimport static org.mockito.Mockito.when;\n\nimport org.junit.Test;\n\npublic class SomeBusinessMockTest {\n\n\t@Test\n\tpublic void testFindTheGreatestFromAllData() {\n\t\tvar dataServiceMock = mock(DataService.class);\n\t\twhen(dataServiceMock.retrieveAllData()).thenReturn(new int[] { 24, 15, 3 });\n\t\tvar businessImpl = new SomeBusinessImpl(dataServiceMock);\n\t\tint result = businessImpl.findTheGreatestFromAllData();\n\t\tassertEquals(24, result);\n\t}\n\n\t@Test\n\tpublic void testFindTheGreatestFromAllData_ForOneValue() {\n\t\tvar dataServiceMock = mock(DataService.class);\n\t\twhen(dataServiceMock.retrieveAllData()).thenReturn(new int[] { 15 });\n\t\tvar businessImpl = new SomeBusinessImpl(dataServiceMock);\n\t\tint result = businessImpl.findTheGreatestFromAllData();\n\t\tassertEquals(15, result);\n\t}\n\n}\n```\n\nNotes\n- ```DataService dataServiceMock = mock(DataService.class)``` - We are using the mock method to create a mock.\n- ```when(dataServiceMock.retrieveAllData()).thenReturn(new int[] { 24, 15, 3 })``` - stubbing the mock to return specific data\n\n### Step 4 : @Mock, @InjectMocks, and @ExtendWith Mockito Annotations (SpringExtension.class)\n\n```java\npackage com.in28minutes.mockito.mockitodemo;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\nimport static org.mockito.Mockito.when;\n\nimport org.junit.jupiter.api.Test;\nimport org.junit.jupiter.api.extension.ExtendWith;\nimport org.mockito.InjectMocks;\nimport org.mockito.Mock;\nimport org.springframework.test.context.junit.jupiter.SpringExtension;\n\n@ExtendWith(SpringExtension.class)\npublic class SomeBusinessMockAnnotationsTest {\n\n    @Mock\n    DataService dataServiceMock;\n\n    @InjectMocks\n    SomeBusinessImpl businessImpl;\n\n    @Test\n    public void testFindTheGreatestFromAllData() {\n        when(dataServiceMock.retrieveAllData()).thenReturn(new int[]{24, 15, 3});\n        assertEquals(24, businessImpl.findTheGreatestFromAllData());\n    }\n\n    @Test\n    public void testFindTheGreatestFromAllData_ForOneValue() {\n        when(dataServiceMock.retrieveAllData()).thenReturn(new int[]{15});\n        assertEquals(15, businessImpl.findTheGreatestFromAllData());\n    }\n\n    @Test\n    public void testFindTheGreatestFromAllData_NoValues() {\n        when(dataServiceMock.retrieveAllData()).thenReturn(new int[]{});\n        assertEquals(Integer.MIN_VALUE, businessImpl.findTheGreatestFromAllData());\n    }\n}\n\n```\nNotes\n- ```@Mock DataService dataServiceMock;``` - Create a mock for DataService.\n- ```@InjectMocks SomeBusinessImpl businessImpl;``` - Inject the mocks as dependencies into businessImpl.\n- ```@ExtendWith(SpringExtension.class)``` - SpringExtension integrates the Spring TestContext Framework into JUnit 5's Jupiter programming model. To use this extension, simply annotate a JUnit Jupiter based test class with `@ExtendWith(SpringExtension.class)`\n\n### Step 5 : Mocking List interface\n\nMocking a method. Mock returns the same value on multiple calls.\n```java\n@Test\npublic void testSize() {\n\tvar listMock = mock(List.class);\n\twhen(listMock.size()).thenReturn(10);\n\tassertEquals(10, listMock.size());\n\tassertEquals(10, listMock.size());\n}\n```\n\nSetting the mock to return 10 on first call and 20 on the second call.\n```java\n@Test\npublic void testSize_multipleReturns() {\n\tvar listMock = mock(List.class);\n\twhen(listMock.size()).thenReturn(10).thenReturn(20);\n\tassertEquals(10, listMock.size());\n\tassertEquals(20, listMock.size());\n\tassertEquals(20, listMock.size());\n}\n```\n\nCustomizing the mock based on a specific parameter value.\n```java\n@Test\npublic void testGet_SpecificParameter() {\n\tvar listMock = mock(List.class);\n\twhen(listMock.get(0)).thenReturn(\"SomeString\");\n\tassertEquals(\"SomeString\", listMock.get(0));\n\tassertEquals(null, listMock.get(1));\n}\n```\n\nUsing a generic argument - Mockito.anyInt()\n```java\n@Test\npublic void testGet_GenericParameter() {\n\tvar listMock = mock(List.class);\n\twhen(listMock.get(Mockito.anyInt())).thenReturn(\"SomeString\");\n\tassertEquals(\"SomeString\", listMock.get(0));\n\tassertEquals(\"SomeString\", listMock.get(1));\n}\n```\n\n## My Course Recommendation\n\n[![Image](/images/Course-Master-Java-Unit-Testing-with-Spring-Boot-Mockito.png \"Master Java Unit Testing with Spring Boot & Mockito\")](https://links.in28minutes.com/MISC-SBT-UT)\n"
  },
  {
    "path": "_blog/articles/2017-11-18-JavaWebApplicationStepByStep-JSP-Servlets.md",
    "content": "---\nlayout:     post\ntitle:      JSP Servlets Tutorial for Beginners - Build Java Web Application in 25 Steps\ndate:       2022-10-18 12:31:19\nsummary:    In this course, you will learn the basics developing a Basic Todo Management Application using Java Servlets and JSP with Login and Logout functionalities.\ncategories: SpringFramework\npermalink:  /first-java-web-application-with-jsp-and-servlets-in-25-steps\nimage: /images/spring-boot-application.png\n---\n\nDeveloping your first Java Web Application using JSP and Servlets is fun.\n\nIn this course, you will learn the basics developing a Basic Todo Management Application using Java Servlets and JSP with Login and Logout functionalities.\n\nYou will build a Dynamic Website using the Core technologies of Java Web Programming. You will understand the basic concepts of Java Web Application Development - HTTP protocol, Request-Response cycle, Java Servlets, JSPs.\n\n[![Image](/images/Course-Java-Servlets-and-JSP-BuildJavaEEAppIn25Steps.png \"Java Servlets and JSP - Build Java EE(JEE) app in 25 Steps\")](https://www.udemy.com/course/learn-java-servlets-and-jsp-web-application-in-25-steps/)\n\n## You will learn\n- To build a Basic Todo Management Application piece by piece in 25 Steps\n- Understand Basic Web Application Architecture\n- Understand and use Basics of Java EE - Servlets, JSP, Scriptlets, JSTL, web.xml and EL\n- Understand Servlet LifeCycle\n- Use HttpRequest - GET/POST, Request Parameters\n- Understand HTTP Response - Response Status - 404,200,500 etc\n- Understand HTML Forms - Method, Action & Form Data\n- Understand Basics of using Maven, Tomcat and Eclipse\n- Understand Difference between Session and Request Scopes\n- Use Maven for Basic Dependency Management\n- Run Web Application in Tomcat\n- Style web applications with Bootstrap (Basics)\n- Use Filters to intercept Request\n\n\n\n## Step By Step Overview\n\n- Step 01 : Up and running with a Web Application in Tomcat\n- Step 02 : First JSP\n- Step 03 : Adding a Get Parameter name\n- Step 04 : Adding another Get Parameter Password\n- Step 05 : Let's add a form\n- Step 06 : New Form and doPost\n- Step 07 : Adding Password and Validation of User Id / Password combination\n- Step 08 : Adding a TodoService and Todos to welcome page\n- Step 09 : Bit of Refactoring - Packages\n- Step 10 : Redirect from One Servlet to another - New TodoServlet.\n- Step 11 : First JSTL Tag : Using a Loop around todos\n- Step 12 : Difference between Session and Request Scopes\n- Step 13 : Add a New Todo\n- Step 14 : Delete Todo with equals and hashcode methods\n- Step 15 : Adding webjars for jquery and bootstrap\n- Step 16 : Missing Step :) We want you to take a break. Nothing in here..\n- Step 17 : Updating Bootstrap to 3.3.6\n- Step 18 : More Refactoring\n- Step 19 : Adding a Filter for More Security.\n- Step 20 : Logout\n- Step 21 : Theory : Understand Maven and Tomcat\n- Step 22 : Theory : Servlet LifeCycle\n- Step 23 : Theory : Model 1 and Model 2 MVC Architectures\n- Step 24 : Moving Add Functionality to a New Page.\n- Step 25 : Add Category Field\n- Step 26 : Format the JSPs better.\n- Step 27 : JSP Fragments\n\n\n\n## Installation Guide\n\n### Installing Java, Eclipse & Embedded Maven\n\n- [Installation Video](https://www.youtube.com/playlist?list=PLBBog2r6uMCSmMVTW_QmDLyASBvovyAO3)\n- [GIT Repository For Installation](https://github.com/in28minutes/getting-started-in-5-steps)\n- [PDF](https://github.com/in28minutes/SpringIn28Minutes/blob/master/InstallationGuide-JavaEclipseAndMaven_v2.pdf)\n\n### Troubleshooting Guide\n\n- [A 50 page troubleshooting guide with more than 200 Errors and Questions answered](https://github.com/in28minutes/in28minutes-initiatives/blob/master/The-in28Minutes-TroubleshootingGuide-And-FAQ)\n\n## Step By Step Details\n\n### Step 01 : Up and running with a Web Application in Tomcat\n\nIn this step, we will quickly setup a running web application and run it in tomcat.\n\n> Tip : This is one of the rare steps where we copy code in! We want to ensure that you have a running web application without any mistakes. We will understand every line of code in the next 2 steps.\n\nCreate a Simple Maven Project and copy the three files in.\n\nYou can copy code from \n- [Step 01 on Github Repository](https://github.com/in28minutes/JavaWebApplicationStepByStep/blob/master/Step01.md)\n\nYou can run the project using Run as > Maven build > tomcat7:run.\n\n\\pom.xml\n\n```xml\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\t<groupId>com.in28minutes</groupId>\n\t<artifactId>in28Minutes-first-webapp</artifactId>\n\t<version>0.0.1-SNAPSHOT</version>\n\t<packaging>war</packaging>\n\t<dependencies>\n\t\t<dependency>\n\t\t\t<groupId>javax</groupId>\n\t\t\t<artifactId>javaee-web-api</artifactId>\n\t\t\t<version>6.0</version>\n\t\t\t<scope>provided</scope>\n\t\t</dependency>\n\t</dependencies>\n\t<build>\n\t\t<pluginManagement>\n\t\t\t<plugins>\n\t\t\t\t<plugin>\n\t\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t\t<artifactId>maven-compiler-plugin</artifactId>\n\t\t\t\t\t<version>3.2</version>\n\t\t\t\t\t<configuration>\n\t\t\t\t\t\t<verbose>true</verbose>\n\t\t\t\t\t\t<source>1.7</source>\n\t\t\t\t\t\t<target>1.7</target>\n\t\t\t\t\t\t<showWarnings>true</showWarnings>\n\t\t\t\t\t</configuration>\n\t\t\t\t</plugin>\n\t\t\t\t<plugin>\n\t\t\t\t\t<groupId>org.apache.tomcat.maven</groupId>\n\t\t\t\t\t<artifactId>tomcat7-maven-plugin</artifactId>\n\t\t\t\t\t<version>2.2</version>\n\t\t\t\t\t<configuration>\n\t\t\t\t\t\t<path>/</path>\n\t\t\t\t\t\t<contextReloadable>true</contextReloadable>\n\t\t\t\t\t</configuration>\n\t\t\t\t</plugin>\n\t\t\t</plugins>\n\t\t</pluginManagement>\n\t</build>\n</project>\n```\n\n\\src\\main\\java\\webapp\\LoginServlet.java\n\n```java\npackage webapp;\n\nimport java.io.IOException;\nimport java.io.PrintWriter;\n\nimport javax.servlet.annotation.WebServlet;\nimport javax.servlet.http.HttpServlet;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\n\n/*\n * Browser sends Http Request to Web Server\n * \n * Code in Web Server => Input:HttpRequest, Output: HttpResponse\n * JEE with Servlets\n * \n * Web Server responds with Http Response\n */\n\n\n@WebServlet(urlPatterns = \"/login.do\")\npublic class LoginServlet extends HttpServlet {\n\n\t@Override\n\tprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {\n\t\tPrintWriter out = response.getWriter();\n\t\tout.println(\"<html>\");\n\t\tout.println(\"<head>\");\n\t\tout.println(\"<title>Yahoo!!!!!!!!</title>\");\n\t\tout.println(\"</head>\");\n\t\tout.println(\"<body>\");\n\t\tout.println(\"My First Servlet\");\n\t\tout.println(\"</body>\");\n\t\tout.println(\"</html>\");\n\n\t}\n\n}\n```\n\\src\\main\\webapp\\WEB-INF\\web.xml\n```xml\n<!-- webapp/WEB-INF/web.xml -->\n<web-app xmlns=\"http://java.sun.com/xml/ns/javaee\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd\"\n\tversion=\"3.0\">\n\n\t<display-name>To do List</display-name>\n\n\t<welcome-file-list>\n\t\t<welcome-file>login.do</welcome-file>\n\t</welcome-file-list>\n\n</web-app>\n```\n### Trouble Shooting\n\nGo to http://www.in28minutes.com/spring-boot-maven-eclipse-troubleshooting-guide-and-faq for any issues that you face!\n\n### Step 01 : Theory\n\nLet's quickly look at some of the important things, we had already configured in the practical part of Step 01.\n\nMaven Tomcat Plugin (configured in pom.xml) helps us to download Tomcat and run the web application in Tomcat. ```mvn tomcat7:run``` is enabled by this plugin.\n\n```\n<plugin>\n\t<groupId>org.apache.tomcat.maven</groupId>\n\t<artifactId>tomcat7-maven-plugin</artifactId>\n\t<version>2.2</version>\n\t<configuration>\n\t\t<path>/</path>\n\t\t<contextReloadable>true</contextReloadable>\n\t</configuration>\n</plugin>\n```\n\nNotes\n- ```<contextReloadable>true</contextReloadable>``` - Enables automatic reload when java or jsp files change without needing to restart the server\n- ```<path>/</path>``` - Setting an empty context root. So, the application can be directly accessed at http://localhost:8080 without a context root\n\n\nTo create a servet, we need HttpServlet which is defined in Java EE Web API. We added a dependency in the pom.xml.\n\n```\n\t\t<dependency>\n\t\t\t<groupId>javax</groupId>\n\t\t\t<artifactId>javaee-web-api</artifactId>\n\t\t\t<version>6.0</version>\n\t\t\t<scope>provided</scope>\n\t\t</dependency>\n```\n\n\n> Servlet takes in a request and gives a response as output. HTTP is the protocol of the internet. Thats how all web applications work. For creating web applications, we extend HttpServlet which takes a HttpRequest as input and give HttpResponse as output.\n\n#### How do web applications work?\n\nOnce you have everything setup and running you would see the following page render at http://localhost:8080\nJSP-Servlets-Step-1-Theory-1\n\nHow does it really work? Let's take a quick look at what happens in the background.\n\nWhen you type in  in the browser url, the browser creates a HTTP GET Request.  Recommended Reading - [GET vs POST](https://www.w3schools.com/tags/ref_httpmethods.asp)\nJSP-Servlets-Step-1-Theory-2\n\nThe HTTP GET Request is received by the web application deployed on Tomcat server. \n\nWe have configured a welcome-file of login.do.\n\n```xml\n<welcome-file-list>\n\t<welcome-file>login.do</welcome-file>\n</welcome-file-list>\n```\n\nurlPattern of LoginServlet is \"/login.do\". We defined a ```doGet(HttpServletRequest request, HttpServletResponse response)``` method in LoginServlet. The doGet method handles the GET requests to the url pattern \"/login.do\". \n\n```java\n@WebServlet(urlPatterns = \"/login.do\")\npublic class LoginServlet extends HttpServlet {\n\n\t@Override\n\tprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {\n```\n\nIn the doGet method, we are writing HTML content into the response.\n\n```\nPrintWriter out = response.getWriter();\nout.println(\"<html>\");\nout.println(\"<head>\");\nout.println(\"<title>Yahoo!!!!!!!!</title>\");\nout.println(\"</head>\");\nout.println(\"<body>\");\nout.println(\"My First Servlet\");\nout.println(\"</body>\");\nout.println(\"</html>\");\n```\n\nThis response is sent out to the browser.\n\nJSP-Servlets-Step-1-Theory-3\n\nThe browser understands the HTML and renders a beautiful page.\n\n#### Notes\n\nJava Platform, Enterprise Edition (Java EE) JEE6\n\nServlet is a Java programming language class used to extend the capabilities of servers  that host applications accessed by means of a request-response programming model.\n\n```java\n@WebServlet(urlPatterns = \"/login.do\")\npublic class LoginServlet extends HttpServlet {\n\n\t@Override\n\tprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {\n```\n\nServlet\n- ```extends javax.servlet.http.HttpServlet``` - All servlets should extend HttpServlet class\n- ```@WebServlet(urlPatterns = \"/login.do\")``` - Provide the url pattern to access the servlet\n- ```doGet(HttpServletRequest request, HttpServletResponse response)``` - To handle the RequestMethod GET we need to implement doGet method.\n\n\n### Step 02 : First JSP\n\n[Complete code](https://github.com/in28minutes/JavaWebApplicationStepByStep/blob/master/Step02.md)\n\n#### What we will learn\n- How to create a JSP?\n- How to redirect to a JSP?\n\n#### Code Snippets and Examples\n\nCreating a JSP\n\n\\src\\main\\webapp\\WEB-INF\\views\\login.jsp\n```jsp\n<html>\n<head>\n<title>Yahoo!!</title>\n</head>\n<body>\nMy First JSP!!!\n</body>\n</html>\n```\n\nRedirect to a view - JSP\n\n\\src\\main\\java\\webapp\\LoginServlet.java\n```java\nrequest\n .getRequestDispatcher(\"/WEB-INF/views/login.jsp\")\n .forward(request, response);\n```\n\n### Step 03 : Adding a Get Parameter name\n\n[Complete code](https://github.com/in28minutes/JavaWebApplicationStepByStep/blob/master/Step03.md)\n\n#### What we will learn\n- Passing a Request Parameter \"name\"\n\n#### Code Snippets and Examples\n\nWe read the parameter from the HTTP Request. \n\nWe would want to show the value on the JSP. We set it as a request attribute.  Request attributes can be accessed from the view (jsp).\n\n\\src\\main\\java\\webapp\\LoginServlet.java\n\n```java\nrequest.setAttribute(\"name\", \n\t\trequest.getParameter(\"name\"));\n```\n\n\\src\\main\\webapp\\WEB-INF\\views\\login.jsp\n```\nMy First JSP!!! My name is ${name}\n```\n\n### Step 04 : Adding another Get Parameter Password\n\n[Complete code](https://github.com/in28minutes/JavaWebApplicationStepByStep/blob/master/Step04.md)\n\n#### Code Snippets and Examples\n\n\\src\\main\\java\\webapp\\LoginServlet.java\n```\nrequest.setAttribute(\"password\",\n                  request.getParameter(\"password\"));\n```\n\n\\src\\main\\webapp\\WEB-INF\\views\\login.jsp\n```\nMy First JSP!!! My name is ${name} and password is ${password}\n```\n\n### Step 05 : Let's add a form\n\n[Complete code](https://github.com/in28minutes/JavaWebApplicationStepByStep/blob/master/Step05.md)\n\n#### Code Snippets and Examples\n\n\\src\\main\\java\\webapp\\LoginServlet.java\n```\n@Override\nprotected void doGet(HttpServletRequest request, HttpServletResponse response)\n\t\tthrows IOException, ServletException {\n\trequest\n\t\t.getRequestDispatcher(\"/WEB-INF/views/login.jsp\")\n\t\t.forward(request, response);\n}\n```\n\n\\src\\main\\webapp\\WEB-INF\\views\\login.jsp\n```jsp\n<html>\n<head>\n<title>Yahoo!!</title>\n</head>\n<body>\n\t<form action=\"/login.do\" method=\"POST\">\n\t\tName : <input type=\"text\" /> <input type=\"submit\" />\n\t</form>\n</body>\n</html>\n```\n\n\\src\\main\\webapp\\WEB-INF\\views\\welcome.jsp\n```\n<html>\n<head>\n<title>Yahoo!!</title>\n</head>\n<body>\nWelcome ${name}\n</body>\n</html>\n```\n\n### Step 06 : New Form and doPost\n\n[Complete code](https://github.com/in28minutes/JavaWebApplicationStepByStep/blob/master/Step06.md)\n\n\\src\\main\\java\\webapp\\LoginServlet.java\n```\n@Override\nprotected void doPost(HttpServletRequest request, HttpServletResponse response)\n\t\tthrows IOException, ServletException {\n\trequest.setAttribute(\"name\", request.getParameter(\"name\"));\n\trequest.getRequestDispatcher(\"/WEB-INF/views/welcome.jsp\").forward(request, response);\n}\n```\n\n\\src\\main\\webapp\\WEB-INF\\views\\welcome.jsp\n```\n<html>\n<head>\n<title>Yahoo!!</title>\n</head>\n<body>\nWelcome ${name}\n</body>\n</html>\n```\n\n### Step 07 : Adding Password and Validation of User Id\n\n[Complete code](https://github.com/in28minutes/JavaWebApplicationStepByStep/blob/master/Step07.md)\n\n#### Code Snippets and Examples\n\n\\src\\main\\java\\webapp\\LoginService.java\n```\npublic class LoginService {\n\tpublic boolean validateUser(String user, String password) {\n\t\treturn user.equalsIgnoreCase(\"in28Minutes\") && password.equals(\"dummy\");\n\t}\n\n}\n```\n\n\\src\\main\\java\\webapp\\LoginServlet.java\n```\n@Override\nprotected void doPost(HttpServletRequest request, HttpServletResponse response)\n\t\tthrows IOException, ServletException {\n\tString name = request.getParameter(\"name\");\n\tString password = request.getParameter(\"password\");\n\n\tboolean isValidUser = service.validateUser(name, password);\n\n\tif (isValidUser) {\n\t\trequest.setAttribute(\"name\", name);\n\t\trequest.getRequestDispatcher(\"/WEB-INF/views/welcome.jsp\")\n\t\t\t\t.forward(request, response);\n\t} else {\n\t\trequest.setAttribute(\"errorMessage\", \"Invalid Credentials!!\");\n\t\trequest.getRequestDispatcher(\"/WEB-INF/views/login.jsp\")\n\t\t\t\t.forward(request, response);\n\t}\n}\n```\n\n\\src\\main\\webapp\\WEB-INF\\views\\login.jsp\n```\n<html>\n<head>\n<title>Yahoo!!</title>\n</head>\n<body>\n\t<p><font color=\"red\">${errorMessage}</font></p>\n\t<form action=\"/login.do\" method=\"POST\">\n\t\tName : <input name=\"name\" type=\"text\" /> Password : <input name=\"password\" type=\"password\" /> <input type=\"submit\" />\n\t</form>\n</body>\n</html>\n```\n\n### Step 08 : Adding a TodoService and Todos to welcome page\n\n\n[Complete code](https://github.com/in28minutes/JavaWebApplicationStepByStep/blob/master/Step08.md)\n\n#### Code Snippets and Examples\n\n\\src\\main\\java\\webapp\\LoginServlet.java\n```\nprivate LoginService service = new LoginService();\nprivate TodoService todoService = new TodoService();\n\n@Override\nprotected void doPost(HttpServletRequest request, HttpServletResponse response)\n\t\tthrows IOException, ServletException {\n\tString name = request.getParameter(\"name\");\n\tString password = request.getParameter(\"password\");\n\n\tboolean isValidUser = service.validateUser(name, password);\n\n\tif (isValidUser) {\n\t\trequest.setAttribute(\"name\", name);\n\t\trequest.setAttribute(\"todos\", \n\t\t\t\ttodoService.retrieveTodos());\n\t\trequest.getRequestDispatcher(\"/WEB-INF/views/welcome.jsp\").forward(request, response);\n\t} else {\n\t\trequest.setAttribute(\"errorMessage\", \"Invalid Credentials!!\");\n\t\trequest.getRequestDispatcher(\"/WEB-INF/views/login.jsp\").forward(request, response);\n\t}\n}\n\n```\n\n\\src\\main\\java\\webapp\\todo\\Todo.java\n```\npublic class Todo {\n\n\tpublic Todo(String name) {\n\t\tsuper();\n\t\tthis.name = name;\n\t}\n\n\tprivate String name;\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Todo [name=\" + name + \"]\";\n\t}\n}\n```\n\n\\src\\main\\java\\webapp\\todo\\TodoService.java\n```\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class TodoService {\n\tprivate static List<Todo> todos = new ArrayList();\n\n\tstatic {\n\t\ttodos.add(new Todo(\"Learn Web Application\"));\n\t\ttodos.add(new Todo(\"Learn Spring\"));\n\t\ttodos.add(new Todo(\"Learn Spring MVC\"));\n\t}\n\n\tpublic List<Todo> retrieveTodos() {\n\t\treturn todos;\n\t}\n}\n```\n\n\\src\\main\\webapp\\WEB-INF\\views\\welcome.jsp\n```\n<html>\n<head>\n<title>Yahoo!!</title>\n</head>\n<body>\n<H1>Welcome ${name}</H2>\n<div>\nYour Todos are\n${todos}\n</div>\n</body>\n</html>\n```\n### Step 09 : Bit of Refactoring - Packages\n\nBasic Refactoring\n\n[Complete code](https://github.com/in28minutes/JavaWebApplicationStepByStep/blob/master/Step09.md)\n\n### Step 10 : Redirect from One Servlet to another - New TodoServlet.\n\n\n[Complete code](https://github.com/in28minutes/JavaWebApplicationStepByStep/blob/master/Step10.md)\n\n#### Code Snippets and Examples\n\nsrc\\main\\java\\in28minutes\\login\\LoginServlet.java\n```\n@Override\nprotected void doPost(HttpServletRequest request, HttpServletResponse response)\n\t\tthrows IOException, ServletException {\n\tString name = request.getParameter(\"name\");\n\tString password = request.getParameter(\"password\");\n\n\tboolean isValidUser = service.validateUser(name, password);\n\n\tif (isValidUser) {\n\t\tresponse.sendRedirect(\"/todo.do\");\n\t} else {\n\t\trequest.setAttribute(\"errorMessage\", \"Invalid Credentials!!\");\n\t\trequest.getRequestDispatcher(\"/WEB-INF/views/login.jsp\").forward(request, response);\n\t}\n}\n\n```\n\nsrc\\main\\java\\in28minutes\\todo\\TodoServlet.java\n```\n\n@WebServlet(urlPatterns = \"/todo.do\")\npublic class TodoServlet extends HttpServlet {\n\n\tprivate static final long serialVersionUID = 1L;\n\tprivate TodoService todoService = new TodoService();\n\n\t@Override\n\tprotected void doGet(HttpServletRequest request, HttpServletResponse response)\n\t\t\tthrows IOException, ServletException {\n\t\trequest.setAttribute(\"todos\", todoService.retrieveTodos());\n\t\trequest.getRequestDispatcher(\"/WEB-INF/views/todo.jsp\").forward(request, response);\n\t}\n}\n```\n\nsrc\\main\\webapp\\WEB-INF\\views\\todo.jsp\n```\n<html>\n<head>\n<title>Yahoo!!</title>\n</head>\n<body>\n<H1>Welcome ${name}</H2>\n<div>\nYour Todos are\n${todos}\n</div>\n</body>\n</html>\n```\n### Step 11 : First JSTL Tag : Using a Loop around todos\n\n[Complete code](https://github.com/in28minutes/JavaWebApplicationStepByStep/blob/master/Step11.md)\n\n#### Code Snippets and Examples\n\npom.xml\n```\n        <dependency>\n            <groupId>javax.servlet</groupId>\n            <artifactId>jstl</artifactId>\n            <version>1.2</version>\n        </dependency>\n```\n\nsrc\\main\\webapp\\WEB-INF\\views\\todo.jsp\n```\n<%@ taglib uri=\"http://java.sun.com/jsp/jstl/core\" prefix=\"c\" %>\n<html>\n<head>\n<title>Yahoo!!</title>\n</head>\n<body>\n<H1>Welcome ${name}</H2>\n<div>\nYour Todos are\n<ol>\n<c:forEach items=\"${todos}\" var=\"todo\">\n   <li>${todo.name}</li>\n</c:forEach>\n</ol>\n</div>\n</body>\n</html>\n```\n### Step 12 : Difference between Session and Request Scopes\n\n- Session Scope \n\t- Valid for the entire session of a user. \n\t- Data in session can be shared between multiple requests from the same user.\n- Request Scope\n\t- Only valid for the duration of the HTTPRequest\n\n> Recommendation : Keep number of objects in a session to a bare minimum.\n\n> Recommendation : Clean up objects in session when they are not needed anymore.\n\n### Step 13 : Add a New Todo\n\n[Complete code](https://github.com/in28minutes/JavaWebApplicationStepByStep/blob/master/Step13.md)\n\n#### Code Snippets and Examples\n\nsrc\\main\\java\\in28minutes\\todo\\TodoService.java\n\n```\npublic void addTodo(String todo) {\n\ttodos.add(new Todo(todo));\n}\n```\n\nsrc\\main\\java\\in28minutes\\todo\\TodoServlet.java\n```\n\n@Override\nprotected void doPost(HttpServletRequest request, HttpServletResponse response)\n\t\tthrows IOException, ServletException {\n\tString todo = request.getParameter(\"todo\");\n\tif (\"\".equals(todo)) {\n\t\trequest.setAttribute(\"errorMessage\", \"Enter a valid todo\");\n\t} else {\n\t\ttodoService.addTodo(todo);\n\t}\n\trequest.setAttribute(\"todos\", todoService.retrieveTodos());\n\trequest.getRequestDispatcher(\"/WEB-INF/views/todo.jsp\").forward(request, response);\n}\n\n```\n\nsrc\\main\\webapp\\WEB-INF\\views\\todo.jsp\n```\n<%@ taglib uri=\"http://java.sun.com/jsp/jstl/core\" prefix=\"c\" %>\n<html>\n<head>\n<title>Yahoo!!</title>\n</head>\n<body>\n<H1>Welcome ${name}</H2>\n<div>\nYour Todos are\n<ol>\n<c:forEach items=\"${todos}\" var=\"todo\">\n   <li>${todo.name}</li>\n</c:forEach>\n</ol>\n\n<p><font color=\"red\">${errorMessage}</font></p>\n<form method=\"POST\" action=\"/todo.do\">\nNew Todo : <input name=\"todo\" type=\"text\" /> <input name=\"add\" type=\"submit\" />\n</form>\n\n</div>\n</body>\n</html>\n```\n\n### Step 14 : Delete Todo with equals and hashcode methods\n\n[Complete code](https://github.com/in28minutes/JavaWebApplicationStepByStep/blob/master/Step14.md)\n\n#### Code Snippets and Examples\n\nsrc\\main\\java\\in28minutes\\todo\\DeleteTodoServlet.java\n```\n@WebServlet(urlPatterns = \"/delete-todo.do\")\npublic class DeleteTodoServlet extends HttpServlet {\n\n\tprivate static final long serialVersionUID = 1L;\n\tprivate TodoService todoService = new TodoService();\n\n\t@Override\n\tprotected void doGet(HttpServletRequest request, HttpServletResponse response)\n\t\t\tthrows IOException, ServletException {\n\t\ttodoService.deleteTodo(request.getParameter(\"todo\"));\n\t\tresponse.sendRedirect(\"/todo.do\");\n\t}\n}\n```\n\nsrc\\main\\java\\in28minutes\\todo\\TodoService.java\n```\npublic void deleteTodo(String todo) {\n\ttodos.remove(new Todo(todo));\n}\n```\n\nsrc\\main\\webapp\\WEB-INF\\views\\todo.jsp\n```\n<%@ taglib uri=\"http://java.sun.com/jsp/jstl/core\" prefix=\"c\" %>\n<html>\n<head>\n<title>Yahoo!!</title>\n</head>\n<body>\n<H1>Welcome ${name}</H2>\n<div>\nYour Todos are\n<ol>\n<c:forEach items=\"${todos}\" var=\"todo\">\n   <li>${todo.name} <a href=\"/deletetodo.do?todo=${todo.name}\">Delete</a></li> \n</c:forEach>\n</ol>\n\n<p><font color=\"red\">${errorMessage}</font></p>\n<form method=\"POST\" action=\"/todo.do\">\nNew Todo : <input name=\"todo\" type=\"text\" /> <input name=\"add\" type=\"submit\" />\n</form>\n</div>\n</body>\n</html>\n```\n\n### Step 15 : Adding webjars for jquery and bootstrap\n\n[Complete code](https://github.com/in28minutes/JavaWebApplicationStepByStep/blob/master/Step15.md)\n\n#### Code Snippets and Examples\n\npom.xml\n\n```\n<dependency>\n\t<groupId>org.webjars</groupId>\n\t<artifactId>bootstrap</artifactId>\n\t<version>3.3.6</version>\n</dependency>\n<dependency>\n\t<groupId>org.webjars</groupId>\n\t<artifactId>jquery</artifactId>\n\t<version>1.9.1</version>\n</dependency>\n```\n\nsrc\\main\\webapp\\WEB-INF\\views\\todo.jsp\n```\n<%@ taglib uri=\"http://java.sun.com/jsp/jstl/core\" prefix=\"c\"%>\n<!DOCTYPE html>\n<html>\n<head>\n<title>Yahoo!!</title>\n<!-- Bootstrap core CSS -->\n<link href=\"webjars/bootstrap/3.3.6/css/bootstrap.min.css\"\n\trel=\"stylesheet\">\n</head>\n<body>\n\t<H1>Welcome ${name}</H1>\n\t<div>\n\t\tYour Todos are\n\t\t<ol>\n\t\t\t<c:forEach items=\"${todos}\" var=\"todo\">\n\t\t\t\t<li>${todo.name} <a href=\"/deletetodo.do?todo=${todo.name}\">Delete</a></li>\n\t\t\t</c:forEach>\n\t\t</ol>\n\n\t\t<p>\n\t\t\t<font color=\"red\">${errorMessage}</font>\n\t\t</p>\n\t\t<form method=\"POST\" action=\"/todo.do\">\n\t\t\tNew Todo : <input name=\"todo\" type=\"text\" /> <input name=\"add\"\n\t\t\t\ttype=\"submit\" />\n\t\t</form>\n\t</div>\n\t<script src=\"webjars/jquery/1.9.1/jquery.min.js\"></script>\n\t<script src=\"webjars/bootstrap/3.3.6/js/bootstrap.min.js\"></script>\n</body>\n</html>\n```\n\n### Step 16 : Missing Step :) \n\nWe want you to take a break. Nothing in here..\n\n### Step 17 : Updating Bootstrap to 3.3.6\n\n- Let's use Bootstrap to make our todo's look better.\n- We will make improvements to reduce duplication in next steps.\n\n[Complete code](https://github.com/in28minutes/JavaWebApplicationStepByStep/blob/master/Step17.md)\n\n#### Code Snippets and Examples\n\nBootstrap Sample Page\n```\n<%@ taglib uri=\"http://java.sun.com/jsp/jstl/core\" prefix=\"c\"%>\n<!DOCTYPE html>\n<html>\n<head>\n<title>Todos</title>\n<link href=\"webjars/bootstrap/3.3.6/css/bootstrap.min.css\"\n\trel=\"stylesheet\">\n\n<style>\n\t.footer {\n\t\tposition: absolute;\n\t\tbottom: 0;\n\t\twidth: 100%;\n\t\theight: 60px;\n\t\tbackground-color: #f5f5f5;\n\t}\n</style>\n</head>\n\n<body>\n\n\t<nav class=\"navbar navbar-default\">\n\n\t\t<a href=\"/\" class=\"navbar-brand\">Brand</a>\n\n\t\t<ul class=\"nav navbar-nav\">\n\t\t\t<li class=\"active\"><a href=\"#\">Home</a></li>\n\t\t\t<li><a href=\"/todo.do\">Todos</a></li>\n\t\t\t<li><a href=\"http://www.in28minutes.com\">In28Minutes</a></li>\n\t\t</ul>\n\n\t\t<ul class=\"nav navbar-nav navbar-right\">\n\t\t\t<li><a href=\"/login.do\">Login</a></li>\n\t\t</ul>\n\n\t</nav>\n\n\t<div class=\"container\">\n\t\t<H1>Heading</H1>\n\t\tBody of the Page\n\t</div>\n\n\t<footer class=\"footer\">\n\t\t<p>footer content</p>\n\t</footer>\n\n\t<script src=\"webjars/jquery/1.9.1/jquery.min.js\"></script>\n\t<script src=\"webjars/bootstrap/3.3.6/js/bootstrap.min.js\"></script>\n\n</body>\n\n</html>\n```\n\nsrc\\main\\webapp\\WEB-INF\\views\\todo.jsp\n```\n<%@ taglib uri=\"http://java.sun.com/jsp/jstl/core\" prefix=\"c\"%>\n\n<!DOCTYPE html>\n<html>\n\n<head>\n<title>Yahoo!!</title>\n<!-- Bootstrap core CSS -->\n<link href=\"webjars/bootstrap/3.3.6/css/bootstrap.min.css\"\n\trel=\"stylesheet\">\n\n<style>\n.footer {\n\tposition: absolute;\n\tbottom: 0;\n\twidth: 100%;\n\theight: 60px;\n\tbackground-color: #f5f5f5;\n}\n\n.footer .container {\nwidth: auto;\nmax-width: 680px;\npadding: 0 15px;\n}\n</style>\n</head>\n\n<body>\n\n\t<nav role=\"navigation\" class=\"navbar navbar-default\">\n\n\t\t<div class=\"\">\n\t\t\t<a href=\"/\" class=\"navbar-brand\">Brand</a>\n\t\t</div>\n\n\t\t<div class=\"navbar-collapse\">\n\t\t\t<ul class=\"nav navbar-nav\">\n\t\t\t\t<li class=\"active\"><a href=\"#\">Home</a></li>\n\t\t\t\t<li><a href=\"/todo.do\">Todos</a></li>\n\t\t\t\t<li><a href=\"http://www.in28minutes.com\">In28Minutes</a></li>\n\t\t\t</ul>\n\t\t\t<ul class=\"nav navbar-nav navbar-right\">\n\t\t\t\t<li><a href=\"/login.do\">Login</a></li>\n\t\t\t</ul>\n\t\t</div>\n\n\t</nav>\n\n\t<div class=\"container\">\n\t\t<H1>Welcome ${name}</H1>\n\n\t\tYour Todos are\n\t\t<ol>\n\t\t\t<c:forEach items=\"${todos}\" var=\"todo\">\n\t\t\t\t<li>${todo.name}&nbsp;<a\n\t\t\t\t\thref=\"/deletetodo.do?todo=${todo.name}\">Delete</a></li>\n\t\t\t</c:forEach>\n\t\t</ol>\n\n\t\t<p>\n\t\t\t<font color=\"red\">${errorMessage}</font>\n\t\t</p>\n\t\t<form method=\"POST\" action=\"/todo.do\">\n\t\t\tNew Todo : <input name=\"todo\" type=\"text\" /> <input name=\"add\"\n\t\t\t\ttype=\"submit\" />\n\t\t</form>\n\t</div>\n\n\t<footer class=\"footer\">\n\t\t<div class=\"container\">\n\t\t\t<p>footer content</p>\n\t\t</div>\n\t</footer>\n\n\t<script src=\"webjars/jquery/1.9.1/jquery.min.js\"></script>\n\t<script src=\"webjars/bootstrap/3.3.6/js/bootstrap.min.js\"></script>\n\n</body>\n\n</html>\n```\n\n\n### Step 18 : More Refactoring\n\n> The Boy Scouts have a rule: \"Always leave the campground cleaner than you found it.\" \n\nLet's follow the boy scout rule by refactoring a little bit.\n\n### Step 19 : Adding a Filter for More Security.\n\nLets ensure that a user cannot get to todo's page without logging in!\n\nWe do that by adding in a Filter to intercept all requests matching the pattern *.do.\n\n#### Code Snippets and Examples\n\n### src/main/java/com/in28minutes/filter/LoginRequiredFilter.java\n```\npackage com.in28minutes.filter;\n\nimport java.io.IOException;\n\nimport javax.servlet.Filter;\nimport javax.servlet.FilterChain;\nimport javax.servlet.FilterConfig;\nimport javax.servlet.ServletException;\nimport javax.servlet.ServletRequest;\nimport javax.servlet.ServletResponse;\nimport javax.servlet.annotation.WebFilter;\nimport javax.servlet.http.HttpServletRequest;\n\n@WebFilter(urlPatterns = \"*.do\")\npublic class LoginRequiredFilter implements Filter {\n\n\t@Override\n\tpublic void destroy() {\n\n\t}\n\n\t@Override\n\tpublic void doFilter(ServletRequest servletRequest,\n\t\t\tServletResponse servletResponse, FilterChain chain)\n\t\t\tthrows IOException, ServletException {\n\t\tHttpServletRequest request = (HttpServletRequest) servletRequest;\n\n\t\tif (request.getSession().getAttribute(\"name\") != null) {\n\t\t\tchain.doFilter(servletRequest, servletResponse);\n\t\t} else {\n\t\t\trequest.getRequestDispatcher(\"/login.do\").forward(servletRequest,\n\t\t\t\t\tservletResponse);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void init(FilterConfig arg0) throws ServletException {\n\t}\n\n}\n```\n### Step 20 : Logout\n\n- What's the use of an application without a logout?\n\t- Add logout link to the todo page\n\t- Add a Logout Servlet to handle the request\n\n#### Code Snippets and Examples\n\n### src/main/java/com/in28minutes/logout/LogoutServlet.java\n\n```\npackage com.in28minutes.logout;\n\nimport java.io.IOException;\n\nimport javax.servlet.ServletException;\nimport javax.servlet.annotation.WebServlet;\nimport javax.servlet.http.HttpServlet;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\n\n@WebServlet(urlPatterns = \"/logout.do\")\npublic class LogoutServlet extends HttpServlet {\n\tprotected void doGet(HttpServletRequest request,\n\t\t\tHttpServletResponse response) throws ServletException, IOException {\n\t\trequest.getSession().invalidate();\n\t\trequest.getRequestDispatcher(\"/WEB-INF/views/login.jsp\").forward(\n\t\t\t\trequest, response);\n\t}\n}\n```\n\n### src/main/webapp/WEB-INF/views/todo.jsp\n\n```\n<nav class=\"navbar navbar-default\">\n\n\t<a href=\"/\" class=\"navbar-brand\">Brand</a>\n\n\t<ul class=\"nav navbar-nav\">\n\t\t<li class=\"active\"><a href=\"#\">Home</a></li>\n\t\t<li><a href=\"/todo.do\">Todos</a></li>\n\t\t<li><a href=\"http://www.in28minutes.com\">In28Minutes</a></li>\n\t</ul>\n\n\t<ul class=\"nav navbar-nav navbar-right\">\n\t\t<li><a href=\"/logout.do\">Logout</a></li>\n\t</ul>\n\n</nav>\n```\n\n### Step 21 : Theory : Understand Maven and Tomcat\n\nMaven is used to manage libraries/dependencies. You don't need to manually download the jars and build the project. Maven does that for you\n- [You can read more about Maven here] (https://github.com/in28minutes/in28minutes-initiatives/tree/master/The-in28Minutes-TroubleshootingGuide-And-FAQ#maven)\n\nWe download Tomcat server using a Maven plugin and deploy the application war to the tomcat server. So, you would not need to install tomcat manually!\n\n### Step 22 : Theory : Servlet LifeCycle\n\nHttpServlet methods\n- init() method \n\t* called only once. \n- service() method\n\t* called once per servlet invocation\n\t* looks at the request method and call the appropriate method - doPost, doGet etc\n- destroy() method\n\t* called only once \n\t* when the application is brought down\n\nJSPs are also servlets. They have all the 3 methods shown above.\n\n### Step 23 : Theory : Model 1 and Model 2 MVC Architectures\n\nModel 1 Architecture \n- JSP\n\t- JSP do everything.\n\t- Very complex to maintain.\n\nModel 2 Architecture \n- Servlet\n\t- Controller \n\t\t- Control the flow. \n\t\t- Decides which view to show and what model is needed to display the view.\n- JSP\n\t- View - Displays the model\n- Model\n\t- Todo\n\nFront Controller\n- One Controller handles all the requests\n\t- It would route the requests to other servlets\n\t- Spring MVC\n\t\t- Dispatcher Servlet\n\n### Step 24 : Moving Add Functionality to a New Page.\n\n> The Boy Scouts have a rule: \"Always leave the campground cleaner than you found it.\" \n\nLet's follow the boy scout rule by refactoring a little bit.\n\n### Step 25 : Add Category Field\n\nLet's add a category field to the todo page\n- We will start with add category to model Todo\n- We would need to add it to servlets and jsp pages\n\n[Complete code](https://github.com/in28minutes/JavaWebApplicationStepByStep/blob/master/Step27.md)\n\n#### Code Snippets and Examples\n\n### src/main/java/com/in28minutes/todo/AddTodoServlet.java\n```\nprotected void doPost(HttpServletRequest request,\n\t\tHttpServletResponse response) throws ServletException, IOException {\n\tString newTodo = request.getParameter(\"todo\");\n\tString category = request.getParameter(\"category\");\n\ttodoService.addTodo(new Todo(newTodo, category));\n\tresponse.sendRedirect(\"/list-todos.do\");\n}\n```\n\n### src/main/java/com/in28minutes/todo/DeleteTodoServlet.java\n```\nprotected void doGet(HttpServletRequest request,\n\t\tHttpServletResponse response) throws ServletException, IOException {\n\ttodoService.deleteTodo(new Todo(request.getParameter(\"todo\"), request\n\t\t\t.getParameter(\"category\")));\n\tresponse.sendRedirect(\"/list-todos.do\");\n}\n```\n\n### src/main/java/com/in28minutes/todo/Todo.java\n\n```\npackage com.in28minutes.todo;\n\npublic class Todo {\n\tprivate String name;\n\tprivate String category;\n\n\tpublic Todo(String name, String category) {\n\t\tsuper();\n\t\tthis.name = name;\n\t\tthis.category = category;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic String getCategory() {\n\t\treturn category;\n\t}\n\n\tpublic void setCategory(String category) {\n\t\tthis.category = category;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn String.format(\"Todo [name=%s, category=%s]\", name, category);\n\t}\n\n\t//hashcode and equals\n\n}\n```\n\n### src/main/java/com/in28minutes/todo/TodoService.java\n\n```\npackage com.in28minutes.todo;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class TodoService {\n\tprivate static List<Todo> todos = new ArrayList<Todo>();\n\tstatic {\n\t\ttodos.add(new Todo(\"Learn Web Application Development\", \"Study\"));\n\t\ttodos.add(new Todo(\"Learn Spring MVC\", \"Study\"));\n\t\ttodos.add(new Todo(\"Learn Spring Rest Services\", \"Study\"));\n\t}\n\n\tpublic List<Todo> retrieveTodos() {\n\t\treturn todos;\n\t}\n\n\tpublic void addTodo(Todo todo) {\n\t\ttodos.add(todo);\n\t}\n\n\tpublic void deleteTodo(Todo todo) {\n\t\ttodos.remove(todo);\n\t}\n\n}\n```\n\n### src/main/webapp/WEB-INF/views/add-todo.jsp\n```\n<div class=\"container\">\n\tYour New Action Item:\n\t<form method=\"POST\" action=\"/add-todo.do\">\n\t\tDescription : <input name=\"todo\" type=\"text\" /> <BR/> \n\t\tCategory : <input name=\"category\" type=\"text\" /> <BR/>\n\t\t<input name=\"add\"\n\t\t\ttype=\"submit\" />\n\t</form>\n</div>\n```\n\n### src/main/webapp/WEB-INF/views/list-todos.jsp\n```\n<ol>\n\t<c:forEach items=\"${todos}\" var=\"todo\">\n\t\t<li>${todo.name}&nbsp;${todo.category}&nbsp;<a\n\t\t\thref=\"/delete-todo.do?todo=${todo.name}&category=${todo.category}\">Delete</a></li>\n\t</c:forEach>\n</ol>\n```\n\n### Step 26 : Format the JSPs better.\n\n> The Boy Scouts have a rule: \"Always leave the campground cleaner than you found it.\" \n\nLet's follow the boy scout rule by refactoring a little bit.\n\n### Step 27 : JSP Fragments\n\n[Complete code](https://github.com/in28minutes/JavaWebApplicationStepByStep/blob/master/Step27.md)\n"
  },
  {
    "path": "_blog/articles/2017-12-01-spring-boot-and-jpa-hibernate-with-h2-top20.md",
    "content": "---\nlayout:     post\ntitle:      Integrating Hibernate and JPA with Spring Boot\ndate:       2023-03-20 07:55:19\nsummary:    Discover how to connect Spring Boot to H2 (in memory database) with Hibernate/JPA by utilising Spring Boot Starter JPA. The fundamentals of JPA and Hibernate - Entities and Keys - will be covered. We will create a simple repository extending JPARepository and explore different methods it exposes.\ncategories:  SpringBootJPA\npermalink:  /hibernate-jpa-tutorial-with-spring-boot-starter-jpa\nimage: /images/spring-data-category.png\n---\n\n![Image](/images/spring-initializer-web-h2-devtools-jpa.png)\n\nThis post will show you how to establish a simple Spring Boot project and connect to a database using Hibernate/JPA. Spring Boot Starter JPA and the in-memory database H2 will be used.\n\n![Image](/images/JPA_02_Architecture.png \"JPA Architecuture\")\n \n## You will learn\n- Basics of JPA/Hibernate\n- How to create a project using Spring Boot, Spring Boot Starter JPA and H2?\n- How to use Spring Boot Starter JPA?\n- How to connect a Spring Boot project to database using JPA/Hibernate?\n- How to create a simple JPA Entity with a primary key?\n- How to write a simple repository interface extending JpaRepository interface?\n- What are the basics of an in memory database?\n\n## Spring Boot and Hibernate Course\n\n[![Image](/images/Course-Master-Hibernate-and-JPA-with-Spring-Boot-in-100-Steps.png \"Master Hibernate and JPA with Spring Boot in 100 Steps\")](https://links.in28minutes.com/MISC-JPA){:target=\"_blank\"}\n\n\n## Structure of the Project Code\n\nThe screenshot below depicts the framework of the project we will be creating.\n\n![Image](/images/SpringBootwithJPA-ProjectStructure.png \"Spring Boot with JPA - Project Structure\") \n\nA few specifics:\n\n- `Student.java` - Entity bean to store student details.\n- `StudentRepository.java` - Extends JpaRepository. Acts as a repository to update/retrieve Student entities.\n- `data.sql` - We use data.sql to populate the initial student data.\n- SpringBoot2JPAWithHibernateAndH2Application.java - The main Spring Boot Application class which is used to launch up the application. We will extend `CommandLineRunner` interface and implement `public void run(String... args)` method to launch the spring jpa repository methods when the server launches up.\n- `pom.xml` - Contains all the dependencies needed to build this project. We will use Spring Boot Starter JPA and Web other than Developer Tools and H2 as in memory database.\n\n## Tools you will need\n- Maven 3.0+ is your build tool\n- Your favorite IDE. We use Eclipse or IntelliJ.\n- JDK 17+\n\n## Maven Project Completion using Code Samples\n> Our Github repository has all the code examples - https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-2-jpa-with-hibernate-and-h2\n\n\n## How Does JPA/Hibernate Function?\n\nTables/Relations are used to design databases. OOPS is used to develop Java objects. We'd want to save data from objects to tables and vice versa.\n\nPrevious techniques required the creation of SQL Queries. Popular techniques included JDBC, Spring JDBC, and myBatis.\n\nJPA, on the other hand, arose as a result of a different conceptual process. \n\n> What about mapping the objects to tables/relationships directly?\n \nORM - Object Relational Mapping - is another name for this mapping. Prior to JPA, these frameworks were more generally referred to as ORM. It is one of the reasons Hibernate is referred to as an ORM framework.\n\n## Key JPA Concepts\n\n![Image](/images/JPA_02_Architecture.png \"JPA Architecuture\")\n\nJPA allows to map application classes to tables in database.\n- `Entity Manager` - Entity manager may manage your entities after the mappings are defined. Entity Manager manages all database interactions.\n- `JPQL (Java Persistence Query Language)` - Offers methods for writing queries to do entity searches. It is critical to recognise that these are not SQL queries. JPQL queries are already aware of the mappings that exist between entities. More criteria can be added as needed.\n- `Criteria API` specifies a Java-based API for doing database searches.\n\n## Choosing between JPA and Hibernate\n\nOne of the most popular ORM frameworks is Hibernate.\n\nThe specification is defined by JPA. It is a programming interface.\n - How do you define entities?\n - How do you map attributes?\n - How do you map relationships between entities?\n - Who manages the entities?\n\nHibernate is a well-known JPA implementation.\n - Hibernate recognises the mappings we create between objects and tables. It guarantees that data is stored and retrieved from the database in accordance with the mappings.\n - Hibernate extends JPA with extra functionality. But, relying on them would bind you to Hibernate. You cannot switch to another JPA implementation, such as Toplink.\n\n## Spring Initializr is used to create a project.\n\nSpring Initializr [http://start.spring.io/](http://start.spring.io/){:target=\"_blank\"} is great tool to bootstrap your Spring Boot projects.\n\n![Image](/images/spring-initializer-web-h2-devtools-jpa.png \"Web, JPA, H2 and Developer Tools\")\n\nAs shown in the image above, following steps have to be done\n\n- Launch Spring Initializr and choose the following\n  - Choose `com.in28minutes.springboot.rest.example` as Group\n  - Choose `spring-boot-2-jpa-with-hibernate-and-h2` as Artifact\n  - Choose following dependencies\n    - Web\n    - JPA\n    - H2\n    - DevTools\n- Click Generate Project.\n- Import the project into Eclipse. File -> Import -> Existing Maven Project.\n\n## Starter Projects in pom.xml\n\nBelow is the list of starter projects in pom.xml. \n\n```\n\t\t<dependency>\n\t\t\t<groupId>org.springframework.boot</groupId>\n\t\t\t<artifactId>spring-boot-starter-jpa</artifactId>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.springframework.boot</groupId>\n\t\t\t<artifactId>spring-boot-starter-web</artifactId>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>org.springframework.boot</groupId>\n\t\t\t<artifactId>spring-boot-devtools</artifactId>\n\t\t\t<scope>runtime</scope>\n\t\t</dependency>\n\t\t\n\t\t<dependency>\n\t\t\t<groupId>com.h2database</groupId>\n\t\t\t<artifactId>h2</artifactId>\n\t\t\t<scope>runtime</scope>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.springframework.boot</groupId>\n\t\t\t<artifactId>spring-boot-starter-test</artifactId>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n```\n\n## Understanding Spring Boot Starter JPA\n\nBelow picture highlights some of the dependencies that are part of the imported JPA project.\n\n![Image](/images/spring-boot-starter-jpa-dependencies.png \"Spring Boot Starter JPA Dependencies\")\n\n> Key Question : How did all these dependencies come in?\n\nSpring-boot-starter-jpa defines all of these dependencies. We obtain the following functionalities from a wide range of dependencies as soon as we include Spring Boot Starter JPA in our project (pom.xml).\n- AOP\n- Transaction Management\n- JPA API\n- JPA Implementation - Default Hibernate\n- JDBC\n\nExtract below shows some code from pom.xml of spring-boot-starter-jpa.\n```\n<dependency>\n  <groupId>org.springframework.boot</groupId>\n  <artifactId>spring-boot-starter-aop</artifactId>\n  <version>3.0.4</version>\n  <scope>compile</scope>\n</dependency>\n<dependency>\n  <groupId>org.springframework.boot</groupId>\n  <artifactId>spring-boot-starter-jdbc</artifactId>\n  <version>3.0.4</version>\n  <scope>compile</scope>\n</dependency>\n<dependency>\n  <groupId>org.springframework.boot</groupId>\n  <artifactId>spring-boot-starter-jdbc</artifactId>\n  <version>3.0.4</version>\n   <scope>compile</scope>\n</dependency>\n<dependency>\n  <groupId>org.hibernate.orm</groupId>\n  <artifactId>hibernate-core</artifactId>\n  <version>6.1.7.Final</version>\n  <scope>compile</scope>\n</dependency>\n<dependency>\n   <groupId>org.springframework.data</groupId>\n   <artifactId>spring-data-jpa</artifactId>\n   <version>3.0.3</version>\n   <scope>compile</scope>\n</dependency>\n<dependency>\n  <groupId>org.springframework</groupId>\n  <artifactId>spring-aspects</artifactId>\n  <version>6.0.6</version>\n  <scope>compile</scope>\n</dependency>\n```\n\n## Enable H2 Console\n\nWe will use H2 as the database. \n\nH2 provides a web interface called H2 Console to see the data. Let's enable h2 console in the application.properties.\n\n/src/main/resources/application.properties\n```properties\n# Enabling H2 Console\nspring.h2.console.enabled=true\nspring.data.jpa.repositories.bootstrap-mode=default\nspring.jpa.defer-datasource-initialization=true\n```\n\nWhen you reload the application, you can launch up H2 Console at http://localhost:8080/h2-console.\n\n![Image](/images/H2-Console-Login-Page.png \"H2 Console Login PAge\") \n\n> Tip - Make sure that you use `jdbc:h2:mem:testdb` as JDBC URL.\n\nWhen you use the right JDBC URL given above, you should see an empty schema when you click `Connect` button.\n\n![Image](/images/H2-Console-Empty-Schema.png \"H2 Console Empty Page\") \n\n### Make Your Very First JPA Entity\n\nThe first thing to do is to build a JPA Entity. Let's start with a basic Student Entity with a primary key id.\n\n\n```java\npackage com.in28minutes.springboot.jpa.hibernate.h2.example.student;\n\n// Changed from javax to jakarta\nimport jakarta.persistence.Entity;\nimport jakarta.persistence.GeneratedValue;\nimport jakarta.persistence.Id;\n\n@Entity\npublic class Student {\n\t@Id\n\t@GeneratedValue\n\tprivate Long id;\n\tprivate String name;\n\tprivate String passportNumber;\n\n\tpublic Student() {\n\t\tsuper();\n\t}\n\n\tpublic Student(Long id, String name, String passportNumber) {\n\t\tsuper();\n\t\tthis.id = id;\n\t\tthis.name = name;\n\t\tthis.passportNumber = passportNumber;\n\t}\n\n\tpublic Student(String name, String passportNumber) {\n\t\tsuper();\n\t\tthis.name = name;\n\t\tthis.passportNumber = passportNumber;\n\t}\n\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic String getPassportNumber() {\n\t\treturn passportNumber;\n\t}\n\n\tpublic void setPassportNumber(String passportNumber) {\n\t\tthis.passportNumber = passportNumber;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn String.format(\"Student [id=%s, name=%s, passportNumber=%s]\", id, name, passportNumber);\n\t}\n\n}\n```\n\nImportant things to note:\n - ```@Entity```: Specifies that the class is an entity. This annotation is applied to the entity class.\n - ```@Id```: Specifies the primary key of an entity.\n - ```@GeneratedValue```: Provides for the specification of generation strategies for the values of primary keys.\n - ```public Student()```: Default constructor to make JPA Happy\n\n\nYou may launch H2 console when the programme reloads. http://localhost:8080/h2-console.\n\nOn H2 Console, you will notice that a new table called `student` is generated.\n\n> How did the Student table get created?\n\nIts because of Spring Boot Auto Configuration. We will talk about this a little later.\n\nLet's now add some information to the student table.\n\n/src/main/resources/data.sql\n\n```sql\ninsert into student values(10001,'Ranga', 'E1234567');\n\ninsert into student values(10002,'Ravi', 'A1234568');\n```\n\nAfter you refresh the application, you should see the following messages in the log showing that the sql files have been picked up.\n\n```\nExecuting SQL script from URL [file:/in28Minutes/git/spring-boot-examples/spring-boot-2-jdbc-with-h2/target/classes/data.sql]\n```\n\nWhen you connect to H2 Console (http://localhost:8080/h2-console) after reloading the app, you will notice that the student table has been created and the data has been loaded.\n\n![Image](/images/H2-Console-With-Student.png \"H2 Console With Student\")\n\n## Build a Repository class to read Student data.\n\n/src/main/java/com/in28minutes/springboot/jpa/hibernate/h2/example/student/StudentRepository.java\n\nWe extend JpaRepository to create a simple interface called StudentRepository.\n\n```java\npackage com.in28minutes.springboot.jpa.hibernate.h2.example.student;\n\nimport org.springframework.data.jpa.repository.JpaRepository;\nimport org.springframework.stereotype.Repository;\n\n@Repository\npublic interface StudentRepository extends JpaRepository<Student, Long>{\n\n}\n```\nNotes\n- We'll go over all of the methods in the JpaRepository later.\n- `public interface StudentRepository extends JpaRepository<Student, Long>` - JpaRepository is being extended with two generics: Student and Long. The entity being handled is Student, and the main key of Student is Long.\n\n### JpaRepository\n\nJpaRepository (Defined in Spring Data JPA) is the JPA specific Repository interface.\n\n```java\npublic interface JpaRepository<T, ID extends Serializable>\n\t\textends PagingAndSortingRepository<T, ID>, QueryByExampleExecutor<T> {\n```\n\n> JpaRepository extends PagingAndSortingRepository which in turn extends CrudRepository interface. So, JpaRepository inherits all the methods from the two interfaces shown below.\n\nPagingAndSortingRepository\n```java\npublic abstract interface PagingAndSortingRepository extends CrudRepository {\n  \n  public abstract Iterable findAll(Sort arg0);\n  \n  public abstract Page findAll(Pageable arg0);\n\n}\n```\n\nCrudRepository\n```java\npublic interface CrudRepository<T, ID extends Serializable>\n    extends Repository<T, ID> {\n\n    <S extends T> S save(S entity);\n\n    T findOne(ID primaryKey);       \n\n    Iterable<T> findAll();          \n\n    Long count();                   \n\n    void delete(T entity);          \n\n    boolean exists(ID primaryKey);  \n\n    // … more functionality omitted.\n}\n```\n\n## Enable Debug Logging for Hibernate and Queries\n\nBefore we go any further, let's enable logging for all queries generated by Hibernate. We also enable statistics and format generated sql statements.\n\n### /src/main/resources/application.properties\n\n```properties\n#Turn Statistics on\nspring.jpa.properties.hibernate.generate_statistics=true\nlogging.level.org.hibernate.stat=debug\n# Show all queries\nspring.jpa.show-sql=true\nspring.datasource.url=jdbc:h2:mem:testdb\nspring.data.jpa.repositories.bootstrap-mode=default\nspring.jpa.properties.hibernate.format_sql=true\nlogging.level.org.hibernate.type=trace\nspring.datasource.url=jdbc:h2:mem:testdb\nspring.data.jpa.repositories.bootstrap-mode=default\nspring.jpa.defer-datasource-initialization=true\n```\n\nSome of the log that is generated (later when we execute queries) when we turn statistics on is shown below.\n\nSession Level Metrics\n```\n023-03-22T13:37:31.818+05:30  INFO 18636 --- [  restartedMain] i.StatisticalLoggingSessionEventListener : Session Metrics {\n    25207 nanoseconds spent acquiring 1 JDBC connections;\n    0 nanoseconds spent releasing 0 JDBC connections;\n    1381963 nanoseconds spent preparing 1 JDBC statements;\n    351842 nanoseconds spent executing 1 JDBC statements;\n    0 nanoseconds spent executing 0 JDBC batches;\n    0 nanoseconds spent performing 0 L2C puts;\n    0 nanoseconds spent performing 0 L2C hits;\n    0 nanoseconds spent performing 0 L2C misses;\n    0 nanoseconds spent executing 0 flushes (flushing a total of 0 entities and 0 collections);\n    0 nanoseconds spent executing 0 partial-flushes (flushing a total of 0 entities and 0 collections)\n}\n\n```\n\nQueries and Parameters\n```\n2023-03-22T13:37:31.819+05:30  INFO 18636 --- [  restartedMain] ibernateAndH2Application$$SpringCGLIB$$0 : Student id 10001 -> Optional[Student [id=10001, name=Ranga, passportNumber=E1234567]]\nHibernate: \n    select\n        next value for student_seq\nHibernate: \n    insert \n    into\n        student\n        (name, passport_number, id) \n    values\n        (?, ?, ?)\n\n```\n\n## Exploring JpaRepository methods\n\nThe code below extends the SpringBoot2JPAWithHibernateAndH2Application class to perform some StudentRepository methods.\n\n```java\n@SpringBootApplication\npublic class SpringBoot2JPAWithHibernateAndH2Application implements CommandLineRunner {\n\n\tprivate final Logger logger = LoggerFactory.getLogger(this.getClass());\n\n\t@Autowired\n\tStudentRepository repository;\n\n\tpublic static void main(String[] args) {\n\t\tSpringApplication.run(SpringBoot2JPAWithHibernateAndH2Application.class, args);\n\t}\n\n\t@Override\n\tpublic void run(String... args) throws Exception {\n\t\t//Code to run at application startup\n\t}\n}\n\n```\n\n> Spring Boot Auto Configuration sees H2 in the classpath. It understands that we would want to talk to an in memory database. It auto configures a datasource and also a JdbcTemplate connecting to that datasource.\n\nImportant Things To Note\n- `SpringBoot2JPAWithHibernateAndH2Application implements CommandLineRunner` - Implementing CommandLineRunner helps to execute the repository methods at start of the application.\n- `public void run(String... args) throws Exception {` - Implement the run method defined in the CommandLineRunner interface. This method is executed as soon as the application is launched up.\n\nLet's extend the `run` method to execute a few methods on the student repository.\n\n```java\n@Override\npublic void run(String... args) throws Exception {\n\n\tlogger.info(\"Student id 10001 -> {}\", repository.findById(10001L));\n\t\n\tlogger.info(\"All users 1 -> {}\", repository.findAll());\n\t\n\t//Insert\n\tlogger.info(\"Inserting -> {}\", repository.save(new Student(\"John\", \"A1234657\")));\n\n\t//Update\n\tlogger.info(\"Update 10001 -> {}\", repository.save(new Student(10001L, \"Name-Updated\", \"New-Passport\")));\n\n\trepository.deleteById(10002L);\n\t\n\tlogger.info(\"All users 2 -> {}\", repository.findAll());\n}\n\n```\n\nImportant points to Note:\n- findById, findAll, deleteById methods are self explanatory.\n- `save' method is used for both insertion and updates. If the entity is already present in the database, it is updated. Else, it is inserted.\n\nOutput from above statements when the code is run is shown below:\n```\nStudent id 10001 -> Optional[Student [id=10001, name=Ranga, passportNumber=E1234567]]\nAll users 1 -> [Student [id=10001, name=Ranga, passportNumber=E1234567], Student [id=10002, name=Ravi, passportNumber=A1234568]]\nInserting -> Student [id=1, name=John, passportNumber=A1234657]\nUpdate 10001 -> Student [id=10001, name=Name-Updated, passportNumber=New-Passport]\nAll users 2 -> [Student [id=1, name=John, passportNumber=A1234657], Student [id=10001, name=Name-Updated, passportNumber=New-Passport]]\n\n```\n\n## Few more advanced JPA/Hibernate ORM Mappings\n\nLets look at a few more examples to understand how JPA can be used to map objects to tables.\n\n#### Example 1 - Relationships @ManyToMany\n\nRelationships between objects are expressed in a different way compared to relationship between tables.\n\nEach Employee can have multiple Tasks. Each Task can be shared by multiple Employees. There is a Many to Many relationship between them. We use @ManyToMany annotation to establish the relationship.\n\n```java\npublic class Employee {\n   \n     //Some other code\n\t\n\t@ManyToMany\n\tprivate List<Task> tasks;\n}\n\npublic class Task {\n\n     //Some other code\n\n\t@ManyToMany(mappedBy = \"tasks\")\n\tprivate List<Employee> employees;\n}\n```\n\n```sql\nCREATE TABLE employee \n  ( \n     id            BIGINT NOT NULL, \n     OTHER_COLUMNS\n  ) \n\n\n  CREATE TABLE employee_tasks \n  ( \n     employees_id BIGINT NOT NULL, \n     tasks_id     INTEGER NOT NULL \n  ) \n\n  CREATE TABLE task \n  ( \n     id          INTEGER GENERATED BY DEFAULT AS IDENTITY, \n     OTHER_COLUMNS\n  ) \n\n```\n\n#### Example 2 - Inheritance Startegies - InheritanceType.SINGLE_TABLE\n\nSeveral classes are sometimes mapped to a single table, and vice versa. In these cases, we devise an inheritance approach. In this example, we employ an InheritanceType technique. SINGLE TABLE.\n\nObjects\n\n```java\n@Entity\n@Inheritance(strategy = InheritanceType.SINGLE_TABLE)\n@DiscriminatorColumn(name = \"EMPLOYEE_TYPE\")\npublic  class Employee {\t\n    //Other Employee Attributes\n}\n\npublic class FullTimeEmployee extends Employee {\n\tprotected Integer salary;\n}\n\npublic class PartTimeEmployee extends Employee {\n\tprotected Float hourlyWage;\n}\n```\n\nTables\n\n```sql\nCREATE TABLE employee \n  ( \n     employee_type VARCHAR(31) NOT NULL, \n     id            BIGINT NOT NULL, \n     city          VARCHAR(255), \n     state         VARCHAR(255), \n     street        VARCHAR(255), \n     zip           VARCHAR(255), \n\n     hourly_wage   FLOAT,  --PartTimeEmployee\n\n     salary        INTEGER, --FullTimeEmployee\n\n     PRIMARY KEY (id) \n  ) \n\n```\n\n## Example of Full Code\n\nGithub repository has all the code examples - https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-2-jpa-with-hibernate-and-h2"
  },
  {
    "path": "_blog/articles/2017-12-02-spring-boot-and-iBatis-with-h2.md",
    "content": "---\nlayout:     post\ntitle:   Spring Boot and iBatis with H2 - A Tutorial\ndate:       2023-03-20 12:31:19\nsummary:    Discover how to connect Spring Boot to H2 (in memory database) using Object Mapping Framework - myBatis with Spring Boot Starter (iBatis).\ncategories:  SpringBootJPA\npermalink:  /spring-boot-and-iBatis-with-h2-tutorial\nimage: /images/spring-data-category.png\n---\n\n![Image](/images/spring-initializer-web-h2-devtools-jdbc.png \"Web, JDBC,H2 and Developer Tools\")\n\nThis article will assist you in creating a basic Spring Boot project. You will add code to the project that will allow you to connect to the H2 Database using myBatis. You will learn how to use myBatis to build all of the core CRUD functions.\n\n![Image](/images/SpringBootwithmyBatis-ProjectStructure.png \"Spring Boot with myBatis - Project Structure\") \n\n \n## You will learn\n- How to connect a Spring Boot project to database using myBatis?\n- How to write a simple repository class with all the CRUD methods to execute queries using myBatis?\n- How to execute basic queries using myBatis?\n- How to create a project using Spring Boot, myBatis and H2?\n- What are the basics of an in memory database?\n\n\n## Project Code Structure\n\nFollowing screenshot shows the structure of the project we will create.\n\n![Image](/images/SpringBootwithmyBatis-ProjectStructure.png \"Spring Boot with myBatis - Project Structure\") \n\nA few details:\n\n- `Student.java` - The bean is used to hold student information.\n- `StudentMyBatisRepository.java` - Includes all of the methods for storing and retrieving student information from the H2 database.\n- `schema.sql` - Because we are utilising an in memory database, we define the tables in this file as part of our application code.\n- `data.sql` - To supply the initial student data, we utilise data.sql.\n- SpringBoot2MyBatisWithH2Application.java - This is the primary Spring Boot Application class that is used to start the application. We will extend the `CommandLineRunner` interface and add the `public void run method (String... args)` method to launch the spring jdbc code when the server launches up.\n- `pom.xml` - This package contains all of the dependencies required to develop this project. In addition to Developer Tools and H2, we will utilise Spring Boot Starter myBatis and Web.\n\n## Tools you will need\n- Maven 3.0+ is your build tool\n- Your favorite IDE. We use Eclipse or IntelliJ.\n- JDK 17+\n\n## Complete Maven Project With Code Examples\n> Our Github repository has all the code examples - https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-2-myBatis-with-h2\n\n## A little bit of Theory\n\nJDBC\n- JDBC is an abbreviation for Java Database Connectivity.\n- It made use of concepts such as `Statement, PreparedStatement, and ResultSet`.\n- In the example below, the query used is ```Update todo set user=?, desc=?, target_date=?, is_done=? where id=?```\n- The values required to run the query are entered into the query using various set methods on the PreparedStatement.\n- The query's results are added to the ResultSet. To convert the ResultSet into objects, we had to create code.\n\n#### Update Todo\n```java\nConnection connection = datasource.getConnection();\n\nPreparedStatement st = connection.prepareStatement(\n\t\t\"Update todo set user=?, desc=?, target_date=?, is_done=? where id=?\");\n\nst.setString(1, todo.getUser());\nst.setString(2, todo.getDesc());\nst.setTimestamp(3, new Timestamp(\n\t\ttodo.getTargetDate().getTime()));\nst.setBoolean(4, todo.isDone());\nst.setInt(5, todo.getId());\n\nst.execute();\n\nst.close();\n\nconnection.close();\n```\n\n### Spring JDBC\n\n- Spring JDBC provides a layer on top of JDBC\n- It used concepts like JDBCTemplate\n- Typically needs lesser number of lines compared to JDBC as following are simplified\n   - mapping parameters to queries\n   - liquidating resultsets to beans\n   - zero exception handling needed because all exceptions are converted to RuntimeExceptions.\n\n### myBatis\n\nMyBatis eliminates the requirement to write code to configure parameters and receive results. It allows you to link Java POJOs to databases using easy XML or Annotation-based setup.\n\nWe compare the approaches used to write queries below:\n\n- JDBC or Spring JDBC - ```Update todo set user=?, desc=?, target_date=?, is_done=? where id=?```\n- myBatis - ```Update todo set user=#{user}, desc=#{desc}, target_date=#{targetDate}, is_done=#{isDone} where id=#{id}```\n\n#### Update Todo and Retrieve Todo\n\n```java\n@Mapper\npublic interface TodoMybatisService\n\t\textends TodoDataService {\n\n\t@Override\n\t@Update(\"Update todo set user=#{user}, desc=#{desc}, target_date=#{targetDate}, is_done=#{isDone} where id=#{id}\")\n\tpublic void updateTodo(Todo todo) throws SQLException;\n\n\t@Override\n\t@Select(\"SELECT * FROM TODO WHERE id = #{id}\")\n\tpublic Todo retrieveTodo(int id) throws SQLException;\n}\n\n```\n\n## Creating the Project with Spring Initializr\n\nCreating a REST service with Spring Initializr is a cake walk. We will use Spring Web MVC as our web framework.  \n\nSpring Initializr [http://start.spring.io/](http://start.spring.io/){:target=\"_blank\"} is great tool to bootstrap your Spring Boot projects.\n\n![Image](/images/spring-initializer-web-h2-devtools-jdbc.png \"Web, JDBC,H2 and Developer Tools\")\n\nAs shown in the image above, following steps have to be done\n\n- Launch Spring Initializr and choose the following\n  - Choose `com.in28minutes.springboot.rest.example` as Group\n  - Choose `spring-boot-2-jdbc-with-h2` as Artifact\n  - Choose following dependencies\n    - Web\n    - H2\n    - DevTools\n- Click Generate Project.\n- Import the project into Eclipse. File -> Import -> Existing Maven Project.\n- If you want to understand all the files that are part of this project, you can go here TODO.\n\n## Add the myBatis starter to pom.xml\n\nmyBatis isn't your typical Spring Boot Starter project. We would need to add it manually to pom.xml.\n```xml\n<dependency>\n\t<groupId>org.mybatis.spring.boot</groupId>\n\t<artifactId>mybatis-spring-boot-starter</artifactId>\n\t<version>3.0.1</version>\n</dependency>\n\n```\n\nRebuild the project to view all the dependencies linked to myBatis.\n\n![Image](/images/myBatisDependencies.png \"my Batis Dependencies\")\n\n## Initialize H2 in-memory database with the schema\n\nWe will use H2 as the database. \n\nH2 provides a web interface called H2 Console to see the data. Let's enable h2 console in the application.properties\n\n/src/main/resources/application.properties\n```properties\n# Enabling H2 Console\n# Enabling H2 Console\nspring.h2.console.enabled=true\n#Turn Statistics on\nspring.jpa.properties.hibernate.generate_statistics=true\nlogging.level.org.hibernate.stat=debug\n# Show all queries\nspring.jpa.show-sql=true\nspring.jpa.properties.hibernate.format_sql=true\nlogging.level.org.hibernate.type=trace\nspring.datasource.url=jdbc:h2:mem:testdb\nspring.data.jpa.repositories.bootstrap-mode=default\nspring.jpa.defer-datasource-initialization=true\n```\nWhen you reload the application, you can launch up H2 Console at http://localhost:8080/h2-console.\n\n![Image](/images/H2-Console-Login-Page.png \"H2 Console Login PAge\") \n\n> Tip - Make sure that you use `jdbc:h2:mem:testdb` as JDBC URL.\n\nWhen you use the right JDBC URL given above, you should see an empty schema when you click `Connect` button.\n\n![Image](/images/H2-Console-Empty-Schema.png \"H2 Console Empty Page\") \n\n### Build a schema using schema.sql and a data set with data.sql.\n\nWe'll make a student table with a few simple columns. We may initialise a schema by generating a `schema.sql` file under the resources.\n\n/src/main/resources/schema.sql\n\n```sql\ncreate table student\n(\n   id integer not null,\n   name varchar(255) not null,\n   passport_number varchar(255) not null,\n   primary key(id)\n);\n```\n\nLet's additionally add some information to the student table.\n\n/src/main/resources/data.sql\n\n```sql\ninsert into student\nvalues(10001,'Ranga', 'E1234567');\n\ninsert into student\nvalues(10002,'Ravi', 'A1234568');\n```\n\nAfter you refresh the application, you should see the following messages in the log showing that the sql files have been picked up.\n```\nExecuting SQL script from URL [file:PATH/schema.sql]\nExecuting SQL script from URL [file:PATH/data.sql]\n```\n\nWhen you login to H2 Console (http://localhost:8080/h2-console) you can see that the student table is created and the data is populated.\n\n![Image](/images/H2-Console-With-Student.png \"H2 Console With Student\")\n\n## Creating Student Bean\n\nLet's make a simple Student bean that has basic student information as well as getters, setters, and a function toString() function.\n\n```java\npackage com.in28minutes.springboot.jdbc.h2.example.student;\n\npublic class Student {\n\tprivate Long id;\n\tprivate String name;\n\tprivate String passportNumber;\n\n\tpublic Student() {\n\t\tsuper();\n\t}\n\n\tpublic Student(Long id, String name, String passportNumber) {\n\t\tsuper();\n\t\tthis.id = id;\n\t\tthis.name = name;\n\t\tthis.passportNumber = passportNumber;\n\t}\n\n\tpublic Student(String name, String passportNumber) {\n\t\tsuper();\n\t\tthis.name = name;\n\t\tthis.passportNumber = passportNumber;\n\t}\n\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic String getPassportNumber() {\n\t\treturn passportNumber;\n\t}\n\n\tpublic void setPassportNumber(String passportNumber) {\n\t\tthis.passportNumber = passportNumber;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn String.format(\"Student [id=%s, name=%s, passportNumber=%s]\", id, name, passportNumber);\n\t}\n\n}\n```\n## Develop a technique for reading student information from a repository.\n\nWe would like to start with constructing a basic repository. This is a myBatis mapper class with `@Mapper`.\n\n```java\n@Mapper\npublic interface StudentMyBatisRepository {\n\n}\n\n```\n> H2 is seen in the classpath by Spring Boot Auto Configuration. It recognises that we wish to communicate with an in-memory database. It automatically configures a datasource as well as a JdbcTemplate that connects to that datasource.\n\nLet's create the findById method to retrieve a student by id in StudentJdbcRepository.\n```java\n@Select(\"SELECT * FROM student WHERE id = #{id}\")\npublic Student findById(long id);\n```\n\nNotes\n- `@Select(\"SELECT * FROM student WHERE id = #{id}\")` - `@Select` highlights that this is a select query. `#{id}` is used to indicate that id is a parameter to this query.\n- You can observe that are defining a simple interface method without the implementation.\n\nWe'd want to use the findById function. To keep things simple, we'll create the SpringBoot2MyBatisWithH2Application class interface CommandLineRunner and implement a run function that calls the repository's findById method.\n\n/src/main/java/com/in28minutes/springboot/jdbc/h2/example/SpringBoot2JdbcWithH2Application.java\n\n```java\npackage com.in28minutes.springboot.mybatis.h2.example;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.CommandLineRunner;\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\nimport com.in28minutes.springboot.mybatis.h2.example.student.Student;\nimport com.in28minutes.springboot.mybatis.h2.example.student.StudentMyBatisRepository;\n\n@SpringBootApplication\npublic class SpringBoot2MyBatisWithH2Application implements CommandLineRunner {\n\n    private final Logger LOGGER = LoggerFactory.getLogger(this.getClass());\n\n    @Autowired\n    StudentMyBatisRepository repository;\n\n    public static void main(String[] args) {\n        SpringApplication.run(SpringBoot2MyBatisWithH2Application.class, args);\n    }\n\n    @Override\n    public void run(String... args) throws Exception {\n\n        LOGGER.info(\"Student id 10001 -> {}\", repository.findById(10001L));\n\n        LOGGER.info(\"Inserting -> {}\", repository.insert(new Student(10010L, \"John\", \"A1234657\")));\n\n        LOGGER.info(\"Update 10003 -> {}\", repository.update(new Student(10001L, \"Name-Updated\", \"New-Passport\")));\n\n        repository.deleteById(10002L);\n\n        LOGGER.info(\"All users -> {}\", repository.findAll());\n    }\n}\n\n```\nNotes\n- `@Autowired StudentMyBatisRepository repository;` - We will autowire StudentMyBatisRepository we created earlier.\n- `public void run(String... args) throws Exception {` - Implement the run method defined in the CommandLineRunner interface. This method is executed as soon as the application is launched up.\n- `logger.info(\"Student id 10001 -> {}\", repository.findById(10001L))` - Log all the information about student id 10001.\n\nWhen the application reloads you will see this in the log. \n```\nStudent id 10001 -> Student [id=10001, name=Ranga, passportNumber=E1234567]\n```\n> Congratulations on executing the first myBatis method! You can see how easy it is with Spring Boot.\n\nLet's now add another method to retrieve details of all the students to StudentJdbcRepository.\n\n```java\n@Select(\"select * from student\")\npublic List<Student> findAll();\n```\nNotes\n- `@Select(\"select * from student\")` - Since we want to return a list of students, we do not need to pass any parameters. Its a simple `@Select` query.\n\nWe can add a call to find all method in the run method of `SpringBoot2MyBatisWithH2Application.java`\n\n```java\n\nlogger.info(\"All users 1 -> {}\", repository.findAll());\n\n```\n\nYou can see following output in the log when the project reloads.\n```\nAll users 1 -> [Student [id=10001, name=Ranga, passportNumber=E1234567], Student [id=10002, name=Ravi, passportNumber=A1234568]]\n```\n\n## Implementing myBatis delete, insert and update methods\n\nThe code below shows the delete, insert and update methods.\n\n```java\n\t@Delete(\"DELETE FROM student WHERE id = #{id}\")\n\tpublic int deleteById(long id);\n\n\t@Insert(\"INSERT INTO student(id, name, passport) VALUES (#{id}, #{name}, #{passport})\")\n\tpublic int insert(Student student);\n\n\t@Update(\"Update student set name=#{name}, passport=#{passport} where id=#{id}\")\n\tpublic int update(Student student);\n\n\n```\n\nNotes \n- These methods are relatively straight forward.\n- All methods use the appropriate annotation with the query and highlight the necessary parameters.\n\nWe can add a call to all the above methods in the run method of `SpringBoot2MyBatisWithH2Application.java`\n\n```java\n\nlogger.info(\"Inserting -> {}\", repository.insert(new Student(10010L, \"John\", \"A1234657\")));\n\nlogger.info(\"Update 10001 -> {}\", repository.update(new Student(10001L, \"Name-Updated\", \"New-Passport\")));\n\nrepository.deleteById(10002L);\n\nlogger.info(\"All users 2 -> {}\", repository.findAll());\n\n```\n\nYou can see following output in the log when the project reloads.\n```\nInserting -> 1\nUpdate 10001 -> 1\nAll users 2 -> [Student [id=10001, name=Name-Updated, passportNumber=New-Passport], Student [id=10010, name=John, passportNumber=A1234657]]\n```\n> Awesome ! You've implemented all the CRUD methods using iBatis and Spring Boot."
  },
  {
    "path": "_blog/articles/2017-12-03-spring-boot-and-h2-an-inmemory-database-top20.md",
    "content": "---\nlayout:     post\ntitle:   Spring Boot and H2 in memory database - Why, What and How?\ndate:       2023-03-22 12:31:19\nsummary:  Discover how to link a Spring Boot application to the H2 in-memory database. Learn why in-memory databases are necessary and how to use them effectively with Spring Boot.\ncategories:  SpringBootJPA\npermalink:  /spring-boot-and-h2-in-memory-database\nimage: /images/spring-data-category.png\n---\n\n![Image](/images/spring-initializer-web-h2-devtools-jpa.png \"Web, JPA, H2 and Developer Tools\")\n\nThis article will assist you in comprehending the notion of an in memory database. To learn the recommended practises for utilising in memory databases, we will look at a basic JPA example.\n\n![](/images/h2-solution-image.png)\n \n## You will learn\n- What is an in memory database?\n- Why do you use an in memory database?\n- What are the best practices in using an in memory database?\n- How to connect a Spring Boot project to H2?\n\n\n## What exactly is an in memory database?\n\nA typical database requires a significant amount of setup. \n\nUsing Oracle or mySQL databases, for example, you would need to\n- Install the Database\n- Setup a Schema\n- Setup the tables\n- Populate the data\n- Set up a data source and a bunch of extra code to connect the application to the database.\n\nCase 1: Assume you need to perform a fast proof of concept. Utilizing a standard database incurs significant expense.\n\nScenario 2 - Consider your unit tests\n- You don't want them to fail if the database's data or schema changes.\n- You'd want to be able to run them concurrently, as various devs may be running the tests concurrently.\n\nIn these situations, an in memory database is the best answer.\n\nAs a programme starts, an in memory database is generated, and it is removed when the application is ended.\n\nAdvantages\n- Zero project setup or infrastructure\n- Zero Configuration\n- Zero Maintainance\n- Easy to use for Learning, POCs and Unit Tests\n- Spring Boot has a Simple Configuration option for switching between a real database and an in memory database, such as H2.\n\n\n## H2\n\nH2 is a well-known in-memory database. Spring Boot provides an excellent interaction with H2.\n\nFrom https://en.wikipedia.org/wiki/H2_(DBMS)\n> H2 is a Java-based relational database management system. It may be integrated in Java programmes or used as a client-server application.\n\nH2 is compatible with a subset of the SQL standard.\n\nH2 also has a web console for database management.\n\n## Spring Boot and H2\n\nSpring Boot application and H2 require very minimal setting.\n\nIn most cases, simply including the H2 runtime jar in dependencies should enough.\n\n```xml\n<dependency>\n    <groupId>com.h2database</groupId>\n    <artifactId>h2</artifactId>\n    <scope>runtime</scope>\n</dependency>\n```\n\n## Creating a Spring Boot Project in H2\n\nSpring Initializr [http://start.spring.io/](http://start.spring.io/){:target=\"_blank\"} is great tool to bootstrap your Spring Boot projects.\n\n![Image](/images/spring-initializer-web-h2-devtools-jpa.png \"Web, JPA, H2 and Developer Tools\")\n\nAs seen in the graphic above, the following actions must be taken.\n\n- Launch Spring Initializr and choose the following\n  - Choose `com.in28minutes.springboot.rest.example` as Group\n  - Choose `spring-boot-2-jpa-with-hibernate-and-h2` as Artifact\n  - Choose following dependencies\n    - Web\n    - JPA\n    - H2\n    - DevTools\n- Click Generate Project.\n- Import the project into Eclipse. File -> Import -> Existing Maven Project.\n\n> Make sure H2 is checked in the dependencies.\n\nCreate a straightforward Student Entity with a primary key id.\n\n```java\n@Entity\npublic class Student {\n\t@Id\n\t@GeneratedValue\n\tprivate Long id;\n\tprivate String name;\n\tprivate String passportNumber;\n```\n\n\n\n## H2 - A Few Pointers\n- An in-memory database is only active during the application's operation. It is an effective method for learning a framework.\n- This is not how your real-world apps should behave.\n- In the answer to the question \"How do we connect to an external database?\" we describe how to connect to a database of your choosing.\n\n## H2 Magic and Spring Boot\n\nTo see the data, H2 provides a web interface called H2 Console. Let's activate the h2 console in the app. properties.\n\n/src/main/resources/application.properties\n```properties\n# Enabling H2 Console\nspring.h2.console.enabled=true\nspring.datasource.url=jdbc:h2:mem:testdb\nspring.data.jpa.repositories.bootstrap-mode=default\n```\n> If you launch the programme right now, you'll witness a lot of magic happen!\n\nWhen you reload the application, you can launch up H2 Console at http://localhost:8080/h2-console.\n\n![Image](/images/H2-Console-Login-Page.png \"H2 Console Login PAge\") \n\n> Tip - Make sure that you use `jdbc:h2:mem:testdb` as JDBC URL.\n\nOn H2 Console, you will notice that a new table called'student' is generated.\n\n> How did the Student table come to be?\n\nIts because of Spring Boot Auto Configuration. We will talk about this in the next section.\n\nYou may alternatively populate the student database with data by including a file called `data.sql`.\n\n/src/main/resources/data.sql\n\n```\ninsert into student\nvalues(10001,'Ranga', 'E1234567');\n\ninsert into student\nvalues(10002,'Ravi', 'A1234568');\n```\n\nWhen you restart the application, H2 Console will show you that the student table has been populated with the data from `data.sql`\n- http://localhost:8080/h2-console.\n\nHow did all of the magic take place? In the next part, we'll go over it question by question.\n\n## Frequently asked questions about Spring Boot, JPA, Hibernate and H2\n\n### Q :  How does H2 and Spring Boot combination work?\n\nThe first and most crucial fact is that Spring Boot is clever.\n\nWhen you communicate to an in memory database, it looks at the entities and constructs the database and tables by default.\n\nWhen you connect to a mysql database, Spring Boot recognises that it is a persistent database. It expects you to set up the database and tables by default, and it uses the connection you setup.\n\n### Q :  How did the Spring Boot Application connect to the database H2?\n\nSpring Boot Auto Configuration is the key!\n\nThe first concept you must grasp is Spring Boot Auto Configuration.\n\nHere’s a good read \n- http://www.springboottutorial.com/spring-boot-auto-configuration\n\nWhen Spring Boot detects H2 in the class path, it automatically configures a data source similar to the one shown below:\n\n```properties\nspring.datasource.url=jdbc:h2:mem:testdb\nspring.datasource.driverClassName=org.h2.Driver\nspring.datasource.username=sa\nspring.datasource.password=\n\nspring.jpa.database-platform=org.hibernate.dialect.H2Dialect\nspring.jpa.defer-datasource-initialization=true\n```\n\nIt recognises that you are using the H2 in-memory database and will use the default url if you do not specify one.\n\n\n### Q :  Where can I get the database connection information? How does it know to connect to H2 automatically?\n\nThat's the power of Spring Boot Auto-configuration.\n\nFrom https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-auto-configuration.html\n\n> Spring Boot auto-configuration attempts to automatically configure your Spring application based on the jar dependencies that you have added. For example, If HSQLDB is on your classpath, and you have not manually configured any database connection beans, then Spring Boot will auto-configure an in-memory database.\n\nRecommended Reading\n- http://www.springboottutorial.com/spring-boot-auto-configuration\n\n### Q :  What happens if H2 is not in the classpath?\n\nYou get this error\n\n```\nCannot determine embedded database driver class for database type NONE\n```\n\nAdd H2 to the pom.xml and Restart your server\n\n```xml\n<dependency>\n\t<groupId>com.h2database</groupId>\n\t<artifactId>h2</artifactId>\n\t<scope>runtime</scope>\n</dependency>\n```\n\n### Q :  Why is the data lost between restart?\n\nH2 is a database that runs in memory. This is not a persistent database.\n\nH2 is an excellent learning tool because it requires no setup.\n\n### Error :  Tables are not automatically created in H2 embedded database, or I am unable to see them.\n\nThe tables are usually produced, however the URL provided in the H2 GUI Console is incorrect.\n\nChange the database URL in the browser to `jdbc:h2:mem:testdb` (Shown in the screen below).\n\n![](/images/h2-solution-image.png)\n\nYou should be good to go!\n\n### Error :  H2 Console is not Launched up?\n\nTry enabling it in the `application.properties`\n\n```\nspring.h2.console.enabled=true\n```\n\n### Q :  How did the insert query from data.sql run at application startup? \n\nThat's part of the Spring Boot startup routine. Any queries in data.sql are run at application startup. You can read more here. \n- https://docs.spring.io/spring-boot/docs/current/reference/html/howto-database-initialization.html\n\n## Running H2 as a persisted database with Spring Boot\n\nWhile we do not encourage it, it is worth noting that H2 includes a persistent database mode.\n- Even after a spring boot restart and a machine restart, the data is not lost with this arrangement. \n\nH2 is very very infrequently utilised in this manner. If you're looking for a durable database, we recommend looking into MySQL, Oracle, or another relational database.\n\n`application.properties`\n```\nspring.datasource.name=yourdbname\nspring.datasource.driverClassName=org.h2.Driver\n \nspring.datasource.initialize=false\nspring.datasource.url=jdbc:h2:file:~/yourdbname;DB_CLOSE_ON_EXIT=FALSE;IFEXISTS=TRUE;DB_CLOSE_DELAY=-1;\n \nspring.jpa.hibernate.ddl-auto = update\n```\n\n## Using H2 for unit tests \n\nApplication.properties is the standard properties file that Spring Boot automatically takes up when executing an application and is located in the src/main/resources folder.\n\nIf we wish to utilise alternative properties for testing, we may override the properties file in the main folder by adding a similar file in src/test/resources.\n\nThe standard key-value pairs required for setting an in memory connection should be contained in the application.properties file in the src/test/resources folder.\n\nThen, add the requirements for your database driver (in this case, mysql) and make the h2 dependency `test` scoped.\n\n```xml\n<dependency>\n    <groupId>mysql</groupId>\n    <artifactId>mysql-connector-java</artifactId>\n</dependency>\n\n<dependency>\n    <groupId>com.h2database</groupId>\n    <artifactId>h2</artifactId>\n    <scope>test</scope>\n</dependency>\n```\n\nFor your real code, use the mysql database.\n\nsrc\\main\\resources\\application.properties\n```\nspring.jpa.hibernate.ddl-auto=none\nspring.datasource.url=jdbc:mysql://localhost:3306/person_example\nspring.datasource.username=personuser\nspring.datasource.password=YOUR_PASSWORD\n```\n\nUse in memory database for your unit tests\n\nsrc\\test\\resources\\application.properties\n```\nspring.datasource.driver-class-name=org.h2.Driver\nspring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1\nspring.datasource.username=sa\nspring.datasource.password=sa\n```\n"
  },
  {
    "path": "_blog/articles/2017-12-04-connecting-spring-boot-with-other-databases-mySql-Oracle-etc.md",
    "content": "---\nlayout:     post\ntitle:   Connecting Spring Boot with databases - MySQL and Oracle\ndate:       2023-03-24 12:31:19\nsummary:  Discover how to integrate a Spring Boot application with relational databases such as Oracle and MySQL. Discover how to create a database schema for them as well as what to put up in application configuration.\ncategories:  SpringBootJPA\npermalink:  /spring-boot-with-mysql-and-oracle\nimage: /images/spring-data-category.png\n---\n\n![Image](/images/SpringBootWebApplication-StaticContent.png \"Spring Boot Web Application with jQuery and Bootstrap- All Files\") \n\nThis post will show you how to connect Spring Boot to databases such as MySQL and Oracle.\n \n## You will learn\n- How do I link a Spring Boot and JPA application to MySQL and Oracle?\n- What should be set in application.properties?\n- How do I create a database schema?\n\n\n\n## Step-by-Step Spring Boot Project Update\n\nLet's go over the five steps in connecting a Spring Boot application to a database.\n\n> You can use the example we created earlier for connecting to H2 in memory database as the starting point for this article- http://www.springboottutorial.com/hibernate-jpa-tutorial-with-spring-boot-starter-jpa\n\n### Step 1 - Add dependency for your database connector to pom.xml \n\nExample for MySQL is shown below.\n\n```xml\n<dependency>\n    <groupId>mysql</groupId>\n    <artifactId>mysql-connector-java</artifactId>\n</dependency>\n```\n\nIf you wish to connect to an Oracle database, use a dependency like the one shown below.\n\n```xml\n<dependency>\n    <groupId>com.oracle</groupId>\n    <artifactId>ojdbc7</artifactId>\n    <version>12.1.0.1</version>\n</dependency>\n\n```\n\n### Step 2 - Remove H2 Dependency from pom.xml\nOr atleast make its scope as test\n\n```xml\n<!--\n<dependency>\n    <groupId>com.h2database</groupId>\n    <artifactId>h2</artifactId>\n    <scope>test</scope>\n</dependency>\n-->\n```\n\n### Step 3 - Setup your My SQL Database\n\nWe would need to create a schema and tables for your database.\n\n> For an example, check out - https://github.com/in28minutes/jpa-with-hibernate#installing-and-setting-up-mysql\n\n### Step 4 - Setup your database connection.\n\nConnect to your database using `application.properties`.\n\nBelow is an example of My SQL:\n```properties\nspring.jpa.hibernate.ddl-auto=none\nspring.datasource.url=jdbc:mysql://localhost:3306/todo_example\nspring.datasource.username=todouser\nspring.datasource.password=YOUR_PASSWORD\n```\n\n#### spring.jpa.hibernate.ddl-auto\nSpring Boot determines the default value for this based on whether or not you are connecting to an embedded database. \n- Embedded Databases - default create-drop\n- Other Databases - default none\n\nHere is a quick guide to all the options\n- none : No action will be performed.\n- create-only : Database creation will be generated from entities.\n- drop : Database dropping will be generated from entities.\n- create : Database dropping will be generated followed by database creation.\n- validate : Validate entites with the database schema\n- update : Update the database schema based on the entities\n\n### Step 5 - Restart, and you're done!\nThat's it\n\n"
  },
  {
    "path": "_blog/articles/2017-12-06-introduction-to-spring-data-rest.md",
    "content": "---\nlayout:     post\ntitle:   Introduction to Spring Data Rest - Create RESTful APIs at F1 Speed\ndate:    2023-03-24 12:31:19\nsummary: Learn how to use Spring Data Rest and Spring Boot to construct RESTful Services. To expose the API, we will develop a JPA Project that connects to H2 (in memory database) and includes the Spring Data JPA Rest Starter.\ncategories:  SpringBoot\npermalink:  /introduction-to-spring-data-rest-using-spring-boot\nimage: /images/spring-boot-application.png\n---\n\n![Image](/images/spring-initializer-web-h2-devtools-jpa.png \"Web, JPA, H2 and Developer Tools\")\n\nThis post will show you how to offer RESTful APIs with Spring Boot, JPA/Hibernate, Spring Data, and Spring Data REST. H2 will be used as the in-memory database. \n \n![Image](/images/SpringDataREST-ExectingPostRequest.png \"Spring Data Rest with Spring Boot and JPA - Post Request\")\n\n## You will learn\n- How do you make a Spring Boot project with Spring Boot Starter JPA, Spring Boot Data Rest Starter, and H2?\n- How to expose RESTful API using Spring Boot Data Rest?\n- How to connect a Spring Boot project to database using JPA/Hibernate?\n- How to create a simple JPA Entity with a primary key?\n- How to write a simple repository interface extending JpaRepository interface?\n\n\n\n## Structure of the Project Code\n\nThe screenshot below depicts the framework of the project we will be creating.\n\n![Image](/images/SpringDataRESTwithSpringBoot-ProjectStructure.png \"Spring Data Rest with Spring Boot and JPA - Project Structure\") \n\nA few details:\n\n- `Student.java` - Entity bean to store student details.\n- `StudentDataRestRepository.java` - Extends PagingAndSortingRepository. Acts as a @RepositoryRestResource to provide RESTful API/Services to update/retrieve Student entities.\n- `data.sql` - To supply the initial student data, we utilise `data.sql`.\n- SpringBoot2JPAWithSpringDataRestApplication.java - The primary Spring Boot Application class used to start the application. \n- `pom.xml` - This package contains all of the dependencies required to develop this project. In addition to Developer Tools and H2, we will utilise Spring Boot Starter JPA, Spring Boot Data REST Starter, and Spring Boot Starter Web.\n\n## You will require the following tools:\n- Maven 3.0+ is your build tool\n- Your favorite IDE. We use Eclipse or IntelliJ.\n- JDK 17\n\n## Maven Project Completion using Code Samples\n> Our Github repository has all the code examples - https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-2-jpa-spring-data-rest\n\n## How Does Spring Data REST Work in the Big Picture?\n\nLet's start with JPA and work our way up to Spring Data and Spring Data REST.\n\n### JPA\nJPA allows you to map application classes to database tables.\n- Entity Manager - Entity manager may manage your entities after the mappings are defined. Entity Manager manages all database interactions.\n- Java Persistence Query Language (JPQL) - Offers methods for writing queries to do entity searches. It is critical to recognise that these are not SQL queries. JPQL queries are already aware of the mappings that exist between entities. More criteria can be added as needed.\n- Criteria API specifies a Java-based API for doing database searches.\n\n### What is Spring Data?\n\nFrom http://projects.spring.io/spring-data/\n> The objective of Spring Data is to provide a familiar and consistent Spring-based programming model for data access while keeping the unique characteristics of the underlying data store. It makes data access technologies, relational and non-relational databases, map-reduce frameworks, and cloud-based data services simple to utilise.\n\nTo make things easier, Spring Data provides Abstractions (interfaces) that may be used regardless of the underlying data source. \n\nAn example is shown below\n```java\ninterface TodoRepository extends CrudRepository<Todo, Long> {\n```\n\nCore idea is that\n> Without writing a lot of code, you may establish a basic repository and use it to insert, update, remove, and retrieve todo entities from the database.\n\n\n### Spring Data REST\n\nSpring Data REST may be used to deliver HATEOAS RESTful resources that are nested within Spring Data repositories.\n\nAn example using JPA is shown below\n\n```java\n@RepositoryRestResource(collectionResourceRel = \"todos\", path = \"todos\")\npublic interface TodoRepository\n\t\textends PagingAndSortingRepository<Todo, Long> {\n\n```\n\n> Without writing a lot of code, we can expose RESTful API around Spring Data Repositories.\n\nA few example REST Services that are automatically exposed are shown below:\n\n#### POST \n- URL : http://localhost:8080/todos\n- Use Header : Content-Type:application/json\n\nRequest Content \n```json\n{\n  \"user\": \"Jill\",\n  \"desc\": \"Learn Hibernate\",\n  \"done\": false\n}\n```\nResponse Content\n```\n{\n  \"user\": \"Jill\",\n  \"desc\": \"Learn Hibernate\",\n  \"done\": false,\n  \"_links\": {\n    \"self\": {\n      \"href\": \"http://localhost:8080/todos/1\"\n    },\n    \"todo\": {\n      \"href\": \"http://localhost:8080/todos/1\"\n    }\n  }\n}\n```\nThe response contains the href of the newly created resource.\n\n#### GET\n\n- URI - http://localhost:8080/todos\n\nResponse\n```json\n{\n  \"_embedded\" : {\n    \"todos\" : [ {\n      \"user\" : \"Jill\",\n      \"desc\" : \"Learn Hibernate\",\n      \"done\" : false,\n      \"_links\" : {\n        \"self\" : {\n          \"href\" : \"http://localhost:8080/todos/1\"\n        },\n        \"todo\" : {\n          \"href\" : \"http://localhost:8080/todos/1\"\n        }\n      }\n    } ]\n  },\n  \"_links\" : {\n    \"self\" : {\n      \"href\" : \"http://localhost:8080/todos\"\n    },\n    \"profile\" : {\n      \"href\" : \"http://localhost:8080/profile/todos\"\n    },\n    \"search\" : {\n      \"href\" : \"http://localhost:8080/todos/search\"\n    }\n  },\n  \"page\" : {\n    \"size\" : 20,\n    \"totalElements\" : 1,\n    \"totalPages\" : 1,\n    \"number\" : 0\n  }\n}\n```\n\n## Creating the Project with Spring Initializr\n\nSpring Initializr [http://start.spring.io/](http://start.spring.io/){:target=\"_blank\"} is great tool to bootstrap your Spring Boot projects.\n\n![Image](/images/spring-initializer-web-h2-devtools-jpa.png \"Web, JPA, H2 and Developer Tools\")\n\nAs shown in the image above, following steps have to be done\n\n- Launch Spring Initializr and choose the following\n  - Choose `com.in28minutes.springboot.jpa.spring.data.rest.example` as Group\n  - Choose `spring-boot-2-jpa-spring-data-rest` as Artifact\n  - Choose following dependencies\n    - Web\n    - JPA\n    - H2\n    - DevTools\n    - Rest Repositories\n- Click Generate Project.\n- Import the project into Eclipse. File -> Import -> Existing Maven Project.\n\n> Do not forget to add the dependency on \"Rest Repositories\" i.e. Spring Boot Data Rest Starter.\n\n## Starter Projects in pom.xml\n\nBelow is the list of starter projects in pom.xml. \n\n```\n\t\t<dependency>\n\t\t\t<groupId>org.springframework.boot</groupId>\n\t\t\t<artifactId>spring-boot-starter-data-rest</artifactId>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>org.springframework.boot</groupId>\n\t\t\t<artifactId>spring-boot-starter-jpa</artifactId>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.springframework.boot</groupId>\n\t\t\t<artifactId>spring-boot-starter-web</artifactId>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>org.springframework.boot</groupId>\n\t\t\t<artifactId>spring-boot-devtools</artifactId>\n\t\t\t<scope>runtime</scope>\n\t\t</dependency>\n\t\t\n\t\t<dependency>\n\t\t\t<groupId>com.h2database</groupId>\n\t\t\t<artifactId>h2</artifactId>\n\t\t\t<scope>runtime</scope>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.springframework.boot</groupId>\n\t\t\t<artifactId>spring-boot-starter-test</artifactId>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n```\n## Understanding Spring Boot Starter Data Rest\n\nBelow picture highlights some of the dependencies that are part of the imported Spring Boot project.\n\n![Image](/images/spring-boot-starter-data-rest-dependencies.png \"Spring Boot Starter Data Rest Dependencies\")\n\n> Key Question : How did all these dependencies come in?\n\nSpring-boot-starter-jpa and spring-boot-starter-data-rest declare all of these dependencies. We obtain the following functionalities from a wide range of dependencies as soon as we include them in our project (pom.xml).\n- Spring Data\n- Spring Data Rest\n- AOP\n- Transaction Management\n- JPA API\n- JPA Implementation - Default Hibernate\n- JDBC\n\nExtract below shows some code from pom.xml of spring-boot-starter-data-rest.\n\n```xml\n    <dependency>\n      <groupId>org.springframework.boot</groupId>\n      <artifactId>spring-boot-starter-web</artifactId>\n      <version>3.0.2</version>\n      <scope>compile</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.springframework.data</groupId>\n      <artifactId>spring-data-rest-webmvc</artifactId>\n      <version>4.0.1</version>\n      <scope>compile</scope>\n    </dependency>\n```\n\n## Turn on H2 Console \n\nH2 will be used as the database. \n\nTo see the data, H2 provides a web interface called H2 Console. Let's activate the h2 console in the app. properties.\n\n/src/main/resources/application.properties\n```properties\n# Enabling H2 Console\nspring.h2.console.enabled=true\nspring.datasource.url=jdbc:h2:mem:testdb\nspring.data.jpa.repositories.bootstrap-mode=default\n\n```\n\nYou may access H2 Console at http://localhost:8080/h2-console after reloading the application.\n\n![Image](/images/H2-Console-Login-Page.png \"H2 Console Login PAge\") \n\n> Tip - Make sure that you use `jdbc:h2:mem:testdb` as JDBC URL.\n\nWhen you provide the correct JDBC URL, you should see an empty schema when you click the `Connect` button.\n\n![Image](/images/H2-Console-Empty-Schema.png \"H2 Console Empty Page\") \n\n## Create Your First JPA Entity\n\nThe first thing to do is to build a JPA Entity. Let's start with a basic Student Entity with a primary key id.\n\n```java\npackage com.in28minutes.springboot.jpa.spring.data.rest.example.student;\n\nimport jakarta.persistence.Entity;\nimport jakarta.persistence.GeneratedValue;\nimport jakarta.persistence.Id;\n\n@Entity\npublic class Student {\n\n    @Id\n    @GeneratedValue\n    private Long id;\n\n    private String name;\n\n    private String passportNumber;\n\n```\n\nImportant things to note:\n - ```@Entity```: Specifies that the class is an entity. This annotation is applied to the entity class.\n - ```@Id```: Specifies the primary key of an entity.\n - ```@GeneratedValue```: Provides for the specification of generation strategies for the values of primary keys.\n - ```public Student()```: Default constructor to make JPA Happy\n\nYou may access H2 Console at http://localhost:8080/h2-console after reloading the application.\n\nOn H2 Console, you will notice that a new table called'student' is generated.\n\n> How did the Student table come to be?\n\nIts because of Spring Boot Auto Configuration. \n\n> You can read more about auto configuration here - http://www.springboottutorial.com/spring-boot-auto-configuration\n\nLet's now add some information to the student table.\n\n/src/main/resources/data.sql\n\n```sql\ninsert into student\nvalues(10001,'Ranga', 'E1234567');\n\ninsert into student\nvalues(10002,'Ravi', 'A1234568');\n```\n\nAfter you refresh the application, you should see the following messages in the log showing that the sql files have been picked up.\n\n```\nExecuting SQL script from URL [file:/in28Minutes/git/spring-boot-examples/spring-boot-2-jdbc-with-h2/target/classes/data.sql]\n```\n\nWhen you connect to H2 Console (http://localhost:8080/h2-console) after reloading the app, you will notice that the student table has been created and the data has been loaded.\n\n![Image](/images/H2-Console-With-Student.png \"H2 Console With Student\")\n\n## Make a Spring Data Rest Repository class that exposes the Student API.\n\nThe code below demonstrates how to use the Spring Data Rest Repository to offer API for the Student resource.\n\n/src/main/java/com/in28minutes/springboot/jpa/spring/data/rest/example/student/StudentDataRestRepository.java\n\n```java\npackage com.in28minutes.springboot.jpa.spring.data.rest.example.student;\n\nimport org.springframework.data.repository.PagingAndSortingRepository;\nimport org.springframework.data.rest.core.annotation.RepositoryRestResource;\n\n@RepositoryRestResource(path = \"students\", collectionResourceRel = \"students\")\npublic interface StudentDataRestRepository extends PagingAndSortingRepository<Student, Long> {\n\n}\n```\n`RepositoryRestResource` annotation is used to expose Spring Data Rest services\n\nWhen the application reloads, you would see that there are a number of new statements in the console log.\n\n```\nMapped \"{[/ || ],methods=[GET],produces=[application/hal+json || application/json]}\" onto public org.springframework.http.HttpEntity<org.springframework.data.rest.webmvc.RepositoryLinksResource> org.springframework.data.rest.webmvc.RepositoryController.listRepositories()\nMapped \"{[/{repository}],methods=[HEAD],produces=[application/hal+json || application/json]}\" onto public org.springframework.http.ResponseEntity<?> org.springframework.data.rest.webmvc.RepositoryEntityController.headCollectionResource(org.springframework.data.rest.webmvc.RootResourceInformation,org.springframework.data.rest.webmvc.support.DefaultedPageable) throws org.springframework.web.HttpRequestMethodNotSupportedException\nMapped \"{[/{repository}],methods=[POST],produces=[application/hal+json || application/json]}\" onto public org.springframework.http.ResponseEntity<org.springframework.hateoas.ResourceSupport> org.springframework.data.rest.webmvc.RepositoryEntityController.postCollectionResource(org.springframework.data.rest.webmvc.RootResourceInformation,org.springframework.data.rest.webmvc.PersistentEntityResource,org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler,java.lang.String) throws org.springframework.web.HttpRequestMethodNotSupportedException\nMapped \"{[/{repository}/{id}],methods=[GET],produces=[application/hal+json || application/json]}\" onto public org.springframework.http.ResponseEntity<org.springframework.hateoas.Resource<?>> org.springframework.data.rest.webmvc.RepositoryEntityController.getItemResource(org.springframework.data.rest.webmvc.RootResourceInformation,java.io.Serializable,org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler,org.springframework.http.HttpHeaders) throws org.springframework.web.HttpRequestMethodNotSupportedException\nMapped \"{[/{repository}/{id}],methods=[PUT],produces=[application/hal+json || application/json]}\" onto public org.springframework.http.ResponseEntity<? extends org.springframework.hateoas.ResourceSupport> org.springframework.data.rest.webmvc.RepositoryEntityController.putItemResource(org.springframework.data.rest.webmvc.RootResourceInformation,org.springframework.data.rest.webmvc.PersistentEntityResource,java.io.Serializable,org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler,org.springframework.data.rest.webmvc.support.ETag,java.lang.String) throws org.springframework.web.HttpRequestMethodNotSupportedException\nMapped \"{[/{repository}/{id}],methods=[PATCH],produces=[application/hal+json || application/json]}\" onto public org.springframework.http.ResponseEntity<org.springframework.hateoas.ResourceSupport> org.springframework.data.rest.webmvc.RepositoryEntityController.patchItemResource(org.springframework.data.rest.webmvc.RootResourceInformation,org.springframework.data.rest.webmvc.PersistentEntityResource,java.io.Serializable,org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler,org.springframework.data.rest.webmvc.support.ETag,java.lang.String) throws org.springframework.web.HttpRequestMethodNotSupportedException,org.springframework.data.rest.webmvc.ResourceNotFoundException\nMapped \"{[/{repository}/{id}],methods=[DELETE],produces=[application/hal+json || application/json]}\" onto public org.springframework.http.ResponseEntity<?> org.springframework.data.rest.webmvc.RepositoryEntityController.deleteItemResource(org.springframework.data.rest.webmvc.RootResourceInformation,java.io.Serializable,org.springframework.data.rest.webmvc.support.ETag) throws org.springframework.data.rest.webmvc.ResourceNotFoundException,org.springframework.web.HttpRequestMethodNotSupportedException\nMapped \"{[/{repository}/search],methods=[GET],produces=[application/hal+json || application/json]}\" onto public org.springframework.data.rest.webmvc.RepositorySearchesResource org.springframework.data.rest.webmvc.RepositorySearchController.listSearches(org.springframework.data.rest.webmvc.RootResourceInformation)\nMapped \"{[/{repository}/search/{search}],methods=[GET],produces=[application/hal+json || application/json]}\" onto public org.springframework.http.ResponseEntity<?> org.springframework.data.rest.webmvc.RepositorySearchController.executeSearch(org.springframework.data.rest.webmvc.RootResourceInformation,org.springframework.util.MultiValueMap<java.lang.String, java.lang.Object>,java.lang.String,org.springframework.data.rest.webmvc.support.DefaultedPageable,org.springframework.data.domain.Sort,org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler,org.springframework.http.HttpHeaders)\nMapped \"{[/{repository}/{id}/{property}/{propertyId}],methods=[GET],produces=[application/hal+json || application/json]}\" onto public org.springframework.http.ResponseEntity<org.springframework.hateoas.ResourceSupport> org.springframework.data.rest.webmvc.RepositoryPropertyReferenceController.followPropertyReference(org.springframework.data.rest.webmvc.RootResourceInformation,java.io.Serializable,java.lang.String,java.lang.String,org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler) throws java.lang.Exception\nMapped \"{[/{repository}/{id}/{property}],methods=[GET],produces=[application/hal+json || application/json]}\" onto public org.springframework.http.ResponseEntity<org.springframework.hateoas.ResourceSupport> org.springframework.data.rest.webmvc.RepositoryPropertyReferenceController.followPropertyReference(org.springframework.data.rest.webmvc.RootResourceInformation,java.io.Serializable,java.lang.String,org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler) throws java.lang.Exception\nMapped \"{[/{repository}/{id}/{property}],methods=[PATCH || PUT || POST],consumes=[application/json || application/x-spring-data-compact+json || text/uri-list],produces=[application/hal+json || application/json]}\" onto public org.springframework.http.ResponseEntity<? extends org.springframework.hateoas.ResourceSupport> org.springframework.data.rest.webmvc.RepositoryPropertyReferenceController.createPropertyReference(org.springframework.data.rest.webmvc.RootResourceInformation,org.springframework.http.HttpMethod,org.springframework.hateoas.Resources<java.lang.Object>,java.io.Serializable,java.lang.String) throws java.lang.Exception\n```\nAs we can see, Spring Data Rest exposes a variety of URIs with varying request methods. All of these resources will be examined in the next section.\n\n## RESTful APIs exposed by Spring Data Rest\n\nLet's have a look at some of the Resource URIs offered by Spring Data Rest in this section.\n\n### Spring Data Rest API - Get All Data for Resource\n\n  localhost:8080/students\n- Request Method - GET\nResponse\n```json\n{\n  \"_embedded\" : {\n    \"students\" : [ {\n      \"name\" : \"Ranga\",\n      \"passportNumber\" : \"E1234567\",\n      \"_links\" : {\n        \"self\" : {\n          \"href\" : \"http://localhost:8080/students/10001\"\n        },\n        \"student\" : {\n          \"href\" : \"http://localhost:8080/students/10001\"\n        }\n      }\n    }, {\n      \"name\" : \"Ravi\",\n      \"passportNumber\" : \"A1234568\",\n      \"_links\" : {\n        \"self\" : {\n          \"href\" : \"http://localhost:8080/students/10002\"\n        },\n        \"student\" : {\n          \"href\" : \"http://localhost:8080/students/10002\"\n        }\n      }\n    } ]\n  },\n  \"_links\" : {\n    \"self\" : {\n      \"href\" : \"http://localhost:8080/students{?page,size,sort}\",\n      \"templated\" : true\n    },\n    \"profile\" : {\n      \"href\" : \"http://localhost:8080/profile/students\"\n    }\n  },\n  \"page\" : {\n    \"size\" : 20,\n    \"totalElements\" : 2,\n    \"totalPages\" : 1,\n    \"number\" : 0\n  }\n}\n```\n\nNotes:\n- `_embedded` - Details of all students are part of this JSON element.\n- `_links` - This section contains the links to other related resources - HATEOAS. \n- `page` - This section contains the details of current page if we are using pagination. For example - http://localhost:8080/students?page=1 (0 indexed) will retrieve the second page of results. In this case, the page will be empty.\n- Support for sorting - http://localhost:8080/students?sort=passportNumber : Sort by passport number. Ravi would appear in the results before Ranga because his passport starts with \"A\".\n\n### Student RESTful API - POST Method\n\n- URI - http://localhost:8080/students\n- Request Method - POST\n- Content-Type - application/json\n\nRequest Body Content\n```json\n{\n  \"name\": \"Adam\",\n  \"passportNumber\": \"Z1234567\"\n}\n\n```\n\nWhen we execute the above request, a new student is created.\n\nResponse\n```json\n{\n    \"name\": \"Adam\",\n    \"passportNumber\": \"Z1234567\",\n    \"_links\": {\n        \"self\": {\n            \"href\": \"http://localhost:8080/students/1\"\n        },\n        \"student\": {\n            \"href\": \"http://localhost:8080/students/1\"\n        }\n    }\n}\n```\nThe response contains the URI to the created resource. Response Status - 201 CREATED.\n\nScreenshot below shows a screenshot of executing the POST request using POSTMan\n\n![Image](/images/SpringDataREST-ExectingPostRequest.png \"Spring Data Rest with Spring Boot and JPA - Post Request\")\n\n### Student RESTful API - GET Method\n\n- URI - http://localhost:8080/students\n- Request Method - GET\n\nWhen we execute the above request, details of a student are retrieved.\n\nResponse\n```json\n{\n    \"name\": \"Adam\",\n    \"passportNumber\": \"Z1234567\",\n    \"_links\": {\n        \"self\": {\n            \"href\": \"http://localhost:8080/students/1\"\n        },\n        \"student\": {\n            \"href\": \"http://localhost:8080/students/1\"\n        }\n    }\n}\n```\n\n### Student RESTful API - PUT Method\n\nUsed to update the details of a Student\n\n- URI - http://localhost:8080/students/1\n- Request Method - PUT\n- Content-Type - application/json\n\nRequest Body Content\n```json\n{\n  \"name\": \"Adam\",\n  \"passportNumber\": \"Z12345678\"\n}\n\n```\n\nWhen we execute the above request, student details are updated.\n\nResponse\n```json\n{\n    \"name\": \"Adam\",\n    \"passportNumber\": \"Z12345678\",\n    \"_links\": {\n        \"self\": {\n            \"href\": \"http://localhost:8080/students/1\"\n        },\n        \"student\": {\n            \"href\": \"http://localhost:8080/students/1\"\n        }\n    }\n}\n```\nThe response contains the URI to the updated resource.\n\n### Student RESTful API - Delete Method\n\n- URI - http://localhost:8080/students/1\n- Request Method - DELETE\n\nStudent 1 is deleted.\n\n### ALPS REST API for Resource Semantics\n\n> ALPS is a data format for defining concise representations of application-level semantics, equivalent to HTML microformats in complexity. An ALPS document can be used as a profile to describe the application semantics of a document that uses an application-independent media type (such as HTML, HAL, Collection+JSON, Siren, and so on). This improves profile document reusability across media formats.\n\n- URI - http://localhost:8080/profile/students \n\nResponse\n```json\n{\n    \"alps\": {\n        \"version\": \"1.0\",\n        \"descriptors\": [\n            {\n                \"id\": \"student-representation\",\n                \"href\": \"http://localhost:8080/profile/students\",\n                \"descriptors\": [\n                    {\n                        \"name\": \"name\",\n                        \"type\": \"SEMANTIC\"\n                    },\n                    {\n                        \"name\": \"passportNumber\",\n                        \"type\": \"SEMANTIC\"\n                    }\n                ]\n            },\n            {\n                \"id\": \"get-students\",\n                \"name\": \"students\",\n                \"type\": \"SAFE\",\n                \"rt\": \"#student-representation\",\n                \"descriptors\": [\n                    {\n                        \"name\": \"page\",\n                        \"doc\": {\n                            \"value\": \"The page to return.\",\n                            \"format\": \"TEXT\"\n                        },\n                        \"type\": \"SEMANTIC\"\n                    },\n                    {\n                        \"name\": \"size\",\n                        \"doc\": {\n                            \"value\": \"The size of the page to return.\",\n                            \"format\": \"TEXT\"\n                        },\n                        \"type\": \"SEMANTIC\"\n                    },\n                    {\n                        \"name\": \"sort\",\n                        \"doc\": {\n                            \"value\": \"The sorting criteria to use to calculate the content of the page.\",\n                            \"format\": \"TEXT\"\n                        },\n                        \"type\": \"SEMANTIC\"\n                    }\n                ]\n            },\n            {\n                \"id\": \"create-students\",\n                \"name\": \"students\",\n                \"type\": \"UNSAFE\",\n                \"rt\": \"#student-representation\"\n            },\n            {\n                \"id\": \"update-student\",\n                \"name\": \"student\",\n                \"type\": \"IDEMPOTENT\",\n                \"rt\": \"#student-representation\"\n            },\n            {\n                \"id\": \"delete-student\",\n                \"name\": \"student\",\n                \"type\": \"IDEMPOTENT\",\n                \"rt\": \"#student-representation\"\n            },\n            {\n                \"id\": \"get-student\",\n                \"name\": \"student\",\n                \"type\": \"SAFE\",\n                \"rt\": \"#student-representation\"\n            },\n            {\n                \"id\": \"patch-student\",\n                \"name\": \"student\",\n                \"type\": \"UNSAFE\",\n                \"rt\": \"#student-representation\"\n            }\n        ]\n    }\n}\n```\n\n## Other Features\n\nSome of the other features of spring data rest include\n- Paging and Sorting\n- Customizing Serialization with Jackson’s ObjectMapper\n- Projections\n- Validation\n- Security\n- CORS Configurability\n\n> Refer to official documentation of Spring Data Rest for more details - https://docs.spring.io/spring-data/rest/docs/3.0.2.RELEASE/reference/html/\n"
  },
  {
    "path": "_blog/articles/2017-12-07-introduction-to-spring-data-with-spring-boot.md",
    "content": "---\nlayout:     post\ntitle:   Introduction to Spring Data - Spring Data JPA, Spring Data REST and MongoDB\ndate:       2023-04-04 12:31:19\nsummary:  The objective of Spring Data is to provide a familiar and consistent Spring-based programming model for data access. In this article, we will look at the various APIs offered by Spring Data. We'll look at Spring Data JPA and Spring Data for MongoDB briefly.\ncategories:  SpringBootJPA\npermalink:  /introduction-to-spring-data-with-spring-boot\nimage: /images/spring-data-category.png\n---\n\n![Image](/images/SpringBootWebApplication-StaticContent.png \"Spring Boot Web Application with jQuery and Bootstrap- All Files\") \n\nThis article will teach you the fundamentals of Spring Data. We will look at the different Spring Data alternatives as well as two examples: Spring Data JPA and Spring Data Mongodb.\n \n## You will learn\n- Basics of Spring Data\n- Why is Spring Data needed? \n- What are the different interfaces provided by Spring Data?\n- How to get started with Spring Data?\n\n\n\n## What is Spring Data?\n\nConsider the progress of databases in recent years.\n\nWhen Spring Framework was built in the early 2000s, the only type of database available was relational databases such as Oracle, MS SQL Server, My SQL, and others. In recent years, a broad range of databases have gained popularity, the majority of which are not relational and do not use SQL. These databases are referred to using a wide range of words. For instance, consider NoSQL. \n\nORM frameworks (Hibernate) and standards (JPA) suited relational databases well. Nevertheless, modern databases have different requirements.\n\nFrom http://projects.spring.io/spring-data/\n> The objective of Spring Data is to provide a familiar and consistent Spring-based programming model for data access while keeping the unique characteristics of the underlying data store. It makes data access technologies, relational and non-relational databases, map-reduce frameworks, and cloud-based data services simple to utilise.\n\nTo make things easier, Spring Data provides Abstractions (interfaces) that may be used regardless of the underlying data source. \n\n## Spring Data Commons\n\nSpring Data Commons offers all of the common abstractions needed to connect to various data storage. \n\n\n### Crud Repository\n`CrudRepository` is the main interface in Spring Data Commons. It offers general CRUD activities regardless of the underlying data storage. It extends Repository, which is the foundation class for all repositories that provide data store access. \n\nThe methods of the `CrudRepository` interface are all listed below.\n\n```\npublic interface CrudRepository<T, ID> extends Repository<T, ID> {\n\t<S extends T> S save(S entity);\n\n\t<S extends T> Iterable<S> saveAll(Iterable<S> entities);\n\n\tOptional<T> findById(ID id);\n\n\tboolean existsById(ID id);\n\n\tIterable<T> findAll();\n\n\tIterable<T> findAllById(Iterable<ID> ids);\n\n\tlong count();\n\n\tvoid deleteById(ID id);\n\n\tvoid delete(T entity);\n\n\tvoid deleteAll(Iterable<? extends T> entities);\n\n\tvoid deleteAll();\n}\n```\n\nThe CrudRepository's methods are self-explanatory.\n\n### PagingAndSortingRepository\n\nPagingAndSortingRepository is another key Spring Data interface. PagingAndSortingRepository allows you to\n- Sort your data using `Sort` interface\n- Paginate your data using `Pageable` interface, which provides methods for pagination - getPageNumber(), getPageSize(), next(), previousOrFirst() etc. \n\npublic abstract interface PagingAndSortingRepository extends CrudRepository {\n  \n  public Iterable findAll(Sort sort);\n  \n  public Page findAll(Pageable pageable);\n\n}\n\n### Defining Custom Repositories\n\nYou may build your own repository by extending one of the repository classes: Repository, PagingAndSortingRepository, or CrudRepository.\n\nAn example is shown below\n```java\ninterface PersonRepository extends CrudRepository<User, Long> {\n```\n\n### Defining custom queries\nSpring Data also supports query generation from interface method names.\n\nConsider the following example:\n\n```java\n  List<Person> findByFirstNameAndLastname(String firstName, String lastname);\n```\n\nThe approach described above allows you to search a data store by entering a person's first and last name. This would construct the proper query for the data store, which would yield the person's information.\n\n> You can find more details in the spring data documentation - https://docs.spring.io/spring-data/commons/docs/current/reference/html/#repositories.query-methods.query-creation\n\n### Auditing with Spring Data\n\nSpring Data also supports auditing with simple annotations.\n\n```java\nclass Student {\n\n  @CreatedBy\n  private User createdUser;\n\n  @CreatedDate\n  private DateTime createdDate;\n\n  // further properties omitted\n}\n```\n\nThere are corresponding annotations for updates as well\n- LastModifiedBy\n- LastModifiedDate\n\n## Spring Data Implementations\n\nThere are Spring Data Modules for any data store you want to utilise.\n- Spring Data JPA - ORM frameworks are used to connect to relational databases.\n- Spring Data MongoDB - Repositories for MongoDB.\n- Spring Data REST - HATEOAS RESTful resources are exposed around Spring Data repositories.\n- Spring Data Redis - Repositories for Redis.\n\n### Spring Data JPA\n\nSpring Data JPA makes it possible to connect to relational databases through ORM frameworks.\n\nThe dependency is shown below:\n\n```xml\n<dependencies>\n  <dependency>\n    <groupId>org.springframework.data</groupId>\n    <artifactId>spring-data-jpa</artifactId>\n  </dependency>\n<dependencies>\n```\n\nHibernate is the default JPA implementation.\n\nThe core interface is the JpaRepository.\n\n```java\npublic interface JpaRepository<T, ID> \n\textends PagingAndSortingRepository<T, ID>, \n\t        QueryByExampleExecutor<T>\n```\n\nSome of the extra methods it provides (in comparison to PagingAndSortingRepository) are listed below. As you can see, all of these methods are JPA-specific.\n\n```\n/**\n * Saves an entity and flushes changes instantly.\n *\n * @param entity\n * @return the saved entity\n */\n<S extends T> S saveAndFlush(S entity);\n\n\t/**\n * Deletes the given entities in a batch which means it will create a single {@link Query}. Assume that we will clear\n * the {@link javax.persistence.EntityManager} after the call.\n *\n * @param entities\n */\nvoid deleteInBatch(Iterable<T> entities);\n\n/**\n * Deletes all entities in a batch call.\n */\nvoid deleteAllInBatch();\n\n```\n\n> Recommended Reading for Spring Data JPA - http://www.springboottutorial.com/introduction-to-jpa-with-spring-boot-data-jpa\n\n\n### Spring Data REST\n\nSpring Data REST may be used to deliver HATEOAS RESTful resources that are nested within Spring Data repositories.\n\nAn example using JPA is shown below\n\n```java\n@RepositoryRestResource(collectionResourceRel = \"todos\", path = \"todos\")\npublic interface TodoRepository\n\t\textends PagingAndSortingRepository<Todo, Long> {\n\n```\n\nA few example REST Services are shown below:\n\n\n#### POST \n- URL : http://localhost:8080/todos\n- Use Header : Content-Type:application/json\n\nRequest Content \n```json\n{\n  \"user\": \"Jill\",\n  \"desc\": \"Learn Hibernate\",\n  \"done\": false\n}\n```\nResponse Content\n```json\n{\n  \"user\": \"Jill\",\n  \"desc\": \"Learn Hibernate\",\n  \"done\": false,\n  \"_links\": {\n    \"self\": {\n      \"href\": \"http://localhost:8080/todos/1\"\n    },\n    \"todo\": {\n      \"href\": \"http://localhost:8080/todos/1\"\n    }\n  }\n}\n```\nThe response contains the href of the newly created resource.\n\n#### GET\n\n- URI - http://localhost:8080/todos\n\nResponse\n```json\n{\n  \"_embedded\" : {\n    \"todos\" : [ {\n      \"user\" : \"Jill\",\n      \"desc\" : \"Learn Hibernate\",\n      \"done\" : false,\n      \"_links\" : {\n        \"self\" : {\n          \"href\" : \"http://localhost:8080/todos/1\"\n        },\n        \"todo\" : {\n          \"href\" : \"http://localhost:8080/todos/1\"\n        }\n      }\n    } ]\n  },\n  \"_links\" : {\n    \"self\" : {\n      \"href\" : \"http://localhost:8080/todos\"\n    },\n    \"profile\" : {\n      \"href\" : \"http://localhost:8080/profile/todos\"\n    },\n    \"search\" : {\n      \"href\" : \"http://localhost:8080/todos/search\"\n    }\n  },\n  \"page\" : {\n    \"size\" : 20,\n    \"totalElements\" : 1,\n    \"totalPages\" : 1,\n    \"number\" : 0\n  }\n}\n```\n\nGET to http://localhost:8080/todos/1\n```json\n{\n  \"user\" : \"Jill\",\n  \"desc\" : \"Learn Hibernate\",\n  \"done\" : false,\n  \"_links\" : {\n    \"self\" : {\n      \"href\" : \"http://localhost:8080/todos/1\"\n    },\n    \"todo\" : {\n      \"href\" : \"http://localhost:8080/todos/1\"\n    }\n  }\n}\n```\n\nSpring Data REST also allows you to search by column name.\n- Example - http://localhost:8080/todos?user=Jill\n\nSpring Data Rest can be extended by defining custom methods in the repositories.\nhttp://localhost:8080/todos/search/findByUser?user=Jill can be used expose specific search method defined below.\n\n```java\n@RepositoryRestResource(collectionResourceRel = \"todos\", path = \"todos\")\npublic interface TodoRepository\n\t\textends PagingAndSortingRepository<Todo, Long> {\n\n\tList<Todo> findByUser(@Param(\"user\") String user);\n\n}\n```\n\nSpring Data REST supports \n- Spring Data JPA\n- Spring Data MongoDB\n- Spring Data Neo4j\n- Spring Data GemFire\n- Spring Data Cassandra\n\n> Recommended Reading for Spring Data Rest - http://www.springboottutorial.com/introduction-to-spring-data-rest-using-spring-boot\n\n### Spring Data MongoDB\n\nSpring Data MongoDB supports the use of MongoDB as a data storage.\n\nThe key interface is MongoRepository.\n\n```java\npublic interface MongoRepository<T, ID> extends PagingAndSortingRepository<T, ID>, QueryByExampleExecutor<T> \n```\n\nSome of the most significant methods (in addition to PagingAndSortingRepository) are listed below. Search samples may be found here.\n\n```java\n\n\t/* \n\t * (non-Javadoc)\n\t * @see org.springframework.data.repository.query.QueryByExampleExecutor#findAll(org.springframework.data.domain.Example)\n\t */\n\t@Override\n\t<S extends T> List<S> findAll(Example<S> example);\n\n\t/* \n\t * (non-Javadoc)\n\t * @see org.springframework.data.repository.query.QueryByExampleExecutor#findAll(org.springframework.data.domain.Example, org.springframework.data.domain.Sort)\n\t */\n\t@Override\n\t<S extends T> List<S> findAll(Example<S> example, Sort sort);\n```\n\n"
  },
  {
    "path": "_blog/articles/2017-12-08-integrating-with-bootstrap-and-jquery.md",
    "content": "---\nlayout:     post\ntitle:      Spring Boot - Integrating with Bootstrap & jQuery using Web Jars\ndate:       2023-04-04 12:31:19\nsummary:    Discover how to use Web Jars to combine Spring Boot with Bootstrap and jQuery. We will create a basic web application and include the web jars for these frameworks. \ncategories:  SpringBoot\npermalink:  /spring-boot-with-jquery-and-bootstrap-web-jars\nimage: /images/spring-boot-application.png\n---\n\n![Image](/images/Spring-Initializr-Web.png \"Web, Actuator and Developer Tools\")   \n\nThis post will walk you through the process of creating a small web application with Spring Boot. We will include the Bootstrap and jQuery webjar requirements. Using jQuery and Bootstrap, we will build a basic jsp view.\n\n![Image](/images/bootstrap-and-jquery-in-dependencies.png \"Bootstrap and jQuery in dependencies\") \n \n## You will learn\n- How to bootstrap a simple project with Spring Initializr?\n- How to initialize a basic web application for Spring Boot?\n- How to add a JSP for web application?\n- How to add webjars for jQuery and Bootstrap?\n- How to create a simple view using jQuery and Bootstrap?\n\n\n## Tools you will need\n- Maven 3.0+ is your build tool\n- Your favorite IDE. We use Eclipse.\n- JDK 1.8+\n\n## Overview of the Web application\n\nWe will create an unformatted static todo page rendered using a jsp.\n\n### Files\n\nThe screenshot below displays the eclipse project with all of the files we will be creating.\n\n![Image](/images/SpringBootWebApplicationWithjQueryAndBootStrap-AllFiles.png \"Spring Boot Web Application with jQuery and Bootstrap- All Files\") \n\nA brief overview of all files\n\n- `SpringBootWebApplicationBootstrapJqueryApplication.java` - Spring Boot Application class. This initialized the Spring Boot application with auto configuration.\n- `WelcomeController.java` - A Controller with a method to redirect to the view - jsp.\n- welcome.jsp - The view - uses Jquery and Bootstrap. \n- `pom.xml` - We will add the webjar dependencies for Bootstrap and jQuery to pom.xml. \n- `application.properties` - This is typically used to configure frameworks in Spring Boot. In this example, we would configure our view resolver in application.properties.\n\n> Complete project on Github : https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-web-application-bootstrap-jquery\n\n## Bootstrapping web application with Spring Initializr\n\nUsing Spring Initializr to create a Web application is a piece of cake.  \n\n> Spring Initializr [http://start.spring.io/](http://start.spring.io/){:target=\"_blank\"} is great tool to bootstrap your Spring Boot projects.\n\n![Image](/images/Spring-Initializr-Web.png \"Web, Actuator and Developer Tools\")   \n\nAs shown in the image above, following steps have to be done\n\n- Launch Spring Initializr and choose the following\n  - Choose `com.in28minutes.springboot.web.application` as Group\n  - Choose `spring-boot-web-application-bootstrap-jquery` as Artifact\n  - Choose following dependencies\n    - Web\n    - Actuator\n    - DevTools\n- Click Generate Project.\n- Import the project into Eclipse.\n- If you want to understand all the files that are part of this project, you can go here.\n\n## Project Dependencies\n\nSpring Boot Starter Web includes all of the dependencies and auto-configuration required to create web apps. That is the first dependence that we would employ.\n\n```xml\n<dependency>\n    <groupId>org.springframework.boot</groupId>\n    <artifactId>spring-boot-starter-web</artifactId>\n</dependency>\n```\n\nAs the view, we intend to utilise JSP. Tomcat is the default embedded servlet container for Spring Boot Starter Web. To enable JSP support, we'd need to add a reliance on tomcat-embed-jasper.\n\n```\n<dependency>\n    <groupId>org.apache.tomcat.embed</groupId>\n    <artifactId>tomcat-embed-jasper</artifactId>\n    <scope>provided</scope> // default while using IntelliJ IDE\n</dependency>\n```\n\n## Configuring a View Resolver\n\nOur jsps would be under /WEB-INF/jsp/. The view resolver would need to be configured with the prefix and suffix.\n\n```properties\nspring.mvc.view.prefix=/WEB-INF/jsp/\nspring.mvc.view.suffix=.jsp\n```\n\n## Controller\n\nLet's build a basic controller that redirects to the view.\n\n/src/main/java/com/in28minutes/springboot/tutorial/basics/application/configuration/WelcomeController.java\n\n```java\n@Controller\npublic class WelcomeController {    \n    @RequestMapping(\"/welcome\")\n    public String loginMessage(){\n        return \"welcome\";\n    }\n}\n```\n\nThe url to this controlle method will be http://localhost:8080/welcome\n\n## Adding a view\n\nLet's start with a simple HTML structure. We'll start by making a basic table, which we'll prepare later. \n\n/src/main/webapp/WEB-INF/jsp/welcome.jsp\n\n```jsp\n<html>\n<head>\n    <title>Welcome</title>\n</head>\n<body>\n    <div class=\"container\">\n        <table class=\"table table-striped\">\n            <caption>Your todos are</caption>\n            <thead>\n                <tr>\n                    <th>Description</th>\n                    <th>Target Date</th>\n                    <th>Is it Done?</th>\n                    <th>Edit</th>\n                    <th>Delete</th>\n                </tr>\n            </thead>\n            <tbody>\n                    <tr>\n                        <td>Todo 1</td>\n                        <td>10/12/2017</td>\n                        <td>No</td>\n                        <td><a class=\"btn btn-warning\" href=\"/edit-todo\">Edit Todo</a></td>\n                        <td><a class=\"btn btn-warning\" href=\"/delete-todo\">Delete Todo</a></td>\n                    </tr>\n            </tbody>\n        </table>\n        <div>\n            <a class=\"btn btn-default\" href=\"/add-todo\">Add a Todo</a>\n            \n        </div>\n    </div>\n</body>\n</html>\n```\n## Webjars for jQuery and Bootstrap\n\nLet's now include the webjars in our `pom.xml` file.\n\n```xml\n<dependency>\n    <groupId>org.webjars</groupId>\n    <artifactId>bootstrap</artifactId>\n    <version>3.3.6</version>\n</dependency>\n\n<dependency>\n    <groupId>org.webjars</groupId>\n    <artifactId>bootstrap-datepicker</artifactId>\n    <version>1.0.1</version>\n</dependency>\n\n<dependency>\n    <groupId>org.webjars</groupId>\n    <artifactId>jquery</artifactId>\n    <version>1.9.1</version>\n</dependency>\n```\n\n## Using Web Jars in View\n\nRestart the application, and we're ready to use jquery and bootstrap in our project.\n\nYou should be able to view the dependencies if you increase your dependencies.\n\n![Image](/images/bootstrap-and-jquery-in-dependencies.png \"Bootstrap and jQuery in dependencies\") \n\nReferring to bootstrap css\n```html\n    <link href=\"webjars/bootstrap/3.3.6/css/bootstrap.min.css\"\n        rel=\"stylesheet\">\n```\n\nReferring to Bootstrap js\n```js\n\n<script src=\"webjars/bootstrap/3.3.6/js/bootstrap.min.js\"></script>\n\n```\n\nReferring to jQuery js\n```html\n<script src=\"webjars/jquery/1.9.1/jquery.min.js\"></script>\n```\nUpdate view using jQuery and Bootstrap is shown below.\n\n/src/main/webapp/WEB-INF/jsp/welcome.jsp\n\n```html\n<html>\n<head>\n    <title>Welcome</title>\n    <link href=\"webjars/bootstrap/3.3.6/css/bootstrap.min.css\"\n        rel=\"stylesheet\">\n</head>\n<body>\n    <div class=\"container\">\n        <table class=\"table table-striped\">\n            <caption>Your todos are</caption>\n            <thead>\n                <tr>\n                    <th>Description</th>\n                    <th>Target Date</th>\n                    <th>Is it Done?</th>\n                    <th>Edit</th>\n                    <th>Delete</th>\n                </tr>\n            </thead>\n            <tbody>\n                    <tr>\n                        <td>Todo 1</td>\n                        <td>10/12/2017</td>\n                        <td>No</td>\n                        <td><a class=\"btn btn-warning\" href=\"/edit-todo\">Edit Todo</a></td>\n                        <td><a class=\"btn btn-warning\" href=\"/delete-todo\">Delete Todo</a></td>\n                    </tr>\n            </tbody>\n        </table>\n        <div>\n            <a class=\"btn btn-default\" href=\"/add-todo\">Add a Todo</a>\n            \n        </div>\n        <script src=\"webjars/jquery/1.9.1/jquery.min.js\"></script>\n        <script src=\"webjars/bootstrap/3.3.6/js/bootstrap.min.js\"></script>\n    </div>\n</body>\n</html>\n```\n\nSpring Boot would configure the webjars resource mapping automatically. Therefore you NO LONGER NEED TO DO THIS.\n\n```xml\n    <mvc:resources mapping=\"/webjars/**\" location=\"/webjars/\"/>\n```\n"
  },
  {
    "path": "_blog/articles/2017-12-09-integrating-static-content-css-js-with-spring-boot.md",
    "content": "---\nlayout:     post\ntitle:      Spring Boot - Integrating Static Content -  Javascript (JS) and CSS files \ndate:       2023-04-04 12:31:19\nsummary:    Discover how to use Spring Boot in conjunction with Static Content - Javascript (JS) and CSS files. We'll create a small web application and populate it with static content for various frameworks. \ncategories:  SpringBoot\npermalink:  /spring-boot-with-static-content-css-and-javascript-js\nimage: /images/spring-boot-application.png\n---\n\n![Image](/images/Spring-Initializr-Web.png \"Web, Actuator and Developer Tools\")   \n\nThis tutorial will lead you through the steps of developing a tiny web application using Spring Boot. A JSP view will add and utilise static content (css and js). \n \n![Image](/images/SpringBootWebApplication-StaticContent.png \"Spring Boot Web Application with jQuery and Bootstrap- All Files\") \n\n## You will learn\n- How to bootstrap a simple project with Spring Initializr?\n- How to initialize a basic web application for Spring Boot?\n- How to add a JSP for web application?\n- How to add static content - JS and CSS?\n\n## Tools you will need\n- Maven 3.0+ is your build tool\n- Your favorite IDE. We use Eclipse.\n- JDK 1.8+\n\n## Overview of the Web application\n\nWe will create an unformatted static todo page rendered using a jsp.\n\n### Files\n\nThe screenshot below displays the eclipse project with all of the files we will be creating.\n\n![Image](/images/SpringBootWebApplication-StaticContent.png \"Spring Boot Web Application with jQuery and Bootstrap- All Files\") \n\nA brief overview of all files\n\n- `SpringBootWebApplicationBootstrapJqueryApplication.java` - Spring Boot Application class. This initializes the Spring Boot application with auto configuration.\n- `WelcomeController.java` - A Controller with a method to redirect to the view - jsp.\n- welcome.jsp - The view - using the custom js and css. \n- `application.properties` - This is typically used to configure frameworks in Spring Boot. In this example, we would configure our view resolver in application.properties.\n- custom.css - contains some basic css.\n- custom.js - contains a javascript alert.\n\n> Complete project on Github : https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-web-application-bootstrap-jquery\n\n## Bootstrapping web application with Spring Initializr\n\nUsing Spring Initializr to create a Web application is a piece of cake. \n\n> Spring Initializr [http://start.spring.io/](http://start.spring.io/){:target=\"_blank\"} is great tool to bootstrap your Spring Boot projects.\n\n![Image](/images/Spring-Initializr-Web.png \"Web, Actuator and Developer Tools\")   \n\nAs seen in the image above, the following actions must be taken.\n\n- Launch Spring Initializr and choose the following\n  - Choose `com.in28minutes.springboot.web.application` as Group\n  - Choose `spring-boot-web-application-bootstrap-jquery` as Artifact\n  - Choose following dependencies\n    - Web\n    - Actuator\n    - DevTools\n- Click Generate Project.\n- Import the project into Eclipse.\n- If you want to understand all the files that are part of this project, you can go here.\n\n## Project Dependencies\n\nSpring Boot Starter Web includes all of the dependencies and auto-configuration required to create web apps. That is the first dependence that we would employ.\n\n```xml\n<dependency>\n    <groupId>org.springframework.boot</groupId>\n    <artifactId>spring-boot-starter-web</artifactId>\n</dependency>\n```\n\nAs the view, we intend to utilise JSP. Tomcat is the default embedded servlet container for Spring Boot Starter Web. To enable JSP support, we'd need to add a reliance on tomcat-embed-jasper.\n\n```xml\n<dependency>\n    <groupId>org.apache.tomcat.embed</groupId>\n    <artifactId>tomcat-embed-jasper</artifactId>\n    <scope>provided</scope> // default for IntelliJ IDE\n</dependency>\n```\n\n## Configuring a View Resolver\n\nOur jsps would be under /WEB-INF/jsp/. The view resolver would need to be configured with the prefix and suffix.\n\n```properties\nspring.mvc.view.prefix=/WEB-INF/jsp/\nspring.mvc.view.suffix=.jsp\n```\n\n## Controller\n\nLets add in a simple controller redirecting to the view.\n\n/src/main/java/com/in28minutes/springboot/tutorial/basics/application/configuration/WelcomeController.java\n\n```java\n@Controller\npublic class WelcomeController {    \n    @RequestMapping(\"/welcome\")\n    public String loginMessage(){\n        return \"welcome\";\n    }\n}\n```\n\nThe url to this controlle method will be http://localhost:8080/welcome\n\n## Adding a view\n\nLet's start with a simple HTML structure. We'll start by making a basic table, which we'll prepare later.\n\n/src/main/webapp/WEB-INF/jsp/welcome.jsp\n\n```html\n<html>\n<head>\n    <title>Welcome</title>\n</head>\n<body>\n    <div class=\"container\">\n        <table class=\"table table-striped\">\n            <caption>Your todos are</caption>\n            <thead>\n                <tr>\n                    <th>Description</th>\n                    <th>Target Date</th>\n                    <th>Is it Done?</th>\n                    <th>Edit</th>\n                    <th>Delete</th>\n                </tr>\n            </thead>\n            <tbody>\n                    <tr>\n                        <td>Todo 1</td>\n                        <td>10/12/2017</td>\n                        <td>No</td>\n                        <td><a class=\"btn btn-warning\" href=\"/edit-todo\">Edit Todo</a></td>\n                        <td><a class=\"btn btn-warning\" href=\"/delete-todo\">Delete Todo</a></td>\n                    </tr>\n            </tbody>\n        </table>\n        <div>\n            <a class=\"btn btn-default\" href=\"/add-todo\">Add a Todo</a>\n            \n        </div>\n    </div>\n</body>\n</html>\n```\n## Adding Static Content CSS and JS\n\nThe recommended folder for static content is `/src/main/resources/static`. \n\nAs stated below, we will generate the CSS. It gives the body of the page a light blue background colour.\n\n/src/main/resources/static/css/custom.css\n```css\nbody {\n    background-color: lightblue;\n}\n```\n\nWe will create a custom js file throwing an alert\n\n### /src/main/resources/static/js/custom.js\n\n```js\nalert(\"I'm active\");\n```\n\n## Using JS and CSS in View\n\n\nReferring to JS file\n```js\n<script src=\"js/custom.js\"></script>\n```\n\nReferring to jQuery js\n```js\n<link href=\"css/custom.css\"\n        rel=\"stylesheet\">\n```\n\nComplete updated view is shown below.\n\n/src/main/webapp/WEB-INF/jsp/welcome.jsp\n\n```\n<html>\n<head>\n    <title>Welcome</title>\n    <link href=\"css/custom.css\"\n        rel=\"stylesheet\">\n</head>\n<body>\n    <div class=\"container\">\n        <table class=\"table table-striped\">\n            <caption>Your todos are</caption>\n            <thead>\n                <tr>\n                    <th>Description</th>\n                    <th>Target Date</th>\n                    <th>Is it Done?</th>\n                    <th>Edit</th>\n                    <th>Delete</th>\n                </tr>\n            </thead>\n            <tbody>\n                    <tr>\n                        <td>Todo 1</td>\n                        <td>10/12/2017</td>\n                        <td>No</td>\n                        <td><a class=\"btn btn-warning\" href=\"/edit-todo\">Edit Todo</a></td>\n                        <td><a class=\"btn btn-warning\" href=\"/delete-todo\">Delete Todo</a></td>\n                    </tr>\n            </tbody>\n        </table>\n        <div>\n            <a class=\"btn btn-default\" href=\"/add-todo\">Add a Todo</a>\n            \n        </div>\n        <script src=\"js/custom.js\"></script>\n    </div>\n</body>\n</html>\n```\n"
  },
  {
    "path": "_blog/articles/2017-12-10-spring-boot-project-with-eclipse-and-maven-top20.md",
    "content": "---\nlayout:     post\ntitle:      Creating a Spring Boot Project with Eclipse and Maven\ndate:       2023-04-05 12:31:19\nsummary:    Spring Boot makes it simple to set up a basic project. In this tutorial, we will look at how to create Spring Boot projects with Maven and Eclipse. \ncategories:  SpringBoot\npermalink:  /creating-spring-boot-project-with-eclipse-and-maven\nimage: /images/spring-boot-category.png\n---\n\n![Image](/images/Spring-Initializr-Web.png \"Web, Actuator and Developer Tools\")   \n\nSpring Boot makes it simple to set up a basic project. In this tutorial, we will look at how to create Spring Boot projects with Maven, Eclipse or IntelliJ.\n\n![Image](/images/CreatingSpringBootProject-Option1-SpringInitializr-Screen2.png \"CreatingSpringBootProject-Option1-SpringInitializr-Screen2\")  \n \n## You will learn\n- How to bootstrap a simple project with Spring Initializr?\n- How to use Spring Starter Eclipse Plugin to create a simple project with Spring Boot, Maven and Eclipse? \n- How to create a Spring Boot Project manually step by step?\n\n\n## Tools you will need\n- Maven 3.0+ is your build tool\n- Your favorite IDE. We use Eclipse or IntelliJ.\n- JDK 17+\n\n## Introduction to Maven\n\n### Q :  Why Maven?\n\nYou do not want to keep all of your libraries in your project!\n\nYou want to tell the tool that I require A, B, and C, and you want it to download the libraries and make them accessible to you.\n\nMaven is the name. The application that you use to manage your libraries.\n\nWhenever you require a new version of the library, simply change the version number and your project is complete!\n\nYou also don't have to worry about which libraries your library need to function. Spring, for example, may require additional libraries like as logging, xml, and so on.\n\nWhen you declare Spring as a dependency, Maven will download it.\n\n- Spring\n- And all dependencies of Spring\n\nIsn't that cool?\n\n## Big Picture of Maven\n\nIt is tough to define what Maven accomplishes.\n\nEvery day, Developer undertakes a variety of tasks.\n- Manages Dependencies \n    - Web Layer (Spring MVC)\n    - Data Layer (JPA - Hibernate) etc.                  \n- Build a jar or a war or an ear\n- Run the application locally \n    - Tomcat or Jetty\n- Deploy to a T environment\n- Add new dependencies to a project\n- Run Unit Tests\n- Generate Projects\n- Create Eclipse or IntelliJ Workspace\n\n > Maven helps us do all these and more...\n\n#### Naming a project\n\nDependencies are specified in your `pom.xml` file.\n\nMaven would fetch the dependencies and include them in your project.\n\nYet, how does Maven know which dependencies to download?\n\nYou must explain it by providing specifics about the dependency.\n\nA maven artefact may be identified by a GroupId and an ArtifactId, much way a Java class can be identified by a class name and a package name.\n\n```xml\n    <groupId>com.in28minutes.learning.maven</groupId>\n    <artifactId>maven-in-few-steps</artifactId>\n```\n\n#### Declaring Dependencies\n\nDependencies are frameworks required to construct your project.\n\nIn the example below we are adding two dependencies.\n\n```xml\n<dependency>\n    <groupId>org.springframework.boot</groupId>\n    <artifactId>spring-boot-starter-web</artifactId>\n</dependency>\n\n<dependency>\n    <groupId>org.springframework.boot</groupId>\n    <artifactId>spring-boot-starter-test</artifactId>\n    <scope>test</scope>\n</dependency>\n```\n\n### Maven Build Life Cycle\nWhen we execute \"mvn clean install,\" we finish the whole maven build life cycle.\n\nLifeCycle construction is a series of phases.\n - Validate\n - Compile\n - Test\n - Package\n - Integration Test\n - Verify\n - Install\n - Deploy\n\n> Maven follows Convention over Configuration.\n\nPre defined folder structure\n- Source Code\n    - ${basedir}/src/main/java\n    - ${basedir}/src/main/resources\n- Test Code\n    - ${basedir}/src/test\n\n### How does Maven Work?\n\nAll jars in the Maven Repository are indexed by artefact id and group id.\n\nWhen we add a dependence to our `pom.xml`, maven queries the maven repository for jar dependencies, using the group id and artefact id as input. \n- Maven repository stores all the versions of all dependencies. JUnit 4.2,4.3,4.4\n \nThe jar dependencies are saved on your system in the maven local repository folder. All of our projects would make use of the jars in the maven local repository.\n\n> Local Repository : a temp folder on your machine where maven stores the jar and dependency files that are downloaded from Maven Repository.\n\n### Important Maven Commands\n - mvn --version -> Find the maven version\n - mvn compile -> compiles source files\n - mvn test-compile -> compiles test files - one thing to observe is this also compiles source files\n - mvn clean -> deletes target directory\n - mvn test -> run unit tests\n - mvn package -> creates a jar for the project\n- help:effective-settings -> Debug Maven Settings\n- help:effective-pom -> Look at the complete pom after all inheritances from parent poms are resolved\n- dependency:tree -> Look at all the dependencies and transitive dependencies\n- dependency:sources -> Download source code for all dependencies\n- --debug -> Debug flag. Can be used with all the above commands\n\n---\n\n<a href=\"https://links.in28minutes.com/in28minutes-Microservices\" ><img src=\"https://www.springboottutorial.com/images/Course-Master-Microservices-with-Spring-Boot-and-Spring-Cloud.png\" alt=\"Image\" title=\"Master Microservices with Spring Boot and Spring Cloud\"></a>\n\n---\n\n## Creating Spring Boot Projects with Eclipse and Maven\n\nThere are three options to create Spring Boot Projects with Eclipse and Maven\n- Spring Initializr - https://start.spring.io\n- Use STS or STS Eclipse Plugin and Create a Spring Boot Maven Project directly from Eclipse\n- Manually Create a Maven Project and add Spring Boot Starter Dependencies.\n\nWe will use a Spring Boot Starter Web as an example.\n\n### Option 1 - Bootstrapping Spring Boot Project with Spring Initializr\n\nCreating a Web application with Spring Initializr is a cake walk. We will use Spring Web MVC as our web framework.  \n\n> Spring Initializr [http://start.spring.io/](http://start.spring.io/){:target=\"_blank\"} is great tool to bootstrap your Spring Boot projects.\n\n![Image](/images/Spring-Initializr-Web.png \"Web, Actuator and Developer Tools\")   \n\nAs shown in the image above, following steps have to be done\n\n- Launch Spring Initializr and choose the following\n  - Choose `com.in28minutes.springboot` as Group\n  - Choose `student-services` as Artifact\n  - Choose following dependencies\n    - Web\n    - Actuator\n    - DevTools\n- Click Generate Project.\n\nThis would download a zip file to your local machine. \n\nUnzip the zip file and extract to a folder.\n\nIn Eclipse, Click File -> Import -> Existing Maven Project as shown below.\n\n![Image](/images/CreatingSpringBootProject-Option1-SpringInitializr-Screen2.png \"CreatingSpringBootProject-Option1-SpringInitializr-Screen2\")\n\nNavigate or type in the path of the folder where you extracted the zip file to in the next screen.\n\n![Image](/images/CreatingSpringBootProject-Option1-SpringInitializr-Screen3.png \"CreatingSpringBootProject-Option1-SpringInitializr-Screen3\")\n\nOnce you click Finish, Maven would take some time to download all the dependencies and initialize the project. \n\nThat's it. Your first Spring Project is Ready.\n\n> Follow these links to understand more about the project that is created - [Spring Boot vs Spring vs Spring MVC](http://www.springboottutorial.com/spring-boot-vs-spring-mvc-vs-spring){:target=\"_blank\"}, [Auto Configuration](http://www.springboottutorial.com/spring-boot-auto-configuration){:target=\"_blank\"}, [Spring Boot Starter Projects](http://www.springboottutorial.com/spring-boot-starter-projects){:target=\"_blank\"}, [Spring Boot Starter Parent](http://www.springboottutorial.com/spring-boot-starter-parent){:target=\"_blank\"}, [Spring Boot Initializr](http://www.springboottutorial.com/spring-initialzr-bootstrap-spring-boot-applications){:target=\"_blank\"}\n\n### Option 2 - Using STS or STS Eclipse Plugin to create Spring Boot Maven Project\n\nYou may create a spring boot project straight from Eclipse using the Spring tool suite.\n\nYou need either download the entire STS installer or install the STS Eclipse plugin.\n\n> https://spring.io/tools/sts/all provides the complete download of STS as well as the Update Sites for STS Eclipse Plugin.\n\nIn Eclipse/STS, start with File -> New -> Spring Starter Project as shown below.\n\n![Image](/images/We \nCreatingSpringBootProject-Option2-EclipsePluginSpringStarterProject-Screen1.png \"CreatingSpringBootProject-Option2-EclipsePluginSpringStarterProject-Screen1\")\n\nIn the next screen, you can choose the following for your project.\n- Group ID\n- Artifact ID\n- Root Package\n- Version\n- Description\n- Java Version\n- Language\n- Packaging\n\nMake sure you choose Maven as Type.\n\n![Image](/images/CreatingSpringBootProject-Option2-EclipsePluginSpringStarterProject-Screen2.png \"CreatingSpringBootProject-Option2-EclipsePluginSpringStarterProject-Screen2\")\n\nIn the following page, you may specify the dependencies you wish to include in your Spring Boot project.\n\n![Image](/images/CreatingSpringBootProject-Option2-EclipsePluginSpringStarterProject-Screen3.png \"CreatingSpringBootProject-Option2-EclipsePluginSpringStarterProject-Screen3\")\n\nMaven will need some time to download all the dependencies and initialise the project when you click Complete. \n\nThat's all. Your first Spring project is complete.\n\n### Option 3 - Manually Create a Maven Spring Boot Project\n\nThe final option is to develop the project by hand.\n\nBegin by selecting File > Create > Maven Project in Eclipse.\n\nChoose Make a basic craft like the one illustrated below:\n\n![Image](/images/CreatingSpringBootProject-Option3-Manually.png \"CreatingSpringBootProject-Option3-Manually\")\n\nIn the next screen, provide these details for your project and click Finish.\n- Group ID\n- Artifact ID\n- Version\n\nThis would create a basic Maven project with Zero dependencies.\n\nNext add in the appropriate Spring Boot Starters into the pom.xml\n\n```xml\n<dependency>\n    <groupId>org.springframework.boot</groupId>\n    <artifactId>spring-boot-starter-web</artifactId>\n</dependency>\n\n<dependency>\n    <groupId>org.springframework.boot</groupId>\n    <artifactId>spring-boot-devtools</artifactId>\n    <scope>runtime</scope>\n</dependency>\n\n<dependency>\n    <groupId>org.springframework.boot</groupId>\n    <artifactId>spring-boot-starter-test</artifactId>\n    <scope>test</scope>\n</dependency>\n```\n\nStarter Web is used to create Spring Boot Web Apps or RESTful Services.\n\nStarter Test supports unit and integration testing with Spring Test, Mockito, and JUnit.\n\nThe version for these dependencies is one thing we are missing.\n\nSpring Boot Starter Parent will be added as the parent pom in the `pom.xml` file.\n```xml\n<parent>\n    <groupId>org.springframework.boot</groupId>\n    <artifactId>spring-boot-starter-parent</artifactId>\n    <version>2.3.1.RELEASE</version>\n    <relativePath /> <!-- lookup parent from repository -->\n</parent>\n\n```\n\nLet's configure the Java version to use as 17\n\n```xml\n<properties>\n    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>\n    <java.version>17</java.version>\n    <maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>\n</properties>\n```\n\nThe next step is to create a Spring Boot Application class that will be used to run the web application.\n\n/src/main/java/com/in28minutes/springboot/tutorial/SpringBootWebApplication.java\n```java\npackage com.in28minutes.springboot.tutorial;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\n@SpringBootApplication\npublic class SpringBootWebApplication {\n\n    public static void main(String[] args) {\n        SpringApplication.run(SpringBootWebApplication.class, args);\n    }\n}\n```\n\nAll that you need to do is to add `@SpringBootApplication` and use `SpringApplication.run()` static method to launch the Spring Application context.\n\nWhen you run this class as a java programme, you will see that an embedded Tomcat server will start up, and you will be able to add functionality to this application.\n\n## Conclusion\n\nIn this post, we looked at how to create Spring Boot projects with Maven and Eclipse. Option 2 of generating the project straight from Eclipse using the STS plugin is my favourite. But, you may have a preference.\n"
  },
  {
    "path": "_blog/articles/2017-12-12-logging-with-spring-boot.md",
    "content": "---\nlayout:     post\ntitle:      Logging with Spring Boot - Logback, SLF4j and LOG4j2\ndate:       2022-07-06 12:31:19\nsummary:    Learn how to log effectively with Spring Boot. We will look at Spring Boot Starter for Logging and Spring Boot starter for log4j2.\ncategories:  SpringBoot\npermalink : /logging-with-spring-boot-logback-slf4j-and-log4j\nimage: /images/spring-boot-feature.png\n---\n\nLearn how to log effectively with Spring Boot. We will look at Spring Boot Starter for Logging. We will look at the defaults in Spring Boot for Logging - Logback and SLF4J. We will also looking at the Spring Boot starter for log4j2.\n\n\n\n## Default Logging Framework with Spring Boot\n\nSpring boot provides a default starter for logging - `spring-boot-starter-logging`. It is included by default in `spring-boot-starter` which is included in all other starters.\n\n> This means whenever you use any starters like `spring-boot-starter-web` or `spring-boot-starter-data-jpa`, you get logging for free!\n\nLet's look at what is present in the Logging Starter.\n```\n<dependency>\n  <groupId>ch.qos.logback</groupId>\n  <artifactId>logback-classic</artifactId>\n  <scope>compile</scope>\n</dependency>\n<dependency>\n  <groupId>org.apache.logging.log4j</groupId>\n  <artifactId>log4j-to-slf4j</artifactId>\n  <scope>compile</scope>\n</dependency>\n<dependency>\n  <groupId>org.slf4j</groupId>\n  <artifactId>jul-to-slf4j</artifactId>\n  <scope>compile</scope>\n</dependency>\n<dependency>\n  <groupId>org.slf4j</groupId>\n  <artifactId>log4j-over-slf4j</artifactId>\n  <scope>compile</scope>\n</dependency>\n\n```\n\nAs you can see the default logging framework is Logback with SLF4j as implementation.\n\nBy default, all logging goes to console.\n\n### Configure Logging Levels\n\nIn application.properties, we can use the \"logging.level\" prefix to set logging levels.\n\n```\nlogging.level.some.package.path=DEBUG\nlogging.level.some.other.package.path=ERROR\n```\n\nRoot logging level can be configured as shown below\n```\nlogging.level.root=WARN\n```\n### Configuring a Log File\n\nYou can configure a log file by using logging.file property in application.properties. The logging here would be in addition to the logging in console.\n\n```\nlogging.file=\\path_to\\logfile.log\n```\n\n### Custom configuration using logback.xml\nSpring Boot will pick up all custom configuration using logback.xml as long as it is in the application class path.\n\n### Example code\n\n```\nLOGGER.trace(\"Your log - {}\", value);\nLOGGER.debug(\"debug - {}\", value);\nLOGGER.info(\"info- {}\", value);          \nLOGGER.warn(\"warn - {}\", value);          \nLOGGER.error(\"error - {}\", value);\n```\n\n## Using Log4j2 for logging with Spring Boot\n\nWe would need to exclude the dependency on `spring-boot-starter-logging` and add a dependency on `spring-boot-starter-log4j2`.\n\n```\n<dependency>\n    <groupId>org.springframework.boot</groupId>\n    <artifactId>spring-boot-starter</artifactId>\n    <exclusions>\n        <exclusion>\n            <groupId>org.springframework.boot</groupId>\n            <artifactId>spring-boot-starter-logging</artifactId>\n        </exclusion>\n    </exclusions>\n</dependency>\n<dependency>\n    <groupId>org.springframework.boot</groupId>\n    <artifactId>spring-boot-starter-log4j2</artifactId>\n</dependency>\n```\n\nLet's take a quick look at the dependencies in log4j2 starter.\n\n```\n<dependency>\n  <groupId>org.apache.logging.log4j</groupId>\n  <artifactId>log4j-slf4j-impl</artifactId>\n  <scope>compile</scope>\n</dependency>\n<dependency>\n  <groupId>org.apache.logging.log4j</groupId>\n  <artifactId>log4j-api</artifactId>\n  <scope>compile</scope>\n</dependency>\n<dependency>\n  <groupId>org.apache.logging.log4j</groupId>\n  <artifactId>log4j-core</artifactId>\n  <scope>compile</scope>\n</dependency>\n<dependency>\n  <groupId>org.slf4j</groupId>\n  <artifactId>jul-to-slf4j</artifactId>\n  <scope>compile</scope>\n</dependency>\n```\n\n### Custom configuration using log4j2.xml\nSpring Boot will pick up all custom configuration using log4j2.xml as long as it is in the application class path.\n\nYou also have the option of using YAML or JSON with Log4j2.\n- YAML - log4j2.yaml or log4j2.yml\n- JSON - log4j2.json or log4j2.jsn\n\nHowever, you would need to include the appropriate dependency to handle yaml(jackson-dataformat-yaml) or json(jackson-databind).\n\n"
  },
  {
    "path": "_blog/articles/2017-12-13-spring-boot-unit-testing-with-junit-and-mockito-top20.md",
    "content": "---\nlayout:     post\ntitle:   Spring Boot - Unit Testing and Mocking with Mockito and JUnit\ndate:       2022-01-02 12:31:19\nsummary:    Learn the basics of JUnit and Mockito. We will Spring Boot to create a Business Service and Data Services. We will unit test the Business Service using Spring Boot, Mockito and JUnit in two different approaches. \ncategories:  SpringBootUnitTesting\npermalink:  /spring-boot-unit-testing-and-mocking-with-mockito-and-junit\nimage: /images/unit-test-category.png\n---\n\n![Image](/images/SpringBootWithMockito-ProjectStructure.png \"Spring Boot with Mockito - Project Structure\") \n\nThis guide will help you create great unit tests with JUnit and Mockito for your Spring Boot Projects. We will use two difference approaches to write unit tests.\n \n![Image](/images/spring-initializer-web-h2-devtools-jdbc.png \"Web, JDBC,H2 and Developer Tools\")\n\n\n## You will learn\n- What is JUnit?\n- What is Mockito?\n- How to create a simple Spring Boot project with Unit Testing?\n- How to write unit tests with Mockito using @Mock and @InjectMocks without launching up a Spring Context?\n- How to write a unit test with mocking and launching up the complete Spring Context using @MockBean?\n\n\n## Project Code Structure\n\nFollowing screenshot shows the structure of the project we will create.\n\n![Image](/images/SpringBootWithMockito-ProjectStructure.png \"Spring Boot with Mockito - Project Structure\") \n\nA few details:\n\n- `BusinessService.java` - The Business Service that we want to test.\n- `DataService.java` - DataService is a dependency of the BusinessService. We would want to mock the DataService in  our unit tests.\n- `BusinessServiceMockTest.java` - Unit test using basic mocking with @Mock and @InjectMocks. This unit test does not launch up a Spring Context.\n- `BusinessServiceMockSpringContextTest.java` - Unit test launching the complete spring context to test BusinessService.\n- SpringBootTutorialBasicsApplication.java - The main Spring Boot Application class which is used to launch up the application.\n- `pom.xml` - Contains all the dependencies needed to build this project. We will use Spring Boot Starter Web and Test other than Developer Tools.\n\n## Tools you will need\n- Maven 3.0+ is your build tool\n- Your favorite IDE. We use Eclipse.\n- JDK 1.8+\n\n## Complete Maven Project With Code Examples\n> Our Github repository has all the code examples - https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-tutorial-basics\n\n## Introduction to JUnit\n\nJUnit is the most popular Java Unit testing framework\n\nWe typically work in large projects  - some of these projects have more than 2000 source files or sometimes it might be as big as 10000 files with one million lines of code. \n\nBefore unit testing, we depend on deploying the entire app and checking if the screens look great. But that's not very efficient. And it is manual.\n\nUnit Testing focuses on writing automated tests for individual classes and methods. \n\nJUnit is a framework which will help you call a method and check (or assert) whether the output is as expected. \n\nThe important thing about automation testing is that these tests can be run with continuous integration - as soon as some code changes.\n\nExample Source Code to Test\n```java\npackage com.in28minutes.junit;\n\npublic class MyMath {\n\tint sum(int[] numbers) {\n\t\tint sum = 0;\n\t\tfor (int i : numbers) {\n\t\t\tsum += i;\n\t\t}\n\t\treturn sum;\n\t}\n}\n```\n\nUnit test for the sum method\n```java\npackage com.in28minutes.junit;\n\nimport static org.junit.Assert.assertEquals;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\npublic class MyMathTest {\n\tMyMath myMath = new MyMath();\n\n\t// MyMath.sum\n\t// 1,2,3 => 6\n\t@Test\n\tpublic void sum_with3numbers() {\n\t\tSystem.out.println(\"Test1\");\n\t\tassertEquals(6, myMath.sum(new int[] { 1, 2, 3 }));\n\t}\n\n\t@Test\n\tpublic void sum_with1number() {\n\t\tSystem.out.println(\"Test2\");\n\t\tassertEquals(3, myMath.sum(new int[] { 3 }));\n\t}\n}\n```\nOther Important JUnit annotations\n- @Before @After annotations\n\t- Run before and after every test method in the class\n- @BeforeClass @AfterClass annotations\n\t- Static methods which are executed once before and after a test class\n\n\n```java\npackage com.in28minutes.junit;\n\nimport static org.junit.Assert.assertEquals;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\npublic class MyMathTest {\n\tMyMath myMath = new MyMath();\n\n\t@Before\n\tpublic void before() {\n\t\tSystem.out.println(\"Before\");\n\t}\n\n\t@After\n\tpublic void after() {\n\t\tSystem.out.println(\"After\");\n\t}\n\n\t@BeforeClass\n\tpublic static void beforeClass() {\n\t\tSystem.out.println(\"Before Class\");\n\t}\n\n\t@AfterClass\n\tpublic static void afterClass() {\n\t\tSystem.out.println(\"After Class\");\n\t}\n\n\t// MyMath.sum\n\t// 1,2,3 => 6\n\t@Test\n\tpublic void sum_with3numbers() {\n\t\tSystem.out.println(\"Test1\");\n\t\tassertEquals(6, myMath.sum(new int[] { 1, 2, 3 }));\n\t}\n\n\t@Test\n\tpublic void sum_with1number() {\n\t\tSystem.out.println(\"Test2\");\n\t\tassertEquals(3, myMath.sum(new int[] { 3 }));\n\t}\n}\n```\n\n## Introduction to Mockito\n\nMockito is the most popular mocking framework in Java.\n\nIn the example below SomeBusinessImpl depends on DataService. When we write a unit test for SomeBusinessImpl, we will want to use a mock DataService - one which does not connect to a database.\n\n```\npackage com.in28minutes.mockito.mockitodemo;\n\npublic class SomeBusinessImpl {\n\tprivate DataService dataService;\n\n\tpublic SomeBusinessImpl(DataService dataService) {\n\t\tsuper();\n\t\tthis.dataService = dataService;\n\t}\n\n```\n\n### Writing a test with Mockito\n\n```\npackage com.in28minutes.mockito.mockitodemo;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.mockito.Mockito.mock;\nimport static org.mockito.Mockito.when;\n\nimport org.junit.Test;\n\npublic class SomeBusinessMockTest {\n\n\t@Test\n\tpublic void testFindTheGreatestFromAllData() {\n\t\tDataService dataServiceMock = mock(DataService.class);\n\t\twhen(dataServiceMock.retrieveAllData()).thenReturn(new int[] { 24, 15, 3 });\n\t\tSomeBusinessImpl businessImpl = new SomeBusinessImpl(dataServiceMock);\n\t\tint result = businessImpl.findTheGreatestFromAllData();\n\t\tassertEquals(24, result);\n\t}\n\n\t@Test\n\tpublic void testFindTheGreatestFromAllData_ForOneValue() {\n\t\tDataService dataServiceMock = mock(DataService.class);\n\t\twhen(dataServiceMock.retrieveAllData()).thenReturn(new int[] { 15 });\n\t\tSomeBusinessImpl businessImpl = new SomeBusinessImpl(dataServiceMock);\n\t\tint result = businessImpl.findTheGreatestFromAllData();\n\t\tassertEquals(15, result);\n\t}\n\n}\n```\n\nNotes\n- ```DataService dataServiceMock = mock(DataService.class)``` - We are using the mock method to create a mock.\n- ```when(dataServiceMock.retrieveAllData()).thenReturn(new int[] { 24, 15, 3 })``` - stubbing the mock to return specific data\n\n\n### Using Mockito Annotations - @Mock, @InjectMocks, @RunWith(MockitoJUnitRunner.class)\n\n```\npackage com.in28minutes.mockito.mockitodemo;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.mockito.Mockito.when;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.mockito.InjectMocks;\nimport org.mockito.Mock;\nimport org.mockito.junit.MockitoJUnitRunner;\n\n@RunWith(MockitoJUnitRunner.class)\npublic class SomeBusinessMockAnnotationsTest {\n\n\t@Mock\n\tDataService dataServiceMock;\n\n\t@InjectMocks\n\tSomeBusinessImpl businessImpl;\n\n\t@Test\n\tpublic void testFindTheGreatestFromAllData() {\n\t\twhen(dataServiceMock.retrieveAllData()).thenReturn(new int[] { 24, 15, 3 });\n\t\tassertEquals(24, businessImpl.findTheGreatestFromAllData());\n\t}\n\n\t@Test\n\tpublic void testFindTheGreatestFromAllData_ForOneValue() {\n\t\twhen(dataServiceMock.retrieveAllData()).thenReturn(new int[] { 15 });\n\t\tassertEquals(15, businessImpl.findTheGreatestFromAllData());\n\t}\n\n\t@Test\n\tpublic void testFindTheGreatestFromAllData_NoValues() {\n\t\twhen(dataServiceMock.retrieveAllData()).thenReturn(new int[] {});\n\t\tassertEquals(Integer.MIN_VALUE, businessImpl.findTheGreatestFromAllData());\n\t}\n}\n```\nNotes\n- ```@Mock DataService dataServiceMock;``` - Create a mock for DataService.\n- ```@InjectMocks SomeBusinessImpl businessImpl;``` - Inject the mocks as dependencies into businessImpl.\n- ```@RunWith(MockitoJUnitRunner.class)``` - The JUnit Runner which causes all the initialization magic with @Mock and @InjectMocks to happen before the tests are run.\n\n## Creating the Project with Spring Initializr\n\nCreating a REST service with Spring Initializr is a cake walk.  \n\nSpring Initializr [http://start.spring.io/](http://start.spring.io/){:target=\"_blank\"} is great tool to bootstrap your Spring Boot projects.\n\n![Image](/images/spring-initializer-web-h2-devtools-jdbc.png \"Web, JDBC,H2 and Developer Tools\")\n\nAs shown in the image above, following steps have to be done\n\n- Launch Spring Initializr and choose the following\n  - Choose `com.in28minutes.springboot.tutorial.basics.example` as Group\n  - Choose `spring-boot-tutorial-basics` as Artifact\n  - Choose following dependencies\n    - Web\n    - DevTools\n- Click Generate Project.\n- Import the project into Eclipse. File -> Import -> Existing Maven Project.\n\n## Starter Projects in pom.xml\n\nBelow are a couple ofstarter projects in pom.xml. \n\n```\n<dependency>\n\t<groupId>org.springframework.boot</groupId>\n\t<artifactId>spring-boot-starter-web</artifactId>\n</dependency>\n<dependency>\n\t<groupId>org.springframework.boot</groupId>\n\t<artifactId>spring-boot-starter-test</artifactId>\n\t<scope>test</scope>\n</dependency>\n```\n\nThe important dependency for unit testing is `spring-boot-starter-test`\n\n> Spring Boot Test Starter is Starter for testing Spring Boot applications with libraries including JUnit, Hamcrest and Mockito\n\nLet's look at important dependencies in spring-boot-starter-test.\n\n```\n<dependency>\n  <groupId>junit</groupId>\n  <artifactId>junit</artifactId>\n  <version>4.12</version>\n  <scope>compile</scope>\n</dependency>\n<dependency>\n  <groupId>org.assertj</groupId>\n  <artifactId>assertj-core</artifactId>\n  <version>3.8.0</version>\n  <scope>compile</scope>\n</dependency>\n<dependency>\n  <groupId>org.mockito</groupId>\n  <artifactId>mockito-core</artifactId>\n  <version>2.11.0</version>\n  <scope>compile</scope>\n</dependency>\n<dependency>\n  <groupId>org.hamcrest</groupId>\n  <artifactId>hamcrest-core</artifactId>\n  <version>1.3</version>\n  <scope>compile</scope>\n</dependency>\n<dependency>\n  <groupId>org.hamcrest</groupId>\n  <artifactId>hamcrest-library</artifactId>\n  <version>1.3</version>\n  <scope>compile</scope>\n</dependency>\n<dependency>\n  <groupId>org.skyscreamer</groupId>\n  <artifactId>jsonassert</artifactId>\n  <version>1.5.0</version>\n  <scope>compile</scope>\n</dependency>\n<dependency>\n  <groupId>org.springframework</groupId>\n  <artifactId>spring-test</artifactId>\n  <version>5.0.1.RELEASE</version>\n  <scope>compile</scope>\n</dependency>\n\n```\n\nSpring Boot Test Starter brings in a wide range of dependencies for Unit Testing\n- Basic Test Framework - JUnit\n- Mocking - Mockito\n- Assertion - AssertJ, Hamcrest\n- Spring Unit Test Framework - Spring Test\n\n## Add the code under Test\n\nLets create a simple DataService. Actually this should talk to some database to get all the data but for now lets keep it simple and return hardcode value. This will be a dependency for the BusinessService\n\n/src/main/java/com/in28minutes/springboot/tutorial/basics/example/unittesting/DataService.java\n```java\n@Repository\npublic class DataService {\n\tpublic int[] retrieveAllData() {\n\t\t// Some dummy data\n\t\t// Actually this should talk to some database to get all the data\n\t\treturn new int[] { 1, 2, 3, 4, 5 };\n\t}\n}\n```\n\n\nLet's create the BusinessService using DataService as a dependency.\n/src/main/java/com/in28minutes/springboot/tutorial/basics/example/unittesting/BusinessService.java\n\n```java\n@Service\npublic class BusinessService {\n\tprivate DataService dataService;\n\n\tpublic BusinessService(DataService dataService) {\n\t\tsuper();\n\t\tthis.dataService = dataService;\n\t}\n\n\tpublic int findTheGreatestFromAllData() {\n\t\tint[] data = dataService.retrieveAllData();\n\t\tint greatest = Integer.MIN_VALUE;\n\n\t\tfor (int value : data) {\n\t\t\tif (value > greatest) {\n\t\t\t\tgreatest = value;\n\t\t\t}\n\t\t}\n\t\treturn greatest;\n\t}\n}\n```\n\nImportant things to note:\n- `public BusinessService(DataService dataService) { ` - we are providing a constructor for injecting the data service.\n- `public int findTheGreatestFromAllData()` - This is the method we would want to write unit tests for. We would want to test with a wide range of combinations\n\n## Unit Testing with Mockito using MockitoRunner\n\nCode below shows a unit test with Mockito using MockitoJUnitRunner.\n\n/src/test/java/com/in28minutes/springboot/tutorial/basics/example/unittest/BusinessServicesMockTest.java\n\n```java\n@RunWith(MockitoJUnitRunner.class)\npublic class BusinessServicesMockTest {\n\n\t@Mock\n\tDataService dataServiceMock;\n\n\t@InjectMocks\n\tBusinessService businessImpl;\n\n\t@Test\n\tpublic void testFindTheGreatestFromAllData() {\n\t\twhen(dataServiceMock.retrieveAllData()).thenReturn(new int[] { 24, 15, 3 });\n\t\tassertEquals(24, businessImpl.findTheGreatestFromAllData());\n\t}\n\n\t@Test\n\tpublic void testFindTheGreatestFromAllData_ForOneValue() {\n\t\twhen(dataServiceMock.retrieveAllData()).thenReturn(new int[] { 15 });\n\t\tassertEquals(15, businessImpl.findTheGreatestFromAllData());\n\t}\n\n\t@Test\n\tpublic void testFindTheGreatestFromAllData_NoValues() {\n\t\twhen(dataServiceMock.retrieveAllData()).thenReturn(new int[] {});\n\t\tassertEquals(Integer.MIN_VALUE, businessImpl.findTheGreatestFromAllData());\n\t}\n}\n```\nNotes\n- `@RunWith(MockitoJUnitRunner.class) public class BusinessServicesMockTest` - The JUnit Runner which causes all the initialization magic with @Mock and @InjectMocks to happen before the tests are run.\n- `@Mock DataService dataServiceMock` - Create a mock for DataService\n- `@InjectMocks BusinessService businessImpl` - Inject the mocks as dependencies into BusinessService\n- There are three test methods testing three different scenarios - multiple values, one value and no value passed in.\n\n## Unit Test launching the complete Spring Context using @MockBean\n\nExample code below shows how we can write the same unit test launching up the complete Spring context.\n\n/src/test/java/com/in28minutes/springboot/tutorial/basics/example/unittest/BusinessServicesMockSpringContextTest.java\n\n```java\n\n@RunWith(SpringRunner.class)\n@SpringBootTest\npublic class BusinessServicesMockSpringContextTest {\n\n\t@MockBean\n\tDataService dataServiceMock;\n\n\t@Autowired\n\tBusinessService businessImpl;\n\n\t@Test\n\tpublic void testFindTheGreatestFromAllData() {\n\t\twhen(dataServiceMock.retrieveAllData()).thenReturn(new int[] { 24, 15, 3 });\n\t\tassertEquals(24, businessImpl.findTheGreatestFromAllData());\n\t}\n\n\t@Test\n\tpublic void testFindTheGreatestFromAllData_ForOneValue() {\n\t\twhen(dataServiceMock.retrieveAllData()).thenReturn(new int[] { 15 });\n\t\tassertEquals(15, businessImpl.findTheGreatestFromAllData());\n\t}\n\n\t@Test\n\tpublic void testFindTheGreatestFromAllData_NoValues() {\n\t\twhen(dataServiceMock.retrieveAllData()).thenReturn(new int[] {});\n\t\tassertEquals(Integer.MIN_VALUE, businessImpl.findTheGreatestFromAllData());\n\t}\n}\n```\nNotes\n- `@RunWith(SpringRunner.class)` - Spring Runner is used to launch up a spring context in unit tests.\n- `@SpringBootTest` - This annotation indicates that the context under test is a `@SpringBootApplication`. The complete SpringBootTutorialBasicsApplication is launched up during the unit test. \n- `@MockBean DataService dataServiceMock` - @MockBean annotation creates a mock for DataService. This mock is used in the Spring Context instead of the real DataService.\n- `@Autowired BusinessService businessImpl` - Pick the Business Service from the Spring Context and autowire it in.\n\n## Choosing between the approaches\n\nLaunching the entire spring context makes the unit test slower. Unit tests will also start failing if there are errors in other beans in the contexts. So, the MockitoJUnitRunner approach is preferred.\n\n\n## Complete Code Example\n\nGithub repository has the complete code - https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-tutorial-basics\n\n"
  },
  {
    "path": "_blog/articles/2017-12-14-spring-boot-developer-tools.md",
    "content": "---\nlayout:     post\ntitle:      Spring Boot Developer Tools and Live Reload - Maximize productivity with Hot Swapping\ndate:       2022-10-10 12:31:19\nsummary:    When we develop web applications with Java, we had to restart the server to pick up all changes. This kills productivity. Spring Boot Developers Tools provides solutions to automatically pick up changes without a complete server restart. Lets get productive with Spring Boot Developer Tools.\ncategories:  SpringBoot\npermalink: /spring-boot-developer-tools-and-live-reload\nimage: /images/spring-boot-feature.png\n---\n\n![Image](/images/Spring-Initializr-Web.png \"Web, Actuator and Developer Tools\")\n\nWhen we develop web applications with Java, we had to restart the server to pick up all changes. This kills productivity. Spring Boot Developers Tools provides solutions to automatically pick up changes without a complete server restart. Lets get productive with Spring Boot Developer Tools.\n \n## You will learn\n- How to use Spring Boot Developer Tools?\n- What kind of changes does Spring Boot Developer Tools pick up automatically?\n- How can you use Live Reload to be more productive?\n\n\n\n## Problem with Server Restarts\n\nWhen we develop our applications (Web or RESTful API), we would want to be able to test our changes quickly. \n\nTypically, in the Java world, we need to restart the server to pick up the changes.\n\n> There are plugins like JRebel which help, but you need shell out $$$ for it.\n\nRestarting server takes about 1 to 5 minutes based on the size of the application. A typical developer does 30 - 40 restarts in a day. I leave it as an exercise to determine how much time a developer can save if the changes are automatically picked up as soon as I make a code change.\n\nThats where Spring Boot Developer Tools comes into picture.\n\n## Adding Spring Boot Developer Tools to Your Project\n\nAdding Spring Boot Developer Tools to your project is very simple.\n\nAdd this dependency to your Spring Boot Project pom.xml\n\n```\n<dependency>\n\t<groupId>org.springframework.boot</groupId>\n\t<artifactId>spring-boot-devtools</artifactId>\n\t<scope>runtime</scope>\n</dependency>\n```\n\nRestart the application. \n\nYou are all Set.\n\nGo ahead and make a simple change to your controller. You would see that these changes are automatically picked up.\n\n## What kind of changes does Spring Boot Developer Tools pick up?\n\n> By default, any entry on the classpath that points to a folder  will be monitored for changes.\n\nHere are few important things to note:\n\nThese folders will not trigger reload by default\n- /META-INF/maven\n- /META-INF/resources \n- /resources \n- /static \n- /public \n- /templates \n\nYou can configure additional folders to scan.\n\napplication.properties\n```\nspring.devtools.restart.additional-paths = /path-to-folder\n```\n\nYou can also configure folders to exclude.\n\n```\nspring.devtools.restart.exclude=static/**,public/** \n```\n\n## Auto refresh your browser with LiveReload\n\nSpring Boot Developer Tools auto loads the changes to application. But if you are developing a web application, you would need to refresh the browser to pickup the change.\n\n> LiveReload aims to solve this problem\n\nLiveReload offers extensions for browsers  \n- Download from http://livereload.com/extensions/\n\nOnce you install the LiveReload plugin for your browser, you would see that the page auto refreshes when you make a change in application code.\n\n> LiveReload is Technology in progress!! So, expect a few problems!\n\n"
  },
  {
    "path": "_blog/articles/2017-12-15-implementing-aop-with-spring-boot.md",
    "content": "---\nlayout:     post\ntitle:      Implementing AOP with Spring Boot and AspectJ\ndate:       2022-07-06 12:31:19\nsummary:    Learn how to implement AOP with Spring Boot Starter AOP and AspectJ. You will understand cross cutting concerns and the basics of AOP - Aspect, Point cut, JoinPoint, Advice and more.\ncategories:  SpringBoot\npermalink:  /spring-boot-and-aop-with-spring-boot-starter-aop\nimage: /images/spring-boot-feature.png\n---\n\nThis guide will help you implement AOP with Spring Boot Starter AOP. We will implement 4 different advices using AspectJ and also create a custom annotation to track execution time of a method.\n\n![Image](/images/SpringBootAOPProjectStructure.png \"Spring Boot AOP Project Structure\") \n \n## You will learn\n- What are cross cutting concerns?\n- How do you implement cross cutting concerns in an application?\n\t- If you would want to log every request to a web application, what are the options you can think of?\n\t- If you would want to track performance of every request, what options can you think of?\n- What is an Aspect and Point cut in AOP?\n- What are the different types of AOP advices?\n- How do you implement AOP with Spring Boot?\n- How to use Spring AOP and AspectJ to implement your aspects?\n- What are the AOP Best Practices?\n\n\n## Project Code Structure\n\nFollowing screenshot shows the structure of the project we will create.\n\n![Image](/images/SpringBootAOPProjectStructure.png \"Spring Boot AOP Project Structure\") \n\nA few details:\n\n- SpringBootTutorialBasicsApplication.java - The Spring Boot Application class generated with Spring Initializer. This class acts as the launching point for application.\n- `pom.xml` - Contains all the dependencies needed to build this project. We will use Spring Boot Starter AOP.\n- `Business1.java`, `Business2.java`, `Dao1.java`, `Dao2.java` - Business classes are dependent on Dao classes. We would write aspects to intercept calls to these business and dao classes.\n- `AfterAopAspect.java` - Implements a few After advices.\n- `UserAccessAspect.java` - Implements a before advice to do an access check.\n- BusinessAopSpringBootTest.java - The unit test which invokes the business methods.\n\n## Tools you will need\n- Maven 3.0+ is your build tool\n- Your favorite IDE. We use Eclipse.\n- JDK 1.8+\n\n## Complete Maven Project With Code Examples\n> Our Github repository has all the code examples - https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-tutorial-basics\n\n\n## Introduction to AOP\n\nApplications are generally developed with multiple layers. A typical Java application has \n- Web Layer - Exposing the services to outside world using REST or a web application\n- Business Layer - Business Logic\n- Data Layer - Persistence Logic \n\nWhile the responsibilities of each of these layers are different, there are a few common aspects that apply to all layers\n- Logging\n- Security\n\nThese common aspects are called Cross Cutting Concerns.\n\nOne option of implementing cross cutting concerns is to implement it seperately in every layer. However, that would mean that the code becomes difficult to maintain.\n\nAspect Oriented Programming provides a solution to implement Cross Cutting Concerns. \n- Implement the cross cutting concern as an aspect.\n- Define point cuts to indicate where the aspect has to be applied.\n\nThis ensures that the cross cutting concerns are defined in one cohesive code component and can be applied as needed.\n\n## Setting up Spring Boot AOP Project\n\nCreating a Spring AOP Project with Spring Initializr is a cake walk. \n\n> Spring Initializr [http://start.spring.io/](http://start.spring.io/){:target=\"_blank\"} is great tool to bootstrap your Spring Boot projects.\n\nNotes\n- Launch Spring Initializr and choose the following\n  - Choose `com.in28minutes.springboot.tutorial.basics.example` as Group\n  - Choose `spring-boot-tutorial-basics` as Artifact\n  - Choose the following Dependencies\n    - AOP\n- Click Generate Project.\n- Import the project into Eclipse.\n\n## Spring Boot AOP Starter\n\n> Starter for aspect-oriented programming with Spring AOP and AspectJ\n\nKey dependencies in the Spring Boot AOP Starter are listed below \n- Spring AOP provides basic AOP Capabilities.\n- AspectJ provides a complete AOP framework.\n\n```\n<dependency>\n  <groupId>org.springframework</groupId>\n  <artifactId>spring-aop</artifactId>\n  <scope>compile</scope>\n</dependency>\n<dependency>\n  <groupId>org.aspectj</groupId>\n  <artifactId>aspectjweaver</artifactId>\n  <scope>compile</scope>\n</dependency>\n\n```\n\n## Setting up AOP Example\n\nLet's add a couple of business classes Business1 and Business2. These business classes are dependent on a couple of data classes Data1 and Data2.\n\n```java\n@Service\npublic class Business1 {\n\t\n\tprivate Logger logger = LoggerFactory.getLogger(this.getClass());\n\n\t@Autowired\n\tprivate Dao1 dao1;\n\t\n\tpublic String calculateSomething(){\n\t\tString value = dao1.retrieveSomething();\n\t\tlogger.info(\"In Business - {}\", value);\n\t\treturn value;\n\t}\n}\n```\n\n```java\n@Service\npublic class Business2 {\n\t\n\t@Autowired\n\tprivate Dao2 dao2;\n\t\n\tpublic String calculateSomething(){\n\t\t//Business Logic\n\t\treturn dao2.retrieveSomething();\n\t}\n}\n```\n\n```java\n@Repository\npublic class Dao1 {\n\n\tpublic String retrieveSomething(){\n\t\treturn \"Dao1\";\n\t}\n\n}\n```\n\n```java\n@Repository\npublic class Dao2 {\n\n\tpublic String retrieveSomething(){\n\t\treturn \"Dao2\";\n\t}\n\n}\n```\n\nNotes\n- `@Autowired private Dao1 dao1` - The Dao's are autowired as dependencies into the Business classes.\n- `public String calculateSomething(){` - Each of the business classes have a simple calculate method.\n\n#### Simple Unit Test to Test AOP\n\nLet's write a simple unit test to invoke the business classes created below.\n\n```\n@RunWith(SpringRunner.class)\n@SpringBootTest\npublic class BusinessAopSpringBootTest {\n\n\tprivate Logger logger = LoggerFactory.getLogger(this.getClass());\n\n\t@Autowired\n\tprivate Business1 business1;\n\n\t@Autowired\n\tprivate Business2 business2;\n\n\t@Test\n\tpublic void invokeAOPStuff() {\n\t\tlogger.info(business1.calculateSomething());\n\t\tlogger.info(business2.calculateSomething());\n\t}\n}\n```\n\nNotes\n- `@RunWith(SpringRunner.class) @SpringBootTest public class BusinessAopSpringBootTest` - We are launching up the complete Spring Boot Application in the Unit Test.\n- `@Autowired private Business1 business1` and `@Autowiredprivate Business2 business2` - Autowire the business classes into the test from the launched up Spring Context\n- `@Test public void invokeAOPStuff() {` - Invoke the methods on the business services.\n\nAt this point, we have no AOP logic implemented. So, the output would be the simple messages from the Dao and Business classes.\n\n```\nc.i.s.t.b.e.a.BusinessAopSpringBootTest  : In Business - Dao1\nc.i.s.t.b.e.a.BusinessAopSpringBootTest  : Dao1\n```\n\n## Implementing @Before advice\n\nTypically when we implement security using AOP, we would want to intercept the call to the method and apply your check. This is typically done using @Before advice.\n\nAn implementation is shown below.\n\n\n```java\n\n@Aspect\n@Configuration\npublic class UserAccessAspect {\n\t\n\tprivate Logger logger = LoggerFactory.getLogger(this.getClass());\n\t\n\t//What kind of method calls I would intercept\n\t//execution(* PACKAGE.*.*(..))\n\t//Weaving & Weaver\n\t@Before(\"execution(* com.in28minutes.springboot.tutorial.basics.example.aop.data.*.*(..))\")\n\tpublic void before(JoinPoint joinPoint){\n\t\t//Advice\n\t\tlogger.info(\" Check for user access \");\n\t\tlogger.info(\" Allowed execution for {}\", joinPoint);\n\t}\n}\n```\n\nNotes\n- `@Aspect` - Indicates that this is an Aspect\n- `@Configuration` - Indicates that this file contains Spring Bean Configuration for an Aspect.\n- `@Before` - We would want to execute the Aspect before execution of the method\n- `(\"execution(* com.in28minutes.springboot.tutorial.basics.example.aop.data.*.*(..))\")` - This defines the point cut - We would want to intercept all method calls made to any methods in the package `com.in28minutes.springboot.tutorial.basics.example.aop.data`\n\n\nWhen you run the unit test, you will see that before executing the DAO method the user access check code is executed.\n```\nCheck for user access \nAllowed execution for execution(String com.in28minutes.springboot.tutorial.basics.example.aop.data.Dao1.retrieveSomething())\nc.i.s.t.b.e.a.BusinessAopSpringBootTest  : In Business - Dao1\nc.i.s.t.b.e.a.BusinessAopSpringBootTest  : Dao1\n\nCheck for user access \nAllowed execution for execution(String com.in28minutes.springboot.tutorial.basics.example.aop.data.Dao2.retrieveSomething())\nc.i.s.t.b.e.a.BusinessAopSpringBootTest  : Dao2\n```\n\n#### Understanding AOP Terminology - Pointcut, Advice, Aspect, Join Point\n\nLet's spend some time understanding the AOP Terminology\n- Pointcut - Pointcut is the expression used to define when a call to a method should be intercepted. In the above example, `execution(* com.in28minutes.springboot.tutorial.basics.example.aop.data.*.*(..))` is the pointcut.\n- Advice - What do you want to do? It is the logic that you would want to invoke when you intercept a method. In the above example, it is the code inside the `before(JoinPoint joinPoint)` method.\n- Aspect - A combination of defining when you want to intercept a method call (Pointcut) and what to do (Advice) is called an Aspect.\n- Join Point - When the code is executed and the condition for pointcut is met, the advice is executed. The Join Point is a specific execution instance of an advice.\n- Weaver - Weaver is the framework which implements AOP - AspectJ or Spring AOP.\n\n####Using @After, @AfterReturning, @AfterThrowing advices\n\nLet's now the other interception options AOP provides.\n- `@After` - Executed in two situations - when a method executes successfully or it throws an exception.\n- `@AfterReturning` - Executed only when a method executes successfully.\n- `@AfterThrowing` - Executed only when a method throws an exception.\n\nLet's create a simple Aspect with a couple of these variations.\n\n```\n@Aspect\n@Configuration\npublic class AfterAopAspect {\n\n\tprivate Logger logger = LoggerFactory.getLogger(this.getClass());\n\n\t@AfterReturning(value = \"execution(* com.in28minutes.springboot.tutorial.basics.example.aop.business.*.*(..))\", \n\t\t\treturning = \"result\")\n\tpublic void afterReturning(JoinPoint joinPoint, Object result) {\n\t\tlogger.info(\"{} returned with value {}\", joinPoint, result);\n\t}\n\t\n\t@After(value = \"execution(* com.in28minutes.springboot.tutorial.basics.example.aop.business.*.*(..))\")\n\tpublic void after(JoinPoint joinPoint) {\n\t\tlogger.info(\"after execution of {}\", joinPoint);\n\t}\n}\n```\n\nThe code is self explanatory. \n\nOutput from execution is shown below:\n```\nCheck for user access \nAllowed execution for execution(String com.in28minutes.springboot.tutorial.basics.example.aop.data.Dao1.retrieveSomething())\nIn Business - Dao1\nafter execution of execution(String com.in28minutes.springboot.tutorial.basics.example.aop.business.Business1.calculateSomething())\nexecution(String com.in28minutes.springboot.tutorial.basics.example.aop.business.Business1.calculateSomething()) returned with value Dao1\nc.i.s.t.b.e.a.BusinessAopSpringBootTest  : Dao1\nCheck for user access \nAllowed execution for execution(String com.in28minutes.springboot.tutorial.basics.example.aop.data.Dao2.retrieveSomething())\nafter execution of execution(String com.in28minutes.springboot.tutorial.basics.example.aop.business.Business2.calculateSomething())\nexecution(String com.in28minutes.springboot.tutorial.basics.example.aop.business.Business2.calculateSomething()) returned with value Dao2\nc.i.s.t.b.e.a.BusinessAopSpringBootTest  : Dao2\n\n```\n\nAs you can see, just before returning the values to the calling business methods, the after advices are executed.\n\n## Other AOP Features - @Around and Annotations\n\nOne of the other features you can implement using AOP are custom annotations for intercepting method calls.\n\nExample below shows a simple `TrackTime` annotation.\n```java\n@Target(ElementType.METHOD)\n@Retention(RetentionPolicy.RUNTIME)\npublic @interface TrackTime {\n```\n\nWe can add an aspect defining what should be done when `TrackTime` annotation is used. MethodExecutionCalculationAspect implements a simple time tracking.\n```java\n@Aspect\n@Configuration\npublic class MethodExecutionCalculationAspect {\n\n\tprivate Logger logger = LoggerFactory.getLogger(this.getClass());\n\n\t@Around(\"@annotation(com.in28minutes.springboot.tutorial.basics.example.aop.TrackTime)\")\n\tpublic void around(ProceedingJoinPoint joinPoint) throws Throwable {\n\t\tlong startTime = System.currentTimeMillis();\n\n\t\tjoinPoint.proceed();\n\n\t\tlong timeTaken = System.currentTimeMillis() - startTime;\n\t\tlogger.info(\"Time Taken by {} is {}\", joinPoint, timeTaken);\n\t}\n}\n```\nNotes\n- `@Around` - Uses an around advice. Intercepts the method call and uses `joinPoint.proceed()` to execute the method.\n- `@annotation(com.in28minutes.springboot.tutorial.basics.example.aop.TrackTime)\n` - Pointcut to define interception based on an annotation - @annotation followed by the complete type name of the annotation.\n\nOnce we define the annotation and the advice, we can use the annotation on methods which we would want to track as shown below.\n\n```\n@Service\npublic class Business1 {\n\t\t\n\t@TrackTime\n\tpublic String calculateSomething(){\n```\n\n## AOP Best Practices\n\nOne of the AOP Best Practices is to deine a Common Class to store all the Pointcuts. This helps in maintaining the pointcuts at one place.\n\n```java\npublic class CommonJoinPointConfig {\n\t\n\t@Pointcut(\"execution(* com.in28minutes.spring.aop.springaop.data.*.*(..))\")\n\tpublic void dataLayerExecution(){}\n\t\n\t@Pointcut(\"execution(* com.in28minutes.spring.aop.springaop.business.*.*(..))\")\n\tpublic void businessLayerExecution(){}\n\n}\n```\nThe above common definition can be used when defining point cuts in other aspects.\n\n```java\n@Around(\"com.in28minutes.spring.aop.springaop.aspect.CommonJoinPointConfig.businessLayerExecution()\")\n```\n"
  },
  {
    "path": "_blog/articles/2017-12-16-spring-boot-java-and-xml-application-contexts-top20.md",
    "content": "---\nlayout:     post\ntitle:      Java Annotation and XML Bean Configurations with Spring Boot\ndate:       2022-07-06 12:31:19\nsummary:    Spring allows you to configure your beans using Java Annotations and XML definitions. In this guide, we will explore how to use XML and Java Annotations to configure your beans with Spring Boot. We will understand how to load these configurations into a Spring Application Context. \ncategories:  SpringFramework\npermalink:  /spring-boot-java-xml-context-configuration\nimage: /images/spring-boot-feature.png\n---\n\n![Image](/images/Spring-Initializr-Web.png \"Web, Actuator and Developer Tools\")   \n\nSpring allows you to configure your beans using Java and XML. In this guide, we will explore how to use XML and Java Configurations with Spring Boot. We will understand how to load these configurations into a Spring Application Context. \n\n![Image](/images/SpringBootXMLAndJavaApplicationContext-ProjectStructure.png \"SpringBootXMLAndJavaApplicationContext-ProjectStructure\") \n\n\n## You will learn\n- How to define a Java bean configuration in a Spring Application?\n- How to define a XML bean configuration in a Spring Application?\n- How to load a XML Bean Configuration file into a Spring Application context?\n- How to load a Java Annotation based Bean Configuration file into a Spring Application context?\n- What are the best practices in using XML and Java bean configurations?\n- How do you choose between XML and Java Bean Configurations?\n\n\n\n\n## Project Code Structure\n\nFollowing screenshot shows the structure of the project we will create.\n\n![Image](/images/SpringBootXMLAndJavaApplicationContext-ProjectStructure.png \"SpringBootXMLAndJavaApplicationContext-ProjectStructure\") \n\nA few details:\n- SpringBootTutorialBasicsApplication.java - The Spring Boot Application class generated with Spring Initializer. This class acts as the launching point for application.\n- `pom.xml` - Contains all the dependencies needed to build this project. We will use Spring Boot Starter AOP.\n- `JavaConfiguration.java` - Java Configuration file that contains the bean definitions.\n- `XmlConfiguration.java` - Defines Configuration based on the applicationContext.xml\n- `applicationContext.xml` - XML Configuration file that contains the bean definitions. \n\n## Tools you will need\n- Maven 3.0+ is your build tool\n- Your favorite IDE. We use Eclipse.\n- JDK 1.8+\n\n## Complete Maven Project With Code Examples\n> Our Github repository has all the code examples - https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-tutorial-basics\n\n## Application Context - Basics of Bean configuration with XML and Java\n\nSpring Framework is most popular Java IOC framework. The core features of Spring Framework - IOC/Dependency Injection - are provided by Application Context. (Basic version is the Bean Factory)\n\nApplication Context (and Bean Factory) takes care of the bean life cycle and wiring up dependencies other than a host of other features.\n\nSpring Beans can be defined in XML and Java Configurations. We would want to be able to load both these configurations from an Application Context.\n\nIn this guide, we look at how to load beans from XML and Java configuration files into an application context in a Spring Boot Application.\n\n## Bootstrapping with Spring Initializr\n\nSpring Initializr [http://start.spring.io/](http://start.spring.io/){:target=\"_blank\"} is great tool to bootstrap your Spring Boot projects.\n\n![Image](/images/Spring-Initializr-Web.png \"Web, Actuator and Developer Tools\")   \n\nAs shown in the image above, following steps have to be done\n\n- Launch Spring Initializr and choose the following\n  - Choose `com.in28minutes.springboot.tutorial.basics.example` as Group\n  - Choose `spring-boot-tutorial-basics` as Artifact\n  - Choose following dependencies\n    - Web\n    - DevTools\n- Click Generate Project.\n- Import the project into Eclipse. File -> Import -> Existing Maven Project.\n- If you want to understand all the files that are part of this project, you can go here TODO.\n\n## Listing all the Spring Beans that are loaded\n\nLet's enhance `SpringBootTutorialBasicsApplication` to list all the beans that are loaded.\n\n```\n@SpringBootApplication\npublic class SpringBootTutorialBasicsApplication {\n\n\tpublic static void main(String[] args) {\n\t\tApplicationContext applicationContext = SpringApplication.run(SpringBootTutorialBasicsApplication.class, args);\n\n\t\tfor (String name : applicationContext.getBeanDefinitionNames()) {\n\t\t\tSystem.out.println(name);\n\t\t}\n\t}\n}\n```\n\nWhen you run this application, it should print a host of beans that are automatically loaded by the application context.\n\n## Loading Beans from Java Configuration\n\nLet's now define beans in a Java Configuration file.\n\n```\npackage com.in28minutes.springboot.tutorial.basics.example.application.context.java;\n\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\n\n@Configuration\npublic class JavaConfiguration {\n\t\n\t@Bean\n\tpublic String someDummyBean1() {\n\t\treturn \"someDummyBean1\";\n\t}\n\t\n\t@Bean\n\tpublic String someDummyBean2() {\n\t\treturn \"someDummyBean2\";\n\t}\n\n}\n```\nKey things to note\n- `@Configuration public class JavaConfiguration` - `@Configuration` indicates that this class contains configuration of Spring Beans.\n- `@Bean public String someDummyBean1() {` - `@Bean` allows us to create a bean in a Spring Configuration class.\n\n> The package in which this class is created is a sub-package of the package in which the `SpringBootTutorialBasicsApplication` is present. So, it is part of the component scan. If you use a package which is not a sub-package of the package in which the `SpringBootTutorialBasicsApplication` is present, then you would need to add an explicit component scan to ensure that this configuration file is picked up\n\nWhen your run the application again, you would see couple of new entries in the list of beans loaded by Application Context.\n\n```\nsomeDummyBean1\nsomeDummyBean2\n```\n## Loading Beans from XML Configuration\n\nLet's start with defining a simple XML Configuration.\n\nsrc/main/resources/applicationContext.xml\n```\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<beans xmlns=\"http://www.springframework.org/schema/beans\"\n\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:context=\"http://www.springframework.org/schema/context\"\n\txsi:schemaLocation=\"http://www.springframework.org/schema/beans\n        http://www.springframework.org/schema/beans/spring-beans.xsd\n        http://www.springframework.org/schema/context\n        http://www.springframework.org/schema/context/spring-context.xsd\">\n\n\t<!-- <context:component-scan base-package=\"com.in28minutes.spring.basics\"/> -->\n\n\t<bean id=\"xmlStringBean1\" class=\"java.lang.String\">\n\t\t<constructor-arg value=\"stringBean1\" />\n\t</bean>\n\n\t<bean id=\"xmlStringBean2\" class=\"java.lang.String\">\n\t\t<constructor-arg value=\"stringBean2\" />\n\t</bean>\n\n</beans>\n```\nAbove xml configuration defines a couple of String Beans.\n\nWe would want to be able to load these beans into the application context.\n\nWhile there are multiple ways of doing this, the recommended way is to create a seperate configuration class to load this xml bean definition file.\n\n```\n@Configuration\n@ImportResource({\"classpath*:applicationContext.xml\"})\npublic class XmlConfiguration {\n}\n```\nThe key part of the definition is `@ImportResource({\"classpath*:applicationContext.xml\"})`. `applicationContext.xml` will be imported from classpath.\n\nWhen you run the application, you see that the beans from the XML Configuration file are also loaded up.\n\n```\njavaConfiguration\nxmlConfiguration\nsomeDummyBean1\nsomeDummyBean2\nxmlStringBean1\nxmlStringBean2\n\n```\n\n## Should you use XML or Annotation based bean definitions?\n\nWhich is better depends on \n- context \n- preference of the team.\n\nIf you are maintaining an old project with XML bean definitions, the choice is already made for you.\n\nIf you are creating a new project and if the configuration is specific to auto-wiring or declaring a bean - for example `@Service`, `@Component`, `@Autowired` - I prefer annotations.\n\nHowever, when it comes to - one time - application related configuration or a common configuration like @ComponentScan, I do not really have a preference. I would leave it to the team to choose. However, I would definitely want the entire team to discuss and agree what they would want to use in a specific project. \n\n\n## Complete Code Example\n\nOur Github repository has all the code examples - https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-tutorial-basics"
  },
  {
    "path": "_blog/articles/2017-12-17-spring-boot-embedded-servers-top20.md",
    "content": "---\nlayout:     post\ntitle:      Spring Boot and Embedded Servers - Tomcat, Jetty and Undertow\ndate:       2022-07-05 12:31:19\nsummary:    Let's understand the need for embedded servers. We will understand the default embedded server provided by Spring Boot i.e. Tomcat and discuss the other options that Spring Boot supports - Jetty and Undertow.\ncategories:  SpringBoot\npermalink:  /spring-boot-with-embedded-servers-tomcat-jetty\nimage: /images/spring-boot-feature.png\n---\n\nThis guide will help you understand why embedded servers are gaining popularity. We will discuss the different options that Spring Boot supports - Tomcat, Jetty and Undertow.\n\n![Image](/images/spring-initializer-web-h2-devtools-jdbc.png \"Web, JDBC,H2 and Developer Tools\")\n\n \n## You will learn\n- What is an embedded server?\n- Why are embedded servers getting popular?\n- What are the different embedded servers that Spring Boot supports?\n- How do you switch from one embedded server to another?\n\n\n\n## What is an Embedded Server?\n\nThink about what you would need to be able to deploy your application (typically) on a virtual machine.\n- Step 1 : Install Java\n- Step 2 : Install the Web/Application Server (Tomcat/Websphere/Weblogic etc)\n- Step 3 : Deploy the application war\n\nWhat if we want to simplify this?\n\nHow about making the server a part of the application? \n\n> You would just need a virtual machine with Java installed and you would be able to directly deploy the application on the virtual machine. Isn't it cool?\n\nThis idea is the genesis for Embedded Servers.\n\nWhen we create an application deployable, we would embed the server (for example, tomcat) inside the deployable. \n> For example, for a Spring Boot Application, you can generate an application jar which contains Embedded Tomcat. You can run a web application as a normal Java application!\n\nEmbedded server implies that our deployable unit contains the binaries for the server (example, tomcat.jar).\n\n## Creating an Embedded Server Project with Spring Initializr\n\nSpring Initializr [http://start.spring.io/](http://start.spring.io/){:target=\"_blank\"} is great tool to bootstrap your Spring Boot projects.\n\n![Image](/images/spring-initializer-web-h2-devtools-jdbc.png \"Web, JDBC,H2 and Developer Tools\")\n\nAs shown in the image above, following steps have to be done\n\n- Launch Spring Initializr and choose the following\n  - Choose `com.in28minutes.springboot.tutorial.basics.example` as Group\n  - Choose `spring-boot-tutorial-basics` as Artifact\n  - Choose following dependencies\n    - Web\n    - DevTools\n- Click Generate Project.\n- Import the project into Eclipse. File -> Import -> Existing Maven Project.\n\n## Default Embedded Server with Spring Boot - Tomcat\n\nWe have included Spring Boot Starter Web in our dependencies when creating the spring boot project.\n\nLet's take a quick look at the dependencies for `spring-boot-starter-web`\n\n```\n<dependency>\n  <groupId>org.springframework.boot</groupId>\n  <artifactId>spring-boot-starter-tomcat</artifactId>\n  <version>2.3.1.RELEASE</version>\n  <scope>compile</scope>\n</dependency>\n```\n\nYou can see that by default Starter Web includes a dependency on starter tomcat.\n\nStarter Tomcat has the following dependencies.\n\n```\n<dependency>\n  <groupId>org.apache.tomcat.embed</groupId>\n  <artifactId>tomcat-embed-core</artifactId>\n  <scope>compile</scope>\n</dependency>\n<dependency>\n  <groupId>org.apache.tomcat.embed</groupId>\n  <artifactId>tomcat-embed-el</artifactId>\n  <scope>compile</scope>\n</dependency>\n<dependency>\n  <groupId>org.apache.tomcat.embed</groupId>\n  <artifactId>tomcat-embed-websocket</artifactId>\n  <scope>compile</scope>\n</dependency>\n```\n\nStarter Tomcat brings in all the dependencies need to run Tomcat as an embedded server.\n\n## Run the web application using an Embedded Server\n\nWhen you run SpringBootTutorialBasicsApplication.java as a Java Application, you would see that the server would start up and start serving requests.\n\nAn extract from the log\n```\no.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)\n```\n\nYou can see that tomcat has started by default on port 8080.\n\nYou can customize the port in application.properties\n```\nserver.port=9080\n```\n\nWhen you do a 'mvn clean install' on the project, a jar artifact named `spring-boot-tutorial-basics-0.0.1-SNAPSHOT.jar` is generated.\n\nThis jar can be used to run the application on any machine where Java 8 is installed.\n\n> The tomcat embedded server is also packaged inside this jar\n\n\n\n## Using Jetty as Embedded Server with Spring Boot\n\nRemove the existing dependency on spring-boot-starter-web and add these in.\n\n```\n<dependency>\n    <groupId>org.springframework.boot</groupId>\n    <artifactId>spring-boot-starter-web</artifactId>\n    <exclusions>\n        <exclusion>\n            <groupId>org.springframework.boot</groupId>\n            <artifactId>spring-boot-starter-tomcat</artifactId>\n        </exclusion>\n    </exclusions>\n</dependency>\n<dependency>\n    <groupId>org.springframework.boot</groupId>\n    <artifactId>spring-boot-starter-jetty</artifactId>\n</dependency>\n```\n\n## Using Undertow as Embedded Server with Spring Boot\n\nRemove the existing dependency on spring-boot-starter-web and add these in.\n\n```\n<dependency>\n    <groupId>org.springframework.boot</groupId>\n    <artifactId>spring-boot-starter-web</artifactId>\n    <exclusions>\n        <exclusion>\n            <groupId>org.springframework.boot</groupId>\n            <artifactId>spring-boot-starter-tomcat</artifactId>\n        </exclusion>\n    </exclusions>\n</dependency>\n<dependency>\n    <groupId>org.springframework.boot</groupId>\n    <artifactId>spring-boot-starter-undertow</artifactId>\n</dependency>\n```\n\n## Embedded Server Spring Boot Configuration\n\nSpring Boot provides a number of options to configure the embedded server through application.properties\n\n```\n# EMBEDDED SERVER CONFIGURATION (ServerProperties)\nserver.compression.enabled=false # If response compression is enabled.\nserver.context-path= # Context path of the application.\nserver.display-name=application # Display name of the application.\nserver.error.include-stacktrace=never # When to include a \"stacktrace\" attribute.\nserver.error.path=/error # Path of the error controller.\nserver.error.whitelabel.enabled=true # Enable the default error page displayed in browsers in case of a server error.\nserver.port=8080 # Server HTTP port.\nserver.server-header= # Value to use for the Server response header (no header is sent if empty)\nserver.servlet-path=/ # Path of the main dispatcher servlet.\n\n```\n\nHere are a few Jetty specific options\n\n```\nserver.jetty.acceptors= # Number of acceptor threads to use.\nserver.jetty.max-http-post-size=0 # Maximum size in bytes of the HTTP post or put content.\nserver.jetty.selectors= # Number of selector threads to use.\n```\n\nYou can also configure ssl on the embedded server\n\n```\nserver.ssl.ciphers= # Supported SSL ciphers.\nserver.ssl.client-auth= # Whether client authentication is wanted (\"want\") or needed (\"need\"). Requires a trust store.\nserver.ssl.enabled= # Enable SSL support.\nserver.ssl.enabled-protocols= # Enabled SSL protocols.\nserver.ssl.key-alias= # Alias that identifies the key in the key store.\nserver.ssl.key-password= # Password used to access the key in the key store.\nserver.ssl.key-store= # Path to the key store that holds the SSL certificate (typically a jks file).\nserver.ssl.key-store-password= # Password used to access the key store.\nserver.ssl.key-store-provider= # Provider for the key store.\nserver.ssl.key-store-type= # Type of the key store.\nserver.ssl.protocol=TLS # SSL protocol to use.\nserver.ssl.trust-store= # Trust store that holds SSL certificates.\nserver.ssl.trust-store-password= # Password used to access the trust store.\nserver.ssl.trust-store-provider= # Provider for the trust store.\nserver.ssl.trust-store-type= # Type of the trust store.\n```\n\nA few tomcat specific properties are listed below\n```\nserver.tomcat.accept-count= # Maximum queue length for incoming connection requests when all possible request processing threads are in use.\nserver.tomcat.accesslog.directory=logs # Directory in which log files are created. Can be relative to the tomcat base dir or absolute.\nserver.tomcat.accesslog.enabled=false # Enable access log.\nserver.tomcat.basedir= # Tomcat base directory. If not specified a temporary directory will be used.\nserver.tomcat.max-connections= # Maximum number of connections that the server will accept and process at any given time.\nserver.tomcat.max-threads=0 # Maximum amount of worker threads.\nserver.tomcat.uri-encoding=UTF-8 # Character encoding to use to decode the URI.\n```\n\nFor complete list options refer spring documentation - https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html\n\n"
  },
  {
    "path": "_blog/articles/2017-12-18-spring-boot-application-configuration-top20.md",
    "content": "---\nlayout:     post\ntitle:      Application Configuration with Spring Boot\ndate:       2022-07-05 12:31:19\nsummary:    Externalizing Application Configuration is a key challenge in developing great Application. Spring Boot provides a variety of options to expose Application Configuration. In this tutorial, we explore the basics of application.properties, @Value and @ConfigurationProperties.\ncategories:  SpringBoot\npermalink:  /spring-boot-application-configuration\nimage: /images/spring-boot-feature.png\n---\n\nThis guide will introduce you to the various application configuration options that are present in Spring Boot. You will also learn how to create custom configuration for an application. \n\n![Image](/images/SpringBootApplicationConfiguration-ProjectStructure.png \"Spring Boot Application Configuration Project Structure\")\n \n## You will learn\n- What is application configuration?\n- Why do we need application configuration?\n- What is application.properties?\n- What are some of the important things that can customized in application.properties?\n- How do you externalize configuration using Spring Boot?\n- How can you add custom application properties using Spring Boot?\n- What is @ConfigurationProperties?\n- What are the advantages of using @ConfigurationProperties?\n\n\n\n## Need for Application Configuration\n\nConfiguration for applications vary from one environment to another\n- You would want to connect to a different database or queues\n- You would want to connect with different services\n- You would want to configure less logging in production\n- You might want to have different custom configuration\n\n## Application Configuration with Spring Boot application.properties\n\nSpring Boot allows you to configure your application configuration using a file named `application.properties`\n\n`application.properties` can reside anywhere in the classpath of the application.\n\nIn application.properties, we can use the \"logging.level\" prefix to set logging levels.\n\n```\nlogging.level.some.package.path=DEBUG\nlogging.level.some.other.package.path=ERROR\n```\n\nYou can configure a log file by using logging.file property in application.properties. The logging here would be in addition to the logging in console.\n\n```\nlogging.file=\\path_to\\logfile.log\n```\n\nYou can also configure the port to run the server on using server.port\n\n```\nserver.port = 9080\n```\n\nFor complete list of options refer spring documentation - https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html\n\n\nIn this guide, we will create three services using proper URIs and HTTP methods:\n\n## Project Code Structure\n\nFollowing screenshot shows the structure of the project we will create.\n\n![Image](/images/SpringBootApplicationConfiguration-ProjectStructure.png \"Spring Boot Application Configuration Project Structure\")\n\nA few details:\n- SpringBootTutorialBasicsConfigurationApplication.java - The Spring Boot Application class generated with Spring Initializer. This class acts as the launching point for application.\n- `pom.xml` - Contains all the dependencies needed to build this project.\n- `BasicConfiguration.java` - We will use this component to define application configuration using @ConfigurationProperties\n- `WelcomeResource.java` - Example of a resource using @Value\n- `application.properties` - Configuration for application\n\n## Tools you will need\n- Maven 3.0+ is your build tool\n- Your favorite IDE. We use Eclipse.\n- JDK 1.8+\n\n## Complete Maven Project With Code Examples\n> Our Github repository has all the code examples - https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-tutorial-basics-configuration\n\n## Bootstrapping with Spring Initializr\n\nSpring Initializr [http://start.spring.io/](http://start.spring.io/){:target=\"_blank\"} is great tool to bootstrap your Spring Boot projects.\n\n![Image](/images/Spring-Initializr-Web.png \"Web, Actuator and Developer Tools\")   \n\n![Image](/images/Spring-Initializr-Web-JPA.png \"Web, JPA, Hibernate and Developer Tools\")\n\nAs shown in the image above, following steps have to be done\n\n- Launch Spring Initializr and choose the following\n  - Choose `com.in28minutes.springboot.tutorial.basics.application.configuration` as Group\n  - Choose `spring-boot-tutorial-basics-configuration` as Artifact\n  - Choose following dependencies\n    - Web\n    - DevTools\n- Click Generate Project.\n- Import the project into Eclipse. File -> Import -> Existing Maven Project.\n\n## Application Configuration using @Value\n\nLet's create a very simple example.\n\n```\n@RestController\npublic class WelcomeResource {\n\n\t@Value(\"${welcome.message}\")\n\tprivate String welcomeMessage;\n\n\t@GetMapping(\"/welcome\")\n\tpublic String retrieveWelcomeMessage() {\n\t\t// Complex Method\n\t\treturn welcomeMessage;\n\t}\n}\n```\n\nNotes\n- `@Value(\"${welcome.message}\") private String welcomeMessage;` - Pick up the value for welcome.message from application configuration and assign it to this member variable.\n- `@GetMapping(\"/welcome\") public String retrieveWelcomeMessage()` - Expose a simple service using the configuration\n\nLet's configure a value for welcome message in the application.properties.\n\n```\nwelcome.message=Welcome message from property file! Welcome to in28Minutes\n```\n\nWhen you launch http://localhost:8080/welcome, you would see a page with this message\n\n`Welcome message from property file! Welcome to in28Minutes`\n\nWe can make the application.properties more creative by using other properties as variables too.\n\n```\napp.name=in28Minutes\nwelcome.message=Welcome message from property file! Welcome to ${app.name}\n\n```\n\nSpring Boot provides different ways of configuring your property values.\n- You can send in a program argument \n   - --welcome.message=\"SomethingElse\"\n- You can use a different file as property file \n   - --spring.config.location=classpath:/default.properties\n- You can configure an environment variable\n\n@Value is the basic approach for application configuration using Spring.\n\n## Application Configuration using Type-safe Configuration Properties\n\nThe problem with @Value is that you would have your configuration values distributed through out your application. A better option would be to have a centralized approach. \n\nYou can define a configuration component using `@ConfigurationProperties`.\n\n```\n@Component\n@ConfigurationProperties(\"basic\")\npublic class BasicConfiguration {\n    private boolean value;\n    private String message;\n    private int number;\n\n    public boolean isValue() {\n        return value;\n    }\n\n    public void setValue(boolean value) {\n        this.value = value;\n    }\n\n    public String getMessage() {\n        return message;\n    }\n\n    public void setMessage(String message) {\n        this.message = message;\n    }\n\n    public int getNumber() {\n        return number;\n    }\n\n    public void setNumber(int number) {\n        this.number = number;\n    }\n\n}\n```\n\nNotes:\n- `@Component @ConfigurationProperties(\"basic\")` - Defines that this java bean contains configuration properties. All property names will start with `basic.`.\n- `private boolean value`  - A boolean value. Can be configured as basic.value.\n- `private String message` - A String value. Can be configured as basic.message.\n\nWe would need to use the BasicConfiguration in a service to expose the values\n\n```\n@Autowired\nprivate BasicConfiguration configuration;\n\n@RequestMapping(\"/dynamic-configuration\")\npublic Map dynamicConfiguration() {\n    // Not the best practice to use a map to store differnt types!\n    Map map = new HashMap();\n    map.put(\"message\", configuration.getMessage());\n    map.put(\"number\", configuration.getNumber());\n    map.put(\"key\", configuration.isValue());\n    return map;\n}\n\n```\n\nNotes\n- `@Autowired private BasicConfiguration configuration` - Its very easy to use BasicConfiguration. Autowire it in when ever you need the value for a property from it.\n- `@RequestMapping(\"/dynamic-configuration\") public Map dynamicConfiguration() {` - Define a simple service to expose the configured values.\n\nThe values can be configured in application.properties\n```\nbasic.value: true\nbasic.message: Dynamic Message\nbasic.number: 100\n```\n\nWhen you browse to http://localhost:8080/dynamic-configuration, you see the following response.\n\n```\n{\"number\":100,\"message\":\"Dynamic Message\",\"key\":true}\n```\n\n### Understand Type Safety\n\n@ConfigurationProperties is type safe. If you configure any property with a value of an invalid type, the application fails at startup.\n\nBelow snippet shows the log when basic.number is assigned a non numberic value.\n```\n***************************\nAPPLICATION FAILED TO START\n***************************\n\nDescription:\n\nBinding to target com.in28minutes.springboot.configuration.BasicConfiguration@391b8545 failed:\n\n    Property: basic.number\n    Value: ABC\n    Reason: Failed to convert property value of type [java.lang.String] to required type [int] for property 'number'; nested exception is org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.String] to type [int]\n\n\nAction:\n\nUpdate your application's configuration\n\n```\n\n\n\n## Complete Code Example\n\n\nGithub repository has all the code examples - https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-tutorial-basics-configuration"
  },
  {
    "path": "_blog/articles/2017-12-19-spring-boot-application-configuration-yaml.md",
    "content": "---\nlayout:     post\ntitle:      Spring Boot Application Configuration with YAML\ndate:       2022-07-05 12:31:19\nsummary:    YAML stands for Yet Another Markup Language. It makes application configuration human readable. In this tutorial, we will understand what YAML is and how your can configure Spring Boot applications using YAML. \ncategories:  SpringBoot\npermalink:  /spring-boot-application-configuration-with-yaml\nimage: /images/spring-boot-feature.png\n---\n\nThis guide will introduce you to YAML and the YAML support with the various application configuration options that are present in Spring Boot. \n\n![Image](/images/Spring-Initializr-Web.png \"Web, Actuator and Developer Tools\")   \n\n \n## You will learn\n- What is application configuration?\n- What is YAML?\n- What are the advantages of YAML?\n- How do you specify application configuration using YAML with Spring Boot?\n\n\n\n## What is YAML?\n\nYAML is a human readable serialization language\n\n> YAML stands for Yet Another Markup Language\n\nLet's consider an example\n\napplication.properties\n```\nlevel1.property1 = 5\nlevel1.property2 = 6\nlevel1.property3 = 7\nlevel1.level2.property4 = 8\nlevel1.level2.property5 = 10\nlevel1.level2.property6 = 11\n```\nAbove property file is cool but it is not very readable.\n\nLet's consider the same example in YAML format:\napplication.yaml\n```\nlevel1:\n  property1: 5\n  property2: 6\n  property3: 7\n  level2:\n     property4: 8\n     property5: 10\n     property6: 11\n```\n\nYAML \n- is concise\n- is more readable\n\n## Spring Boot and YAML\n\nSpring Boot has excellent support for YAML configuration. \n\n### Example 1\n\napplication.properties\n```\nserver.port = 9080\n```\n\napplication.yaml\n```\nserver:\n\tport: 9080\n```\n\n### Example 2\n\napplication.properties\n```\napp.name=in28Minutes\napp.description=${app.name} is your first Spring Boot application\nwelcome.message=Welcome message from property file! Welcome to ${app.name}\n```\n\napplication.yaml\n```\napp:\n   name: In28Minutes\n   description: ${app.name} is your first Spring Boot application\nwelcome:\n    message: Welcome to your first Spring Boot app!\n```\n\n### Example 3 - Dynamic Configuration\n\napplication.properties\n```\nbasic.value: true\nbasic.message: Dynamic Message\nbasic.number: 100\n```\n\napplication.yaml\n```\nbasic: \n   value: true\n   message: Dynamic Message YAML\n   number: 100\n```\n\nComplete project with code example - https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-tutorial-basics-configuration"
  },
  {
    "path": "_blog/articles/2017-12-20-spring-boot-application-configuration-profiles.md",
    "content": "---\nlayout:     post\ntitle:      Spring Boot Profiles - Application Configuration made easy\ndate:       2022-07-05 12:31:19\nsummary:    Different environments have different application configuration. Profiles help you to configure different configuration for different environments. In this tutorial, lets understand how to use Profiles with Spring Boot. Let's learn how to make your Application Configuration simple and dynamic.\ncategories:  SpringBoot\npermalink:  /spring-boot-profiles\nimage: /images/spring-boot-feature.png\n---\n\nThis guide will introduce you to profiles and help you understand how to use profiles with the various application configuration options that are present in Spring Boot. \n\n![Image](/images/Spring-Initializr-Web-JPA.png \"Web, JPA, Hibernate and Developer Tools\")\n \n## You will learn\n- What is application configuration?\n- What is a profile?\n- How do you define beans for a specific profile?\n- How do you create application configuration for a specific profile?\n- How do you have different configuration for different environments?\n\n\n\n## Need for Application Configuration\n\nConfiguration for applications vary from one environment to another\n- You would want to connect to a different database or queues\n- You would want to connect with different services\n- You would want to configure less logging in production\n- You might want to have different custom configuration\n\n## Need for Profiles\n\nEnterprise application development is complex. You have multiple environments\n- Dev\n- QA\n- Stage\n- Production\n\nYou want to have different application configuration in each of the environments.\n\n> Profiles help to have different application configuration for different environments. \n\nSpring and Spring Boot provide features where you can specify\n- What is the configuration for various environments in different profiles?\n- Set the active profile for a specific environment.\n\nSpring Boot would pick up the application configuration based on the active profile that is set in a specific environment.\n\n## Project Code Structure\n\nFollowing screen shot shows the structure of the project we will create.\n\n![Image](/images/SpringBootApplicationConfiguration-ProjectStructure.png \"Spring Boot Application Configuration Project Structure\")\n\nA few details:\n- SpringBootTutorialBasicsConfigurationApplication.java - The Spring Boot Application class generated with Spring Initializer. This class acts as the launching point for application. In this example, a few profile based beans are also created in the Application class.\n- `pom.xml` - Contains all the dependencies needed to build this project.\n- `BasicConfiguration.java` - We will use this component to define application configuration using @ConfigurationProperties\n- `WelcomeResource.java` - Example of a resource using @Value\n- `application.properties` - Configuration for application. Active profile is set in application.properties in this example\n- `application-dev.properties` - Configuration Overrides for dev profile\n- `application-prod.properties` - Configuration Overrides for prod profile\n\n## Tools you will need\n- Maven 3.0+ is your build tool\n- Your favorite IDE. We use Eclipse.\n- JDK 1.8+\n\n## Complete Maven Project With Code Examples\n> Our Github repository has all the code examples - https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-tutorial-basics-configuration\n\n## Bootstrapping with Spring Initializr\n\nSpring Initializr [http://start.spring.io/](http://start.spring.io/){:target=\"_blank\"} is great tool to bootstrap your Spring Boot projects.\n\n![Image](/images/Spring-Initializr-Web.png \"Web, Actuator and Developer Tools\")   \n\n![Image](/images/Spring-Initializr-Web-JPA.png \"Web, JPA, Hibernate and Developer Tools\")\n\nAs shown in the image above, following steps have to be done\n\n- Launch Spring Initializr and choose the following\n  - Choose `com.in28minutes.springboot.tutorial.basics.application.configuration` as Group\n  - Choose `spring-boot-tutorial-basics-configuration` as Artifact\n  - Choose following dependencies\n    - Web\n    - DevTools\n- Click Generate Project.\n- Import the project into Eclipse. File -> Import -> Existing Maven Project.\n\n\n### Set up a Quick Example to illustrate Profiles\n\nLets create a simple resource to expose application configuration using @Value.\n\n```\n@RestController\npublic class WelcomeResource {\n\n\t@Value(\"${welcome.message}\")\n\tprivate String welcomeMessage;\n\n\t@GetMapping(\"/welcome\")\n\tpublic String retrieveWelcomeMessage() {\n\t\t// Complex Method\n\t\treturn welcomeMessage;\n\t}\n}\n```\n\nValue for welcome message can be configured in application.properties.\n\n```\nwelcome.message=Welcome message from property file! Welcome to in28Minutes\n```\n\nWhen you launch http://localhost:8080/welcome, you would see a page with this message\n\n`Welcome message from property file! Welcome to in28Minutes`\n\n\nLet's define another simple resource specifying application configuration using `@ConfigurationProperties`.\n\n```\n@Component\n@ConfigurationProperties(\"basic\")\npublic class BasicConfiguration {\n    private boolean value;\n    private String message;\n    private int number;\n\n    //GETTERS AND SETTERS\n}\n```\nWe would need to use the BasicConfiguration in a service to expose the values\n\n```\n@Autowired\nprivate BasicConfiguration configuration;\n\n@RequestMapping(\"/dynamic-configuration\")\npublic Map dynamicConfiguration() {\n    // Not the best practice to use a map to store differnt types!\n    Map map = new HashMap();\n    map.put(\"message\", configuration.getMessage());\n    map.put(\"number\", configuration.getNumber());\n    map.put(\"key\", configuration.isValue());\n    return map;\n}\n\n```\n\nWhen you browse to http://localhost:8080/dynamic-configuration, you see the following response.\n\n```\n{\"number\":100,\"message\":\"Dynamic Message\",\"key\":true}\n```\n\nThe above example is explained step by step in more detail in the Application Configuration article - http://www.springboottutorial.com/spring-boot-application-configuration\n\n## Using Profiles to configure environment specific configuration\n\nProfile is nothing but a key to identify an environment. \n\nIn this example, we will use two profiles\n- dev\n- prod\n\nThe default application configuration is present in application.properties. Let's consider an example.\n\napplication.properties\n```\nlogging.level.org.springframework.web.servlet: DEBUG\napp.name=in28Minutes\nwelcome.message=Welcome message from property file! Welcome to ${app.name}\n\nbasic.value= true\nbasic.message= Dynamic Message\nbasic.number= 100\n```\n\nWe would want to customize the application.properties for DEV profile. We would need to create a file with name application-dev.properties and override the properties that we would want to customize.\n\napplication-dev.properties\n```\nwelcome.message=Welcome message from property file! Welcome to ${app.name} in DEV\n\nbasic.message: Dynamic Message in DEV\n```\n\nSimilarly you can configure properties for prod profile.\n\napplication-prod.properties\n```\nwelcome.message=Welcome message from property file! Welcome to ${app.name} in Prod\n\nbasic.message: Dynamic Message in Prod\n```\n\n## Setting Active Profile\n\nOnce you have profile specific configuration, you would need to set the active profile in an environment.\n\nThere are multiple ways of doing this\n - Using -Dspring.profiles.active=prod in VM Arguments\n - Use `spring.profiles.active=prod` in application.properties\n\nIn this example let's set it in application.properties. Lets add another property to application.properties\n```\nspring.profiles.active=dev\n```\n\nWhen you restart the application, you would see that the dev profile is active.\n\n```\notTutorialBasicsConfigurationApplication : The following profiles are active: dev\n```\n\nLook at the response from services\n\nhttp://localhost:8080/welcome\n```\nWelcome message from property file! Welcome to in28Minutes in DEV\n```\n\nhttp://localhost:8080/dynamic-configuration\n```\n{\"number\":100,\"message\":\"Dynamic Message in DEV\",\"key\":true}\n```\n\nYou can see that the configuration for dev profile is being picked up by Spring Boot.\n\n## Configuring Profile Specific Beans\n\nYou can take this one step further and configure profile specific beans that are created only in specific profiles.\n\nLet's add this to `SpringBootTutorialBasicsConfigurationApplication.java`\n```\n\t@Profile(\"dev\")\n\t@Bean\n\tpublic String devBean() {\n\t\treturn \"dev\";\n\t}\n\n\t@Profile(\"qa\")\n\t@Bean\n\tpublic String qaBean() {\n\t\treturn \"qa\";\n\t}\n\n\t@Profile(\"prod\")\n\t@Bean\n\tpublic String prodBean() {\n\t\treturn \"prod\";\n\t}\n```\n\nUsing @Profile annotation we can indicate the active profile in which a specific bean should be created.\n\nTo test this let's further enhance `SpringBootTutorialBasicsConfigurationApplication`.\n\nLet's print the name of all the beans that are loaded.\n```\n\tpublic static void main(String[] args) {\n\t\tApplicationContext applicationContext = SpringApplication\n\t\t\t\t.run(SpringBootTutorialBasicsConfigurationApplication.class, args);\n\n\t\tfor (String name : applicationContext.getBeanDefinitionNames()) {\n\t\t\tSystem.out.println(name);\n\t\t}\n\t}\n\n```\n\nWe are currently using dev profile\n```\nspring.profiles.active=dev\n```\n\nWhen you reload the application, you would see the following in the log\n```\ndevBean \n```\n\nYou would see that the devBean is created. However, the beans shown below are not created because those profiles are not active.\n```\n\t@Profile(\"qa\")\n\t@Bean\n\tpublic String qaBean() {\n\t\treturn \"qa\";\n\t}\n\n\t@Profile(\"prod\")\n\t@Bean\n\tpublic String prodBean() {\n\t\treturn \"prod\";\n\t}\n```\n\n## Complete Maven Project With Code Examples\n> Our Github repository has all the code examples - https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-tutorial-basics-configuration\n"
  },
  {
    "path": "_blog/articles/2017-12-21-spring-boot-and-component-scan-top20.md",
    "content": "---\nlayout:     post\ntitle:      Spring, Spring Boot and Component Scan\ndate:       2022-07-05 12:31:19\nsummary:    Understand the most important concept in Spring Framework - Component Scan. Let's see how you can configure a Component Scan in Spring and Spring Boot. We will also look at how you can debug problems related to Component Scan.\ncategories:  SpringBoot\npermalink:  /spring-boot-and-component-scan\nimage: /images/spring-features.png\n---\n\nThis guide will help you understand the most important concept in Spring - Component Scan. Spring Boot does some magic around Component Scan. Let's understand that in this article.\n\n![Image](/images/SpringBootApplicationConfiguration-ProjectStructure.png \"Spring Boot Application Configuration Project Structure\")\n \n## You will learn\n- What is Component Scan?\n- Why is Component Scan important?\n- Which packages does Spring Boot do a Component Scan automatically?\n- How do you define Component Scan with Spring Boot?\n- How do you resolve problems involving Component Scan?\n\n\n\n### @ComponentScan\n\nIf you understand component scan, you understand Spring.\n\n\nSpring is a dependency injection framework. It is all about beans and wiring in dependencies. \n\nThe first step of defining Spring Beans is by adding the right annotation - @Component or @Service or @Repository. \n\nHowever, Spring does not know about the bean unless it knows where to search for it. \n\n> This part of \"telling Spring where to search\" is called a Component Scan. \n\nYou define the packages that have to be scanned.\n\nOnce you define a Component Scan for a package, Spring would search the package and all its sub packages for components/beans.\n\nDefining a Component Scan\n- If you are using Spring Boot, check configuration in Approach 1.\n- If you are doing a JSP/Servlet or a Spring MVC application without using Spring Boot use Approach 2.\n\n\n\n## Approach 1 : Component Scan in a Spring Boot Project\n\nExecutive Summary\n- If your other packages hierarchies are below your main app with the @SpringBootApplication annotation, you're covered by implicit components scan.\n- If there are beans/components in other packages which are not sub packages of the main package, you should manually add them as @ComponentScan\n\n####### Detailed Example\n\nConsider the class below:\n\n```\npackage com.in28minutes.springboot.basics.springbootin10steps;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.ConfigurableApplicationContext;\n\n@SpringBootApplication\npublic class SpringbootIn10StepsApplication {\n\n\tpublic static void main(String[] args) {\n\t\tApplicationContext applicationContext = \n\t\t\t\tSpringApplication.run(SpringbootIn10StepsApplication.class, args);\n\t\t\n\t\tfor (String name : applicationContext.getBeanDefinitionNames()) {\n\t\t\tSystem.out.println(name);\n\t\t}\n\t}\n}\n```\n\n```@SpringBootApplication``` is defined on ```SpringbootIn10StepsApplication class``` which is package ```com.in28minutes.springboot.basics.springbootin10steps.```\n\n```@SpringBootApplication``` defines an automatic component scan on package ```com.in28minutes.springboot.basics.springbootin10steps```.\n\nYou are fine if all your components are defined in the above package or a sub-package of it.\n\nHowever, let's say one of the components is defined in a package ```com.in28minutes.springboot.somethingelse```\n\nIn this case, you would need add the new package into component scan.\n\nTwo Options\n-  Define @ComponentScan(“com.in28minutes.springboot”) \n    - This would scan the entire parent tree of com.in28minutes.springboot.\n- Or Define two specific Component Scans by using an array. \n    - @ComponentScan({\"com.in28minutes.springboot.basics.springbootin10steps\",\"com.in28minutes.springboot.somethingelse\"})\n\nOption 1\n```\n@ComponentScan(“com.in28minutes.springboot”)\n@SpringBootApplication\npublic class SpringbootIn10StepsApplication {\n```\n\nOption 2\n```\n@ComponentScan({\"com.in28minutes.springboot.basics.springbootin10steps\",\"com.in28minutes.springboot.somethingelse\"})\n@SpringBootApplication\npublic class SpringbootIn10StepsApplication {\n```\n\n### Approach 2: Non Spring Boot Project\n\nIn a non Spring Boot Project, we would typically define the component scan explicitly in an XML application context or a Java Application Context.\n\n####### Java Application Context\n\nOption 1\n```\n@ComponentScan(“com.in28minutes)\n@Configuration\npublic class SpringConfiguration {\n```\n\nOption 2\n```\n@ComponentScan({\"com.in28minutes.package1\",\"com.in28minutes.package2\"})\n@Configuration\npublic class SpringConfiguration {\n```\n\n####### XML Application Context\n\n```\n<context:component-scan base-package=\"com.in28minutes\" />\n```\n\nor Specific Multiple Packages\n\n```\n<context:component-scan base-package=\"com.in28minutes.package1, com.in28minutes.package2\" />\n```\n\n### Errors related to Component Scan\n\n#### URL Not working\n\nServer starts up fine but\n- My URL is not working\n- My login url is not working\n- My todo url is not working\n```\nWARNING: No mapping found for HTTP request with URI [/spring-mvc/login] in DispatcherServlet with name 'dispatcher'\nWARNING: No mapping found for HTTP request with URI [/login] in DispatcherServlet with name 'dispatcher'\nWARNING: No mapping found for HTTP request with URI [/list-todos] in DispatcherServlet with name 'dispatcher'\n\n```\n\n#### No qualifying bean of type found\n```\nNo qualifying bean of type [com.in28minutes.springboot.jpa.UserRepository] found for dependency [com.in28minutes.springboot.jpa.UserRepository]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}\n\n```\n> Same root cause for both above problems - The component is not being picked up.\n\nThree possible things you would need to look at\na. You have not added the right annotation - @Controller, @Repository or @Controller\nb. You have not added a component scan. \nc. The package of your component is not defined in component scan.\n\nYou have two options\n1) Add the annotation or component scan\n2) Move the component to a package already under component scan\n\n#### What is the difference between @Component and @ComponentScan? \n\n@Component and @ComponentScan are for different purposes.\n- @Component indicates that a class might be a candidate for creating a bean. Its like putting a hand up.\n- @ComponentScan is searching packages for Components. Trying to find out who all put their hands up.\n\n"
  },
  {
    "path": "_blog/articles/2017-12-23-spring-boot-interview-questions-top20.md",
    "content": "---\nlayout:     post\ntitle:      Spring Boot Interview Questions\ndate:       2022-07-05 12:31:19\nsummary:    Let's take a quick look at some of the important Spring Boot concepts with examples to get ready for a Spring Boot Interview. We will understand all the basics of Spring Boot - Auto Configuration, Starter Parent, a variety of Starter Projects - Web, JPA, Data REST and Test.\ncategories:  SpringBoot\npermalink:  /spring-boot-interview-questions\nimage: /images/spring-boot-category.png\n\n---\n\nThis guide will help you understand the most important concepts in Spring Boot in preparation for a Spring Boot Interview.\n\n![Image](/images/SpringBootApplicationConfiguration-ProjectStructure.png \"Spring Boot Application Configuration Project Structure\")\n\n \n## Spring Boot\n\nSpring Boot is the best Java framework for microservices. We recommend you to become an expert at Spring Boot!\n\n### Q : Spring Boot vs Spring MVC vs Spring - How do they compare?\n\n##### Spring Framework\n\n> Most important feature of Spring Framework is Dependency Injection. At the core of all Spring Modules is Dependency Injection or IOC Inversion of Control.\n\nWhen DI or IOC is used properly, we can develop loosely coupled applications. And loosely coupled applications can be easily unit tested.\n\n##### Spring MVC\n\n> Spring MVC Framework provides decoupled way of developing web applications. With simple concepts like Dispatcher Servlet, ModelAndView and View Resolver, it makes it easy to develop web applications.\n\n##### Spring Boot\n\nThe problem with Spring and Spring MVC is the amount of configuration that is needed.\n\n```\n  <bean\n        class=\"org.springframework.web.servlet.view.InternalResourceViewResolver\">\n        <property name=\"prefix\">\n            <value>/WEB-INF/views/</value>\n        </property>\n        <property name=\"suffix\">\n            <value>.jsp</value>\n        </property>\n  </bean>\n  \n  <mvc:resources mapping=\"/webjars/**\" location=\"/webjars/\"/>\n```\n\nSpring Boot solves this problem through a combination of  Auto Configuration and Starter Projects. Spring Boot also provide a few non functional features to make building production ready applications faster. \n\nFor complete answer with code examples refer - [Spring Boot vs Spring vs Spring MVC](http://www.springboottutorial.com/spring-boot-vs-spring-mvc-vs-spring)\n\n\n## Java and Spring Interview Guides\n\n[![Image](https://www.springboottutorial.com/images/Course-Spring-Framework-Interview-Guide-200-Questions-Answers.png \"Spring Framework Interview Guide - 200+ Questions & Answers\")](https://links.in28minutes.com/in28minutes-spring-interview)\n\n[![Image](https://www.springboottutorial.com/images/Course-Java-Interview-Guide-200-Interview-Questions-and-Answers.png \"Java Interview Guide : 200+ Interview Questions and Answers\")](https://links.in28minutes.com/in28minutes-java-interview)\n\n### Q : What is Auto Configuration?\n\nThe problem with Spring and Spring MVC is the amount of configuration that is needed.\n\n```\n  <bean\n        class=\"org.springframework.web.servlet.view.InternalResourceViewResolver\">\n        <property name=\"prefix\">\n            <value>/WEB-INF/views/</value>\n        </property>\n        <property name=\"suffix\">\n            <value>.jsp</value>\n        </property>\n  </bean>\n  \n  <mvc:resources mapping=\"/webjars/**\" location=\"/webjars/\"/>\n```\n\nCan we bring more intelligence into this? When a spring mvc jar is added into an application, can we auto configure some beans automatically?\n\n> Spring Boot looks at a) Frameworks available on the CLASSPATH b) Existing configuration for the application. Based on these, Spring Boot provides basic configuration needed to configure the application with these frameworks. This is called Auto Configuration.\n\nFor complete answer with code examples refer [Auto Configuration](http://www.springboottutorial.com/spring-boot-auto-configuration).\n\n### Q : What are Spring Boot Starter Projects?\n\n> Starters are a set of convenient dependency descriptors that you can include in your application. You get a one-stop-shop for all the Spring and related technology that you need, without having to hunt through sample code and copy paste loads of dependency descriptors. \n\nFor example, if you want to get started using Spring and JPA for database access, just include the spring-boot-starter-data-jpa dependency in your project, and you are good to go.\n\n### Q : Can you explain more about Starters with an example?\n\nLet's consider an example starter - Spring Boot Starter Web.\n\nIf you want to develop a web application or an application to expose restful services, Spring Boot Start Web is the starter to pick. Lets create a quick project with Spring Boot Starter Web using Spring Initializr.\n\nDependency for Spring Boot Starter Web\n```xml\n<dependency>\n    <groupId>org.springframework.boot</groupId>\n    <artifactId>spring-boot-starter-web</artifactId>\n</dependency>\n```\n\nFollowing screenshot shows the different dependencies that are added in to our application \n\n![Image](/images/SpringBootStarterWeb-Dependencies.png \"Spring Boot Starter Web - Dependencies\")\n\nDependencies can be classified into:\n- Spring - core, beans, context, aop\n- Web MVC - (Spring MVC)\n- Jackson - for JSON Binding \n- Validation - Hibernate Validator, Validation API\n- Embedded Servlet Container - Tomcat\n- Logging - logback, slf4j\n\nAny typical web application would use all these dependencies. Spring Boot Starter Web comes pre packaged with these. \n\n> As a developer, I would not need to worry about either these dependencies or their compatible versions. \n\n\n### Q : What are the other Starter Project Options that Spring Boot provides?\nSpring Boot also provides other starter projects including the typical dependencies to develop specific type of applications\n- spring-boot-starter-web-services - SOAP Web Services\n- spring-boot-starter-web - Web & RESTful applications\n- spring-boot-starter-test - Unit testing and Integration Testing\n- spring-boot-starter-jdbc - Traditional JDBC\n- spring-boot-starter-hateoas - Add HATEOAS features to your services\n- spring-boot-starter-security - Authentication and Authorization using Spring Security\n- spring-boot-starter-data-jpa - Spring Data JPA with Hibernate\n- spring-boot-starter-data-rest - Expose Simple REST Services using Spring Data REST\n\n### Q : How does Spring enable creating production ready applications in quick time?\n\nSpring Boot aims to enable production ready applications in quick time. Spring Boot provides a few non functional features out of the box like caching, logging, monitoring and embedded servers.\n- spring-boot-starter-actuator - To use advanced features like monitoring & tracing to your application out of the box\n- spring-boot-starter-undertow, spring-boot-starter-jetty, spring-boot-starter-tomcat - To pick your specific choice of Embedded Servlet Container\n- spring-boot-starter-logging - For Logging using logback\n- spring-boot-starter-cache - Enabling Spring Framework’s caching support\n\n### What is the minimum baseline Java Version for Spring Boot 2 and Spring 5?\n\nSpring Boot 2.0 requires Java 8 or later. Java 6 and 7 are no longer supported.\n\nRecommended Reading \n- https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.0.0-M1-Release-Notes\n\n### Q : What is the easiest approach to create a Spring Boot Project?\n\nSpring Initializr [http://start.spring.io/](http://start.spring.io/){:target=\"_blank\"} is great tool to bootstrap your Spring Boot projects.\n\n![Image](/images/Spring-Initializr-Web.png \"Web, Actuator and Developer Tools\")   \n\nAs shown in the image above, following steps have to be done\n\n- Launch Spring Initializr and choose the following\n  - Choose `com.in28minutes.springboot` as Group\n  - Choose `student-services` as Artifact\n  - Choose following dependencies\n    - Web\n    - Actuator\n    - DevTools\n- Click Generate Project.\n- Import the project into Eclipse. File -> Import -> Existing Maven Project.\n\n### Q :  Is Spring Initializr the only way to create Spring Boot Projects?\n\nNo.\n\nSpring Initializr makes it easy to create Spring Boot Projects. But you can setup a maven project and add the right dependencies to start off. \n\nIn our Spring course, we use 2 approaches to create projects. \n- The first one is start.spring.io. \n- The other one - setting up a project manually is used in the Section titled - “Basic Web Application”\n\n###### Setting up a maven project manually\n\nHere are the important steps:\n- In Eclipse, Use File -> New Maven Project to create a new project.\n- Add dependencies.\n- Add the maven plugins!\n- Add the Spring Boot Application class\n\nYou are ready to go!\n\n### Q :  Why do we need spring-boot-maven-plugin?\n\nspring-boot-maven-plugin provides a few commands which enable you to package the code as a jar or run the application\n- spring-boot:run runs your Spring Boot application.\n- spring-boot:repackage repackages your jar/war to be executable.\n- spring-boot:start and spring-boot:stop to manage the lifecycle of your Spring Boot application (i.e. for integration tests).\n- spring-boot:build-info generates build information that can be used by the Actuator.\n\n### Q :  How can I enable auto reload of my application with Spring Boot?\n\nUse Spring Boot Developer Tools.\n\nAdding Spring Boot Developer Tools to your project is very simple.\n\nAdd this dependency to your Spring Boot Project pom.xml\n\n```\n<dependency>\n    <groupId>org.springframework.boot</groupId>\n    <artifactId>spring-boot-devtools</artifactId>\n    <scope>runtime</scope>\n</dependency>\n```\n\nRestart the application. \n\nYou are all Set.\n\nIf you would want to auto load the page as well, you can look at LiveReload \n- http://www.logicbig.com/tutorials/spring-framework/spring-boot/boot-live-reload/.\n\nIn my trials, we found LiveReload buggy. Do let us know if you have a better experience with it. \n\n### Q :  What and Why Embedded Servers?\n\nThink about what you would need to be able to deploy your application (typically) on a virtual machine.\n- Step 1 : Install Java\n- Step 2 : Install the Web/Application Server (Tomcat/Websphere/Weblogic etc)\n- Step 3 : Deploy the application war\n\nWhat if we want to simplify this?\n\nHow about making the server a part of the application? \n\n> You would just need a virtual machine with Java installed and you would be able to directly deploy the application on the virtual machine. Isn't it cool?\n\nThis idea is the genesis for Embedded Servers.\n\nWhen we create an application deployable, we would embed the server (for example, tomcat) inside the deployable. \n> For example, for a Spring Boot Application, you can generate an application jar which contains Embedded Tomcat. You can run a web application as a normal Java application!\n\nEmbedded server is when our deployable unit contains the binaries for the server (example, tomcat.jar).\n\n### Q :  How can I add custom JS code with Spring Boot? \n\nCreate a folder called static under resources folder. You can put your static content in that folder.\n\nFor your example the path to myapp.js would be resources\\static\\js\\myapp.js\n\nYou can refer to it in jsp using\n\n```\n<script src=\"/js/myapp.js\"></script>\n```\n\n### Error :  HAL browser gives me unauthorized error - Full authentication is required to access this resource. How can I fix it?\n\n```\n{\n  \"timestamp\": 1488656019562,\n  \"status\": 401,\n  \"error\": \"Unauthorized\",\n  \"message\": \"Full authentication is required to access this resource.\",\n  \"path\": \"/beans\"\n}\n```\n\nTwo options\n\n###### Option 1 : Disable security\n\napplication.properties\n```\nmanagement.security.enabled: FALSE \n```\n###### Option 2 : Search for password in the log and pass it in the request header\n\n###  Q : What is Spring Data?\n\nFrom http://projects.spring.io/spring-data/\n\n> Spring Data’s mission is to provide a familiar and consistent, Spring-based programming model for data access while still retaining the special traits of the underlying data store. It makes it easy to use data access technologies, relational and non-relational databases, map-reduce frameworks, and cloud-based data services.\n\nTo make it simpler, Spring Data provides Abstractions (interfaces) you can use irrespective of underlying data source.\n\nAn example is shown below\n\n```java\ninterface TodoRepository extends CrudRepository<Todo, Long> {\n```\n\nYou can define a simple repository and use it to insert, update, delete and retrieve todo entities from the database - without writing a lot of code.\n\n### Q : What is Spring Data REST?\n\nSpring Data REST can be used to expose HATEOAS RESTful resources around Spring Data repositories.\n\nAn example using JPA is shown below\n\n```java\n@RepositoryRestResource(collectionResourceRel = \"todos\", path = \"todos\")\npublic interface TodoRepository\n        extends PagingAndSortingRepository<Todo, Long> {\n```\n\nWithout writing a lot of code, we can expose RESTful API around Spring Data Repositories.\n\nA few example REST Services are shown below:\n\n#### POST\n- URL : http://localhost:8080/todos\n- Use Header : Content-Type:application/json\n- Request Content\n\n```\n{\n  \"user\": \"Jill\",\n  \"desc\": \"Learn Hibernate\",\n  \"done\": false\n}\n```\n\nResponse Content\n```\n{\n  \"user\": \"Jill\",\n  \"desc\": \"Learn Hibernate\",\n  \"done\": false,\n  \"_links\": {\n    \"self\": {\n      \"href\": \"http://localhost:8080/todos/1\"\n    },\n    \"todo\": {\n      \"href\": \"http://localhost:8080/todos/1\"\n    }\n  }\n}\n```\n\nThe response contains the href of the newly created resource.\n\n### Q :  How does path=\"users\", collectionResourceRel=\"users\" work with Spring Data Rest?\n\n```\n@RepositoryRestResource(collectionResourceRel = \"users\", path = \"users\")\n\npublic interface UserRestRepository extends\nPagingAndSortingRepository<User, Long>\n```\n\n- path - The path segment under which this resource is to be exported.\n- collectionResourceRel - The rel value to use when generating links to the collection resource. This is used when generating HATEOAS links.\n\n\n### Q :  What happens in the background when a Spring Boot Application is \"Run as Java Application\"?\n\nIf you are using Eclipse IDE, Eclipse maven plugin ensures that as soon as you add a dependency or make a change to the class file, it is compiled and ready in the target folder! And after that its just like any other Java application. \n\nWhen you launch the java application, then the spring boot auto configuration magic kicks in. \n- It launches up tomcat when it sees that you are developing a web application!\n\n### Q :  Can we use jetty instead of tomcat in spring-boot-starter-web?\n\nRemove the existing dependency on spring-boot-starter-web and add these in.\n\n```\n<dependency>\n    <groupId>org.springframework.boot</groupId>\n    <artifactId>spring-boot-starter-web</artifactId>\n    <exclusions>\n        <exclusion>\n            <groupId>org.springframework.boot</groupId>\n            <artifactId>spring-boot-starter-tomcat</artifactId>\n        </exclusion>\n    </exclusions>\n</dependency>\n<dependency>\n    <groupId>org.springframework.boot</groupId>\n    <artifactId>spring-boot-starter-jetty</artifactId>\n</dependency>\n```\n\n### Q :  How to generate a WAR file with Spring Boot?\n\nRecommended Reading\n- https://spring.io/guides/gs/convert-jar-to-war/\n\nHere’s the direct link to spring documentation \n- https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#build-tool-plugins-maven-packaging\n\n### Q :  How to deploy to a different server with with Spring Boot?\n\nYou would need to do 2 Steps\n- Generate a war from the project. \n- Deploy it to your favourite server (Websphere or Weblogic or Tomcat or ...).\n\nStep 1 : This getting started guide should help - https://spring.io/guides/gs/convert-jar-to-war/\n\nStep 2 : Depends on your server\n\n### Q :  What is the difference between RequestMapping and GetMapping?\n- RequestMapping is generic - you can use with GET, POST, PUT or any of the other request methods using the method attribute on the annotation.\n- GetMapping is specific to GET request method. It’s just an extension of RequestMapping to improve clarity. \n\n### Q :  Why do we recommend not to use Spring Data Rest in real world applications?\n\nWe think Spring Data Rest is Good for quick prototyping! Be cautious about using this in Big applications!\n\nWith Spring Data REST you are exposing your database entitities directly as REST Services. \n\nWhen you design RESTful services, Best design practices suggests that your interface should consider two important things\n- Your Domain Model\n- Your Consumers\n\nWith Spring Data REST, you are not considering either of those. You just expose entities as REST Services.\n\nThats why we suggest to use it for quick prototyping or the initial evolution of a project. It may not be a great idea for a fully evolved project.\n\n### Q :  How do I change the package name of a project in Spring Initializer?\n\nGood news is you can customise it. Click the link “Switch to the full version.“. You would be able to configure the package name you would want!\n\n### Q :  Where can I find the complete list of properties that can be configured in application.properties?\n\nHere’s the complete guide \n- https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html\n\n### Q :  What is the difference between JPA and Hibernate?\n\nShort Story\n- JPA is a specification/Interface \n- Hibernate is one of JPA implementations\n\nWhen we use JPA, we use the annotation and interfaces from javax.persistence package, without using the hibernate import packages.\n\nWe recommend using JPA annotations as we are not tied to Hibernate as implementation. Later (I know - <1% Chance), we can use another JPA implementation.\n\n### Q :  In which layer, should the boundary of a transaction start?\n\nWe recommend managing transactions in the Service layer. Logic for business transactions is in the business/service layer and you would want to enforce transaction management at that level.\n\n### Q :  What are the dependencies needed to start up a JPA Application connecting to in memory database H2 with Spring Boot?\n\nIn a Spring Boot project, you should be able to launch up H2 Console as long as you ensure the following dependencies are on the class path.\n- web starter\n- h2  \n- data jpa starter\n\nThe exact dependencies are shown below:\n```\n<dependency>\n    <groupId>org.springframework.boot</groupId>\n    <artifactId>spring-boot-starter-web</artifactId>\n</dependency>\n\n<dependency>\n    <groupId>org.springframework.boot</groupId>\n    <artifactId>spring-boot-starter-data-jpa</artifactId>\n</dependency>\n\n<dependency>\n    <groupId>com.h2database</groupId>\n    <artifactId>h2</artifactId>\n    <scope>runtime</scope>\n</dependency>\n```\n\nA few tips:\n- An in-memory database is live only during the time of execution of the application. It is an efficient way to learn a framework.\n- This is not how you want your real world applications to behave.\n- We explain how to connect to a database of your choice in the answer to the question \"How do we connect to a external database?\".\n\n### Q :  How is Hibernate chosen as the default implementation for JPA without any configuration?\n\nBecause of Spring Boot Auto Configuration.\n\nThis is the dependency we added in \n\n```\n<dependency>\n            <groupId>org.springframework.boot</groupId>\n            <artifactId>spring-boot-starter-data-jpa</artifactId>\n        </dependency>\n```\n\nThe Starter spring-boot-starter-data-jpa has a transitive dependency on Hibernate and JPA.\n\nWhen Spring Boot sees Hibernate in the class path, it auto configures it as the default JPA Implementation.\n\n### Q :  Where is the database connection info specified? How does it know to automatically connect to H2?\n\nThats Spring Boot Autoconfiguration magic.\n\nFrom https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-auto-configuration.html\n\n> Spring Boot auto-configuration attempts to automatically configure your Spring application based on the jar dependencies that you have added. For example, If HSQLDBis on your classpath, and you have not manually configured any database connection beans, then we will auto-configure an in-memory database\n\nMore Reading\n- http://www.springboottutorial.com/spring-boot-auto-configuration\n\n### Q :  How do we connect to a external database like MSSQL or oracle? \n\nLet's consider one of those as an example - MySQL\n\n###### Step 1 - Add dependency for mqsql connector to pom.xml \n```\n<dependency>\n    <groupId>mysql</groupId>\n    <artifactId>mysql-connector-java</artifactId>\n</dependency>\n```\n\n###### Step 2 - Remove H2 Dependency from pom.xml\nOr atleast make its scope as test\n\n```\n<!--\n<dependency>\n    <groupId>com.h2database</groupId>\n    <artifactId>h2</artifactId>\n    <scope>test</scope>\n</dependency>\n-->\n```\n\n###### Step 3 - Setup your My SQL Database\n- For more check out - https://github.com/in28minutes/jpa-with-hibernate#installing-and-setting-up-mysql\n\n###### Step 4 - Configure your connection to My SQL Database\nConfigure application.properties\n```\nspring.jpa.hibernate.ddl-auto=none\nspring.datasource.url=jdbc:mysql://localhost:3306/todo_example\nspring.datasource.username=todouser\nspring.datasource.password=YOUR_PASSWORD\n```\n\n###### Step 5 - Restart and You are ready!\nThat's it\n\n### Q :  What is the default h2 database name configured by Spring Boot? Why is the default database name testdb?\n\nThis is where all the default values in application.properties are listed\n- https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html\n\nLook for the property below\n```\nspring.datasource.name=testdb # Name of the datasource.\n```\n\nIf you are using an H2 in-memory database, thats exactly the name that Spring Boot uses to setup your H2 database.\n\n### Q :  What happens if H2 is not in the classpath?\n\nYou get this error\n\n```\nCannot determine embedded database driver class for database type NONE\n```\n\nAdd H2 to the pom.xml and Restart your server\n```\n<dependency>\n    <groupId>com.h2database</groupId>\n    <artifactId>h2</artifactId>\n    <scope>runtime</scope>\n</dependency>\n```\n\n### Q :  Can you give an example for ReadOnly as true in Transaction management?\n- When you read stuff from the database, user details or any other details, you wanna set read only on the transaction so that Hibernate does not need to check for changes to the entities. This is more efficient.\n\n### Q : What is best way to expose custom application configuration with Spring Boot?\n\nThe problem with @Value is that you would have your configuration values distributed through out your application. A better option would be to have a centralized approach. \n\nYou can define a configuration component using `@ConfigurationProperties`.\n\n```\n@Component\n@ConfigurationProperties(\"basic\")\npublic class BasicConfiguration {\n    private boolean value;\n    private String message;\n    private int number;\n\n```\n\nThe values can be configured in application.properties\n```\nbasic.value: true\nbasic.message: Dynamic Message\nbasic.number: 100\n```\n### Q : What is the need for Profiles?\n\nEnterprise application development is complex. You have multiple environments\n- Dev\n- QA\n- Stage\n- Production\n\nYou want to have different application configuration in each of the environments.\n\n> Profiles help to have different application configuration for different environments. \n\nSpring and Spring Boot provide features where you can specify\n- What is the configuration for various environments in different profiles?\n- Set the active profile for a specific environment.\n\nSpring Boot would pick up the application configuration based on the active profile that is set in a specific environment.\n\n### Q : How can you use profiles to configure environment specific configuration with Spring Boot?\n\nProfile is nothing but a key to identify an environment. \n\nIn this example, we will use two profiles\n- dev\n- prod\n\nThe default application configuration is present in application.properties. Let's consider an example.\n\napplication.properties\n```\nbasic.value= true\nbasic.message= Dynamic Message\nbasic.number= 100\n```\n\nWe would want to customize the application.properties for dev profile. We would need to create a file with name application-dev.properties and override the properties that we would want to customize.\n\napplication-dev.properties\n```\nbasic.message: Dynamic Message in DEV\n```\n\nSimilarly you can configure properties for prod profile.\n\napplication-prod.properties\n```\nbasic.message: Dynamic Message in Prod\n```\n\nOnce you have profile specific configuration, you would need to set the active profile in an environment.\n\nThere are multiple ways of doing this\n - Using -Dspring.profiles.active=prod in VM Arguments\n - Use `spring.profiles.active=prod` in application.properties\n\n## Java and Spring Interview Guides\n\n[![Image](https://www.springboottutorial.com/images/Course-Spring-Framework-Interview-Guide-200-Questions-Answers.png \"Spring Framework Interview Guide - 200+ Questions & Answers\")](https://links.in28minutes.com/in28minutes-spring-interview)\n\n[![Image](https://www.springboottutorial.com/images/Course-Java-Interview-Guide-200-Interview-Questions-and-Answers.png \"Java Interview Guide : 200+ Interview Questions and Answers\")](https://links.in28minutes.com/in28minutes-java-interview)\n\n"
  },
  {
    "path": "_blog/articles/2017-12-24-spring-interview-questions-top20.md",
    "content": "---\nlayout:     post\ntitle:      Spring Interview Questions\ndate:       2022-07-04 12:31:19\nsummary:    Let's take a quick look at some of the important Spring concepts with examples to get ready for a Spring Interview. We will look at defining beans with Spring (@Component, @Service, etc), auto wiring them (@Autowired), @ComponentScan and understand the basics of Application Context and Bean Factory. We will also look a few important Spring MVC interview questions.\ncategories:  SpringFramework\npermalink:  /spring-interview-questions\nimage: /images/spring-framework-category.png\n---\n\n![Image](/images/Spring-Initializr-Web-JPA.png \"Web, JPA, Hibernate and Developer Tools\")\n\nThis guide will help you understand the most important concepts in Spring in preparation for a Spring Interview.\n\n![Image](/images/SpringBootApplicationConfiguration-ProjectStructure.png \"Spring Boot Application Configuration Project Structure\")\n\n \n### Q :  What is the need for a Component Scan?\n\n> If you understand component scan, you understand Spring.\n\nThe first step of defining Spring Beans is by adding the right annotation - @Component or @Service or @Repository. \n\nHowever, Spring does not know about the bean unless it knows where to search for it. This part of \"telling Spring where to search\" is called a Component Scan. You define the packages that have to be scanned.\n\nOnce you define a Component Scan for a package, Spring would search the package and all its sub packages for components.\n\n### Q :  How do you define a Component Scan with Spring Boot?\n\nConsider the class below:\n\n```\npackage com.in28minutes.springboot.basics.springbootin10steps;\n\n@SpringBootApplication\npublic class SpringbootIn10StepsApplication {\n\n\tpublic static void main(String[] args) {\n\t\tApplicationContext applicationContext = \n\t\t\t\tSpringApplication.run(SpringbootIn10StepsApplication.class, args);\n```\n\n```@SpringBootApplication``` is defined on ```SpringbootIn10StepsApplication class``` which is package ```com.in28minutes.springboot.basics.springbootin10steps.```\n\n```@SpringBootApplication``` defines an automatic component scan on package ```com.in28minutes.springboot.basics.springbootin10steps```.\n\nYou are fine if all your components are defined in the above package or a sub-package.\n\nHowever, let's say one of the components is defined in a package ```com.in28minutes.springboot.somethingelse```\n\nIn this case, you would need add the new package into component scan.\n\nTwo Options\n-  Define @ComponentScan(“com.in28minutes.springboot”) - This would scan the entire parent tree of com.in28minutes.springboot.\n- Or Define two specific Component Scans by using an array. \n   - @ComponentScan({\"com.in28minutes.springboot.basics.springbootin10steps\",\"com.in28minutes.springboot.somethingelse\"})\n\n### Q :  What is the difference between @Component and @ComponentScan? \n\n@Component and @ComponentScan are for different purposes.\n- @Component indicates that a class might be a candidate for creating a bean. Its like putting a hand up.\n- @ComponentScan is searching packages for Components. Trying to find out who all put their hands up.\n\n\n### Q :  What is the use of an @Bean annotation?\nWithin a Spring Configuration Class , @Bean is used to define beans with custom configuration. You define the beans to be created!\n\n### Q :  What is the difference between @Bean and @Component?\n\nHere's a quick fire answer\n- @Bean is used in Spring Configuration Files and Classes. It is used to directly instantiate or configure spring beans.\n- @Component is used with everything that you want Spring to manage. When Spring sees @Component, it creates a bean for you!\n\n### Q :  What is the difference between @Component, @Service and @Repository annotations?\n\nAt the core, all of these define spring beans. However, you can further classify them based on the layer you are using them. \n- @Component - Generic Component\n- @Repository - encapsulating storage, retrieval, and search behavior typically from a relational database\n- @Service - Business Service Facade\n- @Controller - Controller in MVC pattern\n\nIn addition, these can be used at later point to add additional behaviour using AOP, for example. \n- For example, in case of @Repository, Spring automatically wires in JDBC Exception translation features.\n\nBy using a specific annotation, you are giving more information to the framework about your intentions.\n\n### Q :  Can we use @Component annotation instead of @Service for Business Services?\n\nHeres an extract from spring documentation. Since we were creating a business layer service, we used @Service. \n\n> \"@Component serves as a generic stereotype for any Spring-managed component; whereas, @Repository, @Service, and @Controller serve as specializations of @Component for more specific use cases (e.g., in the persistence, service, and presentation layers, respectively). What this means is that you can annotate your component classes with @Component, but by annotating them with @Repository, @Service, or @Controller instead, your classes are more properly suited for processing by tools or associating with aspects. For example, these stereotype annotations make ideal targets for pointcuts. Of course, it is also possible that @Repository, @Service, and @Controller may carry additional semantics in future releases of the Spring Framework. Thus, if you are making a decision between using @Component or @Service for your service layer, @Service is clearly the better choice. Similarly, as stated above, @Repository is already supported as a marker for automatic exception translation in your persistence layer.\"\n\n### Q :  What is the difference between web.xml and the Spring Context - servlet.xml?\n\nShort Answer:\n- web.xml - Java EE Web application Standard. Meta data and configuration of any Java EE compliant web application is stored in web.xml.\n- todo-servlet.xml - Spring Configuration file. Specific to Spring Framework.\n\n### Q :  Should we use XML or Annotation based wiring?\n\nWhich is better depends on a) context b) preference of the team.\n\nIf the configuration is specific to a bean, that is part of the current project code base - for example @Service, @Component, @Autowired - I prefer annotations.\n\nHowever, when it comes to some application related configuration or a common configuration example @ComponentScan, I do not really have a preference. I would leave it to the team. However, I would definitely want the entire team to discuss and agree what they prefer. \n\n### Q :  Can we do autowiring with Non Setter and Non Constructor Methods?\nYes you can. \n\n@Autowired annotation can be used with constructor, setter method or just any other method. Whenever Spring finds @Autowired annotation it will try to find beans matching to method parameters and will invoke that method. If multiple methods (setter or non-setter) have @Autowiredannotation, all will be invoked by Spring after bean instantiation.\n\nWhenever you use an @Autowired on a method in the bean, it will be called after bean instantiation. So, this method would be called and Spring would auto wire the matching objects from the Spring Context.\n\nHere's a recommended reading:\n- http://stackoverflow.com/questions/30188262/spring-autowired-for-setter-methods-vs-non-setter-methods\n\n### Q :  Where should we use Checked Exceptions?\n\nI've a simple philosophy!\n\nIf you can do something about an Exception other than showing an error page to the user, then consider Checked Exceptions. You want the consumer of the method to do something about that exception!\n\nIn all other scenarios where there is nothing a programmer can do - other than showing an error page - use Unchecked exceptions. \n\nI love keeping exception handling code to a bare minimum!\n\nThat's what Spring enables by converting most Checked exceptions into Runtime (also called Unchecked) exceptions.\n\n### Q :  What is the difference between Cross Cutting Concerns and AOP?\n\nA quick fire answer\n- Cross Cutting Concerns are features or functionality that you would need in multiple layers - logging, performance management, security etc.\n- AOP is one of the preferred approaches to implement Cross Cutting Concerns.\n\n### Q :  What is difference between IOC and Application Context?\n\nIOC is a concept - Inversion of Control. Instead of the programmer injecting dependencies, the framework takes the responsibility of auto wiring.\n\nApplicationContext is the Spring implementation of IOC.\n\nBean Factory is the basic version of IOC Container. \n\nApplication Context adds in all the features that are typically needed by enterprise applications. \n\n### Q :  What is the difference between classPathXmlApplicationContext and annotationConfigApplicationContext ?\n\n- classPathXmlApplicationContext > You want to load an application context using an Spring Config XML present in the class path.\n- annotationConfigApplicationContext > You want to load an application context using a Java Config class.\n\n\n### Q :  When @Around aspect is introduced the value returned by@AfterReturning is lost. Why is this happening?\nThe around method should return an Object - value returned by joinpoint.proceed(). \n\n```\n@Around(\"com.in28minutes.spring.aop.springaop.aspect.CommonJoinPointConfig.trackTimeAnnotation()\")\npublic Object around(ProceedingJoinPoint joinPoint) throws Throwable{\n    long startTime = System.currentTimeMillis();\n \n    Object retVal = joinPoint.proceed();\n \n    long timeTaken = System.currentTimeMillis() - startTime;\n    logger.info(\"Time taken by {} is equal to {}\",joinPoint, timeTaken);\n \n    return retVal;\n}\n```\n### Q :  How do you decide which autowiring type to use when there are multiple matching beans - @Primary or @Qualifier?\n\nIf there is a default bean (a bean you prefer over all others) that you want to use most of the times, then go for @Primary and use @Qualifier for non-default scenarios.\n\nIf all of the beans have same priority, we would go with @Qualifier always.\n\nIf you want to select a bean at runtime, thats business logic - Not auto wiring.\n\nYou would need to create a separate class for Selector which has both the sorting algorithms auto wired. It should have the business logic to choose the appropriate algorithm.\n\n### Q :  What are the New Features in Spring Framework 5.0?\n\nI’ve recently wrote a book on Mastering Spring 5.0.\n\nImportant features in Spring 5.0 are Functional Web Framework, Kotlin and Reactive Programming support. But none of these are mainstream yet. \n\nhttps://github.com/spring-projects/spring-framework/wiki/What%27s-New-in-the-Spring-Framework#whats-new-in-spring-framework-5x \n\n\n### Q :  Compare Application Context vs IOC Container vs Web Container vs EJB Container\n\nDo we need a Web Container to run a Spring Boot Application?\n\nBasically spring runs anywhere where we have a JVM because that JVM will have capability to run some sort of a container or capability to run an application. Difference would be that the mechanism to load application context would be different based on where it runs. e.g. 2  high level categories - ApplicationContext for Web and Applicationcontext for standalone and again in those 2 categories we will choose \"how\" and \"from where\" we want to load that metadata for those applicationContext. \n\nWeb Container & EJB Containers are part of the application/web servers - Tomcat, Websphere, Weblogic. They run what ever application is given to them. Java EE defines a contract for web applications (web.xml etc etc) and these are the implementations of that contract.\n\nSpring Container is part of the application you are building - the jar or the war. It can run inside a web container, EJB container or even without them :) You can launch it as a java application or you can even run it in an embedded server.\n\n### Q :  How do we inject different bean depending on the configuration in application.properties?\n\nConsider the example\n\n```\ninterface GreetingService {\npublic String sayHello();\n}\n```\n\nTwo components\n```\n@Component(value=\"real\")\nclass RealGreetingService implements GreetingService {\n\tpublic String sayHello() {\n\t\treturn \"I'm real\";\n\t}\n}\n\n \n@Component(value=\"mock\")\nclass MockGreetingService implements GreetingService {\n\tpublic String sayHello() {\n\t\treturn \"I'm mock\";\n\t}\n}\n```\n\napplication.properties\n```\napplication.greeting: real \n```\n\nAdding @Resource with the name of the property\n\n```\n@RestController\npublic class WelcomeController {\n \n@Resource(name=\"${application.greeting}\")\nprivate GreeterService service1;\n```\n\n### Q :  What is the minimum baseline Java Version for Spring Boot 2 and Spring 5?\n\nSpring 5.0 and Spring Boot 2.0 requires Java 8 or later. Java 6 and 7 are no longer supported.\n\nRecommended Reading \n- https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.0.0-M1-Release-Notes\n\n### Q :  What is the difference between @Controller and @RestController?\n\n@RestController = @Controller + @ResponseBody\n\nThe response from the @RestController are directly returned as a response after conversion to JSON or XML.\n\nIn Summary\n- @Controller : Uses a view resolver to find the view. You are returning either the View, View Name or Model and View.\n- @RestController : You are returning a bean. The bean would be converted to a JSON using a Jackson message converter.\n\n\n```\n@Controller\n@ResponseBody\npublic class MyController { }\n \n@RestController\npublic class MyRestController { }\n```\n\n### Q :  Why do we use  @ResponseBody sometimes and ResponseEntity<T> some other times?\n\nQuick Answer - You use ResponseEntity when you want to customize the Response Status. In all other situations, we use @ResponseBody.\n\n###### Example 1\n@GetMapping(value=\"/resource\")\n@ResponseBody\npublic Resource sayHello() { \n   return resource;\n}\n\n###### Example 2\n@PostMapping(value=\"/resource\")\npublic ResponseEntity<String> createResource() {\n    ....\n    ....\n    return ResponseEntity.created(resource).build();\n}\n\nThere are a variety of HTTP Response Status Codes that you can return with your response.\n\n- 200 - SUCCESS\n- 201 - CREATED\n- 404 - RESOURCE NOT FOUND\n- 400 - BAD REQUEST\n- 401 - UNAUTHORIZED\n- 500 - SERVER ERROR\n\nWith @ResponseBody the only response type that goes out is SUCCESS (Example 1). (or 500 if a server error happens)\n\nLet's say you are creating a resource. You would want to send a status of 201 CREATED. In this case, we use ResponseEntity as in Example 2.\n\n### Q :  What is the difference between Filters, Listeners and Interceptors?\n\nConceptually similar. Servlet filters can intercept only HTTPServlets. Listeners can intercept a few specific events. How do you intercept events which are neither of the above.\n\nBoth filters and interceptors do the same things - They intercept something and do something before/after an action is performed.\n\nJava EE uses the term filter (in web.xml) and Spring calls them Interceptors.\n\nThats where AOP comes in. You can intercept calls to any object with AOP. \n\nMore Reading\n- http://www.programering.com/a/MzM3EDNwATY.html\n\n### Q :  What is the difference between ModelMap and ModelAndView?\n\nModel is an interface while ModelMap is a class.\n\nModelAndView is just a container for both a ModelMap and a View object. It allows a controller to return both as a single value.\n\nI usually like ModelAndView to return the model and view from a controller. However, there is an option where you can just add values to ModelMap and return viewname from the controller method. \n\nMore Reading\n- http://stackoverflow.com/questions/16951609/when-to-use-modelandview-vs-model-in-spring \n\n### Q :  What is the difference between model.put() and model.addAttribute()? \n\nCode for addAttribute method is listed below. It does an additional null check before calling a put. Doesn't really matter which one you use. \n\nI like addAttribute because you are separated from underlying data structure (```put``` implies you are using a hashmap).\n\n/**\n     * Add the supplied attribute under the supplied name.\n     * @param attributeName the name of the model attribute (never <code>null</code>)\n     * @param attributeValue the model attribute value (can be <code>null</code>)\n     */\n    public ModelMap addAttribute(String attributeName, Object attributeValue) {\n        Assert.notNull(attributeName, \"Model attribute name must not be null\");\n        put(attributeName, attributeValue);\n        return this;\n    }\n\nOne more difference is that addAttribute returns the ModelMap back. So, you can chain calls.\n\nmodel.addAttribute(\"attribute1\",\"value1\").addAttribute(\"attribute2\",\"value2\");\n\n### Q :  What is Form Binding?\nWe want to take values from screen and store them to the database. The value on the HTML form needs to be transferred to the bean on the Controller. \n\nIf you use the Spring MVC form tags, Spring MVC automatically takes care of the binding the values in the HTML form to the bean.\n- I would recommend you to do a View Source on the browser and see the html that is generated with the form tags\n\nYou need a form to bind the value to a bean. \n\nYou can look up the documentation for Spring MVC Form Tags for more details.\n\nI would recommend you to start looking at each of the things thats happening in the browser. See the html that is generated (view source), look at what are the values in the request when you click the submit button on the screen (Look at the network tab : http://code.tutsplus.com/articles/chrome-dev-tools-networking-and-the-console--net-28167)\n\nCouple of Sources which might be useful for you\n- Spring MVC Documentation : http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#mvc\n- Spring MVC Code : https://github.com/spring-projects/spring-framework/tree/master/spring-webmvc/src\n\n### Q :  Why do we use Hibernate Validator?\n\nHibernate Validator is not related to Database. It is a validation framework.\n\nHibernate Validator 5.x is the reference implementation Bean Validation 1.1! \n\nActually, you can use any implementation of Bean Validation API.  However, there are really no other popular options.\n\nAs you can see at http://beanvalidation.org/2.0/, Hibernate Validator is the only one which is certified!\n\n### Q :  Are Model objects specific to a request?\n\nYes. They are specific to a request.\n\nModel objects cannot be shared across requests. So, 2 different requests mean 2 different model objects.\n\nIf you look at the jsp for a todo page, it shares the responsibility of creating a new todo and modifying an existing todo. And the todo object is binded to the form. \n\nTo display todo page for new todo, we need a model with no values. That's the first model object that's created.\n- This is used only for the display of new todo page. \n\nOnce the page is displayed, the first model does not exist anymore. \n\nWhen user fills in the values and clicks submit, the values in the form gets bound to a new model object - the second one.\n\n### Q :  How to use own CSS with Spring MVC?\n\nSpring Configuration XML\n<mvc:resources mapping=\"/resources/**\" location=\"/WEB-INF/resources/\" />\n\nJSP\n<link href=\"resources/css/main.css\" rel=\"stylesheet\">\n\n### Q :  Where should we place our static (css, js, html) resources in a Spring MVC application?\n\nFor the Java script, I would have separate Java script files and include them into your jsp.\n\nHere's a small discussion where static files should be located:\n- https://stackoverflow.com/questions/7836930/where-do-css-and-javascript-files-go-in-a-maven-web-app-project\n\n### Q :  How to add a custom login page in Spring Security?\n\nComplete example down here \n- http://docs.spring.io/spring-security/site/docs/current/guides/html5/form-javaconfig.html\n\nOther Recommended Reading\n- https://docs.spring.io/spring-security/site/docs/3.2.0.RELEASE/guides/form.html\n- http://www.concretepage.com/spring-4/spring-4-mvc-security-custom-login-form-and-logout-example-with-csrf-protection-using-annotation-and-xml-configuration\n\n### Q :  Why is request method POST recommended compared to GET for sensitive data?\n\nFollowing are the steps that happen when you interact with a web page\n- Browser : You enter the details\n- Browser : Creates a POST request where details are put into the request (and encrypted if you are using https)\n- Routers and Network : The POST request is sent through multiple routers before it reaches the destination\n\nIn the case of a get request and post request, in steps a and b you can see the details on the browser. The real change is in step c. \n\n> Important Question to ask is \"What is going across the network?\"\n\nIn the case of GET request, your details are part of url and all routers can see those details. However, in the case of POST, the details are sent as part of the body of the request and hence more safe.\n\n### Q :  We use ${todo.done} in JSP even though the name of the field in Todo.java is isDone. Shouldn't we be using ${todo.isDone}?\n\nIsn't it tricky? Welcome to the fun of Java Beans. \n\nYou can try renaming the variable to done or what ever you want. The important thing is what is the name of getters and setters.\n\nJava Beans work based on the names of your getters and setters. The setter is named setDone. So, we use ${todo.done}.\n\nI would recommend playing with getters and setters to understand this further.\n\n```\npublic boolean isDone() {\n    return isDone;\n}\n\npublic void setDone(boolean isDone) {\n    this.isDone = isDone;\n}\n```\n\n### Q :  Can I have multiple parameters with the same name in a request?\n\nLet's take an example\n\nhttp://localhost:8080/login?name=Ranga&name=Ravi&name=Sathish\n\nYou can accept all values using an array in the controller method.\n\nHere's a snippet!\n\n```\npublic String method(@RequestParam(value=\"name\") String[] names){\n \n    //if length of names is not 1, throw an error!\n \n    //Continue processing.\n \n}\n```\n\n### Q :  What is the benefit of using view resolver? Will it not take more time to process a request?\n\nIt all boils down to good design!\n\nDo one thing very well. \n\nView Resolver maps a logical view name to a physical view (JSP).\n\nAs far as Java is concerned, more method calls does not mean bad performance.\n\n### Q :  What is the difference between put and patch request methods?\n- PUT : When you update the entire resource - when you want to update all/most of the fields of a resource.\n- PATCH: When you want to update specific details of the resource. All other details remain unchanged. \n\n\n## Java and Spring Interview Guides\n\n[![Image](https://www.springboottutorial.com/images/Course-Spring-Framework-Interview-Guide-200-Questions-Answers.png \"Spring Framework Interview Guide - 200+ Questions & Answers\")](https://links.in28minutes.com/in28minutes-spring-interview)\n\n[![Image](https://www.springboottutorial.com/images/Course-Java-Interview-Guide-200-Interview-Questions-and-Answers.png \"Java Interview Guide : 200+ Interview Questions and Answers\")](https://links.in28minutes.com/in28minutes-java-interview)\n"
  },
  {
    "path": "_blog/articles/2017-12-25-spring-boot-rest-service-with-jpa-top20.md",
    "content": "---\nlayout:     post\ntitle:      Creating a CRUD REST API/Service with Spring Boot, JPA, and Hibernate\ndate:       2022-08-19 12:31:19\nsummary:    The first step in developing RESTful Services is to create a complete CRUD API with GET, POST, PUT, and DELETE methods.In this tutorial, let's learn to create an awesome CRUD REST API with Spring Boot, Spring MVC, JPA, and Hibernate.\ncategories:  SpringBoot\npermalink:  /spring-boot-crud-rest-service-with-jpa-hibernate\nimage: /images/spring-boot-application.png\n---\n\n![Image](/images/Spring-Initializr-Web-JPA.png \"Web, JPA, Hibernate and Developer Tools\")\n\nThis guide will help you create a CRUD REST API/Service with Spring Boot, JPA, and Hibernate. We will create a JPA Repository for a Student Entity and expose it using a Student Resource.\n \n![Image](/images/H2-Console-With-Student.png \"H2 Console With Student\")\n\n## You will learn\n- What is a RESTful Service?\n- Basics of designing a REST API.\n- How to create a RESTful service offering all CRUD operations?\n- How to use Spring Boot, Spring MVC, JPA, and Hibernate to create a RESTful API?\n- How to execute different kinds of REST API with Postman?\n- What are the differences between GET, POST, PUT, and DELETE request methods?\n\n## Resources Overview\n\nIn this guide, we will create a student resource exposing three services using proper URIs and HTTP methods:\n- Retrieve all students: `@GetMapping(\"/students\")`\n- Get details of a specific student: `@GetMapping(\"/students/{id}\")`\n- Delete a student: `@DeleteMapping(\"/students/{id}\")`\n- Create a new student: `@PostMapping(\"/students\")`\n- Update student details with `@PutMapping(\"/students/{id}\")`\n\n## Project Code Structure\n\nThe following screenshot shows the structure of the project we will create.\n\n![Image](/images/CRUDServiceWithHibernate.png \"CRUDServiceWithHibernate\") \n\nA few details\n- `SpringBoot2RestServiceApplication.java` - The Spring Boot Application class that Spring Initializer generates.This class acts as the launching point for applications.\n- `pom.xml`-Contains all the dependencies needed to build this project. We will use Spring Boot Starter AOP.\n- `Student.java` - Student JPA Entity\n- `StudentRepository.java`-Student JPA Repository This was created using Spring Data JpaRepository.\n- `StudentResource.java`-Spring Rest Controller exposing all services on the student resource.\n- `data.sql`: initial data for the student table. Spring Boot would execute this script after the tables are created from the entities.\n\n## You will require the following tools:\n- Maven 3.0+ is your build tool\n- Your favorite IDE. We use Eclipse.\n- JDK 17\n\n## A Complete Maven Project With Code Examples\n> Our Github repository has all the code examples - https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-2-rest-service-basic\n\n## Types of Web Services\n\nNot exactly types, but rather a broad classification\n- SOAP\n- REST\n\nThese are not really mutually exclusive. Some SOAP services can actually be RESTful. \n\n### REST\n\nFirst of all, REST does not define a standard message exchange format. You can build REST services with both XML and JSON. However, JSON is a more popular format than REST.\n\nSo, if it does not define a standard message exchange format, what is REST then?\n\n> REST is a style of software architecture for distributed hypermedia systems.\n\nREST stands for REpresentational State Transfer. The definitions of REST can be vague. So let's understand the important concepts.\n\nA key abstraction in REST is a resource. There is no restriction on what can be a resource. A todo is a resource. A person on Facebook is a resource.\n\nA resource has a URI (Uniform Resource Identifier):\n- /user/Ranga/todos/1\n- /person/Ranga\n\nA resource will have representation.\n- XML\n- HTML\n- JSON\n\nA resource will have a state. The representation of a resource should capture its current state.\n\nWhen a resource is requested, we provide a representation of the resource. \n\n### REST and HTTP\n\nREST is built on top of HTTP (Hypertext Transfer Protocol). HTTP is the language of the web. \n\nHTTP has a few important verbs.\n- POST: Create a new resource\n- GET: Read an article\n- PUT: Update an existing resource\n- DELETE: Delete a resource\n\nHTTP also defines standard response codes.\n- 200 - SUCCESS\n- 404 - RESOURCE NOT FOUND\n- 400 - BAD REQUEST\n- 201 - CREATED\n- 401 - UNAUTHORIZED\n- 415 - UNSUPPORTED TYPE - Representation not supported for the resource\n- 500 - SERVER ERROR\n\nRestful Service Constraints\n- Client-Server: There should be a service producer and a service consumer.\n- The interface (URL) is uniform and exposes resources. The interface uses nouns (not actions).\n- The service is stateless. Even if the service is called 10 times, the result must be the same.\n- The service response should be cacheable. HTTP cache, for example.\n- Services should assume a layered architecture. The client should not assume direct connection to the server-it might be getting info from a middle layer-cache.\n\n### Creating RESTful APIs\n\nFollowing are the important things to consider when designing RESTful API's:\n- While designing any API, the most important thing is to think about the api consumer, i.e., the client who is going to use the service. What are his needs? Does the service make sense to him? Does the request and response format make sense to him?\n- For the rest, we think nouns (resources) and not verbs (not actions). So, URIs should represent resources. URIs should be hierarchical and as self-descriptive as possible. Prefer plurals.\n- Always use HTTP methods. \n  - GET : You should not update anything. should be idempotent (results the same in multiple calls). 200 (OK) + 404 (NOT FOUND) +400 (BAD REQUEST) are possible return codes.\n  - POST : Should create new resource. Ideally, return JSON with a link to the newly created resource. same return codes as possible. In addition, return code 201 (CREATED) is possible.\n  - PUT : Update an existing resource. update client details. Possible Return Codes : 200(OK)\n  - DELETE : Used to delete a resource.\n\n## When do you use JPA? \n\n- SQL Database\n- Static Domain Model \n- Mostly CRUD \n- Mostly simple queries/mappings\n\n## Bootstrapping with Spring Initializr\n\nCreating a REST service with Spring Initializr is a cake walk. We will use Spring Web MVC as our web framework.  \n\nSpring Initializr [http://start.spring.io/](http://start.spring.io/){:target=\"_blank\"} is great tool to bootstrap your Spring Boot projects.\n\n![Image](/images/Spring-Initializr-Web.png \"Web, Actuator and Developer Tools\")   \n\n![Image](/images/Spring-Initializr-Web-JPA.png \"Web, JPA, Hibernate and Developer Tools\")\n\nAs shown in the image above, following steps have to be done\n\n- Launch Spring Initializr and choose the following\n  - Choose `com.in28minutes.springboot.rest.example` as Group\n  - Choose `spring-boot-2-rest-service-basic` as Artifact\n  - Choose following dependencies\n    - Web\n    - JPA\n    - H2\n    - DevTools\n- Click Generate.\n- Import the project into Eclipse. File > Import > Existing Maven Project\n\n> Do not forget to add JPA and H2 as dependencies.\n\n\n### Make Your Very First JPA Entity \n\nThe first step is to create a JPA Entity. Let's create a simple student entity with a primary key id.\n\n```java\n@Entity\npublic class Student {\n\n\t@Id\n\t@GeneratedValue\n\tprivate Long id;\n\n\tprivate String name;\n\n\tprivate String passportNumber;\n```\nImportant things to note:\n - ```@Entity```: Specifies that the class is an entity. This annotation is applied to the entity class.\n - ```@Id```: Specifies the primary key of an entity.\n - ```@GeneratedValue```: It provides for the specification of generation strategies for the values of primary keys.\n - ```public Student()```: JPA-friendly default function Object() { [native code] } \n\nWhen the application reloads, you can launch the H2 console at http://localhost:8080/h2-console.\n\nYou will see that a new table called 'student' is created in H2 Console.\n\nHow did the Student table get created?\n\n> Spring Boot Auto Configuration detects that we are using an in-memory database H2. It autoconfigures the property to create the database tables based on the entities.\n\nLet's now populate some data into the student table.\n\n/src/main/resources/data.sql\n\n```\ninsert into student values(10001,'Ranga', 'E1234567');\n\ninsert into student values(10002,'Ravi', 'A1234568');\n```\n\nWhen the application reloads, you will see the following statements in the log, indicating that the sql files are picked up.\n\n```\nExecuting SQL script from URL [file:/in28Minutes/git/spring-boot-examples/spring-boot-2-jdbc-with-h2/target/classes/data.sql]\n```\n\nAfter app reload, when you login to H2 Console (http://localhost:8080/h2-console), you can see that the student table is created and the data is populated.\n\n![Image](/images/H2-Console-With-Student.png \"H2 Console With Student\")\n\n\n## Make a JPA Repository class that reads students from a database.\n\n/src/main/java/com/in28minutes/springboot/jpa/hibernate/h2/example/student/StudentRepository.java\n\nWe created a simple interface for StudentRepository, extending JpaRepository.\n\n```java\n@Repository\npublic interface StudentRepository extends JpaRepository<Student, Long>{\n```\nNotes\n- We will talk about all the methods in the JpaRepository a little later.\n- `public interface StudentRepository extends JpaRepository<Student, Long>` - We are extending JpaRepository using two generics—Student and Long. Student is the entity that is being managed and the primary key of Student is Long.\n\n### JpaRepository\nJpaRepository (defined in Spring Data JPA) is the JPA-specific repository interface.\n\n```java\npublic interface JpaRepository<T, ID extends Serializable>\n\t\textends PagingAndSortingRepository<T, ID>, QueryByExampleExecutor<T> {\n```\n> `JpaRepository` extends `PagingAndSortingRepository`, which in turn extends the `CrudRepository` interface. So, JpaRepository inherits all the methods from the two interfaces shown below.\n\nPagingAndSortingRepository\n```java\npublic abstract interface PagingAndSortingRepository extends CrudRepository {\n  \n  public abstract Iterable findAll(Sort arg0);\n  \n  public abstract Page findAll(Pageable arg0);\n\n}\n```\n\nCrudRepository\n```java\npublic interface CrudRepository<T, ID extends Serializable>\n    extends Repository<T, ID> {\n\n    <S extends T> S save(S entity);\n\n    T findOne(ID primaryKey);       \n\n    Iterable<T> findAll();          \n\n    Long count();                   \n\n    void delete(T entity);          \n\n    boolean exists(ID primaryKey);  \n\n    // … more functionality omitted.\n}\n```\n\n\n## Exposing resources using StudentResource\n\nLet's start with setting up the StudentResource class and then move into creating methods to handle different kinds of request methods to the Student Resource.\n\n### Setting up Student Resource\n\n```\n@RestController\npublic class StudentResource {\n\n\t@Autowired\n\tprivate StudentRepository studentRepository;\n```\n\nNotes\n- `@RestController` : Combination of @Controller and @ResponseBody. Beans returned are converted to and from JSON or XML.\n- `@Autowired private StudentRepository studentRepository` : Autowire the StudentRepository so that we can retrieve and save data to the database.\n\n### Getting Access to Resources for Students\n\nLet's create the method to expose the details of all students.\n```\n@GetMapping(\"/students\")\npublic List<Student> retrieveAllStudents() {\n\treturn studentRepository.findAll();\n}\n```\n\nThe below picture shows how we can execute a Get Request Method on a resource using Postman, my favourite tool to run rest services.\n\n![Image](/images/POSTMAN_Executing_Get_Request.png \"Executing Get Rest Service From Postman\")   \n\n- URL - http://localhost:8080/students\n- Request Method - GET\n\nResponse\n```json\n[\n  {\n    \"id\": 10001,\n    \"name\": \"Ranga\",\n    \"passportNumber\": \"E1234567\"\n  },\n  {\n    \"id\": 10002,\n    \"name\": \"Ravi\",\n    \"passportNumber\": \"A1234568\"\n  }\n]\n\n```\n\nLet's create a method to expose the details of a specific student.\n\n```\n@GetMapping(\"/students/{id}\")\npublic Student retrieveStudent(@PathVariable long id) {\n\tOptional<Student> student = studentRepository.findById(id);\n\n\tif (student.isEmpty())\n\t\tthrow new StudentNotFoundException(\"id-\" + id);\n\n\treturn student.get();\n}\n```\n\nLet's execute another GET request\n![Image](/images/POSTMAN_Executing_Get_Request.png \"Executing Get Rest Service From Postman\")   \n\n- URL - http://localhost:8080/students/10002\n- Request Method - GET\n\nResponse\n```json\n{\n  \"id\": 10002,\n  \"name\": \"Ravi\",\n  \"passportNumber\": \"A1234568\"\n}\n```\n\n### Showcase the DELETE Method on Student Resources\n\nThe delete method is simple. All you have to do is to call `studentRepository.deleteById(id)`.\n\n```\n@DeleteMapping(\"/students/{id}\")\npublic void deleteStudent(@PathVariable long id) {\n\tstudentRepository.deleteById(id);\n}\n```\n\nThe below picture shows how we can execute a DELETE Request method on a resource from Postman, my favourite tool to run rest services.\n\n![Image](/images/POSTMAN_Executing_Delete_Request.png \"Executing Delete Operation Rest Service From Postman\")   \n\n- URL - http://localhost:8080/students/10002\n- Request Method - DELETE\n\nRequest - Empty Body\nResponse with status 200 - Successful\n\n### Expose the POST method to create a new student\n\nThe POST method is simple. All you have to do is to call `studentRepository.save(student)`. Note that we are using `@RequestBody` to map the student details from request to bean. We are also returning a ResponseEntity with a header containing the URL of the created resource.\n\n```\n@PostMapping(\"/students\")\npublic ResponseEntity<Object> createStudent(@RequestBody Student student) {\n\tStudent savedStudent = studentRepository.save(student);\n\n\tURI location = ServletUriComponentsBuilder.fromCurrentRequest().path(\"/{id}\")\n\t\t\t.buildAndExpand(savedStudent.getId()).toUri();\n\n\treturn ResponseEntity.created(location).build();\n\n}\n```\n\nThe below picture shows how we can execute a POST Request method on a resource from Postman, my favourite tool to run rest services.\n\n![Image](/images/POSTMAN_Executing_Post_Request.png \"Executing Post Rest Service From Postman\")   \n\n- URL - http://localhost:8080/students\n- Request Method - POST\n\nRequest\n```json\n  {\n    \"name\": \"Tom\",\n    \"passportNumber\": \"Z1234567\"\n  }\n```\n\nResponse \n- Status 201 - CREATED\n- Header Location →http://localhost:8080/students/2\n\n### To update existing students, use the PUT Method.\n\nBefore updating the student, we check if the student exists. If the student does not exist, we return a not found statur. Otherwise, we save the student details using `studentRepository.save` method.\n\n```\n@PutMapping(\"/students/{id}\")\npublic ResponseEntity<Object> updateStudent(@RequestBody Student student, @PathVariable long id) {\n\n\tOptional<Student> studentOptional = studentRepository.findById(id);\n\n\tif (studentOptional.isEmpty())\n\t\treturn ResponseEntity.notFound().build();\n\n\tstudent.setId(id);\n\t\n\tstudentRepository.save(student);\n\n\treturn ResponseEntity.noContent().build();\n}\n```\n\nThe below picture shows how we can execute a PUT Request method on a resource from Postman, my favourite tool to run rest services.\n\n![Image](/images/POSTMAN_Executing_Put_Request.png \"Executing PUT Operation Rest Service From Postman\")   \n\n- URL → http://localhost:8080/students/10002\n- Request \n    - Method → PUT\n\nRequest\n```json\n{\n\t\"name\": \"Tom\",\n\t\"passportNumber\": \"Z1234567\"\n}\n```\n\nResponse with status 200 - Successful\n\n\n> Remember that you can check the updates in the database using H2 Console `http://localhost:8080/h2-console` after each of the requests.\n\n\n## Example of Complete Code\n\nGithub repository has all the code examples - https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-2-rest-service-basic"
  },
  {
    "path": "_blog/articles/2017-12-26-spring-boot-exception-handling-for-rest-services-top20.md",
    "content": "---\nlayout:     post\ntitle:      Spring Boot Exception Handling for RESTful Services Errors\ndate:       2022-07-03 12:31:19\nsummary:    Great REST APIs have Great Exception Handling. You don't want to leave your API consumer hanging not knowing what to do when an error occurs. Let's learn how to implement effective exception handling for a REST API/Service with Spring Boot. You will understand and implement HTTP Error Response statuses based on the type of error.\ncategories:  SpringBoot\npermalink:  /spring-boot-exception-handling-for-rest-services\nimage: /images/spring-boot-feature.png\n---\n\nThis guide will help you implement effective exception/error handling for a REST API/Service with Spring Boot.\n\n![Image](/images/SpringBootExceptionHandling-ProjectStructure.png \"CRUDServiceWithHibernate\") \n\n \n## You will learn\n- What is exception handling?\n- Why do you need exception handling?\n- What are the default exception handling capabilities provided by Spring Boot?\n- How to implement exception handling with Spring Boot for RESTful Services?\n- What are different return statuses you can use based on the API?\n- How/What to think when you design error handling for REST API?\n\n\n\n## Project Code Structure\n\nFollowing screen shot shows the structure of the project we will create.\n\n![Image](/images/SpringBootExceptionHandling-ProjectStructure.png \"CRUDServiceWithHibernate\") \n\nA few details:\n- `SpringBoot2RestServiceApplication.java` - The Spring Boot Application class generated with Spring Initializer. This class acts as the launching point for application.\n- `pom.xml` - Contains all the dependencies needed to build this project. We will use Spring Boot Starter AOP.\n- `Student.java` - Student JPA Entity\n- `StudentRepository.java` - Student JPA Repository. This is created using Spring Data JpaRepository.\n- `StudentResource.java` - Spring Rest Controller exposing all services on the student resource.\n- `CustomizedResponseEntityExceptionHandler.java` - Component to implement global exception handling and customize the response based on the exception type.\n- `ErrorDetails.java` - Response Bean to use when exceptions are thrown from API.\n- `StudentNotFoundException.java` - Exception thrown from resources when student is not found.\n- `data.sql` - Initial data for the student table. Spring Boot would execute this script after the tables are created from the entities.\n\n## Tools you will need\n- Maven 3.0+ is your build tool\n- Your favorite IDE. We use Eclipse.\n- JDK 1.8+\n\n## Complete Maven Project With Code Examples\n> Our Github repository has all the code examples - https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-2-rest-service-exception-handling\n\n## What is Exception Handling?\n\nConsider these\n- What do you do when something goes wrong in your RESTful API?\n- What do you do when you get an invalid request?\n- What do you do when you something unexpected happens?\n\nThink. What should you do?\n\nCan I just return a Page Not Found - 404? Can I return a generic message `Something went wrong.`. Is that good enough?\n\nOne of the core design principles for RESTful services is \n> Think about the consumer\n\nSo, what should you when an error or exception happens in a RESTful service?\n\nYou should return a proper error response \n- Clear message indicating what went wrong and what the consumer can do to fix the error.\n- Include information necessary to solve the error.\n- Proper Response Status based on the context.\n- Do not include sensitive information in the response.\n\n### Response Statuses for Errors\n\nUse appropriate status code based on the error.\n- 404 - RESOURCE NOT FOUND\n- 400 - BAD REQUEST\n- 401 - UNAUTHORIZED\n- 415 - UNSUPPORTED TYPE - Representation not supported for the resource\n- 500 - SERVER ERROR\n\nLet's consider a few HTTP Methods:\n- GET : Should not update anything. Should be idempotent (same result in multiple calls). Possible Return Codes 200 (OK) + 404 (NOT FOUND) +400 (BAD REQUEST)\n- POST : Should create new resource. Ideally return JSON with link to newly created resource. Same return codes as get possible. In addition - Return code 201 (CREATED) can be used.\n- PUT : Update a known resource. ex: update client details. Possible Return Codes : 200(OK) + 404 (NOT FOUND) +400 (BAD REQUEST)\n- DELETE : Used to delete a resource. Possible Return Codes : 200(OK).\n\n> 500 - SERVER ERROR is possible with all the above HTTP methods. In the case of a 500, include the contact details of the help desk in the response.\n\n\n## Bootstrapping a Project with REST Resouce\n\nIn the previous article in the series - http://www.springboottutorial.com/spring-boot-crud-rest-service-with-jpa-hibernate, we set up a simple restful service with a resource exposing CRUD methods. \n\n> We will use the same example to discuss about Exception Handling.\n\n## Default Exception Handling with Spring Boot\n\nSpring Boot provides good default implementation for exception handling for RESTful Services. Let's quickly look at the default Exception Handling features provided by Spring Boot.\n\n\n### Resource Not Present\n\nHeres what happens when you fire a request to a non existent resource `http://localhost:8080/some-dummy-url`\n\n```json\n{\n  \"timestamp\": 1512713804164,\n  \"status\": 404,\n  \"error\": \"Not Found\",\n  \"message\": \"No message available\",\n  \"path\": \"/some-dummy-url\"\n}\n```\n\nThats a cool error response. It contains all the details that are typically needed.\n\n\n### What happens when you throw an Exception?\n\nLet's see what Spring Boot does when an exception is thrown from a Resource.\n\nLets create a `StudentNotFoundException`.\n\n/src/main/java/com/in28minutes/springboot/rest/example/student/StudentNotFoundException.java\n\n```java\npublic class StudentNotFoundException extends RuntimeException {\n\n  public StudentNotFoundException(String exception) {\n    super(exception);\n  }\n\n}\n```\n\nLet's enhance the GET method to throw this exception when a student is not found.\n\n```\n  @GetMapping(\"/students/{id}\")\n  public Resource<Student> retrieveStudent(@PathVariable long id) {\n    Optional<Student> student = studentRepository.findById(id);\n\n    if (!student.isPresent())\n      throw new StudentNotFoundException(\"id-\" + id);\n\n    Resource<Student> resource = new Resource<Student>(student.get());\n\n    ControllerLinkBuilder linkTo = linkTo(methodOn(this.getClass()).retrieveAllStudents());\n\n    resource.add(linkTo.withRel(\"all-students\"));\n\n    return resource;\n  }\n```\n\nThis is the response when you try getting details of a non existing student `http://localhost:8080/students/9`.\n\n```\n{\n  \"timestamp\": 1512714275589,\n  \"status\": 500,\n  \"error\": \"Internal Server Error\",\n  \"message\": \"id-9\",\n  \"path\": \"/students/9\"\n}\n```\n\nOne thing I do not like is the status code of the response. It is 500 - Server Error. Actually, the error is with the request. So, I would rather return a 404 - Resource not found. \n\nLet's see how to customize this and more in the next section.\n\n## Customizing Exception Handling with Spring Boot\n\nA combination of Spring and Spring Boot provide multiple options to customize responses for errors. \n\n### Customizing Return Status for a Specific Exception\n\nYou can specify the Response Status for a specific exception along with the definition of the Exception with '@ResponseStatus' annotation.\n\n```\n@ResponseStatus(HttpStatus.NOT_FOUND)\npublic class StudentNotFoundException extends RuntimeException {\n```\n\nThis is the response when you try getting details of a non existing student `http://localhost:8080/students/9`.\n\n```\n{\n  \"timestamp\": 1512714594153,\n  \"status\": 404,\n  \"error\": \"Not Found\",\n  \"message\": \"id-9\",\n  \"path\": \"/students/9\"\n}\n```\n\n### Customizing Error Response Structure\n\nDefault error response provided by Spring Boot contains all the details that are typically needed.\n\nHowever, you might want to create a framework independent response structure for your organization. In that case, you can define a specific error response structure. \n\nLet's define a simple error response bean.\n\n```\npublic class ErrorDetails {\n  private Date timestamp;\n  private String message;\n  private String details;\n\n  public ErrorDetails(Date timestamp, String message, String details) {\n    super();\n    this.timestamp = timestamp;\n    this.message = message;\n    this.details = details;\n  }\n```\n\nTo use `ErrorDetails` to return the error response, let's define a ControllerAdvice as shown below.\n\n```\n@ControllerAdvice\n@RestController\npublic class CustomizedResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {\n\n  @ExceptionHandler(StudentNotFoundException.class)\n  public final ResponseEntity<ErrorDetails> handleUserNotFoundException(StudentNotFoundException ex, WebRequest request) {\n    ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(),\n        request.getDescription(false));\n    return new ResponseEntity<>(errorDetails, HttpStatus.NOT_FOUND);\n  }\n```\n\nNotes\n- `@ExceptionHandler(StudentNotFoundException.class)` indicates that this method would handle exceptions of the specific type.\n- `new ResponseEntity<>(errorDetails, HttpStatus.NOT_FOUND)` - Create an error response object and return it with a specific Http Status.\n\nThis is the response when you try getting details of a non existing student `http://localhost:8080/students/9`.\n\n```\n{\n  \"timestamp\": 1512714887537,\n  \"message\": \"id-9\",\n  \"details\": \"uri=/students/9\"\n}\n```\n\nResponse uses the custom error structure that we had defined earlier.\n\n### Using Error Response Structure for all Exceptions\n\nYou can further enhance `CustomizedResponseEntityExceptionHandler` to handle all other exceptions.\n\n```\n@ExceptionHandler(Exception.class)\npublic final ResponseEntity<ErrorDetails> handleAllExceptions(Exception ex, WebRequest request) {\n  ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(),\n      request.getDescription(false));\n  return new ResponseEntity<>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR);\n}\n\n```\n\n\n## Complete Code Example\n\nOur Github repository has all the code examples - https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-2-rest-service-exception-handling"
  },
  {
    "path": "_blog/articles/2017-12-27-spring-boot-validation-for-rest-services-top20.md",
    "content": "---\nlayout:     post\ntitle:      Implementing Validation for RESTful Services with Spring Boot\ndate:       2022-07-03 12:31:19\nsummary:    Validating a request is a critical component of a Great REST API. In this tutorial, Let's explore how to do implement effective validation for a RESTful Service with Spring Boot. We will use Bean Validation API and Hibernate Validator as the implementation.\ncategories:  SpringBoot\npermalink:  /spring-boot-validation-for-rest-services\nimage: /images/spring-boot-feature.png\n---\n\n![Image](/images/Spring-Initializr-Web-JPA.png \"Web, JPA, Hibernate and Developer Tools\")\n\nThis guide will help you implement effective validations for a REST API/Service with Spring Boot.\n \n## You will learn\n- What is validation?\n- Why do you need validation?\n- What is Hibernate Validator?\n- What is Bean Validation API?\n- What are the default validation capabilities provided by Spring Boot?\n- How to implement validation with Spring Boot?\n- How to implement validation with Bean Validation API?\n\n\n\n## Project Code Structure\n\nFollowing files contain the important components of the project we will create. A few details:\n- `SpringBoot2RestServiceApplication.java` - The Spring Boot Application class generated with Spring Initializer. This class acts as the launching point for application.\n- `pom.xml` - Contains all the dependencies needed to build this project. We will use Spring Boot Starter AOP.\n- `Student.java` - Student JPA Entity\n- `StudentRepository.java` - Student JPA Repository. This is created using Spring Data JpaRepository.\n- `StudentResource.java` - Spring Rest Controller exposing all services on the student resource.\n- `CustomizedResponseEntityExceptionHandler.java` - Component to implement global exception handling and customize the response based on the exception type.\n- `ErrorDetails.java` - Response Bean to use when exceptions are thrown from API.\n- `StudentNotFoundException.java` - Exception thrown from resources when student is not found.\n- `data.sql` - Initial data for the student table. Spring Boot would execute this script after the tables are created from the entities.\n\n## Tools you will need\n- Maven 3.0+ is your build tool\n- Your favorite IDE. We use Eclipse.\n- JDK 1.8+\n\n## Complete Maven Project With Code Examples\n> Our Github repository has all the code examples - https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-2-rest-service-validation\n\n## What is Validation?\n\nYou expect a certain format of request for your RESTful Service. You except the elements of your request to have certain data types, certain domain constraints.\n\nWhat if you get a request not meeting this constraints?\n\nThink. What should you do?\n\nCan I just return a generic message `Something went wrong.`. Is that good enough?\n\nOne of the core design principles for RESTful services is \n> Think about the consumer\n\nSo, what should you do when something in the request is not valid. \n\nYou should return a proper error response \n- Clear message indicating what went wrong? Which field has an error and what are the accepted values? What the consumer can do to fix the error?\n- Proper Response Status Bad Request.\n- Do not include sensitive information in the response.\n\n### Response Statuses for Validation Errors\n\nRecommended response status for validation error is -> 400 - BAD REQUEST\n\n## Bootstrapping a Project with REST Resouce\n\nIn the previous article in the series - http://www.springboottutorial.com/spring-boot-crud-rest-service-with-jpa-hibernate, we set up a simple restful service with a resource exposing CRUD methods. \n\n> We will use the same example to discuss about Exception Handling.\n\n## Default Validation with Spring Boot\n\nSpring Boot provides good default implementation for validation for RESTful Services. Let's quickly look at the default Exception Handling features provided by Spring Boot.\n\n### Wrong Content Type\nIf you use Content-Type as `application/xml` and this is not supported by your application, Spring Boot by default returns a response status of 415 - Unsupported Media Type\n\n### Invalid JSON Content\nIf you send a invalid JSON content to a method expecting a body, you would get a 400 - Bad Request\n\n### Valid JSON with Missing Elements\nHowever, if you send a valid JSON structure with missing/invalid attributes/elements, application will execute the request with what ever data is available.\n\nFollowing request executes with a status of -> 201 Created\n\nPOST `http://localhost:8080/students`\n\nEmpty Request Content\n```\n{\n  \n}\n```\n\nFollowing request executes with a status of -> 201 Created\n\nPOST `http://localhost:8080/students`\n\nRequest Content\n```\n{\n    \"name1\": null,\n    \"passportNumber\": \"A12345678\"\n}\n```\nYou can notice that the above request has an invalid attribute name1.\n\nThis is the response when you fire a GET to `http://localhost:8080/students`\n\n[\n  {\n    \"id\": 1,\n    \"name\": null,\n    \"passportNumber\": null\n  },\n  {\n    \"id\": 2,\n    \"name\": null,\n    \"passportNumber\": \"A12345678\"\n  },\n  {\n    \"id\": 10001,\n    \"name\": \"Ranga\",\n    \"passportNumber\": \"E1234567\"\n  },\n  {\n    \"id\": 10002,\n    \"name\": \"Ravi\",\n    \"passportNumber\": \"A1234568\"\n  }\n]\n\nYou can see that both the resources were created with ids 1 and 2 with nulls for values that were not available. Invalid elements/attributes are ignored.\n\n## Customizing Validations\n\nTo customize the validation, we will use Hibernate Validator, which is one of the implementations of the bean validation api.\n\nWe get Hibernate Validator for free when we use Spring Boot Starter Web.\n\nSo, we can get started with implementing the validations.\n\n### Implementing Validations on the Bean\n\nBefore we add validations, we need to add a dependency.\n\n```\n<dependency>\n      <groupId>org.springframework.boot</groupId>\n      <artifactId>spring-boot-starter-validation</artifactId>\n</dependency>\n```\n\nLet's add a few validations to the Student bean. We are using `@Size` to specify the minimum length and also a message when a validation error occurs.\n\n```\n@Entity\npublic class Student {\n  @Id\n  @GeneratedValue\n  private Long id;\n  \n  @NotNull\n  @Size(min=2, message=\"Name should have atleast 2 characters\")\n  private String name;\n  \n  @NotNull\n  @Size(min=7, message=\"Passport should have atleast 2 characters\")\n  private String passportNumber;\n  \n\n```\n\nBean Validation API provides a number of such annotations. Most of these are self explanatory.\n- DecimalMax\n- DecimalMin\n- Digits\n- Email\n- Future\n- FutureOrPresent\n- Max\n- Min\n- Negative\n- NegativeOrZero\n- NotBlank\n- NotEmpty\n- NotNull\n- Null\n- Past\n- PastOrPresent\n- Pattern\n- Positive\n- PositiveOrZero\n\n### Enabling Validation on the Resource\n\nSimple. Add @Valid in addition to @RequestBody.\n\n```\npublic ResponseEntity<Object> createStudent(@Valid @RequestBody Student student) {\n```\n\nThat's it.\n\nWhen you execute a request with attributes not matching the constraint, you get a 404 BAD Request status back.\n\nRequest\n```\n{\n    \"name\": \"\",\n    \"passportNumber\": \"A12345678\"\n  }\n```\n\nBut the problem is that there are no details returned indicating what went wrong.\n- The consumer knows its a bad request.\n- But, how do they no what is wrong? Which element did not pass the validation? What should the consumer do to fix it?\n\n### Customizing Validation Response\n\n\nLet's define a simple error response bean.\n\n```\npublic class ErrorDetails {\n  private Date timestamp;\n  private String message;\n  private String details;\n\n  public ErrorDetails(Date timestamp, String message, String details) {\n    super();\n    this.timestamp = timestamp;\n    this.message = message;\n    this.details = details;\n  }\n```\n\nLet's now define a `@ControllerAdvice` to handle validation errors. We do that by overriding `handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request)` method in the `ResponseEntityExceptionHandler`.\n\n```\n@ControllerAdvice\n@RestController\npublic class CustomizedResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {\n\n  @Override\n  protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,\n      HttpHeaders headers, HttpStatus status, WebRequest request) {\n    ErrorDetails errorDetails = new ErrorDetails(new Date(), \"Validation Failed\",\n        ex.getBindingResult().toString());\n    return new ResponseEntity(errorDetails, HttpStatus.BAD_REQUEST);\n  } \n```\n\nTo use `ErrorDetails` to return the error response, let's define a ControllerAdvice as shown below.\n\n```\n@ControllerAdvice\n@RestController\npublic class CustomizedResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {\n\n  @ExceptionHandler(StudentNotFoundException)\n  public final ResponseEntity<ErrorDetails> handleUserNotFoundException(StudentNotFoundException ex, WebRequest request) {\n    ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(),\n        request.getDescription(false));\n    return new ResponseEntity<>(errorDetails, HttpStatus.NOT_FOUND);\n  }\n```\n\nWhen you execute a request with attributes not matching the constraint, you get a 404 BAD Request status back.\n\nRequest\n```\n{\n    \"name\": \"\",\n    \"passportNumber\": \"A12345678\"\n  }\n```\n\nYou also get a Response Body indicating what is wrong!\n\n```\n{\n  \"timestamp\": 1512717715118,\n  \"message\": \"Validation Failed\",\n  \"details\": \"org.springframework.validation.BeanPropertyBindingResult: 1 errors\\nField error in object 'student' on field 'name': rejected value []; codes [Size.student.name,Size.name,Size.java.lang.String,Size]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [student.name,name]; arguments []; default message [name],2147483647,2]; default message [Name should have atleast 2 characters]\"\n}\n```\n\nGood Luck! You are all set now to customize the message based on your needs.\n\n\n## Complete Code Example\n\nGithub repository has all the code examples - https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-2-rest-service-validation"
  },
  {
    "path": "_blog/articles/2017-12-28-spring-boot-HATEOAS-for-rest-services.md",
    "content": "---\nlayout:     post\ntitle:      Spring Boot - HATEOAS for RESTful Services\ndate:       2023-04-10 12:31:19\nsummary:    \"Hypermedia as the engine of application state\" is abbreviated as HATEOAS. It's a lengthy acronym. In this tutorial, we will decode HATEOAS and show you how to implement it for a REST API/Service using Spring Boot.\ncategories:  SpringBoot\npermalink:  /spring-boot-hateoas-for-rest-services\nimage: /images/spring-boot-feature.png\n\n---\n\n![Image](/images/CRUDServiceWithHibernate.png \"CRUDServiceWithHibernate\") \n\nThis post will walk you through the process of implementing HATEOAS for a REST API/Service using Spring Boot.\n \n## You will learn\n- What is HATEOAS?\n- Why do you need HATEOAS?\n- How do you implement HATEOAS with Spring Boot?\n- What are the HATEOAS best practices?\n\n\n## Project Code Structure\n\nThe screenshot below depicts the framework of the project we will be creating.\n\n![Image](/images/CRUDServiceWithHibernate.png \"CRUDServiceWithHibernate\") \n\nA few details:\n- SpringBoot2RestServiceApplication.java - The Spring Boot Application class generated with Spring Initializer. This class acts as the launching point for application.\n- `pom.xml` - Contains all the dependencies needed to build this project. We will use Spring Boot Starter AOP.\n- `Student.java` - Student JPA Entity\n- StudentRepository.java - Student JPA Repository. This is created using Spring Data JpaRepository.\n- StudentResource.java - Spring Rest Controller exposing all services on the student resource.\n- data.sql - Initial data for the student table. Spring Boot would execute this script after the tables are created from the entities.\n\n## Tools you will need\n- Maven 3.0+ is your build tool\n- Your favorite IDE. We use Eclipse or IntelliJ.\n- JDK 17\n\n## Maven Project Completion using Code Examples\n\n> Our Github repository has all the code examples - https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-2-rest-service-with-hateoas\n\n## Richardson Maturity Model \n\nA Restful Web Service's maturity level is defined by the Richardson Maturity Model. The following are the various levels and their features.\n- **Level 0** : Expose SOAP web services in REST style. Expose action based services (http://server/getPosts, http://server/deletePosts, http://server/doThis, http://server/doThat etc) using REST.\n- **Level 1** : Expose Resources with proper URI’s (using nouns). Ex: http://server/accounts, http://server/accounts/10. However, HTTP Methods are not used.\n- **Level 2** : Resources use proper URI's + HTTP Methods. For example, to update an account, you do a PUT to . The create an account, you do a POST to . Uri’s look like posts/1/comments/5 and accounts/1/friends/1.\n- **Level 3** : HATEOAS (Hypermedia as the engine of application state). You will tell not only about the information being requested but also about the next possible actions that the service consumer can do. When requesting information about a facebook user, a REST service can return user details along with information about how to get his recent posts, how to get his recent comments and how to retrieve his friend’s list.\n\n## What is HATEOAS?\n\n> \"Hypermedia as the engine of application state\" is abbreviated as HATEOAS.\n\nIt's a lengthy acronym. Let us decipher it for you.\n\nWhat do you see when you go to a website?\n\nThe information that you are looking for. Is that it? There would also be links and buttons for viewing relevant data.\n\nIf you go to a student page, for example, you will observe \n- Student profile\n- Links to Edit and Delete Student details\n- Links to see details of other students\n- Link to see details of the courses and grades of the student\n\nHATEOAS applies the same ideas to RESTful Web Services.\n\nWhen certain information about a resource is requested, you will supply that information as well as information about related resources and various actions you may do with the resource. A REST service, for example, can return the following information when asked for information on a Facebook user.\n- User details \n- Links to get his recent posts\n- Links to get his recent comments \n- Links to retrieve his friend’s list.\n\n## Using a REST Resource to Launch a Project\n\nIn the previous article in the series - http://www.springboottutorial.com/spring-boot-crud-rest-service-with-jpa-hibernate, we set up a simple restful service with a resource exposing CRUD methods. \n\n> The same example will be used to discuss HATEOAS.\n\n## Implementing HATEOAS with Spring Boot\n\nSpring Boot serves as a starting point for HATEOAS. Include the dependency in the `pom.xml` file.\n```xml\n    <dependency>\n      <groupId>org.springframework.boot</groupId>\n      <artifactId>spring-boot-starter-hateoas</artifactId>\n    </dependency>\n```\n\n### Components in Spring Boot HATEOAS Starter\n\nSome of the most critical dependencies from are listed here. `spring-boot-starter-hateoas`.\n\n```xml\n  <dependency>\n      <groupId>org.springframework.boot</groupId>\n      <artifactId>spring-boot-starter-web</artifactId>\n      <version>3.0.2</version>\n      <scope>compile</scope>\n  </dependency>\n  <dependency>\n      <groupId>org.springframework.hateoas</groupId>\n      <artifactId>spring-hateoas</artifactId>\n      <version>2.0.1</version>\n      <scope>compile</scope>\n  </dependency>\n\n```\n\n'spring-hateoas' is the most crucial dependent.\n\n### Improving the resource's ability to return HATEOAS responses\n\nWe would need to add associated materials in the answer to implement HATEOAS.\n\nInstead of Student we use a return type of `EntityModel<Student>`. \n\n> EntityModel is a basic class that wraps a domain object and allows you to add connections to it.\n\n```java\n@GetMapping(\"/students/{id}\")\npublic EntityModel<Student> retrieveStudent(@PathVariable long id) {\n    Optional<Student> student = studentRepository.findById(id);\n\n    if (!student.isPresent())\n      throw new StudentNotFoundException(\"id-\" + id);\n\n    EntityModel<Student> resource = EntityModel.of(student.get());\n\n    WebMvcLinkBuilder linkTo = linkTo(methodOn(this.getClass()).retrieveAllStudents());\n\n    resource.add(linkTo.withRel(\"all-students\"));\n\n    return resource;\n  }\n```\n\nWe create a new resource.\n```java\n  EntityModel<Student> resource = EntityModel.of(student.get());\n```\n\nWe add the link to retrieve all students method to the links.\n```java\n      WebMvcLinkBuilder linkTo = linkTo(methodOn(this.getClass()).retrieveAllStudents());\n\n    resource.add(linkTo.withRel(\"all-students\"));\n\n```\n\nThe response when we execute a GET request to `http://localhost:8080/students/10001` is shown below:\n\n```\n{\n  \"id\": 10001,\n  \"name\": \"Ranga\",\n  \"passportNumber\": \"E1234567\",\n  \"_links\": {\n    \"all-students\": {\n      \"href\": \"http://localhost:8080/students\"\n    }\n  }\n}\n```\n\nYou can see that there is a new section `_links` with a link to all students Resource.\n\n### Enhance Other Resources with HATEOAS\n\nThe above example illustrates key aspects in increasing resources using HATEOAS. \n\nHowever, you must make a critical decision: \n- What are the most significant resources for a certain resource?\n\nGo ahead and enhance the application with more HATEOAS links.\n\n## Maven Project Completion using Code Examples\n> Our Github repository has all the code examples - https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-2-rest-service-with-hateoas\n"
  },
  {
    "path": "_blog/articles/2017-12-29-spring-boot-content-negotiation-xml-and-json.md",
    "content": "---\nlayout:     post\ntitle:      Spring Boot and Content Negotiation - XML and JSON Representations \ndate:       2023-04-03 12:31:19\nsummary:    Learn how to use Spring Boot to build Content Negotiation for a REST API/Service. Content Negotiation facilitates interaction between the Consumer and the Provider over the data exchange format. We will cover both XML and JSON formats in this post.\ncategories:  SpringBoot\npermalink:  /spring-boot-content-negotiation-with-xml-json-representations\nimage: /images/rest-api-category.png\n---\n\nThis post will walk you through the process of implementing Content Negotiation for a REST API/Service using Spring Boot. Content Negotiation facilitates interaction between the Consumer and the Provider over the data exchange format. We will cover both XML and JSON formats in this post.\n \n![Image](/images/ContentNegotiationHeaders-AcceptAndContentType.png \"Content Negotiation Headers - Accept and Content-Type\") \n\n## You will learn\n- What is Content Negotiation?\n- Why do you need Content Negotiation?\n- How do you implement Content Negotiation with Spring Boot?\n- How do you use XML representation for request and response with Spring Boot RESTful Services?\n- How do you use JSON representation for request and response with Spring Boot RESTful Services?\n\n## Project Code Structure\n\nThe screenshot below depicts the framework of the project we will be creating.\n\n![Image](/images/CRUDServiceWithHibernate.png \"CRUDServiceWithHibernate\") \n\nA few details:\n- SpringBoot2RestServiceApplication.java - The Spring Boot Application class generated with Spring Initializer. This class acts as the launching point for application.\n- `pom.xml` - Contains all the dependencies needed to build this project. We will use Spring Boot Starter AOP.\n- `Student.java` - Student JPA Entity\n- StudentRepository.java - Student JPA Repository. This is created using Spring Data JpaRepository.\n- StudentResource.java - Spring Rest Controller exposing all services on the student resource.\n- data.sql - Initial data for the student table. Spring Boot would execute this script after the tables are created from the entities.\n\n## Tools you will need\n- Maven 3.0+ is your build tool\n- Your favorite IDE. We use Eclipse or IntelliJ.\n- JDK 17\n\n## Maven Project Completion using Code Examples\n> Our Github repository has all the code examples - https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-2-rest-service-content-negotiation\n\n## What is Content Negotiation?\n\n> REST is an acronym that stands for REpresentational State Transfer.\n\nA Resource is a key abstraction in REST. There are no restrictions on what can be considered a resource. A todo list is a useful resource. A Facebook friend is a valuable resource.\n\nA resource can have multiple representations\n- XML\n- HTML\n- JSON\n\nWhen a resource is requested, we deliver the resource's representation.\n\nWhen a consumer makes a request, he or she might include two HTTP Headers relating to Content Negotiation.\n- Accept and\n- Content-Type\n\nThe Content-Type header specifies the content type of the request's body.\n\nAccept specifies the intended response content type.\n\n## Content Negotiation Example\n\nThe screenshot below explains how to include these headers in a Postman request.\n\n![Image](/images/ContentNegotiationHeaders-AcceptAndContentType.png \"Content Negotiation Headers - Accept and Content-Type\") \n\nBased on the Accept header, the server is anticipated to reply.\n\nFor example, if a consumer sends a request to `http://localhost:8080/students/10001` with Accept header as 'application/xml', we need to provide the xml representation of the resource.\n\n```xml\n<Student>\n    <id>10001</id>\n    <name>Ranga</name>\n    <passportNumber>E1234567</passportNumber>\n</Student>\n```\n\nIf a consumer submits a request with the Accept header set to 'application/json,' we must offer the resource's JSON representation.\n\n```json\n{\n  \"id\": 10001,\n  \"name\": \"Ranga\",\n  \"passportNumber\": \"E1234567\"\n}\n```\n\nBased on the Content-Type, a same approach applies to the Response Body Content.\n\nA consumer can send a POST request to `http://localhost:8080/students` with Content-Type header as 'application/xml', and provide the XML representation of the resource to be created.\n\n```xml\n<Student>\n    <name>Ranga</name>\n    <passportNumber>E1234567</passportNumber>\n</Student>\n```\n\nA consumer can also send a POST request to `http://localhost:8080/students` with Content-Type header as 'application/json', and provide the JSON representation of the resource to be created.\n\n```json\n{\n  \"name\": \"Ranga\",\n  \"passportNumber\": \"E1234567\"\n}\n```\n\n> This dialog which happens between the Consumer and Service Provider is called Content Negotiation.\n\n## Bootstrapping a Project with a REST Resource\n\nIn the previous article in the series - http://www.springboottutorial.com/spring-boot-crud-rest-service-with-jpa-hibernate, we set up a simple restful service with a resource exposing CRUD methods. \n\n> The same example will be used to demonstrate Content Negotiation.\n\n## Using Spring Boot to Implement Content Negotiation\n\nLet's run a few requests to see if the project we established using Spring Boot Starter Web includes content negotiation by default, and then we'll continue on to adding content negotiation to our application.\n\n### Executing a request with Accept Header 'application/xml'\n\nSend a request to `http://localhost:8080/students/10001` with Accept header as 'application/xml'. \n\nYou are expecting to get an XML representation of the resource.\n\nYou would, however, receive a response with the status -> 406 Not Acceptable. This means that the programme does not allow responding with the content type `application/xml`. \n\nHowever, if you submit a request to `http://localhost:8080/students/10001` with the Accept header set to `application/json`, you will receive the anticipated result.\n\n```json\n{\n  \"id\": 10001,\n  \"name\": \"Ranga\",\n  \"passportNumber\": \"E1234567\"\n}\n```\n\n### Spring Boot Services XML Representation Implementation\n\nIt's straightforward. All you'd have to do is add a simple dependency to your `pom.xml`.\n\n```xml\n<dependency>\n  <groupId>com.fasterxml.jackson.dataformat</groupId>\n  <artifactId>jackson-dataformat-xml</artifactId>\n</dependency>\n```\n\nRestart your application. \n\nSend a request to `http://localhost:8080/students/10001` with Accept header as 'application/xml'. \n\nResponse\n```xml\n<Student>\n    <id>10001</id>\n    <name>Ranga</name>\n    <passportNumber>E1234567</passportNumber>\n</Student>\n```\n\nCool! Your application now supports the student resource in both XML and JSON formats.\n\nYou can use \n- Content-Type to indicate content type of the body  for POST and PUT requests.\n- Accept indicates the expected content type of the response for GET requests.\n\n### Experimenting with Content Negotiation\n\n#### GET Request\n\n- URL - http://localhost:8080/students\n- Request Method - GET\n- Request Headers\n  - Accept - application/xml\n\nResponse\n```xml\n<List>\n    <item>\n        <id>10001</id>\n        <name>Ranga</name>\n        <passportNumber>E1234567</passportNumber>\n    </item>\n    <item>\n        <id>10002</id>\n        <name>Ravi</name>\n        <passportNumber>A1234568</passportNumber>\n    </item>\n</List>\n```\n\n#### POST Request\n\n- URL - http://localhost:8080/students\n- Request Method - POST\n- Request Headers\n  - Content-Type - application/xml\n  \nRequest\n```json\n    <item>\n        <name>Tom</name>\n        <passportNumber>Z1234567</passportNumber>\n    </item>\n```\n\nResponse \n- Status 201 - CREATED\n- Header Location →http://localhost:8080/students/2\n\n#### PUT Request\n\n- URL → http://localhost:8080/students/10002\n- Request \n    - Method → PUT\n- Request Headers\n  - Content-Type - application/xml\n\nRequest\n\n```xml\n<item>\n    <name>Tom</name>\n    <passportNumber>Z1234567</passportNumber>\n</item>\n```\n\nResponse code 204 - No Content\n\n\n## Maven Project Completion using Code Examples\n\n> Our Github repository has all the code examples - https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-2-rest-service-content-negotiation\n"
  },
  {
    "path": "_blog/articles/2017-12-30-spring-boot-documenting-with-swagger.md",
    "content": "---\nlayout:     post\ntitle:      Spring Boot and Swagger - Documenting RESTful Services (REST API)\ndate:       2023-04-10 12:31:19\nsummary:    Learn how to document your RESTful services with Swagger and Spring Boot. We'll look at how to use your REST API to offer automatic swagger documentation. We will also use swagger annotations to add documentation to the REST API.\ncategories:  SpringBoot\npermalink:  /spring-boot-swagger-documentation-for-rest-services\nimage: /images/rest-api-category.png\n---\n\nThis post will show you how to document your RESTful services using Swagger and Spring Boot. We'll look at how to expose automatic swagger documentation from your app. We will also use swagger annotations to add documentation to the REST API.\n\n![Image](/images/SwaggerDocumentation-1-HomePage.png \"SwaggerDocumentation-1-HomePage\") \n\n \n## You will learn\n- What is the need for documenting your RESTful services?\n- How do you document RESTful web services?\n- Why Swagger?\n- How can you use Swagger UI?\n- How do you automate generation of Swagger Documentation from RESTful Web Services?\n- How do you add custom information to Swagger Documentation generated from RESTful Web Services?\n- What is Swagger-UI?\n\n\n## Project Code Structure\n\nFollowing screen shot shows the structure of the project we will create.\n\n![Image](/images/SpringBootSwaggerDocumentation-ProjectStructure.png \"SpringBootSwaggerDocumentation-ProjectStructure\") \n\nA few details:\n- SpringBoot2RestServiceApplication.java - The Spring Boot Application class generated with Spring Initializer. This class acts as the launching point for application.\n- `pom.xml` - Contains all the dependencies needed to build this project. We will use Spring Boot Starter AOP.\n- `Student.java` - Student JPA Entity\n- StudentRepository.java - Student JPA Repository. This is created using Spring Data JpaRepository.\n- StudentResource.java - Spring Rest Controller exposing all services on the student resource.\n- data.sql - Initial data for the student table. Spring Boot would execute this script after the tables are created from the entities.\n- ApiDocumentationConfig.java - Meta Information about the API that will included in the documentation.\n- SwaggerConfig.java - Contains the Swagger Configuration for generating documentation\n\n## Tools you will need\n- Maven 3.0+ is your build tool\n- Your favorite IDE. We use Eclipse or IntelliJ.\n- JDK 17\n\n## Complete Maven Project With Code Examples\n> Our Github repository has all the code examples - https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-2-rest-service-with-swagger\n\n## Why should we describe your RESTful API?\n\nThe most important design principle for RESTful Services is \n> Think about consumer of the API.\n\nHow does the consumer know\n- What is format of the request?\n- What content types your API supports?\n- What is the structure of the response?\n- Do you use HATEOAS?\n- How to test your API?\n- What kind of security mechanism you use?\n\nREST, unlike SOAP (WSDL), does not establish a documentation standard or contract. REST allows you to select your documentation format and strategy. However, this does not imply that \"no documentation\" exists.\n\n> It is a common misperception that REST implies no documentation. Your API must be documented.\n\n## How do you document your RESTful API?\n\nOne alternative is to manually maintain documentation. But that rapidly becomes obsolete.\n\nAn alternative is to produce documentation from code. That is the strategy we will use in this tutorial.\n\nThere are multiple approaches to documenting your RESTful API\n- WADL\n- RESTDocs\n- Swagger or OpenDocs\n\nSwagger has gained traction in recent years and is now the most widely used REST API description standard. This guide will make use of Swagger.\n\n## Bootstrapping a Project with a REST Resource\n\nWe set up a basic restful service with a resource exposing CRUD methods in the previous post in the series - http://www.springboottutorial.com/spring-boot-crud-rest-service-with-jpa-hibernate. \n\n> We will use the same example to generate Swagger Documentation.\n\n## Spring Boot Documentation Generation for Swaggger\n\nTo produce Swagger documentation, we would need to add a few Swagger-related dependencies and establish a Docket. We will also utilise Swagger UI to visualise the documentation and to conduct Test Requests.\n\n### Adding Swagger Dependencies\n\nLet's add a couple of dependencies to our Swagger Project pom.xml.\n\n```xml\n    <dependency>\n      <groupId>io.springfox</groupId>\n      <artifactId>springfox-boot-starter</artifactId>\n      <version>3.0.5</version>\n    </dependency>\n```\n\nBecause we're utilising a SNAPSHOT version, you'll need to include a jfrog-snapshots repository in your pom.xml.\n\n```xml\n<repository>\n      <id>jfrog-snapshots</id>\n      <name>JFROG Snapshots</name>\n      <url>http://oss.jfrog.org/artifactory/oss-snapshot-local</url>\n      <snapshots>\n        <enabled>true</enabled>\n      </snapshots>\n</repository>\n```\n\n\n### Docket for Swagger Spring Configuration\n\nAdd the Spring setup required to produce Swagger documentation today. \n\n/src/main/java/com/in28minutes/springboot/rest/example/swagger/OpenApiConfig.java\n\n```java\n@Configuration\npublic class OpenApiConfig {\n\n    @Bean\n    public OpenAPI awesomeAPI() {\n        return new OpenAPI()\n                .info(new Info().title(\"Awesome API Title\")\n                        .description(\"Awesome API Description\")\n                        .version(\"1.0\")\n                        .license(new License().name(\"Apache 2.0\").url(\"http://www.apache.org/licenses/LICENSE-2.0\")))\n                .externalDocs(new ExternalDocumentation()\n                        .description(\"Ranga Karanam, in28minutes@gmail.com\")\n                        .url(\"http://www.in28minutes.com\"));\n    }\n\n}\n```\nNotes\n- `@Configuration` - This file contains Spring configuration.\n\n### Exposing meta API information using @SwaggerDefinition\n\n\n### Swagger documentation generated\n\nWhen you restart the program, you will be able to see the created documentation.\n\nGo to URL `http://localhost:8080/v2/api-docs`\n\nAt the top of the documentation is the Meta Information of the API\n```\n{\n  \"swagger\": \"2.0\",\n  \"info\": {\n    \"description\": \"Awesome API Description\",\n    \"version\": \"1.0\",\n    \"title\": \"Awesome API Title\",\n    \"termsOfService\": \"urn:tos\",\n    \"contact\": {\n      \"name\": \"Ranga Karanam\",\n      \"url\": \"http://www.in28minutes.com\",\n      \"email\": \"in28minutes@gmail.com\"\n    },\n    \"license\": {\n      \"name\": \"Apache 2.0\",\n      \"url\": \"http://www.apache.org/licenses/LICENSE-2.0\"\n    }\n  },\n  \"host\": \"localhost:8080\",\n  \"basePath\": \"/\",\n  \"tags\": [\n    {\n      \"name\": \"web-mvc-endpoint-handler-mapping\",\n      \"description\": \"Web Mvc Endpoint Handler Mapping\"\n    },\n    {\n      \"name\": \"student-resource\",\n      \"description\": \"Student Resource\"\n    },\n    {\n      \"name\": \"operation-handler\",\n      \"description\": \"Operation Handler\"\n    },\n    {\n      \"name\": \"basic-error-controller\",\n      \"description\": \"Basic Error Controller\"\n    }\n  ],\n  \"consumes\": [\n    \"application/xml\",\n    \"application/json\"\n  ],\n  \"produces\": [\n    \"application/xml\",\n    \"application/json\"\n  ],\n```\n\nThe paths contain the details of the resources being exposed\n- You can see the different request methods, a summary of each method and all details about each request and response \n\n```\n  \"paths\": {\n    \"/students\": {\n      \"get\": {\n        \"tags\": [\n          \"student-resource\"\n        ],\n        \"summary\": \"retrieveAllStudents\",\n        \"operationId\": \"retrieveAllStudentsUsingGET\",\n        \"consumes\": [\n          \"application/xml\",\n          \"application/json\"\n        ],\n        \"produces\": [\n          \"application/xml\",\n          \"application/json\"\n        ],\n        \"responses\": {\n          \"200\": {\n            \"description\": \"OK\",\n            \"schema\": {\n              \"type\": \"array\",\n              \"items\": {\n                \"$ref\": \"#/definitions/Student\"\n              }\n            }\n          },\n          \"401\": {\n            \"description\": \"Unauthorized\"\n          },\n          \"403\": {\n            \"description\": \"Forbidden\"\n          },\n          \"404\": {\n            \"description\": \"Not Found\"\n          }\n        }\n      },\n      \"post\": {\n        \"tags\": [\n          \"student-resource\"\n        ],\n        \"summary\": \"createStudent\",\n        \"operationId\": \"createStudentUsingPOST\",\n        \"consumes\": [\n          \"application/xml\",\n          \"application/json\"\n        ],\n        \"produces\": [\n          \"application/xml\",\n          \"application/json\"\n        ],\n        \"parameters\": [\n          {\n            \"in\": \"body\",\n            \"name\": \"student\",\n            \"description\": \"student\",\n            \"required\": true,\n            \"schema\": {\n              \"$ref\": \"#/definitions/Student\"\n            }\n          }\n        ],\n        \"responses\": {\n          \"200\": {\n            \"description\": \"OK\",\n            \"schema\": {\n              \"type\": \"object\"\n            }\n          },\n          \"201\": {\n            \"description\": \"Created\"\n          },\n          \"401\": {\n            \"description\": \"Unauthorized\"\n          },\n          \"403\": {\n            \"description\": \"Forbidden\"\n          },\n          \"404\": {\n            \"description\": \"Not Found\"\n          }\n        }\n      }\n    },\n    \"/students/{id}\": {\n      \"get\": {\n        \"tags\": [\n          \"student-resource\"\n        ],\n        \"summary\": \"Find student by id\",\n        \"description\": \"Also returns a link to retrieve all students with rel - all-students\",\n        \"operationId\": \"retrieveStudentUsingGET\",\n        \"consumes\": [\n          \"application/xml\",\n          \"application/json\"\n        ],\n        \"produces\": [\n          \"application/xml\",\n          \"application/json\"\n        ],\n        \"parameters\": [\n          {\n            \"name\": \"id\",\n            \"in\": \"path\",\n            \"description\": \"id\",\n            \"required\": true,\n            \"type\": \"integer\",\n            \"format\": \"int64\"\n          }\n        ],\n        \"responses\": {\n          \"200\": {\n            \"description\": \"OK\",\n            \"schema\": {\n              \"$ref\": \"#/definitions/Resource«Student»\"\n            }\n          },\n          \"401\": {\n            \"description\": \"Unauthorized\"\n          },\n          \"403\": {\n            \"description\": \"Forbidden\"\n          },\n          \"404\": {\n            \"description\": \"Not Found\"\n          }\n        }\n      },\n      \"put\": {\n        \"tags\": [\n          \"student-resource\"\n        ],\n        \"summary\": \"updateStudent\",\n        \"operationId\": \"updateStudentUsingPUT\",\n        \"consumes\": [\n          \"application/xml\",\n          \"application/json\"\n        ],\n        \"produces\": [\n          \"application/xml\",\n          \"application/json\"\n        ],\n        \"parameters\": [\n          {\n            \"in\": \"body\",\n            \"name\": \"student\",\n            \"description\": \"student\",\n            \"required\": true,\n            \"schema\": {\n              \"$ref\": \"#/definitions/Student\"\n            }\n          },\n          {\n            \"name\": \"id\",\n            \"in\": \"path\",\n            \"description\": \"id\",\n            \"required\": true,\n            \"type\": \"integer\",\n            \"format\": \"int64\"\n          }\n        ],\n        \"responses\": {\n          \"200\": {\n            \"description\": \"OK\",\n            \"schema\": {\n              \"type\": \"object\"\n            }\n          },\n          \"201\": {\n            \"description\": \"Created\"\n          },\n          \"401\": {\n            \"description\": \"Unauthorized\"\n          },\n          \"403\": {\n            \"description\": \"Forbidden\"\n          },\n          \"404\": {\n            \"description\": \"Not Found\"\n          }\n        }\n      },\n      \"delete\": {\n        \"tags\": [\n          \"student-resource\"\n        ],\n        \"summary\": \"deleteStudent\",\n        \"operationId\": \"deleteStudentUsingDELETE\",\n        \"consumes\": [\n          \"application/xml\",\n          \"application/json\"\n        ],\n        \"produces\": [\n          \"application/xml\",\n          \"application/json\"\n        ],\n        \"parameters\": [\n          {\n            \"name\": \"id\",\n            \"in\": \"path\",\n            \"description\": \"id\",\n            \"required\": true,\n            \"type\": \"integer\",\n            \"format\": \"int64\"\n          }\n        ],\n        \"responses\": {\n          \"200\": {\n            \"description\": \"OK\"\n          },\n          \"204\": {\n            \"description\": \"No Content\"\n          },\n          \"401\": {\n            \"description\": \"Unauthorized\"\n          },\n          \"403\": {\n            \"description\": \"Forbidden\"\n          }\n        }\n      }\n    }\n  },\n```\n\nDefinitions contain the detailed structure of the elements used in Request and Responses above.\n```\n  \"definitions\": {\n    \"Resource«Student»\": {\n      \"type\": \"object\",\n      \"properties\": {\n        \"id\": {\n          \"type\": \"integer\",\n          \"format\": \"int64\"\n        },\n        \"links\": {\n          \"type\": \"array\",\n          \"items\": {\n            \"$ref\": \"#/definitions/Link\"\n          }\n        },\n        \"name\": {\n          \"type\": \"string\",\n          \"description\": \"Name should have atleast 2 characters\"\n        },\n        \"passportNumber\": {\n          \"type\": \"string\"\n        }\n      }\n    },\n    \"Map«string,Link»\": {\n      \"type\": \"object\",\n      \"additionalProperties\": {\n        \"$ref\": \"#/definitions/Link\"\n      }\n    },\n    \"Student\": {\n      \"type\": \"object\",\n      \"properties\": {\n        \"id\": {\n          \"type\": \"integer\",\n          \"format\": \"int64\"\n        },\n        \"name\": {\n          \"type\": \"string\",\n          \"description\": \"Name should have atleast 2 characters\"\n        },\n        \"passportNumber\": {\n          \"type\": \"string\"\n        }\n      },\n      \"description\": \"All details about the student. \"\n    },\n    \"Link\": {\n      \"type\": \"object\",\n      \"properties\": {\n        \"href\": {\n          \"type\": \"string\"\n        },\n        \"templated\": {\n          \"type\": \"boolean\"\n        }\n      }\n    }\n  }\n}\n```\n\n### Launching Swagger UI\n\nYou can also use the Swagger UI available at `http://localhost:8080/swagger-ui/index.html`.\n\n> Older url was http://localhost:8080/swagger-ui.html\n\nBelow screenshot shows the Home Page of Swagger UI. It shows a list of all the resources that are exposed.\n\n![Image](/images/SwaggerDocumentation-1-HomePage.png \"SwaggerDocumentation-1-HomePage\") \n\n\nChoosing the Student resource takes you to details of the resource. It shows all the request methods that can be used with a Resource.\n\n![Image](/images/SwaggerDocumentation-2-ResourceDetails-Student.png \"SwaggerDocumentation-2-ResourceDetails-Student\") \n\nYou can also see the details for a Specific Request Method.\n\n![Image](/images/SwaggerDocumentation-3-StudentGetMethodDetails.png \"SwaggerDocumentation-3-StudentGetMethodDetails\") \n\nYou can use the 'Try it out' button to execute a request and see the response.\n\n![Image](/images/SwaggerDocumentation-4-TryItOut-Request-And-Response.png \"SwaggerDocumentation-4-TryItOut-Request-And-Response\") \n\n### Customizing Swagger Documentation with Annotations\nYou can add notes on the resource method to add more documentation\n```java\n  \t@GetMapping(\"/students/{id}\")\n\t@Operation(summary = \"Find student by id, also returns a link to retrieve all students with rel - all-students\")\n\tpublic EntityModel<Student> retrieveStudent(@PathVariable long id) {\n\n```\n\nAlso supported is enhancing the documentation on the Request and Response Beans. \n```java\n@Entity\n@Schema(description = \"All details about the student. \")\npublic class Student {\n    @Id\n    @GeneratedValue\n    private Long id;\n\n    @Schema(name = \"Name should have atleast 2 characters\")\n    @Size(min = 2, message = \"Name should have atleast 2 characters\")\n    private String name;\n\n```\n\n## Maven Project Completion using Code Examples\n> Our Github repository has all the code examples - https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-2-rest-service-with-swagger\n"
  },
  {
    "path": "_blog/articles/2017-12-31-spring-boot-versioning-restful-services.md",
    "content": "---\nlayout:     post\ntitle:      Versioning RESTful Services - Spring Boot REST API\ndate:       2022-07-02 12:31:19\nsummary:    Learn why versioning is needed and how you can version your REST API. We will look at 4 ways of versioning and also compare the different approaches.\ncategories:  SpringBoot\npermalink:  /spring-boot-versioning-for-rest-services\nimage: /images/rest-api-category.png\n---\n\n![Image](/images/Spring-Initializr-Web-JPA.png \"Web, JPA, Hibernate and Developer Tools\")\n\nThis guide will help you understand why versioning is needed and how you can version your REST API. We will look at 4 ways of versioning and also compare the different approaches.\n \n![Image](/images/Postman-ProvidingRequestHeaders.png \"Postman-ProvidingRequestHeaders\")   \n\n## You will learn\n- Why do we need Versioning for  RESTful Web Services?\n- What are the versioning options that are available?\n- How do you implement Versioning for RESTful Web Services?\n\n\n## Project Code Structure\n\nFollowing screenshot shows the structure of the project we will create.\n\n![Image](/images/SpringBootVersioningRESTAPI-ProjectStructure.png \"SpringBootVersioningRESTAPI-ProjectStructure\") \n\nA few details:\n- SpringBoot2RestServiceApplication.java - The Spring Boot Application class generated with Spring Initializer. This class acts as the launching point for application.\n- `pom.xml` - Contains all the dependencies needed to build this project. We will use Spring Boot Starter AOP.\n- StudentV1.java - Basic Version of the Student Bean.\n- StudentV2.java - Advanced Version of the Student Bean using a seperate bean for Name.\n- Name.java - Seperate bean for Name having different parts of the Name.\n- StudentVersioningController.java - Controller from where all the service versions are exposed.\n\n## Tools you will need\n- Maven 3.0+ is your build tool\n- Your favorite IDE. We use Eclipse.\n- JDK 1.8+\n\n## Complete Maven Project With Code Examples\n> Our Github repository has all the code examples - https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-2-rest-service-versioning\n\n## Why do we need to version our RESTful API?\n\nThe best approach to versioning is NOT to do it. Yeah, that's right. Do not version as long as versioning is not needed.\n\n> Build your services to backward compatible so that you can avoid versioning as much as possible!\n\nHowever there are a number of situations where versioning is needed.\n\nLet's consider an example.\n\nYou had this version of the student service initially\n```\n{\n  \"name\": \"Bob Charlie\"\n}\n```\n\nAt a later point, you wanted to split the name up. So, you created this version of the service.\n\n```\n{\n  \"name\": {\n    \"firstName\": \"Bob\",\n    \"lastName\": \"Charlie\"\n  }\n}\n```\n\nYou can support both these requests from the same service, but it becomes complex as the requirements diversify for each of the versions.\n\nIn these kind of situations, versioning becomes mandatory.\n\nLet's create a simple project and understand the 4 different approaches to versioning your RESTful services.\n\n## Bootstrapping with Spring Initializr\n\nCreating a REST service with Spring Initializr is a cake walk. We will use Spring Web MVC as our web framework.  \n\nSpring Initializr [http://start.spring.io/](http://start.spring.io/){:target=\"_blank\"} is great tool to bootstrap your Spring Boot projects.\n\n![Image](/images/Spring-Initializr-Web.png \"Web, Actuator and Developer Tools\")   \n\n![Image](/images/Spring-Initializr-Web-JPA.png \"Web, JPA, Hibernate and Developer Tools\")\n\nAs shown in the image above, following steps have to be done\n\n- Launch Spring Initializr and choose the following\n  - Choose `com.in28minutes.springboot.rest.example` as Group\n  - Choose `spring-boot-2-rest-service-basic` as Artifact\n  - Choose following dependencies\n    - Web\n    - DevTools\n- Click Generate Project.\n- Import the project into Eclipse. File -> Import -> Existing Maven Project.\n\n### Implementing Beans for Versioning\n\nFirst version of Bean\n```\npublic class StudentV1 {\n  private String name;\n```\n\nSecond Version of Bean\n```\npublic class StudentV2 {\n  private Name name;\n```\n\nName has firstName and lastName and is used by `StudentV2`\n```\npublic class Name {\n  private String firstName;\n  private String lastName;\n```\n\n## Versioning Approaches for RESTful Services\n\nWe would want to create two versions of services, one returning `StudentV1` and the other returning `StudentV2`. \n\nLet's look at the 4 Different Approaches for creating versions of the same service.\n\n### URI Versioning\n\nBasic approach to versioning is to create a completely different URI for the new service. Example implementation is shown below.\n\nExamples\n- `http://localhost:8080/v1/person`\n- `http://localhost:8080/v2/person`\n\n```\n@RestController\npublic class StudentVersioningController {\n\n  @GetMapping(\"v1/student\")\n  public StudentV1 studentV1() {\n    return new StudentV1(\"Bob Charlie\");\n  }\n\n  @GetMapping(\"v2/student\")\n  public StudentV2 studentV2() {\n    return new StudentV2(new Name(\"Bob\", \"Charlie\"));\n  }\n\n```\n\n`http://localhost:8080/v1/person`\n\nResponse\n```\n{\n  \"name\": \"Bob Charlie\"\n}\n```\n\n`http://localhost:8080/v2/person`\n\nResponse\n```\n{\n  \"name\": {\n    \"firstName\": \"Bob\",\n    \"lastName\": \"Charlie\"\n  }\n}\n```\n\n### Request Parameter versioning \n\nNext approach to versioning is to use the request parameter to differentiate versions.\n\nExamples\n- http://localhost:8080/person/param?version=1\n- http://localhost:8080/person/param?version=2\n\nImplementations are shown below:\n```\n  @GetMapping(value = \"/student/param\", params = \"version=1\")\n  public StudentV1 paramV1() {\n    return new StudentV1(\"Bob Charlie\");\n  }\n\n  @GetMapping(value = \"/student/param\", params = \"version=2\")\n  public StudentV2 paramV2() {\n    return new StudentV2(new Name(\"Bob\", \"Charlie\"));\n  }\n```\n\n`http://localhost:8080/person/param?version=1`\n\nResponse\n```\n{\n  \"name\": \"Bob Charlie\"\n}\n```\n\n`http://localhost:8080/person/param?version=2`\nResponse\n```\n{\n  \"name\": {\n    \"firstName\": \"Bob\",\n    \"lastName\": \"Charlie\"\n  }\n}\n```\n\n### (Custom) Headers versioning\n\nThe third approach to versioning is to use a Request Header to differentiate the versions.\n\nExamples\n- http://localhost:8080/person/header\n   - headers=[X-API-VERSION=1]\n- http://localhost:8080/person/header\n   - headers=[X-API-VERSION=2]\n\nImplementations are shown below:\n\n```\n  @GetMapping(value = \"/student/header\", headers = \"X-API-VERSION=1\")\n  public StudentV1 headerV1() {\n    return new StudentV1(\"Bob Charlie\");\n  }\n\n  @GetMapping(value = \"/student/header\", headers = \"X-API-VERSION=2\")\n  public StudentV2 headerV2() {\n    return new StudentV2(new Name(\"Bob\", \"Charlie\"));\n  }\n```\n\nBelow picture shows how we can execute a Get Request Method with Request Headers using Postman.\n\n![Image](/images/Postman-ProvidingRequestHeaders.png \"Postman-ProvidingRequestHeaders\")   \n\n`http://localhost:8080/person/header` with a header\n- X-API-VERSION=1\n\nResponse\n```\n{\n  \"name\": \"Bob Charlie\"\n}\n```\n\n`http://localhost:8080/person/header` with a header\n- X-API-VERSION=2\n\nResponse\n```\n{\n  \"name\": {\n    \"firstName\": \"Bob\",\n    \"lastName\": \"Charlie\"\n  }\n}\n```\n\n### Media type versioning (a.k.a “content negotiation” or “accept header”)\nThe last versioning approach is to use the Accept Header in the request. \n\nExamples\n- http://localhost:8080/person/produces\n   - headers[Accept=application/vnd.company.app-v1+json]\n- http://localhost:8080/person/produces\n   - headers[Accept=application/vnd.company.app-v2+json]\n\n```\n  @GetMapping(value = \"/student/produces\", produces = \"application/vnd.company.app-v1+json\")\n  public StudentV1 producesV1() {\n    return new StudentV1(\"Bob Charlie\");\n  }\n\n  @GetMapping(value = \"/student/produces\", produces = \"application/vnd.company.app-v2+json\")\n  public StudentV2 producesV2() {\n    return new StudentV2(new Name(\"Bob\", \"Charlie\"));\n  }\n\n```\n\nBelow picture shows how we can execute a Get Request Method with Request Headers using Postman.\n\n![Image](/images/Postman-ProvidingRequestHeaders.png \"Postman-ProvidingRequestHeaders\")   \n\n`http://localhost:8080/person/produces` with a header\n- Accept=application/vnd.company.app-v1+json\nResponse\n```\n{\n  \"name\": \"Bob Charlie\"\n}\n```\n\n`http://localhost:8080/person/produces` with a header \n- Accept=application/vnd.company.app-v2+json\n\nResponse\n```\n{\n  \"name\": {\n    \"firstName\": \"Bob\",\n    \"lastName\": \"Charlie\"\n  }\n}\n```\n\n## Factors affecting Versioning Choice\n\nFollowing factors affect the choice of versioning:\n- URI Pollution - URL versions and Request Param versioning pollute the URI space.\n- Misuse of HTTP Headers - Accept Header is not designed to be used for versioning.\n- Caching - If you use Header based versioning, we cannot cache just based on the URL. You would need take the specific header into consideration.\n- Can we execute the request on the browser? - If you have non technical consumers, then the URL based version would be easier to use as they can be executed directly on the browser.\n- API Documentation - How do you get your documentation generation to understand that two different urls are versions of the same service?\n\n> The fact is that there is `No Perfect Solution` for versioning.\n\nThe list below shows Major API providers using different versioning approaches.\n- Media type versioning (a.k.a “content negotiation” or “accept header”)\n   - GitHub\n- (Custom) Headers versioning\n   - Microsoft\n- URI Versioning\n   - Twitter\n- Request Parameter versioning \n   - Amazon\n\n> Plan to avoid versioning as far as possible but evaluate and be ready with a versioing strategy before you expose your first service to your consumer. Good Luck!\n\n"
  },
  {
    "path": "_blog/articles/2018-01-01-spring-boot-soap-web-service.md",
    "content": "---\nlayout:     post\ntitle:      Creating a SOAP Web Service with Spring Boot Starter Web Services\ndate:       2022-07-02 12:31:19\nsummary:    Let's learn how to create a SOAP Web Service with Spring Boot Starter Web Services. We will take a Contract First approach by definining an XSD and exposing a WSDL from it.\ncategories:  SpringBoot\npermalink:  /creating-soap-web-service-with-spring-boot-web-services-starter\nimage: /images/rest-api-category.png\n---\n\n![Image](/images/Spring-Initializr-Web-JPA.png \"Web, JPA, Hibernate and Developer Tools\")\n\nThis guide will help you create a SOAP Web Service with Spring Boot Starter Web Services. We will take a Contract First approach by definining an XSD and exposing a WSDL from it.\n \n![Image](/images/ExecutingSOAPRequestsWithWizdler-1.png \"ExecutingSOAPRequestsWithWizdler-1\")\n\n## You will learn\n- What is a web service?\n- What are the different types of web services?\n- What is SOAP Web Service?\n- What is SOAP?\n- What is a SOAP Envelope?\n- What is SOAP Header and SOAP Body?\n- What is WSDL (Web Service Definition Language)? \n- What are the different parts of a WSDL?\n- What is Contract First Approach?\n- What is an XSD?\n- What is JAXB?\n- How do you configure a JAXB Plugin?\n- What is an Endpoint?\n- Can you show an example endpoint written with Spring Web Services?\n- What is a MessageDispatcherServlet?\n- How do you configure a MessageDispatcherServlet?\n- How do you generate a WSDL using Spring Web Services?\n\n\n\n## Resources Overview\n\nIn this guide, we will create a Student Resource exposing three services using proper URIs and HTTP methods:\n- Retrieve all Students - @GetMapping(\"/students\")\n- Get details of specific student - @GetMapping(\"/students/{id}\")\n- Delete a student - @DeleteMapping(\"/students/{id}\")\n- Create a new student - @PostMapping(\"/students\")\n- Update student details - @PutMapping(\"/students/{id}\")\n\n## Project Code Structure\n\nFollowing screenshot shows the structure of the project we will create.\n\n![Image](/images/CRUDServiceWithHibernate.png \"CRUDServiceWithHibernate\") \n\nA few details:\n- SpringBoot2RestServiceApplication.java - The Spring Boot Application class generated with Spring Initializer. This class acts as the launching point for application.\n- `pom.xml` - Contains all the dependencies needed to build this project. We will use Spring Boot Starter AOP.\n- `Student.java` - Student JPA Entity\n- StudentRepository.java - Student JPA Repository. This is created using Spring Data JpaRepository.\n- StudentResource.java - Spring Rest Controller exposing all services on the student resource.\n- data.sql - Initial data for the student table. Spring Boot would execute this script after the tables are created from the entities.\n\n## Tools you will need\n- Maven 3.0+ is your build tool\n- Your favorite IDE. We use Eclipse.\n- JDK 1.8+\n\n## Complete Maven Project With Code Examples\n> Our Github repository has all the code examples - https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-tutorial-soap-web-services\n\n# What is a Web Service?\n\n> Service delivered over the web\n\nIs this really a complete definition. Is everything thats delivered over the web \"Web Service\"?\n\nThe key things to understand is \n- Web services are designed for machine-to-machine (or application-to-application) interaction\n- Web services should be interoperable - Not platform dependent\n- Web services should allow communication over a network\n\n## Types of Web Services\n\nNot really types but a broad classification\n- SOAP\n- REST\n\nThese are not really mutually exclusive. Some SOAP services can actually be RESTful. \n\n### SOAP\n\nSOAP was earlier an abbreviation for Simple Object Access Protocol. In SOAP, the request and response are in XML format. However, not all types of XML are valid SOAP Requests. \n\nSOAP defines a standard XML format. We will use WSDL (Web Service Definition Language) to define the format of request xml and the response xml.\n\nNow lets say Facebook wants to know how to call the TODO Service? What should I give to the Facebook developer? \n\nI will give him a WSDL of the Todo service. It will explain: \n- What are the different services (operations) exposed by the server?\n- How can a service (operation) be called? What url to use? (also called End Point).\n- What should the structure of request xml?\n- What should be the structure of response xml?\n\nSOAP format defines a SOAP-Envelope which envelopes the entire document. \n- SOAP-Header (optional) contains any information needed to identify the request. Also, part of the Header is authentication, authorization information (signatures, encrypted information etc).\n- SOAP-Body contains the real xml content of request or response.\n- In case of error response, server responds back with SOAP-Fault.\n\n## REST vs SOAP\n\nREST vs SOAP are not really comparable. REST is an architectural style. SOAP is a message exchange format.\n\nLet's compare the popular implementations of REST and SOAP styles.\n- RESTful Sample Implementation : JSON over HTTP\n- SOAP Sample Implementation : XML over SOAP over HTTP\n\nFollowing are the important things to consider:\n- REST is built over simple HTTP protocol. SOAP services are more complex to implement and more complex to consume.\n- REST has better performance and scalability. REST reads can be cached, SOAP based reads cannot be cached.\n- REST permits many different data formats (JSON is the most popular choice) where as SOAP only permits XML.\n- SOAP services have well defined structure and interface (WSDL) and has a set of well defined standards (WS-Security, WS-AtomicTransaction and WS-ReliableMessaging). Documentation standards with REST are evolving(We will use Swagger in this course).\n\n## SOAP Service Examples\n\n### Request\n```xml\n<Envelope xmlns=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <Body>\n        <getCourseDetailsRequest xmlns=\"http://in28minutes.com/courses\">\n            <id>Course1</id>\n        </getCourseDetailsRequest>\n    </Body>\n</Envelope>\n```\n\n### Response\n```\n<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <SOAP-ENV:Header/>\n    <SOAP-ENV:Body>\n        <ns2:getCourseDetailsResponse xmlns:ns2=\"http://in28minutes.com/courses\">\n            <ns2:course>\n                <ns2:id>Course1</ns2:id>\n                <ns2:name>Spring</ns2:name>\n                <ns2:description>10 Steps</ns2:description>\n            </ns2:course>\n        </ns2:getCourseDetailsResponse>\n    </SOAP-ENV:Body>\n</SOAP-ENV:Envelope>\n```\n\n### Fault\n\n```xml\n<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <SOAP-ENV:Header/>\n    <SOAP-ENV:Body>\n        <SOAP-ENV:Fault>\n            <faultcode>SOAP-ENV:Server</faultcode>\n            <faultstring xml:lang=\"en\">java.lang.NullPointerException</faultstring>\n        </SOAP-ENV:Fault>\n    </SOAP-ENV:Body>\n</SOAP-ENV:Envelope>\n```\n\n### WSDL\n\nWSDL is used to define the structure of Request and the Structure of Response.\n\n- view-source:http://localhost:8080/ws/courses.wsdl\n\n```xml\n<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><wsdl:definitions xmlns:wsdl=\"http://schemas.xmlsoap.org/wsdl/\" xmlns:sch=\"http://in28minutes.com/courses\" xmlns:soap=\"http://schemas.xmlsoap.org/wsdl/soap/\" xmlns:tns=\"http://in28minutes.com/courses\" targetNamespace=\"http://in28minutes.com/courses\">\n  <wsdl:types>\n    <xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" elementFormDefault=\"qualified\" targetNamespace=\"http://in28minutes.com/courses\">\n\n    <xs:element name=\"getCourseDetailsRequest\">\n        <xs:complexType>\n            <xs:sequence>\n                <xs:element name=\"id\" type=\"xs:string\"/>\n            </xs:sequence>\n        </xs:complexType>\n    </xs:element>\n\n    <xs:element name=\"getCourseDetailsResponse\">\n        <xs:complexType>\n            <xs:sequence>\n                <xs:element name=\"course\" type=\"tns:course\"/>\n            </xs:sequence>\n        </xs:complexType>\n    </xs:element>\n\n    <xs:complexType name=\"course\">\n        <xs:sequence>\n            <xs:element name=\"id\" type=\"xs:string\"/>\n            <xs:element name=\"name\" type=\"xs:string\"/>\n            <xs:element name=\"description\" type=\"xs:string\"/>\n        </xs:sequence>\n    </xs:complexType>\n</xs:schema>\n  </wsdl:types>\n  <wsdl:message name=\"getCourseDetailsRequest\">\n    <wsdl:part element=\"tns:getCourseDetailsRequest\" name=\"getCourseDetailsRequest\">\n    </wsdl:part>\n  </wsdl:message>\n  <wsdl:message name=\"getCourseDetailsResponse\">\n    <wsdl:part element=\"tns:getCourseDetailsResponse\" name=\"getCourseDetailsResponse\">\n    </wsdl:part>\n  </wsdl:message>\n  <wsdl:portType name=\"CoursesPort\">\n    <wsdl:operation name=\"getCourseDetails\">\n      <wsdl:input message=\"tns:getCourseDetailsRequest\" name=\"getCourseDetailsRequest\">\n    </wsdl:input>\n      <wsdl:output message=\"tns:getCourseDetailsResponse\" name=\"getCourseDetailsResponse\">\n    </wsdl:output>\n    </wsdl:operation>\n  </wsdl:portType>\n  <wsdl:binding name=\"CoursesPortSoap11\" type=\"tns:CoursesPort\">\n    <soap:binding style=\"document\" transport=\"http://schemas.xmlsoap.org/soap/http\"/>\n    <wsdl:operation name=\"getCourseDetails\">\n      <soap:operation soapAction=\"\"/>\n      <wsdl:input name=\"getCourseDetailsRequest\">\n        <soap:body use=\"literal\"/>\n      </wsdl:input>\n      <wsdl:output name=\"getCourseDetailsResponse\">\n        <soap:body use=\"literal\"/>\n      </wsdl:output>\n    </wsdl:operation>\n  </wsdl:binding>\n  <wsdl:service name=\"CoursesPortService\">\n    <wsdl:port binding=\"tns:CoursesPortSoap11\" name=\"CoursesPortSoap11\">\n      <soap:address location=\"http://localhost:8080/ws\"/>\n    </wsdl:port>\n  </wsdl:service>\n</wsdl:definitions>\n```\n\n## Bootstrapping with Spring Initializr\n\nCreating a SOAP Web service with Spring Initializr is a cake walk. \n\nSpring Initializr [http://start.spring.io/](http://start.spring.io/){:target=\"_blank\"} is great tool to bootstrap your Spring Boot projects.\n\nYou can create a wide variety of projects using Spring Initializr.\n\n![Image](/images/Spring-Initializr-Web.png \"Web, Actuator and Developer Tools\")   \n\n![Image](/images/Spring-Initializr-Web-JPA.png \"Web, JPA, Hibernate and Developer Tools\")\n\nFollowing steps have to be done for a Web Services project\n\n- Launch Spring Initializr and choose the following\n  - Choose `com.in28minutes.springboot.soap.web.services.example` as Group\n  - Choose `spring-boot-tutorial-soap-web-services` as Artifact\n  - Choose following dependencies\n    - Web Services\n    - DevTools\n- Click Generate Project.\n- Import the project into Eclipse. File -> Import -> Existing Maven Project.\n\n> Do not forget to add Web Services as a dependency.\n\n## Creating a SOAP Web Service with Spring Boot\n\nWe will use a contract first approach and first define the XSD for the request and response.\n\n### Define XSD for Request and Response\n\n/src/main/resources/student-details.xsd\n\n```\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" \ntargetNamespace=\"http://in28minutes.com/students\" \nxmlns:tns=\"http://in28minutes.com/students\" elementFormDefault=\"qualified\">\n  \n  <xs:element name=\"GetStudentDetailsRequest\">\n    <xs:complexType>\n      <xs:sequence>\n        <xs:element name= \"id\" type=\"xs:int\"/>\n      </xs:sequence>  \n    </xs:complexType>\n  </xs:element>\n  \n  <xs:element name=\"GetStudentDetailsResponse\">\n    <xs:complexType>\n      <xs:sequence>\n        <xs:element name= \"StudentDetails\" type=\"tns:StudentDetails\"/>\n      </xs:sequence>  \n    </xs:complexType>\n  </xs:element>\n  \n  <xs:complexType name=\"StudentDetails\">\n    <xs:sequence>\n      <xs:element name=\"id\" type=\"xs:int\"/>\n      <xs:element name=\"name\" type=\"xs:string\"/>\n      <xs:element name=\"passportNumber\" type=\"xs:string\"/>\n    </xs:sequence>\n  </xs:complexType>\n  \n</xs:schema>\n```\n\nWe are create a simple xsd defining the request `GetStudentDetailsRequest` and the response `GetStudentDetailsResponse`.\n\nExample request and response are shown below\n\nRequest\n```xml\n<Envelope xmlns=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <Body>\n        <GetStudentDetailsRequest xmlns=\"http://in28minutes.com/students\">\n            <id>1</id>\n        </GetStudentDetailsRequest>\n    </Body>\n</Envelope>\n```\n\nResponse\n```xml\n<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <SOAP-ENV:Header/>\n    <SOAP-ENV:Body>\n        <ns2:GetStudentDetailsResponse xmlns:ns2=\"http://in28minutes.com/students\">\n            <ns2:StudentDetails>\n                <ns2:id>1</ns2:id>\n                <ns2:name>Adam</ns2:name>\n                <ns2:passportNumber>E1234567</ns2:passportNumber>\n            </ns2:StudentDetails>\n        </ns2:GetStudentDetailsResponse>\n    </SOAP-ENV:Body>\n</SOAP-ENV:Envelope>\n```\n\n### Java API for XML Binding (JAXB) and Configuring JAXB 2 Maven Plugin\n\nWhen we implement our code using Spring Web Services, following are the steps that are typically involved in processing a request\n- Map Request XML to Java Request Objects\n- Do the business logic and create the Java Response Objects\n- Map the Response Object to a Response XML and return the response.\n\nWe do mapping from XML to Java and Java to XML. This is done using JAXB - Java API for XML Binding.\n\nA Maven JAXB Plugin helps us in generating the Java objects based on the XSD. Lets add it to our pom.xml.\n\n```\n  <plugin>\n    <groupId>org.codehaus.mojo</groupId>\n    <artifactId>jaxb2-maven-plugin</artifactId>\n    <version>1.6</version>\n    <executions>\n      <execution>\n        <id>xjc</id>\n        <goals>\n          <goal>xjc</goal>\n        </goals>\n      </execution>\n    </executions>\n    <configuration>\n      <schemaDirectory>${project.basedir}/src/main/resources</schemaDirectory>\n      <outputDirectory>${project.basedir}/src/main/java</outputDirectory>\n      <clearOutputDir>false</clearOutputDir>\n    </configuration>\n  </plugin>\n\n```\n\nThree important configurations\n- `<schemaDirectory>${project.basedir}/src/main/resources</schemaDirectory>` - The location of XSD files.\n- `<outputDirectory>${project.basedir}/src/main/java</outputDirectory>` - Where do you want your Java code to be generated to?\n- `<clearOutputDir>false</clearOutputDir>` - Should the output directory be cleaned every time? We use false because we write our java source code in the same directory.\n\n### Configuring an Endpoint for GetCourseDetailsRequest\n\nEndpoint is the component that receives the request, initiates the processing and sends the response back.\n\nLet's first create a bean for storing the Student details.\n\n/src/main/java/com/in28minutes/springboot/soap/web/services/example/student/Student.java\n\n```java\npackage com.in28minutes.springboot.soap.web.services.example.student;\n\npublic class Student {\n  private Long id;\n  private String name;\n  private String passportNumber;\n\n  public Student() {\n    super();\n  }\n\n  public Student(Long id, String name, String passportNumber) {\n    super();\n    this.id = id;\n    this.name = name;\n    this.passportNumber = passportNumber;\n  }\n\n  public Student(String name, String passportNumber) {\n    super();\n    this.name = name;\n    this.passportNumber = passportNumber;\n  }\n\n  // Getters and Setters omitted\n  \n  @Override\n  public String toString() {\n    return String.format(\"Student [id=%s, name=%s, passportNumber=%s]\", id, name, passportNumber);\n  }\n\n}\n```\n\n/src/main/java/com/in28minutes/springboot/soap/web/services/example/student/StudentDetailsEndpoint.java\n\n```java\npackage com.in28minutes.springboot.soap.web.services.example.student;\n\nimport org.springframework.ws.server.endpoint.annotation.Endpoint;\nimport org.springframework.ws.server.endpoint.annotation.PayloadRoot;\nimport org.springframework.ws.server.endpoint.annotation.RequestPayload;\nimport org.springframework.ws.server.endpoint.annotation.ResponsePayload;\n\nimport com.in28minutes.students.GetStudentDetailsRequest;\nimport com.in28minutes.students.GetStudentDetailsResponse;\nimport com.in28minutes.students.StudentDetails;\n\n@Endpoint\npublic class StudentDetailsEndpoint {\n\n  @PayloadRoot(namespace = \"http://in28minutes.com/students\", localPart = \"GetStudentDetailsRequest\")\n  @ResponsePayload\n  public GetStudentDetailsResponse processCourseDetailsRequest(@RequestPayload GetStudentDetailsRequest request) {\n    GetStudentDetailsResponse response = new GetStudentDetailsResponse();\n    \n    StudentDetails studentDetails = new StudentDetails();\n    studentDetails.setId(request.getId());\n    studentDetails.setName(\"Adam\");\n    studentDetails.setPassportNumber(\"E1234567\");\n    \n    response.setStudentDetails(studentDetails);\n    \n    return response;\n  }\n\n}\n```\n\nFew important things to note:\n- `@Endpoint` - Annotation to indicate that this is a Web Service Endpoint.\n- `@PayloadRoot(namespace = \"http://in28minutes.com/students\", localPart = \"GetStudentDetailsRequest\")` - Defines the details of the request that this method would handle. We will handle `GetStudentDetailsRequest` with the given namespace.\n- `@ResponsePayload` - This method will return a response which would need to be converted to a response xml.\n- `public GetStudentDetailsResponse processCourseDetailsRequest(@RequestPayload GetStudentDetailsRequest request)` - Method would handle the request. `@RequestPayload` indicates that this is got from the request.\n\n### Configure the Message Dispatcher Servlet to receive the request\n\n/src/main/java/com/in28minutes/springboot/soap/web/services/example/WebServiceConfig.java\n\n```java\n@EnableWs\n@Configuration\npublic class WebServiceConfig {\n\n  @Bean\n  public ServletRegistrationBean messageDispatcherServlet(ApplicationContext context) {\n    MessageDispatcherServlet messageDispatcherServlet = new MessageDispatcherServlet();\n    messageDispatcherServlet.setApplicationContext(context);\n    messageDispatcherServlet.setTransformWsdlLocations(true);\n    return new ServletRegistrationBean(messageDispatcherServlet, \"/ws/*\");\n  }\n}\n```\n\nNotes\n- `@EnableWs` - Enable SOAP Web Service features in this Spring Boot application.\n- `@Configuration` - This class contains Apring configuration.\n- `@Bean public ServletRegistrationBean messageDispatcherServlet(ApplicationContext context)` - We would want to create message dispatcher servlet to act as a front controller.\n`return new ServletRegistrationBean(messageDispatcherServlet, \"/ws/*\")` - Configure the URL to the web services.\n\n### Spring Web Services Configuration to Generate WSDL\n\nLets add the `wsdl4j` dependency to our pom.xml.\n\n/pom.xml \n```\n    <dependency>\n      <groupId>wsdl4j</groupId>\n      <artifactId>wsdl4j</artifactId>\n    </dependency>\n```\n\nLet's enhance the `WebServiceConfig` to expose the WSDL.\n\n/src/main/java/com/in28minutes/springboot/soap/web/services/example/WebServiceConfig.java\n\n```java\n@Bean(name = \"students\")\npublic DefaultWsdl11Definition defaultWsdl11Definition(XsdSchema studentsSchema) {\n  DefaultWsdl11Definition definition = new DefaultWsdl11Definition();\n  definition.setPortTypeName(\"StudentPort\");\n  definition.setTargetNamespace(\"http://in28minutes.com/students\");\n  definition.setLocationUri(\"/ws\");\n  definition.setSchema(studentsSchema);\n  return definition;\n}\n\n@Bean\npublic XsdSchema studentsSchema() {\n  return new SimpleXsdSchema(new ClassPathResource(\"student-details.xsd\"));\n}\n```\n\nNotes\n- `@Bean(name = \"students\")` - A spring bean. The name of the bean is the name of the wsdl in the URL.\n- `DefaultWsdl11Definition defaultWsdl11Definition(XsdSchema studentsSchema)`\n- `definition.setTargetNamespace(\"http://in28minutes.com/students\")` - Default name space\n- `definition.setLocationUri(\"/ws\")` - The url where we want to expose the wsdl at.\n- `definition.setSchema(studentsSchema)` - We would create WSDL based on the xsd defined here - `new SimpleXsdSchema(new ClassPathResource(\"student-details.xsd\"))`\n\n\nURL of the WSDL - http://localhost:8080/ws/students.wsdl\n\n```\n\n<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><wsdl:definitions xmlns:wsdl=\"http://schemas.xmlsoap.org/wsdl/\" xmlns:sch=\"http://in28minutes.com/students\" xmlns:soap=\"http://schemas.xmlsoap.org/wsdl/soap/\" xmlns:tns=\"http://in28minutes.com/students\" targetNamespace=\"http://in28minutes.com/students\">\n  <wsdl:types>\n    <xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" elementFormDefault=\"qualified\" targetNamespace=\"http://in28minutes.com/students\">\n  \n  <xs:element name=\"GetStudentDetailsRequest\">\n    <xs:complexType>\n      <xs:sequence>\n        <xs:element name=\"id\" type=\"xs:int\"/>\n      </xs:sequence>  \n    </xs:complexType>\n  </xs:element>\n  \n  <xs:element name=\"GetStudentDetailsResponse\">\n    <xs:complexType>\n      <xs:sequence>\n        <xs:element name=\"StudentDetails\" type=\"tns:StudentDetails\"/>\n      </xs:sequence>  \n    </xs:complexType>\n  </xs:element>\n  \n  <xs:complexType name=\"StudentDetails\">\n    <xs:sequence>\n      <xs:element name=\"id\" type=\"xs:int\"/>\n      <xs:element name=\"name\" type=\"xs:string\"/>\n      <xs:element name=\"passportNumber\" type=\"xs:string\"/>\n    </xs:sequence>\n  </xs:complexType>\n  \n</xs:schema>\n  </wsdl:types>\n  <wsdl:message name=\"GetStudentDetailsResponse\">\n    <wsdl:part element=\"tns:GetStudentDetailsResponse\" name=\"GetStudentDetailsResponse\">\n    </wsdl:part>\n  </wsdl:message>\n  <wsdl:message name=\"GetStudentDetailsRequest\">\n    <wsdl:part element=\"tns:GetStudentDetailsRequest\" name=\"GetStudentDetailsRequest\">\n    </wsdl:part>\n  </wsdl:message>\n  <wsdl:portType name=\"StudentPort\">\n    <wsdl:operation name=\"GetStudentDetails\">\n      <wsdl:input message=\"tns:GetStudentDetailsRequest\" name=\"GetStudentDetailsRequest\">\n    </wsdl:input>\n      <wsdl:output message=\"tns:GetStudentDetailsResponse\" name=\"GetStudentDetailsResponse\">\n    </wsdl:output>\n    </wsdl:operation>\n  </wsdl:portType>\n  <wsdl:binding name=\"StudentPortSoap11\" type=\"tns:StudentPort\">\n    <soap:binding style=\"document\" transport=\"http://schemas.xmlsoap.org/soap/http\"/>\n    <wsdl:operation name=\"GetStudentDetails\">\n      <soap:operation soapAction=\"\"/>\n      <wsdl:input name=\"GetStudentDetailsRequest\">\n        <soap:body use=\"literal\"/>\n      </wsdl:input>\n      <wsdl:output name=\"GetStudentDetailsResponse\">\n        <soap:body use=\"literal\"/>\n      </wsdl:output>\n    </wsdl:operation>\n  </wsdl:binding>\n  <wsdl:service name=\"StudentPortService\">\n    <wsdl:port binding=\"tns:StudentPortSoap11\" name=\"StudentPortSoap11\">\n      <soap:address location=\"http://localhost:8080/ws\"/>\n    </wsdl:port>\n  </wsdl:service>\n</wsdl:definitions>\n```\n\n### Executing Request using Wizdler\n\n> Install the chrome plugin Wizdler.\n\nOnce you install wizdler and launch the wsdl url `http://localhost:8080/ws/students.wsdl`, you would see a small icon at the corner of the chrome browser, which you can click to see the services that are part of the wsdl. Go ahead and click the Wizdler icon and click the service `GetStudentDetails`\n\n![Image](/images/ExecutingSOAPRequestsWithWizdler-1.png \"ExecutingSOAPRequestsWithWizdler-1\") \n\nThis would launch a window to execute the request. Change the id to 1. Click Go button at the top right corner of the screen.\n\n![Image](/images/ExecutingSOAPRequestsWithWizdler-2.png \"ExecutingSOAPRequestsWithWizdler-2\")\n\nYou should see the response as shown below.\n\n![Image](/images/ExecutingSOAPRequestsWithWizdler-3.png \"ExecutingSOAPRequestsWithWizdler-3\")\n\nRequest\n```xml\n<Envelope xmlns=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <Body>\n        <GetStudentDetailsRequest xmlns=\"http://in28minutes.com/students\">\n            <id>1</id>\n        </GetStudentDetailsRequest>\n    </Body>\n</Envelope>\n```\n\nResponse\n```xml\n<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <SOAP-ENV:Header/>\n    <SOAP-ENV:Body>\n        <ns2:GetStudentDetailsResponse xmlns:ns2=\"http://in28minutes.com/students\">\n            <ns2:StudentDetails>\n                <ns2:id>1</ns2:id>\n                <ns2:name>Adam</ns2:name>\n                <ns2:passportNumber>E1234567</ns2:passportNumber>\n            </ns2:StudentDetails>\n        </ns2:GetStudentDetailsResponse>\n    </SOAP-ENV:Body>\n</SOAP-ENV:Envelope>\n```\n\n## More SOAP Methods\n\nYou can enhance the endpoint to expose more operations. The steps would be\n- Define the structure for Request and Response in XSD\n- Enhance the Endpoint to process the Request\n- Go ahead and test it.\n\nOther thing you can work on is to remove the hardcoding and add business logic and persistence stuff using JPA.\n\nGood Luck!\n\n## Complete Maven Project With Code Examples\n> Our Github repository has all the code examples - https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-tutorial-soap-web-services\n"
  },
  {
    "path": "_blog/articles/2018-01-02-spring-boot-example-projects-with-code-top20.md",
    "content": "---\nlayout:     post\ntitle:      20+ Spring Boot Projects with Code Examples\ndate:       2022-07-02 12:31:19\nsummary:    At in28Minutes, we have created more than 20 projects with code examples on Github. We have 50+ articles explaining these projects. These code examples will you learn and gain expertise at Spring Boot.\ncategories:  SpringBoot\npermalink:  /spring-boot-projects-with-code-examples\nimage: /images/spring-boot-application.png\n---\n\nThis guide will help you understand our 20+ projects with code examples on Github. We have 50+ articles explaining these projects.  These code examples will help beginners and experts to learn and gain expertise at Spring Boot. \n\n![Image](/images/Spring-Initializr-Web-JPA.png \"Web, JPA, Hibernate and Developer Tools\")\n\n## Spring Boot Projects - Code Examples on Github\n\n|Title|Category|URL|Github|\n| -------------------- |:------------------:|---------------:|--------------|\n|Creating REST Service with Spring Boot|REST API|[URL](http://www.springboottutorial.com/creating-rest-service-with-spring-boot){: target='_blank'}  |[Project Code on Github](https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-rest-services){:target='_blank'} |\n|Spring Initializr - Bootstrap Your Spring Boot Applications at F1 speed!|Spring Boot Basics|[URL](http://www.springboottutorial.com/spring-initialzr-bootstrap-spring-boot-applications){: target='_blank'}  | |\n|Unit Testing Rest Services with Spring Boot and JUnit|REST API|[URL](http://www.springboottutorial.com/unit-testing-for-spring-boot-rest-services){: target='_blank'}  |[Project Code on Github](https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-rest-services-with-unit-and-integration-tests){:target='_blank'} |\n|What is Spring Boot Auto Configuration?|Spring Boot Basics|[URL](http://www.springboottutorial.com/spring-boot-auto-configuration){: target='_blank'}  | |\n|Writing Integration Tests for Rest Services with Spring Boot|REST API|[URL](http://www.springboottutorial.com/integration-testing-for-spring-boot-rest-services){: target='_blank'}  |[Project Code on Github](https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-rest-services-with-unit-and-integration-tests){:target='_blank'} |\n|Introduction to Spring Boot Starter Parent|Spring Boot Basics|[URL](http://www.springboottutorial.com/spring-boot-starter-parent){: target='_blank'}  | |\n|Initializing Projects with Spring Boot Starters - Web and JPA|Spring Boot Basics|[URL](http://www.springboottutorial.com/spring-boot-starter-projects){: target='_blank'}  | |\n|Secure Rest Services and Web Applications with Spring Boot Security Starter|Spring Boot Basics|[URL](http://www.springboottutorial.com/securing-rest-services-with-spring-boot-starter-security){: target='_blank'}  |[Project Code on Github](https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-rest-services){:target='_blank'} |\n|Creating a Web Application with Spring Boot with JSP|Spring Boot Web Application|[URL](http://www.springboottutorial.com/creating-web-application-with-spring-boot){: target='_blank'}  |[Project Code on Github](https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-web-application){:target='_blank'} |\n|Spring Boot vs Spring MVC vs Spring - How do they compare?|Spring Boot Basics|[URL](http://www.springboottutorial.com/spring-boot-vs-spring-mvc-vs-spring){: target='_blank'}  | |\n|Spring Boot Tutorials for Beginners|Combined|[URL](http://www.springboottutorial.com/spring-boot-tutorials-for-beginners){: target='_blank'}  | |\n|Introduction to JPA and Hibernate using Spring Boot Data Jpa|Spring Data|[URL](http://www.springboottutorial.com/introduction-to-jpa-with-spring-boot-data-jpa){: target='_blank'}  | |\n|Introduction to Web Services - Restful and SOAP|REST API|[URL](http://www.springboottutorial.com/introduction-to-web-services-with-soap-and-rest){: target='_blank'}  | |\n|Integrating Spring Boot and Spring JDBC with H2 and Starter JDBC|Spring Data|[URL](http://www.springboottutorial.com/spring-boot-and-spring-jdbc-with-h2){: target='_blank'}  |[Project Code on Github](https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-2-jdbc-with-h2){:target='_blank'} |\n|Integrating Hibernate and JPA with Spring Boot|Spring Data|[URL](http://www.springboottutorial.com/hibernate-jpa-tutorial-with-spring-boot-starter-jpa){: target='_blank'}  |[Project Code on Github](https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-2-jpa-with-hibernate-and-h2){:target='_blank'} |\n|Spring Boot and iBatis with H2 - A Tutorial|Spring Data|[URL](http://www.springboottutorial.com/spring-boot-and-iBatis-with-h2-tutorial){: target='_blank'}  |[Project Code on Github](https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-2-myBatis-with-h2){:target='_blank'} |\n|Spring Boot and H2 in memory database - Why, What and How?|Spring Data|[URL](http://www.springboottutorial.com/spring-boot-and-h2-in-memory-database){: target='_blank'}  |[Project Code on Github](https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-2-jpa-with-hibernate-and-h2){:target='_blank'} |\n|Connecting Spring Boot with databases - MySQL and Oracle|Spring Data|[URL](http://www.springboottutorial.com/spring-boot-with-mysql-and-oracle){: target='_blank'}  | |\n|Introduction to Spring Data Rest - Create RESTful APIs at F1 Speed|Spring Data|[URL](http://www.springboottutorial.com/introduction-to-spring-data-rest-using-spring-boot){: target='_blank'}  |[Project Code on Github](https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-2-jpa-spring-data-rest){:target='_blank'} |\n|Introduction to Spring Data - Spring Data JPA, Spring Data REST and MongoDB|Spring Data|[URL](http://www.springboottutorial.com/introduction-to-spring-data-with-spring-boot){: target='_blank'}  | |\n|Spring Boot - Integrating with Bootstrap & jQuery using Web Jars|Spring Boot Web Application|[URL](http://www.springboottutorial.com/spring-boot-with-jquery-and-bootstrap-web-jars){: target='_blank'}  |[Project Code on Github](https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-web-application-bootstrap-jquery){:target='_blank'} |\n|Spring Boot - Integrating Static Content -  Javascript (JS) and CSS files |Spring Boot Web Application|[URL](http://www.springboottutorial.com/spring-boot-with-static-content-css-and-javascript-js){: target='_blank'}  |[Project Code on Github](https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-web-application-bootstrap-jquery){:target='_blank'} |\n|Creating a Spring Boot Project with Eclipse and Maven|Spring Boot Basics|[URL](http://www.springboottutorial.com/creating-spring-boot-project-with-eclipse-and-maven){: target='_blank'}  |[Project Code on Github](https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-2-rest-service-basic){:target='_blank'} |\n|Logging with Spring Boot - Logback, SLF4j and LOG4j2|Spring Boot Basics|[URL](http://www.springboottutorial.com/logging-with-spring-boot-logback-slf4j-and-log4j){: target='_blank'}  |[Project Code on Github](https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-tutorial-basics){:target='_blank'} |\n|Spring Boot - Unit Testing and Mocking with Mockito and JUnit|Spring Boot Unit Testing|[URL](http://www.springboottutorial.com/spring-boot-unit-testing-and-mocking-with-mockito-and-junit){: target='_blank'}  |[Project Code on Github](https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-tutorial-basics){:target='_blank'} |\n|Spring Boot Developer Tools and Live Reload - Maximize productivity with Hot Swapping|Spring Boot Basics|[URL](http://www.springboottutorial.com/spring-boot-developer-tools-and-live-reload){: target='_blank'}  |[Project Code on Github](https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-tutorial-basics){:target='_blank'} |\n|Implementing AOP with Spring Boot and AspectJ|Spring Boot Basics|[URL](http://www.springboottutorial.com/spring-boot-and-aop-with-spring-boot-starter-aop){: target='_blank'}  |[Project Code on Github](https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-tutorial-basics){:target='_blank'} |\n|Java Annotation and XML Bean Configurations with Spring Boot|Spring Boot Basics|[URL](http://www.springboottutorial.com/spring-boot-java-xml-context-configuration){: target='_blank'}  |[Project Code on Github](https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-tutorial-basics){:target='_blank'} |\n|Spring Boot and Embedded Servers - Tomcat, Jetty and Undertow|Spring Boot Basics|[URL](http://www.springboottutorial.com/spring-boot-with-embedded-servers-tomcat-jetty){: target='_blank'}  |[Project Code on Github](https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-tutorial-basics){:target='_blank'} |\n|Application Configuration with Spring Boot|Spring Boot Basics|[URL](http://www.springboottutorial.com/spring-boot-application-configuration){: target='_blank'}  |[Project Code on Github](https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-tutorial-basics-configuration){:target='_blank'} |\n|Spring Boot Application Configuration with YAML|Spring Boot Basics|[URL](http://www.springboottutorial.com/spring-boot-application-configuration-with-yaml){: target='_blank'}  |[Project Code on Github](https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-tutorial-basics-configuration){:target='_blank'} |\n|Spring Boot Profiles - Application Configuration made easy|Spring Boot Basics|[URL](http://www.springboottutorial.com/spring-boot-profiles){: target='_blank'}  |[Project Code on Github](https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-tutorial-basics-configuration){:target='_blank'} |\n|Spring, Spring Boot and Component Scan|Spring Boot Basics|[URL](http://www.springboottutorial.com/spring-boot-and-component-scan){: target='_blank'}  |[Project Code on Github](https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-tutorial-basics){:target='_blank'} |\n|Spring Boot Interview Questions|Interview Questions|[URL](http://www.springboottutorial.com/spring-boot-interview-questions){: target='_blank'}  | |\n|Spring Interview Questions|Interview Questions|[URL](http://www.springboottutorial.com/spring-interview-questions){: target='_blank'}  | |\n|Creating a CRUD REST API/Service with Spring Boot, JPA and Hibernate|REST API|[URL](http://www.springboottutorial.com/spring-boot-crud-rest-service-with-jpa-hibernate){: target='_blank'}  |[Project Code on Github](https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-2-rest-service-basic){:target='_blank'} |\n|Spring Boot Exception(Error) Handling for RESTful Services|REST API|[URL](http://www.springboottutorial.com/spring-boot-exception-handling-for-rest-services){: target='_blank'}  |[Project Code on Github](https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-2-rest-service-exception-handling){:target='_blank'} |\n|Implementing Validation for RESTful Services with Spring Boot|REST API|[URL](http://www.springboottutorial.com/spring-boot-validation-for-rest-services){: target='_blank'}  |[Project Code on Github](https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-2-rest-service-validation){:target='_blank'} |\n|Spring Boot - HATEOAS for RESTful Services|REST API|[URL](http://www.springboottutorial.com/spring-boot-hateoas-for-rest-services){: target='_blank'}  |[Project Code on Github](https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-2-rest-service-with-hateoas){:target='_blank'} |\n|Spring Boot and Content Negotiation - XML and JSON Representations |REST API|[URL](http://www.springboottutorial.com/spring-boot-content-negotiation-with-xml-json-representations){: target='_blank'}  |[Project Code on Github](https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-2-rest-service-content-negotiation){:target='_blank'} |\n|Spring Boot and Swagger - Documenting RESTful Services|REST API|[URL](http://www.springboottutorial.com/spring-boot-swagger-documentation-for-rest-services){: target='_blank'}  |[Project Code on Github](https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-2-rest-service-with-swagger){:target='_blank'} |\n|Versioning RESTful Services|REST API|[URL](http://www.springboottutorial.com/spring-boot-versioning-for-rest-services){: target='_blank'}  |[Project Code on Github](https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-2-rest-service-versioning){:target='_blank'} |\n|Creating a SOAP Web Service with Spring Boot Starter Web Services|SOAP Web Services|[URL](http://www.springboottutorial.com/creating-soap-web-service-with-spring-boot-web-services-starter){: target='_blank'}  |[Project Code on Github](https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-tutorial-soap-web-services){:target='_blank'} |\n\n"
  },
  {
    "path": "_blog/articles/2018-01-03-spring-boot-rest-api-example-projects-with-code.md",
    "content": "---\nlayout:     post\ntitle:      Spring Boot REST API Projects with Code Examples\ndate:       2022-07-02 12:31:19\nsummary:    At in28Minutes, we have created 8 Spring Boot REST API projects with code examples on Github. We have 10+ tutorial articles explaining these projects.  These code examples will help beginners and experts to learn and gain expertise at developing RESTful Services with Spring Boot.\ncategories:  SpringBoot\npermalink:  /spring-boot-rest-api-projects-with-code-examples\nimage: /images/spring-boot-application.png\n---\n\n![Image](/images/Spring-Initializr-Web.png \"Web, Actuator and Developer Tools\")   \n\nThis guide will help you understand the REST API projects with code examples on Github. We have a number of articles explaining these projects.  These code examples will help beginners and experts to learn and gain expertise at developing RESTful Services with Spring Boot. \n\n\n \n## Spring Boot REST API Projects - Code Examples on Github\n\nLet's look at the articles in the following sections\n- Projects Creating Basic REST API \n- Adding Unit and Integration Tests to RESTful Services\n- Securing RESTful Services\n- Basic RESTful Service Features\n- Advanced RESTful Service Features\n\n### Projects Creating Basic REST API\n\nWe explore couple of options of create RESTful Services with Spring Boot\n- Using Spring Boot Web Starter\n- Using Spring Data REST Starter\n\nUsing Spring Boot Web Starter, we have articles with \n- An article focusing on basics of a REST Service\n- A project exposing an end to end CRUD API for an entire Resource. The project uses JPA (Hibernate) to connect to a H2 in memory database.\n\n|Title|Category|URL|Github|\n| -------------------- |:------------------:|---------------:|--------------|\n|Creating REST Service with Spring Boot|REST API|[URL](http://www.springboottutorial.com/creating-rest-service-with-spring-boot){: target='_blank'}  |[Project Code on Github](https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-rest-services){:target='_blank'} |\n|Introduction to Spring Data Rest - Create RESTful APIs at F1 Speed|Spring Data|[URL](http://www.springboottutorial.com/introduction-to-spring-data-rest-using-spring-boot){: target='_blank'}  |[Project Code on Github](https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-2-jpa-spring-data-rest){:target='_blank'} |\n|Creating a CRUD REST API/Service with Spring Boot, JPA and Hibernate|REST API|[URL](http://www.springboottutorial.com/spring-boot-crud-rest-service-with-jpa-hibernate){: target='_blank'}  |[Project Code on Github](https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-2-rest-service-basic){:target='_blank'} |\n\n### Adding Unit and Integration Tests to RESTful Services\n\nAutomation Tests (including Unit and Integration Tests) are a key part of ensuring your services and APIs evolve over a time period.\n\nLet's consider a StudentController which depends on StudentService.\n\nIn the unit test\n- We will mock out the StudentService using Mockito\n- We will use Mock MVC framework to launch only StudentController. \n\n> A key part of unit testing is to restrict the scope to a minimum. In this unit test, we want to test only the methods in `StudentController`.\n\nIn the integration test\n\n- We will launch the complete Spring Boot application using `@SpringBootTest`\n- We will invoke the service methods using `TestRestTemplate`\n- We will assert the results using a great JSON assert framework - `org.skyscreamer.jsonassert.JSONAssert`\n\n> A key part of integration testing is testing all the layers in the application.\n\n|Title|Category|URL|Github|\n| -------------------- |:------------------:|---------------:|--------------|\n|Unit Testing Rest Services with Spring Boot and JUnit|REST API|[URL](http://www.springboottutorial.com/unit-testing-for-spring-boot-rest-services){: target='_blank'}  |[Project Code on Github](https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-rest-services-with-unit-and-integration-tests){:target='_blank'} |\n|Writing Integration Tests for Rest Services with Spring Boot|REST API|[URL](http://www.springboottutorial.com/integration-testing-for-spring-boot-rest-services){: target='_blank'}  |[Project Code on Github](https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-rest-services-with-unit-and-integration-tests){:target='_blank'} |\n|Spring Boot - Unit Testing and Mocking with Mockito and JUnit|Spring Boot Unit Testing|[URL](http://www.springboottutorial.com/spring-boot-unit-testing-and-mocking-with-mockito-and-junit){: target='_blank'}  |[Project Code on Github](https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-tutorial-basics){:target='_blank'} |\n\n### Securing RESTful Services\n\nIn the article below, we implement basic security for a REST API.\n\n|Title|Category|URL|Github|\n| -------------------- |:------------------:|---------------:|--------------|\n|Secure Rest Services and Web Applications with Spring Boot Security Starter|Spring Boot Basics|[URL](http://www.springboottutorial.com/securing-rest-services-with-spring-boot-starter-security){: target='_blank'}  |[Project Code on Github](https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-rest-services){:target='_blank'} |\n\n\n### Basic RESTful Service Features\n\nGreat REST APIs have\n- Awesome Exception Handling - You would want to return the right response with the exact response status based on the situation.\n- Proper Validation - You would want to validate the right stuff and return a message which helps the consumer understand what failed.\n- Current Documentation - A Consumer need to understand how to use your API. Great documentation makes your consumer and your job easy.\n\nArticles below explore these features in depth.\n\n|Title|Category|URL|Github|\n| -------------------- |:------------------:|---------------:|--------------|\n|Spring Boot Exception(Error) Handling for RESTful Services|REST API|[URL](http://www.springboottutorial.com/spring-boot-exception-handling-for-rest-services){: target='_blank'}  |[Project Code on Github](https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-2-rest-service-exception-handling){:target='_blank'} |\n|Implementing Validation for RESTful Services with Spring Boot|REST API|[URL](http://www.springboottutorial.com/spring-boot-validation-for-rest-services){: target='_blank'}  |[Project Code on Github](https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-2-rest-service-validation){:target='_blank'} |\n|Spring Boot and Swagger - Documenting RESTful Services|REST API|[URL](http://www.springboottutorial.com/spring-boot-swagger-documentation-for-rest-services){: target='_blank'}  |[Project Code on Github](https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-2-rest-service-with-swagger){:target='_blank'} |\n\n### REST API Advanced Features\n\nAt the next level, REST APIs have \n- HATEOAS - HATEOAS stands for \"Hypermedia as the engine of application state\". When some details of a resource are requested, you will provide the resource details as well as details of related resources and the possible actions you can perform on the resource. For example, when requesting information about a facebook user, a REST service can return the following\n    - user details \n    - Links to get his recent posts\n    - Links to get his recent comments \n    - Links to retrieve his friend’s list.\n- Content Negotiation - Why should JSON be the only data exchange format to be supported? What if your consumer loves (or is stuck with) XML? Content Negotiation helps you support multiple data exchange formats for your RESTful API.\n- Versioning - As your API evolves with your and your consumer needs, you would have the need to have multiple versions of the same Resource API. How do you handle that?\n\nArticles below explore these features in depth.\n\n|Spring Boot - HATEOAS for RESTful Services|REST API|[URL](http://www.springboottutorial.com/spring-boot-hateoas-for-rest-services){: target='_blank'}  |[Project Code on Github](https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-2-rest-service-with-hateoas){:target='_blank'} |\n|Spring Boot and Content Negotiation - XML and JSON Representations |REST API|[URL](http://www.springboottutorial.com/spring-boot-content-negotiation-with-xml-json-representations){: target='_blank'}  |[Project Code on Github](https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-2-rest-service-content-negotiation){:target='_blank'} |\n|Versioning RESTful Services|REST API|[URL](http://www.springboottutorial.com/spring-boot-versioning-for-rest-services){: target='_blank'}  |[Project Code on Github](https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-2-rest-service-versioning){:target='_blank'} |\n\n\n"
  },
  {
    "path": "_blog/articles/2018-01-04-getting-started-with-spring-boot-projects-with-code.md",
    "content": "---\nlayout:     post\ntitle:      Getting Started with Spring Boot - 7 things a beginner should know!\ndate:       2022-07-01 12:31:19\nsummary:    Spring Boot is a tricky framework to understand. In this tutorial for beginnners with Spring Boot, we will look at the basics of Spring Boot and help you understand the important concepts - Architecture, Starter Projects, Auto Configuration and Starter Parent. We will look at the architecture of Spring Boot and explore a variety of resources - tutorials, courses and videos - we created to help you get started with Spring Boot effectively.\ncategories:  SpringBoot\npermalink:  /introduction-to-spring-boot-for-beginners\nimage: /images/spring-boot-feature.png\n---\n\n![Image](/images/Spring-Initializr-Web.png \"Web, Actuator and Developer Tools\")   \n\nSpring Boot is a tricky framework to understand. In this tutorial for beginnners with Spring Boot, we will look at the basics of Spring Boot and help you understand the important concepts - Starter Projects, Auto Configuration and Starter Parent. We will explore a variety of resources - tutorials, courses and videos - we created to help you get started with Spring Boot effectively. \n\n\n\n## Understand Spring Boot Architecture\n\nBuilding blocks of Spring Boot are \n- Spring Boot Starter Projects\n- Spring Boot Starter Parent\n- Auto Configuration\n\nWe will start with understanding what Spring Boot wants to achieve by comparing it with Spring and Spring MVC. \n\nOnce you understand that you would be in a good position to start with the building blocks of Spring Boot. \n\nLet's get started on the roller coaster ride of Spring Boot\n\n## Spring Boot vs Spring MVC vs Spring - How do they compare?\n\nMost important thing to understand is\n\n> Spring Boot does not compete with Spring or Spring MVC. It makes it easy to use them.\n\n##### Spring Framework\n> Most important feature of Spring Framework is Dependency Injection. At the core of all Spring Modules is Dependency Injection or IOC Inversion of Control.\n\nWhen DI or IOC is used properly, we can develop loosely coupled applications. And loosely coupled applications can be easily unit tested.\n\n##### Spring MVC\n\n> Spring MVC Framework provides decoupled way of developing web applications. With simple concepts like Dispatcher Servlet, ModelAndView and View Resolver, it makes it easy to develop web applications.\n\n##### Spring Boot\n\nThe problem with Spring and Spring MVC is the amount of configuration that is needed.\n\n```\n  <bean\n        class=\"org.springframework.web.servlet.view.InternalResourceViewResolver\">\n        <property name=\"prefix\">\n            <value>/WEB-INF/views/</value>\n        </property>\n        <property name=\"suffix\">\n            <value>.jsp</value>\n        </property>\n  </bean>\n  \n  <mvc:resources mapping=\"/webjars/**\" location=\"/webjars/\"/>\n```\n\nSpring Boot solves this problem through a combination of  Auto Configuration and Starter Projects. Spring Boot also provide a few non functional features to make building production ready applications faster. \n\nFollowing article digs deeper and give you a full blown comparison between Spring, Spring MVC and Spring Boot.\n\n|Title|Category|URL|Github|\n| -------------------- |:------------------:|---------------:|--------------|\n|Spring Boot vs Spring MVC vs Spring - How do they compare?|Spring Boot Basics|[URL](http://www.springboottutorial.com/spring-boot-vs-spring-mvc-vs-spring){: target='_blank'}  | |\n\n## Spring Boot Auto Configuration\n\nSpring and Spring MVC applications have a lot of XML or Java Bean Configuration.\n\nSpring Boot brings in new thought process around this. \n\n> Can we bring more intelligence into this? When a spring mvc jar is added into an application, can we auto configure some beans automatically? \n\n- How about auto configuring a Data Source if Hibernate jar is on the classpath? \n- How about auto configuring a Dispatcher Servlet if Spring MVC jar is on the classpath?\n\nThere would be provisions to override the default auto configuration. \n\n> Spring Boot looks at a) Frameworks available on the CLASSPATH b) Existing configuration for the application. Based on these, Spring Boot provides basic configuration needed to configure the application with these frameworks. This is called `Auto Configuration`.  \n\nFollowing article explores Auto Configuration in depth.\n\n|Title|Category|URL|Github|\n| -------------------- |:------------------:|---------------:|--------------|\n|What is Spring Boot Auto Configuration?|Spring Boot Basics|[URL](http://www.springboottutorial.com/spring-boot-auto-configuration){: target='_blank'}  | |\n\n## Spring Boot Starter Projects\n\nHere's what the Spring Boot documentations says about starters.\n\n> Starters are a set of convenient dependency descriptors that you can include in your application. You get a one-stop-shop for all the Spring and related technology that you need, without having to hunt through sample code and copy paste loads of dependency descriptors. For example, if you want to get started using Spring and JPA for database access, just include the spring-boot-starter-data-jpa dependency in your project, and you are good to go.\n\nLet's consider an example starter - Spring Boot Starter Web.\n\nIf you want to develop a web application or an application to expose restful services, Spring Boot Start Web is the starter to pick.\n\nFollowing screenshot shows the different dependencies that are added in to our application when you add Spring Boot Start Web into the dependencies of your project.\n\n![Image](/images/SpringBootStarterWeb-Dependencies.png \"Spring Boot Starter Web - Dependencies\")\n\nThis is a wide variety of components that are typically used to develop web applications. Spring Boot Starter Web brings them together and provides a simple approach to use them. \n- Spring - core, beans, context, aop\n- Web MVC - (Spring MVC)\n- Jackson - for JSON Binding \n- Validation - Hibernate Validator, Validation API\n- Embedded Servlet Container - Tomcat\n- Logging - logback, slf4j\n\n> Any typical web application would use all these dependencies. Spring Boot Starter Web comes pre packaged with these. As a developer, I would not need to worry about either these dependencies or their compatible versions.  \n\nSpring Boot provides a wide range of starter projects. Spring Initializr suppports all of them and more. Among a varied range of starter projects and options supported are:\n\n- spring-boot-starter-web-services : For building applications exposing SOAP Web Services\n- spring-boot-starter-web - Build Web applications & RESTful applications\n- spring-boot-starter-test - Write great Unit  and Integration Tests\n- spring-boot-starter-jdbc - Traditional JDBC Applications\n- spring-boot-starter-hateoas - Make your services more RESTful by adding HATEOAS features\n- spring-boot-starter-security - Authentication and Authorization using Spring Security\n- spring-boot-starter-data-jpa -  Spring Data JPA with Hibernate\n- spring-boot-starter-cache - Enabling Spring Framework’s caching support\n- spring-boot-starter-data-rest - Expose Simple REST Services using Spring Data REST\n\nYou can explore starter projects in depth with the article below.\n\n|Title|Category|URL|Github|\n| -------------------- |:------------------:|---------------:|--------------|\n|Initializing Projects with Spring Boot Starters - Web and JPA|Spring Boot Basics|[URL](http://www.springboottutorial.com/spring-boot-starter-projects){: target='_blank'}  | |\n\n## Spring Boot Starter Parent\n\nAll Spring Boot projects typically use spring-boot-starter-parent as the parent in pom.xml.\n\n```\n    <parent>\n        <groupId>org.springframework.boot</groupId>\n        <artifactId>spring-boot-starter-parent</artifactId>\n        <version>2.3.1.RELEASE</version>\n    </parent>\n```\n\nParent Poms allow you to manage the following things for multiple child projects and modules:\n- Configuration - Java Version and Other Properties\n- Depedency Management - Version of dependencies\n- Default Plugin Configuration\n\nYou can read more about Spring Boot Starter Parent at the article below.\n\n|Title|Category|URL|Github|\n| -------------------- |:------------------:|---------------:|--------------|\n|Introduction to Spring Boot Starter Parent|Spring Boot Basics|[URL](http://www.springboottutorial.com/spring-boot-starter-parent){: target='_blank'}  | |\n\n## Spring Initializr - Create Spring Boot Projects at F1 Speed\n\nSpring Initializr [http://start.spring.io/](http://start.spring.io/){:target=\"_blank\"} is great tool to bootstrap your Spring Boot projects.\n\nIt allows you to create varied range of Spring Boot based Applications from a very simple UI. Some of the types of applications you can bootstrap are:\n\n- Web Applications\n- Restful Applications\n- Batch Applications\n\nLet's take the example of creating a Web application with Spring Initializr.\n\n![Image](/images/Spring-Initializr-Web.png \"Web, Actuator and Developer Tools\")   \n\nAs shown in the image above, following steps have to be done\n\n- Launch Spring Initializr [http://start.spring.io/](http://start.spring.io/){:target=\"_blank\"} and choose the following\n  - Choose `com.in28minutes.springboot` as Group\n  - Choose `student-services` as Artifact\n  - Choose following dependencies\n    - Web\n- Click Generate Project button at the bottom of the page.\n- Import the project into Eclipse.\n\nFollowing article delves more into Spring Initializr.\n\n|Title|Category|URL|Github|\n| -------------------- |:------------------:|---------------:|--------------|\n|Spring Initializr - Bootstrap Your Spring Boot Applications at F1 speed!|Spring Boot Basics|[URL](http://www.springboottutorial.com/spring-initialzr-bootstrap-spring-boot-applications){: target='_blank'}  | |\n\n## Spring Boot and Embedded Servers\n\nWhen we create an application deployable, we would embed the server (for example, tomcat) inside the deployable. \n> For example, for a Spring Boot Application, you can generate an application jar which contains Embedded Tomcat. You can run a web application as a normal Java application!\n\nEmbedded server implies that our deployable unit contains the binaries for the server (example, tomcat.jar).\n\nLet's take a quick look at the dependencies for `spring-boot-starter-web`\n\n```\n<dependency>\n  <groupId>org.springframework.boot</groupId>\n  <artifactId>spring-boot-starter-tomcat</artifactId>\n  <version>2.3.1.RELEASE</version>\n  <scope>compile</scope>\n</dependency>\n```\n\nYou can see that by default Starter Web includes a dependency on starter tomcat. \n- Tomcat is the default embedded server with Spring Boot. \n- Spring Boot also supports Jetty and Undertow.\n\nFollowing article explores more about Embedded Servers.\n\n|Title|Category|URL|Github|\n| -------------------- |:------------------:|---------------:|--------------|\n|Spring Boot and Embedded Servers - Tomcat, Jetty and Undertow|Spring Boot Basics|[URL](http://www.springboottutorial.com/spring-boot-with-embedded-servers-tomcat-jetty){: target='_blank'}  |[Project Code on Github](https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-tutorial-basics){:target='_blank'} |\n\n\n## Spring Data\n\nFrom http://projects.spring.io/spring-data/\n> Spring Data's mission is to provide a familiar and consistent, Spring-based programming model for data access while still retaining the special traits of the underlying data store. It makes it easy to use data access technologies, relational and non-relational databases, map-reduce frameworks, and cloud-based data services.\n\nTo make it simpler, Spring Data provides Abstractions (interfaces) you can use irrespective of underlying data source. \n\nSome of the sub modules in Spring Data are \n- Spring Data JPA - Relational Databases\n- Spring Data Mongodb\n- Spring Data Rest - Expose awesome REST API around Spring Data Repositories\n\nFollowing articles digs deeper into Spring Data.\n\n|Title|Category|URL|Github|\n| -------------------- |:------------------:|---------------:|--------------|\n|Introduction to Spring Data - Spring Data JPA, Spring Data REST and MongoDB|Spring Data|[URL](http://www.springboottutorial.com/introduction-to-spring-data-with-spring-boot){: target='_blank'}  | |\n\n"
  },
  {
    "path": "_blog/articles/2018-01-05-spring-boot-microservices-part1-top20.md",
    "content": "---\nlayout:     post\ntitle:      Microservices with Spring Boot and Java - Part 1 - Getting Started\ndate:       2022-07-01 12:31:19\nsummary:    Let's learn the basics of microservices and microservices architectures. We will also start looking at a basic implementation of a microservice with Spring Boot. We will create a couple of microservices and get them to talk to each other using Eureka Naming Server and Ribbon for Client Side Load Balancing. In part 1 of this series, lets get introduced to the concept of microservices and understand how to create great microservices with Spring Boot and Spring Cloud.\ncategories:  SpringBootMicroservices\npermalink:  /creating-microservices-with-spring-boot-part-1-getting-started\nimage: /images/microservices-category.png\n---\n\nThis guide will help you learn the basics of microservices and microservices architectures. We will also start looking at a basic implementation of a microservice with Spring Boot. \n\n![Image](/images/Spring-Boot-Microservice-1-CCS-FS.png \"Spring-Boot-Microservice-1-CCS-FS\") \n\n> We will create a couple of microservices and get them to talk to each other using Eureka Naming Server and Ribbon for Client Side Load Balancing. \n\nThis is a 5 Part Article Series\n\nMicroservices with Spring Boot \n- Current Part - Part 1 - Getting Started with Microservices Architecture\n- Part 2 - [Creating Forex Microservice](http://www.springboottutorial.com/creating-microservices-with-spring-boot-part-2-forex-microservice){:target=\"_blank\"}\n- Part 3 - [Creating Currency Conversion Microservice](http://www.springboottutorial.com/creating-microservices-with-spring-boot-part-3-currency-conversion-microservice){:target=\"_blank\"}\n- Part 4 - [Using Ribbon for Load Balancing](http://www.springboottutorial.com/microservices-with-spring-boot-part-4-ribbon-for-load-balancing){:target=\"_blank\"}\n- Part 5 - [Using Eureka Naming Server](http://www.springboottutorial.com/microservices-with-spring-boot-part-5-eureka-naming-server){:target=\"_blank\"}\n\nIn part 1 of this series, lets get introduced to the concept of microservices and understand how to create great microservices with Spring Boot and Spring Cloud.\n \n## You will learn\n- What is a Monolith?\n- What is a Microservice?\n- What are the Challenges with Microservices?\n- How does Spring Boot and Spring Cloud make developing Microservices easy?\n- How to implement client side load balancing with Ribbon?\n- How to implement a Naming Server (Eureka Naming Server)?\n- How to connect the microservices with Naming Server and Ribbon?\n\n\n\n## Microservices Overview - A Big Picture\n\nIn this series of articles, we would create two microservices:\n- Forex Service - Abbreviated as FS\n- Currency Conversion Service - Abbreviated as CCS\n\n> Do not worry if you are not clear about a few things. The idea is to give a big picture before we get our hands dirty and create the microservices step by step\n\n\n\n\n### Forex Service\n\nForex Service (FS) is the Service Provider. It provides currency exchange values for various currency. Let's assume that it talks to a Forex Exchange and provides the current conversion value between currencies.\n\nAn example request and response is shown below:\n\nGET to http://localhost:8000/currency-exchange/from/EUR/to/INR\n\n```json\n{\n  id: 10002,\n  from: \"EUR\",\n  to: \"INR\",\n  conversionMultiple: 75,\n  port: 8000,\n}\n```\n\nThe request above is the currency exchange value for EUR to INR. In the response, conversionMultiple is 75.\n\n> We will talk about port in the response a little later.\n\n### Currency Conversion Service\n\nCurrency Conversion Service (CCS) can convert a bucket of currencies into another currency. It uses the Forex Service to get current currency exchange values. CCS is the Service Consumer.\n\nAn example request and response is shown below:\n\nGET to http://localhost:8100/currency-converter/from/EUR/to/INR/quantity/10000\n\n```json\n{\n  id: 10002,\n  from: \"EUR\",\n  to: \"INR\",\n  conversionMultiple: 75,\n  quantity: 10000,\n  totalCalculatedAmount: 750000,\n  port: 8000,\n}\n```\n\nThe request above is to find the value of 10000 EUR in INR. The totalCalculatedAmount is 750000 INR.\n\nThe diagram below shows the communication between CCS and FS.\n\n![Image](/images/Spring-Boot-Microservice-1-CCS-FS.png \"Spring-Boot-Microservice-1-CCS-FS\") \n\n### Eureka Naming Server and Ribbon\n\nBased on the load, we can have multiple instances of the Currency Conversion Service and the Forex Service running.\n\n![Image](/images/Spring-Boot-Microservice-2-CCS.png \"Spring-Boot-Microservice-2-CCS.png\")\n\n![Image](/images/Spring-Boot-Microservice-3-FSInstances.png \"Spring-Boot-Microservice-3-FSInstances.png\")\n\nAnd the number of instances for each service might vary with time. Below picture shows a specific instance where there are 5 instances of the Forex Service.\n\n![Image](/images/Spring-Boot-Microservice-4-5FSInstances.png \"Spring-Boot-Microservice-4-5FSInstances.png\")\n\nWhat needs to happen in the above situation is load should be uniformly distributed among these 5 instances.\n\n![Image](/images/Spring-Boot-Microservice-5-CCSToFS5instances.png \"Spring-Boot-Microservice-5-CCSToFS5instances.png\")\n\nIn this series of articles, we will use Ribbon for Load Balancing and Eureka Naming server for registering all microservices.\n\n![Image](/images/Spring-Boot-Microservice-6-EurekaNamingServer-Deployment.png \"Spring-Boot-Microservice-6-EurekaNamingServer-Deployment.png\")\n\n> Do not worry if you are not clear about a few things. The idea is to give a big picture before we get our hands dirty and create the microservices step by step\n\n## What is a Monolith Application?\n\nHave you ever worked in a project\n- Which is released (taken to production) once every few months\n- Which has a wide range of features and functionality\n- Which has a team of more than 50 working for it\n- Where debugging problems is a big challenge\n- Where bringing in new technology and new process is almost impossible\n\nThese are typical characteristics of a Monolith applications.\n\n> Monolith applications are typically huge - more 100,000 line of code. In some instances even more than million lines of code.\n\nMonoliths are characterized by\n- Large Application Size\n- Long Release Cycles\n- Large Teams\n\nTypical Challenges include\n- Scalability Challenges\n- New Technology Adoption\n- New Processes - Agile?\n- Difficult to Automation Test\n- Difficult ot Adapt to Modern Development Practices\n- Adapting to Device Explosion\n\n\n## Microservices\n\nMicroservice Architectures evolved as a solution to the scalability and innovotation challenges with Monolith architectures.\n\nThere are a number of definitions proposed for Microservices\n\n> Small autonomous services that work together - Sam Newman\n\n> Developing a single application as a suite of small services each running in its own process and communicating with lightweight mechanisms, often an HTTP resource API. These services are built around business capabilities and independently deployable by fully automated deployment machinery. There is a bare minimum of centralized management of these services, which may be written in different programming languages and use different data storage technologies - James Lewis and Martin Fowler\n\nWhile there is no single accepted definition for microservices, for me, there are a few important characteristics:\n- REST - Built around RESTful Resources. Communication can be HTTP or event based.\n- Small Well Chosen Deployable Units - Bounded Contexts\n- Cloud Enabled - Dynamic Scaling\n\n\n## How does Microservice Architecture look like?\n\nThis is how a monolith would look like. One application for everything.\n![](images/MonolithApplication.png)\n\nThis is how the same application would look like when developed using Microservices Architecture.\n![](images/MicroservicesArchitectureSplit.png)\n\nMicroservice Architectures involve a number of small, well designed, components interacting with messages.\n![](images/Microservices-Chain-Example.png)\n\n## Advantages of Microservices\n\nAdvantages\n- New Technology & Process Adaption becomes easier. You can try new technologies with the newer microservices that we create.\n- Faster Release Cycles\n- Scaling with Cloud\n\n## Challenges with Microservice Architectures\n\nWhile developing a number of smaller components might look easy, there are a number of inherent complexities that are associated with microservices architectures.\n\nLets look at some of the challenges:\n- Quick Setup needed : You cannot spend a month setting up each microservice. You should be able to create microservices quickly.\n- Automation : Because there are a number of smaller components instead of a monolith, you need to automate everything - Builds, Deployment, Monitoring etc. \n- Visibility : You now have a number of smaller components to deploy and maintain. Maybe 100 or maybe 1000 components. You should be able to monitor and identify problems automatically. You need great visibility around all the components.\n- Bounded Context : Deciding the boundaries of a microservice is not an easy task. Bounded Contexts from Domain Driven Design is a good starting point. Your understanding of the domain evolves over a period of time. You need to ensure that the microservice boundaries evolve.\n- Configuration Management : You need to maintain configurations for hundreds of components across environments. You would need a Configuration Management solution\n- Dynamic Scale Up and Scale Down : The advantages of microservices will only be realized if your applications can scaled up and down easily in the cloud.\n- Pack of Cards : If a microservice at the bottom of the call chain fails, it can have knock on effects on all other microservices. Microservices should be fault tolerant by Design.\n- Debugging : When there is a problem that needs investigation, you might need to look into multiple services across different components. Centralized Logging and Dashboards are essential to make it easy to debug problems.\n- Consistency : You cannot have a wide range of tools solving the same problem. While it is important to foster innovation, it is also important to have some decentralized governance around the languages, platforms, technology and tools used for implementing/deploying/monitoring microservices.\n## Solutions to Challenges with Microservice Architectures\n\n### Spring Boot\n\n> Enable building production ready applications quickly\n\nProvide non-functional features \n  - embedded servers  (easy deployment with containers)\n  - metrics (monitoring)\n  - health checks (monitoring)\n  - externalized configuration\n\n### Spring Cloud\n\n> Spring Cloud provides solutions to cloud enable your microservices. It leverages and builds on top of some of the Cloud solutions opensourced by Netflix (Netflix OSS).\n\n#### Important Spring Cloud Modules\n\nDynamic Scale Up and Down. Using a combination of \n- Naming Server (Eureka)\n- Ribbon (Client Side Load Balancing)\n- Feign (Easier REST Clients)\n\nVisibility and Monitoring with\n- Zipkin Distributed Tracing\n- Netflix API Gateway\n\nConfiguration Management with\n- Spring Cloud Config Server\n\nFault Tolerance with\n- Hystrix\n\n## Microservice Series of Articles\n\nIn this series of articles, we would create two microservices:\n- Forex Service - Abbreviated as FS\n- Currency Conversion Service - Abbreviated as CCS\n\nThe diagram below shows the communication between CCS and FS. We would establish communication between these two components.\n\n![Image](/images/Spring-Boot-Microservice-1-CCS-FS.png \"Spring-Boot-Microservice-1-CCS-FS\") \n\nWe would want to be able to dynamically scale up and scale down the number of instances of each of these services.\n\n![Image](/images/Spring-Boot-Microservice-2-CCS.png \"Spring-Boot-Microservice-2-CCS.png\")\n![Image](/images/Spring-Boot-Microservice-3-FSInstances.png \"Spring-Boot-Microservice-3-FSInstances.png\")\n\nAnd the number of instances for each service might vary with time. Below picture shows a specific instance where there are 5 instances of the Forex Service.\n\n![Image](/images/Spring-Boot-Microservice-4-5FSInstances.png \"Spring-Boot-Microservice-4-5FSInstances.png\")\n\nImplementing a solution for dynamic scale up and down needs to answer two questions\n- How does the Currency Conversion Service (CCS) know how many instances of Forex Service (FS) are active?\n- How does the Currency Conversion Service (CCS) distribute the load between the active instances.\n\nBecause we want this to be dynamic, we cannot hardcode the urls of FS in CCS. Thats why we bring in a Naming Server.\n\n![Image](/images/Spring-Boot-Microservice-6-EurekaNamingServer-Deployment.png \"Spring-Boot-Microservice-6-EurekaNamingServer-Deployment.png\")\n\nAll instances of the components (CCS and FS) register with the Eureka Naming Server. When FS needs to call the CCS, it will ask Eureka Naming Server for the active instances. We will use Ribbon to do Client Side Load Balancing between the different instances of FS.\n\nA high level sequence diagram of what would happen when there is a request from CCS to FS is shown below:\n![Image](/images/Spring-Boot-Microservice-7-Eureka-Sequence-Diagram.png \"Spring-Boot-Microservice-7-Eureka-Sequence-Diagram.png\")\n\n## Next Steps\n\nContinue Learning Microservices with Spring Boot \n- Current Part - Part 1 - Getting Started with Microservices Architecture\n- Part 2 - [Creating Forex Microservice](http://www.springboottutorial.com/creating-microservices-with-spring-boot-part-2-forex-microservice){:target=\"_blank\"}\n- Part 3 - [Creating Currency Conversion Microservice](http://www.springboottutorial.com/creating-microservices-with-spring-boot-part-3-currency-conversion-microservice){:target=\"_blank\"}\n- Part 4 - [Using Ribbon for Load Balancing](http://www.springboottutorial.com/microservices-with-spring-boot-part-4-ribbon-for-load-balancing){:target=\"_blank\"}\n- Part 5 - [Using Eureka Naming Server](http://www.springboottutorial.com/microservices-with-spring-boot-part-5-eureka-naming-server){:target=\"_blank\"}\n"
  },
  {
    "path": "_blog/articles/2018-01-06-spring-boot-microservices-part2.md",
    "content": "---\nlayout:     post\ntitle:      Microservices with Spring Boot and Java - Part 2 - Architecture of Forex Microservice\ndate:       2022-07-01 12:31:19\nsummary:    Let's learn the basics of microservices and microservices architectures. We will also start looking at a basic implementation of a microservice with Spring Boot. We will create a couple of microservices and get them to talk to each other using Eureka Naming Server and Ribbon for Client Side Load Balancing. In part 2 of this series, we will focus on Creating Forex Microservice.\ncategories:  SpringBootMicroservices\npermalink:  /creating-microservices-with-spring-boot-part-2-forex-microservice\nimage: /images/microservices-category.png\n---\n\n![Image](/images/Spring-Initializr-Web-JPA.png \"Web, JPA, Hibernate and Developer Tools\")\n\nLet's learn the basics of microservices and microservices architectures. We will also start looking at a basic implementation of a microservice with Spring Boot. We will create a couple of microservices and get them to talk to each other using Eureka Naming Server and Ribbon for Client Side Load Balancing. \n\nHere is the Microservice Series Outline:\nMicroservices with Spring Boot \n- Part 1 - [Getting Started with Microservices Architecture](http://www.springboottutorial.com/creating-microservices-with-spring-boot-part-1-getting-started){:target=\"_blank\"}\n- Current Part - Part 2 - Creating Forex Microservice\n- Part 3 - [Creating Currency Conversion Microservice](http://www.springboottutorial.com/creating-microservices-with-spring-boot-part-3-currency-conversion-microservice){:target=\"_blank\"}\n- Part 4 - [Using Ribbon for Load Balancing](http://www.springboottutorial.com/microservices-with-spring-boot-part-4-ribbon-for-load-balancing){:target=\"_blank\"}\n- Part 5 - [Using Eureka Naming Server](http://www.springboottutorial.com/microservices-with-spring-boot-part-5-eureka-naming-server){:target=\"_blank\"}\n\nThis is part 2 of this series. In this part, we will focus on creating the Forex Microservice.\n \n## You will learn\n- How to create a microservice with Spring Boot?\n- How to create a JPA Entity and Resource?\n- How to get Spring MVC, Spring Boot, JPA, Hibernate and H2 to work together?\n\n\n\n## Resources Overview\n\nForex Service (FS) is the Service Provider. It provides currency exchange values for various currency. Let's assume that it talks to a Forex Exchange and provides the current conversion value between currencies.\n\nAn example request and response is shown below:\n\nGET to http://localhost:8000/currency-exchange/from/EUR/to/INR\n\n```json\n{\n  id: 10002,\n  from: \"EUR\",\n  to: \"INR\",\n  conversionMultiple: 75,\n  port: 8000,\n}\n```\n\nThe request above is the currency exchange value for EUR to INR. In the response, conversionMultiple is 75.\n\n## Project Code Structure\n\nFollowing screenshot shows the structure of the project we will create.\n\n![Image](/images/spring-boot-microservice-forex-service-project-structure.png \"Project Structure\") \n\nA few details:\n- SpringBootMicroserviceForexServiceApplication.java - The Spring Boot Application class generated with Spring Initializer. This class acts as the launching point for application.\n- `pom.xml` - Contains all the dependencies needed to build this project. We will use Spring Boot Starter Web and JPA.\n- `ExchangeValue.java` - Exchange Value Entity\n- `ExchangeValueRepository.java` - ExchangeValue JPA Repository. This is created using Spring Data JpaRepository.\n- `ForexController.java` - Spring Rest Controller exposing the forex conversion service.\n- data.sql - Initial data for the exchange_value table. Spring Boot would execute this script after the tables are created from the entities.\n\n## Tools you will need\n- Maven 3.0+ is your build tool\n- Your favorite IDE. We use Eclipse.\n- JDK 1.8+\n\n## Complete Maven Project With Code Examples\n> Our Github repository has all the code examples - https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-basic-microservice\n\n## Bootstrapping with Spring Initializr\n\nCreating a Microservice with Spring Initializr is a cake walk. \n\nSpring Initializr [http://start.spring.io/](http://start.spring.io/){:target=\"_blank\"} is great tool to bootstrap your Spring Boot projects.\n\nYou can create a wide variety of projects using Spring Initializr.\n\n![Image](/images/Spring-Initializr-Web-JPA.png \"Web, JPA, Hibernate and Developer Tools\")\n\nFollowing steps have to be done for a Web Services project\n\n- Launch Spring Initializr and choose the following\n  - Choose `com.in28minutes.springboot.microservice.example.forex` as Group\n  - Choose `spring-boot-microservice-forex-service` as Artifact\n  - Choose following dependencies\n    - Web\n    - DevTools\n    - Starter JPA\n    - H2\n- Click Generate Project.\n- Import the project into Eclipse. File -> Import -> Existing Maven Project.\n\n## Creating Exchange Value Entity\n\n```\n@Entity\npublic class ExchangeValue {\n  \n  @Id\n  private Long id;\n  \n  @Column(name=\"currency_from\")\n  private String from;\n  \n  @Column(name=\"currency_to\")\n  private String to;\n  \n  private BigDecimal conversionMultiple;\n  private int port;\n  \n  public ExchangeValue() {\n    \n  }\n  \n\n  public ExchangeValue(Long id, String from, String to, BigDecimal conversionMultiple) {\n    super();\n    this.id = id;\n    this.from = from;\n    this.to = to;\n    this.conversionMultiple = conversionMultiple;\n  }\n\n  public Long getId() {\n    return id;\n  }\n\n  public String getFrom() {\n    return from;\n  }\n\n  public String getTo() {\n    return to;\n  }\n\n  public BigDecimal getConversionMultiple() {\n    return conversionMultiple;\n  }\n  \n  public int getPort() {\n    return port;\n  }\n\n  public void setPort(int port) {\n    this.port = port;\n  }\n\n}\n```\n\nImportant things to note:\n - ```@Entity```: Specifies that the class is an entity. This annotation is applied to the entity class.\n - ```@Id```: Specifies the primary key of an entity.\n\n\n### Creating Exchange Value JPA Repository\n\n/spring-boot-microservice-forex-service/src/main/java/com/in28minutes/springboot/microservice/example/forex/ExchangeValueRepository.java\n\n```java\npackage com.in28minutes.springboot.microservice.example.forex;\nimport org.springframework.data.jpa.repository.JpaRepository;\n\npublic interface ExchangeValueRepository extends \n    JpaRepository<ExchangeValue, Long>{\n  ExchangeValue findByFromAndTo(String from, String to);\n}\n```\n\nNotes\n- `public interface ExchangeValueRepository extends JpaRepository<ExchangeValue, Long>` - We are extending JpaRepository using two generics - ExchangeValue & Long. ExchangeValue is the entity that is being managed and the primary key of ExchangeValue is Long.\n- `ExchangeValue findByFromAndTo(String from, String to);`  - We would want to query the conversion value from one currency to another. We are defining a query method for it.\n\n## Create the Resource - ForexController\n\n/spring-boot-microservice-forex-service/src/main/java/com/in28minutes/springboot/microservice/example/forex/ForexController.java\n\n```java\n@RestController\npublic class ForexController {\n  \n  @Autowired\n  private Environment environment;\n  \n  @Autowired\n  private ExchangeValueRepository repository;\n  \n  @GetMapping(\"/currency-exchange/from/{from}/to/{to}\")\n  public ExchangeValue retrieveExchangeValue\n    (@PathVariable String from, @PathVariable String to){\n    \n    ExchangeValue exchangeValue = \n        repository.findByFromAndTo(from, to);\n    \n    exchangeValue.setPort(\n        Integer.parseInt(environment.getProperty(\"local.server.port\")));\n    \n    return exchangeValue;\n  }\n}\n```\n\nNotes\n- `@RestController public class ForexController {` - Create a Controller to expose a Rest Service\n- `@Autowired private Environment environment` - We would want to return the server port back. This will help us identify which instance service is giving the response back.\n- `@Autowired private ExchangeValueRepository repository` - Autowire the repository.\n- `ExchangeValue exchangeValue = repository.findByFromAndTo(from, to)` - Get the exchange value from the database.\n- `exchangeValue.setPort(Integer.parseInt(environment.getProperty(\"local.server.port\")))` - Get the port from environment and set it into the response bean.\n\n## Configure Application Name and a few other configuration\n\n/spring-boot-microservice-forex-service/src/main/resources/application.properties\n\n```properties\nspring.application.name=forex-service\nserver.port=8000\n\nspring.jpa.show-sql=true\nspring.datasource.url=jdbc:h2:mem:testdb\nspring.data.jpa.repositories.bootstrap-mode=default\nspring.h2.console.enabled=true\n\n```\n\nWe are assigning a port of 8000 for this application and enabling debug logging.\n\n## Insert some test data into data.sql\n\nLet's insert some test data by creating a file called data.sql. Spring Boot Auto Configuration ensures that this data is loaded up when application starts up.\n\n/spring-boot-microservice-forex-service/src/main/resources/data.sql\n\n```\ninsert into exchange_value(id,currency_from,currency_to,conversion_multiple,port)\nvalues(10001,'USD','INR',65,0);\ninsert into exchange_value(id,currency_from,currency_to,conversion_multiple,port)\nvalues(10002,'EUR','INR',75,0);\ninsert into exchange_value(id,currency_from,currency_to,conversion_multiple,port)\nvalues(10003,'AUD','INR',25,0);\n```\n\n## Test Forex Microservice\n\nGET to http://localhost:8000/currency-exchange/from/EUR/to/INR\n\n```json\n{\n  id: 10002,\n  from: \"EUR\",\n  to: \"INR\",\n  conversionMultiple: 75,\n  port: 8000,\n}\n```\n\n## Next Steps\n\nMicroservices with Spring Boot \n- Part 1 - [Getting Started with Microservices Architecture](http://www.springboottutorial.com/creating-microservices-with-spring-boot-part-1-getting-started){:target=\"_blank\"}\n- Current Part - Part 2 - Creating Forex Microservice\n- Part 3 - [Creating Currency Conversion Microservice](http://www.springboottutorial.com/creating-microservices-with-spring-boot-part-3-currency-conversion-microservice){:target=\"_blank\"}\n- Part 4 - [Using Ribbon for Load Balancing](http://www.springboottutorial.com/microservices-with-spring-boot-part-4-ribbon-for-load-balancing){:target=\"_blank\"}\n- Part 5 - [Using Eureka Naming Server](http://www.springboottutorial.com/microservices-with-spring-boot-part-5-eureka-naming-server){:target=\"_blank\"}\n\n"
  },
  {
    "path": "_blog/articles/2018-01-07-spring-boot-microservices-part3.md",
    "content": "---\nlayout:     post\ntitle:      Microservices with Spring Boot and Java - Part 3 - Example 2 - Creating Currency Conversion Microservice\ndate:       2022-07-01 12:31:19\nsummary:    Let's learn the basics of microservices and microservices architectures. We will also start looking at a basic implementation of a microservice with Spring Boot. We will create a couple of microservices and get them to talk to each other using Eureka Naming Server and Ribbon for Client Side Load Balancing. In part 3 of this series, we will focus on Creating Currency Conversion Microservice.\ncategories:  SpringBootMicroservices\npermalink:  /creating-microservices-with-spring-boot-part-3-currency-conversion-microservice\nimage: /images/microservices-category.png\n---\n\n![Image](/images/Spring-Boot-Microservice-1-CCS-FS.png \"Spring-Boot-Microservice-1-CCS-FS\") \n\nLet's learn the basics of microservices and microservices architectures. We will also start looking at a basic implementation of a microservice with Spring Boot. We will create a couple of microservices and get them to talk to each other using Eureka Naming Server and Ribbon for Client Side Load Balancing. \n\n![Image](/images/spring-boot-microservice-currency-conversion-service-project-structure.png \"Project Structure\") \n\nHere is the Microservice Series Outline:\nMicroservices with Spring Boot \n- Part 1 - [Getting Started with Microservices Architecture](http://www.springboottutorial.com/creating-microservices-with-spring-boot-part-1-getting-started){:target=\"_blank\"}\n- Part 2 - [Creating Forex Microservice](http://www.springboottutorial.com/creating-microservices-with-spring-boot-part-2-forex-microservice){:target=\"_blank\"}\n- Current Part - Part 3 - Creating Currency Conversion Microservice\n- Part 4 - [Using Ribbon for Load Balancing](http://www.springboottutorial.com/microservices-with-spring-boot-part-4-ribbon-for-load-balancing){:target=\"_blank\"}\n- Part 5 - [Using Eureka Naming Server](http://www.springboottutorial.com/microservices-with-spring-boot-part-5-eureka-naming-server){:target=\"_blank\"}\n\nThis is part 3 of this series. In this part, we will focus on creating the Currency Conversion Microservice.\n \n## You will learn\n- How to create a microservice with Spring Boot?\n- How to use RestTemplate to execute a REST Service?\n- How to use Feign to execute a REST Service?\n- What are the advantages of Feign over RestTemplate?\n\n\n\n## Resources Overview\n\nCurrency Conversion Service (CCS) can convert a bucket of currencies into another currency. It uses the Forex Service to get current currency exchange values. CCS is the Service Consumer.\n\nAn example request and response is shown below:\n\nGET to http://localhost:8100/currency-converter/from/EUR/to/INR/quantity/10000\n\n```json\n{\n  id: 10002,\n  from: \"EUR\",\n  to: \"INR\",\n  conversionMultiple: 75,\n  quantity: 10000,\n  totalCalculatedAmount: 750000,\n  port: 8000,\n}\n```\n\nThe request above is to find the value of 10000 EUR in INR. The totalCalculatedAmount is 750000 INR.\n\nThe diagram below shows the communication between CCS and FS.\n\n![Image](/images/Spring-Boot-Microservice-1-CCS-FS.png \"Spring-Boot-Microservice-1-CCS-FS\") \n\n## Project Code Structure\n\nFollowing screenshot shows the structure of the project we will create.\n\n![Image](/images/spring-boot-microservice-currency-conversion-service-project-structure.png \"Project Structure\") \n\nA few details:\n- `SpringBootMicroserviceCurrencyConversionApplication.java` - The Spring Boot Application class generated with Spring Initializer. This class acts as the launching point for application.\n- `pom.xml` - Contains all the dependencies needed to build this project. We will use Spring Boot Starter Web.\n- `CurrencyConversionBean.java` - Bean to hold the response that we want to send out.\n- `CurrencyExchangeServiceProxy.java` - This will be the Feign Proxy to call the Forex Service.\n- `CurrencyConversionController.java` - Spring Rest Controller exposing the currency conversion service. This will use the `CurrencyExchangeServiceProxy` to call the Forex Service.\n\n## Tools you will need\n- Maven 3.0+ is your build tool\n- Your favorite IDE. We use Eclipse.\n- JDK 1.8+\n\n## Complete Maven Project With Code Examples\n> Our Github repository has all the code examples - https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-basic-microservice\n\n## Bootstrapping with Spring Initializr\n\nCreating a Microservice with Spring Initializr is a cake walk. \n\nSpring Initializr [http://start.spring.io/](http://start.spring.io/){:target=\"_blank\"} is great tool to bootstrap your Spring Boot projects.\n\nYou can create a wide variety of projects using Spring Initializr.\n\n![Image](/images/Spring-Initializr-Web-JPA.png \"Web, JPA, Hibernate and Developer Tools\")\n\nFollowing steps have to be done for a Web Services project\n\n- Launch Spring Initializr and choose the following\n  - Choose `com.in28minutes.springboot.microservice.example.currencyconversion` as Group\n  - Choose `spring-boot-microservice-currency-conversion` as Artifact\n  - Choose following dependencies\n    - Web\n    - DevTools\n    - Feign\n- Click Generate Project.\n- Import the project into Eclipse. File -> Import -> Existing Maven Project.\n\n> Do not forget to choose Feign in the dependencies\n\n## Creating CurrencyConversionBean\n\nThis is a simple bean for creating the response.\n\n```\npublic class CurrencyConversionBean {\n  private Long id;\n  private String from;\n  private String to;\n  private BigDecimal conversionMultiple;\n  private BigDecimal quantity;\n  private BigDecimal totalCalculatedAmount;\n  private int port;\n\n  public CurrencyConversionBean() {\n\n  }\n\n  public CurrencyConversionBean(Long id, String from, String to, BigDecimal conversionMultiple, BigDecimal quantity,\n      BigDecimal totalCalculatedAmount, int port) {\n    super();\n    this.id = id;\n    this.from = from;\n    this.to = to;\n    this.conversionMultiple = conversionMultiple;\n    this.quantity = quantity;\n    this.totalCalculatedAmount = totalCalculatedAmount;\n    this.port = port;\n  }\n\n```\n\n## Implement REST Client with RestTemplate\n\nThe code below shows the implementation of REST Client to call the forex service and process the response. As you can see there is a lot of code that needs to be written for making a simple service call.\n\n```\n@RestController\npublic class CurrencyConversionController {\n\n  private Logger logger = LoggerFactory.getLogger(this.getClass());\n\n  @GetMapping(\"/currency-converter/from/{from}/to/{to}/quantity/{quantity}\")\n  public CurrencyConversionBean convertCurrency(@PathVariable String from, @PathVariable String to,\n      @PathVariable BigDecimal quantity) {\n\n    Map<String, String> uriVariables = new HashMap<>();\n    uriVariables.put(\"from\", from);\n    uriVariables.put(\"to\", to);\n\n    ResponseEntity<CurrencyConversionBean> responseEntity = new RestTemplate().getForEntity(\n        \"http://localhost:8000/currency-exchange/from/{from}/to/{to}\", CurrencyConversionBean.class,\n        uriVariables);\n\n    CurrencyConversionBean response = responseEntity.getBody();\n\n    return new CurrencyConversionBean(response.getId(), from, to, response.getConversionMultiple(), quantity,\n        quantity.multiply(response.getConversionMultiple()), response.getPort());\n  }\n\n```\n\n## Configure application name and port\n\n/spring-boot-microservice-currency-conversion-service/src/main/resources/application.properties\n\n```properties\nspring.application.name=currency-conversion-service\nserver.port=8100\n```\n\nWe are assigning an application name as well as a default port of `8100`.\n\n## Testing the Microservice\n\nStart the Spring Boot Application by launching SpringBootMicroserviceCurrencyConversionApplication.java\n\n\nGET to `http://localhost:8100/currency-converter/from/EUR/to/INR/quantity/10000`\n\n```json\n{\n  id: 10002,\n  from: \"EUR\",\n  to: \"INR\",\n  conversionMultiple: 75,\n  quantity: 10000,\n  totalCalculatedAmount: 750000,\n  port: 8000,\n}\n```\n\n## Creating a Feign Proxy\n\nFeign provide a better alternative to RestTemplate to call REST API.\n\n/spring-boot-microservice-currency-conversion-service/src/main/java/com/in28minutes/springboot/microservice/example/currencyconversion/CurrencyExchangeServiceProxy.java\n\n```java\npackage com.in28minutes.springboot.microservice.example.currencyconversion;\n\nimport org.springframework.cloud.openfeign.FeignClient;\nimport org.springframework.cloud.netflix.ribbon.RibbonClient;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.PathVariable;\n\n@FeignClient(name=\"forex-service\" url=\"localhost:8000\")\npublic interface CurrencyExchangeServiceProxy {\n  @GetMapping(\"/currency-exchange/from/{from}/to/{to}\")\n  public CurrencyConversionBean retrieveExchangeValue\n    (@PathVariable(\"from\") String from, @PathVariable(\"to\") String to);\n}\n```\n\nWe first define a simple proxy. \n- `@FeignClient(name=\"forex-service\" url=\"localhost:8100\")` - Declares that this is a Feign Client and the url at which forex-service is present is `localhost:8100`\n- `@GetMapping(\"/currency-exchange/from/{from}/to/{to}\")` - URI of the service we would want to consume\n\n\n## Using Feign Proxy from the Microservice Controller\n\nMaking the call using the proxy is very simple. You can see it in action in the code below. All that we had to do was to autowire the proxy and use to call the method.\n\n```\n  @Autowired\n  private CurrencyExchangeServiceProxy proxy;\n\n  @GetMapping(\"/currency-converter-feign/from/{from}/to/{to}/quantity/{quantity}\")\n  public CurrencyConversionBean convertCurrencyFeign(@PathVariable String from, @PathVariable String to,\n      @PathVariable BigDecimal quantity) {\n\n    CurrencyConversionBean response = proxy.retrieveExchangeValue(from, to);\n\n    logger.info(\"{}\", response);\n\n    return new CurrencyConversionBean(response.getId(), from, to, response.getConversionMultiple(), quantity,\n        quantity.multiply(response.getConversionMultiple()), response.getPort());\n  }\n\n```\n\n## Enable Feign Clients\n\nBefore we are able to use Feign, we need to enable it by using `@EnableFeignClients` annotation on the appropriate package where the client proxies are defined.\n\n```\n@SpringBootApplication\n@EnableFeignClients(\"com.in28minutes.springboot.microservice.example.currencyconversion\")\n@EnableDiscoveryClient\npublic class SpringBootMicroserviceCurrencyConversionApplication {\n\n  public static void main(String[] args) {\n    SpringApplication.run(SpringBootMicroserviceCurrencyConversionApplication.class, args);\n  }\n}\n```\n\n## Testing the Microservice using Feign\n\nGET to http://localhost:8100/currency-converter-feign/from/EUR/to/INR/quantity/10000\n\n```json\n{\n  id: 10002,\n  from: \"EUR\",\n  to: \"INR\",\n  conversionMultiple: 75,\n  quantity: 10000,\n  totalCalculatedAmount: 750000,\n  port: 8000,\n}\n```\n\n## Summary\n\nWe have now created two microservices and established communication between them.\n\n![Image](/images/Spring-Boot-Microservice-1-CCS-FS.png \"Spring-Boot-Microservice-1-CCS-FS\") \n\nHowever, we are hardcoding the url for FS in CCS. That means when new instances of FS are launched up we have no way to distribute load between them.\n\n\n## Next Steps\n\nIn the next part, we will enable client side load distribution using Ribbon.\n\nMicroservices with Spring Boot \n- Part 1 - [Getting Started with Microservices Architecture](http://www.springboottutorial.com/creating-microservices-with-spring-boot-part-1-getting-started){:target=\"_blank\"}\n- Part 2 - [Creating Forex Microservice](http://www.springboottutorial.com/creating-microservices-with-spring-boot-part-2-forex-microservice){:target=\"_blank\"}\n- Current Part - Part 3 - Creating Currency Conversion Microservice\n- Part 4 - [Using Ribbon for Load Balancing](http://www.springboottutorial.com/microservices-with-spring-boot-part-4-ribbon-for-load-balancing){:target=\"_blank\"}\n- Part 5 - [Using Eureka Naming Server](http://www.springboottutorial.com/microservices-with-spring-boot-part-5-eureka-naming-server){:target=\"_blank\"}\n\n\n## Complete Maven Project With Code Examples\n> Our Github repository has all the code examples - https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-basic-microservice\n"
  },
  {
    "path": "_blog/articles/2018-01-08-spring-boot-microservices-part4.md",
    "content": "---\nlayout:     post\ntitle:      Microservices with Spring Boot - Part 4 - Load Balancing Example - Using Ribbon\ndate:       2022-07-01 12:31:19\nsummary:    Let's learn the basics of microservices and microservices architectures. We will also start looking at a basic implementation of a microservice with Spring Boot. We will create a couple of microservices and get them to talk to each other using Eureka Naming Server and Ribbon for Client Side Load Balancing. In part 4 of this series, we will focus on using Ribbon to do Load Balancing.\ncategories:  SpringBootMicroservices\npermalink:  /microservices-with-spring-boot-part-4-ribbon-for-load-balancing\nimage: /images/microservices-category.png\n---\n\nLet's learn the basics of microservices and microservices architectures. We will also start looking at a basic implementation of a microservice with Spring Boot. We will create a couple of microservices and get them to talk to each other using Eureka Naming Server and Ribbon for Client Side Load Balancing. \n\n![Image](/images/Spring-Boot-Microservice-1-CCS-FS.png \"Spring-Boot-Microservice-1-CCS-FS\") \n\n\nHere is the Microservice Series Outline:\nMicroservices with Spring Boot \n- Part 1 - [Getting Started with Microservices Architecture](http://www.springboottutorial.com/creating-microservices-with-spring-boot-part-1-getting-started){:target=\"_blank\"}\n- Part 2 - [Creating Forex Microservice](http://www.springboottutorial.com/creating-microservices-with-spring-boot-part-2-forex-microservice){:target=\"_blank\"}\n- Part 3 - [Creating Currency Conversion Microservice](http://www.springboottutorial.com/creating-microservices-with-spring-boot-part-3-currency-conversion-microservice){:target=\"_blank\"}\n- Current Part - Part 4 - Using Ribbon for Load Balancing\n- Part 5 - [Using Eureka Naming Server](http://www.springboottutorial.com/microservices-with-spring-boot-part-5-eureka-naming-server){:target=\"_blank\"}\n\nThis is part 4 of this series. In this part, we will focus on using Ribbon for Load Balancing.\n \n## You will learn\n- What is the need for Load Balancing?\n- What is Ribbon?\n- How do you add Ribbon to your Spring Boot Project?\n- How do you enable and configure Ribbon to do Load Balancing?\n\n\n\n## Microservices Overview\n\nIn the previous two parts, we created the microservices and established communication between them.\n\nGET to http://localhost:8100/currency-converter-feign/from/EUR/to/INR/quantity/10000\n\n```json\n{\n  id: 10002,\n  from: \"EUR\",\n  to: \"INR\",\n  conversionMultiple: 75,\n  quantity: 10000,\n  totalCalculatedAmount: 750000,\n  port: 8000,\n}\n```\n\n> When we execute the above service, you would see that a request is also sent over to the forex-service.\n\nThats cool!\n\nWe have now created two microservices and established communication between them.\n\n![Image](/images/Spring-Boot-Microservice-1-CCS-FS.png \"Spring-Boot-Microservice-1-CCS-FS\") \n\nHowever, we are hardcoding the url for FS in CCS component `CurrencyExchangeServiceProxy`. \n\n```\n@FeignClient(name=\"forex-service\" url=\"localhost:8000\")\npublic interface CurrencyExchangeServiceProxy {\n  @GetMapping(\"/currency-exchange/from/{from}/to/{to}\")\n  public CurrencyConversionBean retrieveExchangeValue\n    (@PathVariable(\"from\") String from, @PathVariable(\"to\") String to);\n}\n\n```\n\nThat means when new instances of Forex Service are launched up, we have no way to distributing load to them.\n\nIn this part, let's now enable client side load distribution using Ribbon.\n\n\n## Tools you will need\n- Maven 3.0+ is your build tool\n- Your favorite IDE. We use Eclipse.\n- JDK 1.8+\n\n## Complete Maven Project With Code Examples\n> Our Github repository has all the code examples - https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-basic-microservice\n\n## Enabling Ribbon\n\nAdd Ribbon Dependency to pom.xml\n```\n    <dependency>\n      <groupId>org.springframework.cloud</groupId>\n      <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>\n    </dependency>\n```\n\nEnable RibbonClient in CurrencyExchangeServiceProxy\n\n```\n@FeignClient(name=\"forex-service\")\n@RibbonClient(name=\"forex-service\")\npublic interface CurrencyExchangeServiceProxy {\n```\n\nConfigure the instances in application.properties\n```\nforex-service.ribbon.listOfServers=localhost:8000,localhost:8001\n```\n\n## Launch up Forex Service on 8001\n\nIn the above step, we configured ribbon to distribute load to instances. However, we do not have any instance of Forex Service running on 8001.\n\nWe can launch it up by configuring a launch configuration as shown in the figure below.\n\n![Image](/images/Spring-Boot-Microservice-91-LauchingFSOn8081.png \"Spring-Boot-Microservice-91-LauchingFSOn8081\")\n\n## Ribbon in Action\n\nCurrently we have the following service up and running\n- Currency Conversion Micro Service (CCS) on 8100\n- Two instances of Forex MicroService on 8000 and 8001\n\nNow you would see that the requests to CCS would get distributed between the two instances of Forex Microservice by Ribbon\n\n### Request 1\nGET to http://localhost:8100/currency-converter-feign/from/EUR/to/INR/quantity/10000\n\n```json\n{\n  id: 10002,\n  from: \"EUR\",\n  to: \"INR\",\n  conversionMultiple: 75,\n  quantity: 10000,\n  totalCalculatedAmount: 750000,\n  port: 8000,\n}\n```\n\n### Request 2\nGET to http://localhost:8100/currency-converter-feign/from/EUR/to/INR/quantity/10000\n\n```json\n{\n  id: 10002,\n  from: \"EUR\",\n  to: \"INR\",\n  conversionMultiple: 75,\n  quantity: 10000,\n  totalCalculatedAmount: 750000,\n  port: 8001,\n}\n```\n\nYou can see that the port numbers in the two responses are different.\n\n## Summary\n\nWe have now created two microservices and established communication between them.\n\n![Image](/images/Spring-Boot-Microservice-1-CCS-FS.png \"Spring-Boot-Microservice-1-CCS-FS\") \n\nWe are using Ribbon to distribute load between the two instances of Forex Service.\n\nHowever, we are hardcoding the urls of both instances of  FS in CCS. That means every time there is a new instance of FS, we would need to change the configuration of CCS. Thats not cool. \n\nIn the next part, we will use Eureka Naming Server to fix this problem.\n\n## Next Steps\n\nContinue the Microservice Series - Microservices with Spring Boot \n- Part 1 - [Getting Started with Microservices Architecture](http://www.springboottutorial.com/creating-microservices-with-spring-boot-part-1-getting-started){:target=\"_blank\"}\n- Part 2 - [Creating Forex Microservice](http://www.springboottutorial.com/creating-microservices-with-spring-boot-part-2-forex-microservice){:target=\"_blank\"}\n- Part 3 - [Creating Currency Conversion Microservice](http://www.springboottutorial.com/creating-microservices-with-spring-boot-part-3-currency-conversion-microservice){:target=\"_blank\"}\n- Current Part - Part 4 - Using Ribbon for Load Balancing\n- Part 5 - [Using Eureka Naming Server](http://www.springboottutorial.com/microservices-with-spring-boot-part-5-eureka-naming-server){:target=\"_blank\"}\n\n\n\n## Complete Maven Project With Code Examples\n> Our Github repository has all the code examples - https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-basic-microservice\n"
  },
  {
    "path": "_blog/articles/2018-01-09-spring-boot-microservices-part5.md",
    "content": "---\nlayout:     post\ntitle:      Microservices with Spring Boot - Part 5 - Example using Eureka Naming Server\ndate:       2022-07-01 12:31:19\nsummary:    Let's learn the basics of microservices and microservices architectures. We will also start looking at a basic implementation of a microservice with Spring Boot. We will create a couple of microservices and get them to talk to each other using Eureka Naming Server and Ribbon for Client Side Load Balancing. In part 5 of this series, we will focus on enabling Eureka Naming Server and have the microservices communicate with it.\ncategories:  SpringBootMicroservices\npermalink:  /microservices-with-spring-boot-part-5-eureka-naming-server\nimage: /images/microservices-category.png\n---\n\nLet's learn the basics of microservices and microservices architectures. We will also start looking at a basic implementation of a microservice with Spring Boot. We will create a couple of microservices and get them to talk to each other using Eureka Naming Server and Ribbon for Client Side Load Balancing. \n\n![Image](/images/Spring-Boot-Microservice-1-CCS-FS.png \"Spring-Boot-Microservice-1-CCS-FS\") \n\n\nHere is the Microservice Series Outline:\nMicroservices with Spring Boot \n- Part 1 - [Getting Started with Microservices Architecture](http://www.springboottutorial.com/creating-microservices-with-spring-boot-part-1-getting-started){:target=\"_blank\"}\n- Part 2 - [Creating Forex Microservice](http://www.springboottutorial.com/creating-microservices-with-spring-boot-part-2-forex-microservice){:target=\"_blank\"}\n- Part 3 - [Creating Currency Conversion Microservice](http://www.springboottutorial.com/creating-microservices-with-spring-boot-part-3-currency-conversion-microservice){:target=\"_blank\"}\n- Part 4 - [Using Ribbon for Load Balancing](http://www.springboottutorial.com/microservices-with-spring-boot-part-4-ribbon-for-load-balancing){:target=\"_blank\"}\n- Current Part - Part 5 - Using Eureka Naming Server\n\nThis is part 5 of this series. In this part, we will focus on enabling Eureka Naming Server and have the microservices communicate with it.\n \n## You will learn\n- What is the need for Naming Server?\n- What is Eureka?\n- How does Naming Server enable location transparancy between microservices?\n\n\n## Microservices Overview\n\nIn Parts 2 & 3, we created two microservices and established communication between them.\n\n![Image](/images/Spring-Boot-Microservice-1-CCS-FS.png \"Spring-Boot-Microservice-1-CCS-FS\") \n\nIn Part 4, we used Ribbon to distribute load between the two instances of Forex Service.\n\nHowever, we are hardcoding the urls of both instances of Forex Service in CCS. \n\n```\nforex-service.ribbon.listOfServers=localhost:8000,localhost:8001\n```\n\nThat means every time there is a new instance of FS, we would need to change the configuration of CCS. Thats not cool. \n\nIn this part, we will use Eureka Naming Server to fix this problem.\n\n![Image](/images/Spring-Boot-Microservice-6-EurekaNamingServer-Deployment.png \"Spring-Boot-Microservice-6-EurekaNamingServer-Deployment\")\n\n## Tools you will need\n- Maven 3.0+ is your build tool\n- Your favorite IDE. We use Eclipse.\n- JDK 1.8+\n\n## Complete Maven Project With Code Examples\n> Our Github repository has all the code examples - https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-basic-microservice\n\n\n## Bootstrapping Eureka Naming Server with Spring Initializr\n\nCreating Eureka Naming Server with Spring Initializr is a cake walk. \n\nSpring Initializr [http://start.spring.io/](http://start.spring.io/){:target=\"_blank\"} is great tool to bootstrap your Spring Boot projects.\n\nYou can create a wide variety of projects using Spring Initializr.\n\nFollowing steps have to be done for a Web Services project\n\n- Launch Spring Initializr and choose the following\n  - Choose `com.in28minutes.springboot.microservice.eureka.naming.server` as Group\n  - Choose `spring-boot-microservice-eureka-naming-server` as Artifact\n  - Choose following dependencies\n    - Eureka\n    - DevTools\n- Click Generate Project.\n- Import the project into Eclipse. File -> Import -> Existing Maven Project.\n\n> Do not forget to choose Eureka in the dependencies\n\n## Enabling Eureka\n\nEnableEurekaServer in `SpringBootMicroserviceEurekaNamingServerApplication`.\n\n```\n@SpringBootApplication\n@EnableEurekaServer\npublic class SpringBootMicroserviceEurekaNamingServerApplication {\n```\n\nConfigure the application name and port for the Eureka Server\n\n/spring-boot-microservice-eureka-naming-server/src/main/resources/application.properties\n\n```properties\nspring.application.name=netflix-eureka-naming-server\nserver.port=8761\n\neureka.client.register-with-eureka=false\neureka.client.fetch-registry=false\n```\n\n## Launching Eureka Naming Server\n\nLaunch `SpringBootMicroserviceEurekaNamingServerApplication` as a Java application.\n\nYou can launch up Eureka at `http://localhost:8761`\n\nYou would see that there are no instances yet connect to Eureka.\n\n![Image](/images/Spring-Boot-Microservice-8-LaunchingEurekaServer.png \"Spring-Boot-Microservice-8-LaunchingEurekaServer\")\n\n## Connect FS and CCS Microservices with Eureka\n\nMake these changes on both the microservices\n\nAdd to pom.xml\n```\n    <dependency>\n      <groupId>org.springframework.cloud</groupId>\n      <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>\n    </dependency>\n\n```\n\nConfigure Eureka URL in application.properties\n\n```properties\neureka.client.service-url.default-zone=http://localhost:8761/eureka\n```\n\nRestart all the instances of CCS and FS. You would see that the CCS and FS microservices are registered with Eureka Naming Server. Thats Cool!\n![Image](/images/Spring-Boot-Microservice-9-ConnectCCSandFSToEureka.png \"Spring-Boot-Microservice-9-ConnectCCSandFSToEureka\")\n\nScreenshot shows how to launch an additional instance of Forex Service on 8081.\n\n![Image](/images/Spring-Boot-Microservice-91-LauchingFSOn8081.png \"Spring-Boot-Microservice-91-LauchingFSOn8081\")\n\nYou would see that one instance of CCS and two instances of FS microservices are registered with Eureka Naming Server.\n\n![Image](/images/Spring-Boot-Microservice-92-TwoinstancesofFSOnEureka.png \"Spring-Boot-Microservice-92-TwoinstancesofFSOnEureka\")\n\n## Routing Ribbon Requests Through Eureka\n\nAll that you would need to do is to remove this configuration\n\nRemove this configuration in application.properties\n```\nforex-service.ribbon.listOfServers=localhost:8000,localhost:8001\n```\n\nRestart the CCS instance. \n\n## Eureka in Action\n\nCurrently we have the following services up and running\n- Currency Conversion Micro Service (CCS) on 8100\n- Two instances of Forex MicroService on 8000 and 8001\n- Eureka Server launched\n\nNow you would see that the requests to CCS would get distributed between the two instances of Forex Microservice by Ribbon through Eureka.\n\n### Request 1\nGET to http://localhost:8100/currency-converter-feign/from/EUR/to/INR/quantity/10000\n\n```json\n{\n  id: 10002,\n  from: \"EUR\",\n  to: \"INR\",\n  conversionMultiple: 75,\n  quantity: 10000,\n  totalCalculatedAmount: 750000,\n  port: 8000,\n}\n```\n\n### Request 2\nGET to http://localhost:8100/currency-converter-feign/from/EUR/to/INR/quantity/10000\n\n```json\n{\n  id: 10002,\n  from: \"EUR\",\n  to: \"INR\",\n  conversionMultiple: 75,\n  quantity: 10000,\n  totalCalculatedAmount: 750000,\n  port: 8001,\n}\n```\n\nYou can see that the port numbers in the two responses are different.\n\n> Exercise : Launch up another instance of Forex Service on 8002. You would see that load gets automatically routed to it as well\n\nCool! Thats awesome. Isn't it.\n\n## Summary\n\nWe have now created two microservices and established communication between them.\n\n![Image](/images/Spring-Boot-Microservice-1-CCS-FS.png \"Spring-Boot-Microservice-1-CCS-FS\") \n\nWe are using Ribbon to distribute load between the two instances of Forex Service and Eureka as the naming server.\n\nWhen we launch new instances of Forex Service, you would see that load is automatically distribute to them.\n\nThe idea behind these series of 5 articles was to give a flavor of Spring Boot and Spring Cloud with Microservices.\n\nThere is a lot more ground to conver with Microservices. Until next time, Cheers!\n\n## Complete Maven Project With Code Examples\n> Our Github repository has all the code examples - https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-basic-microservice\n"
  },
  {
    "path": "_blog/articles/2019-02-02-the-in28minutes-way.md",
    "content": "---\nlayout:     post\ntitle:      The in28Minutes Way\ndate:       2017-11-19 12:31:19\nsummary:    Understand what, why and the how about in28Minutes. Hear what our learners say about our courses. Understand how we design them. \ncategories: TheIn28MinutesWay\npermalink:  /the-in28minutes-way\n---\n\n\n\n### In28Minutes Ways\n> How did in28Minutes get to 100,000 learners across the world? \n\n![](/images/udemy-total-students.png)\n\n> We are focused on creating the awesome course (learning) experiences. Period.\n\n#### An awesome learning experience? What's that?\n\nYou need to get insight into the in28Minutes world to answer that. \n\nYou need to understand \"The in28Minutes Way\"\n- What are our beliefs? \n- What do we love? \n- Why do we do what we do? \n- How do we design our courses?\n\nTo find out more about our courses visit http://www.in28minutes.com\n\nLet's get started on \"The in28Minutes Way\"!\n\n## Important Components of \"The in28Minutes Way\"\n\n* [Continuous Learning](#continuous-learning)\n* [Hands-on](#hands-on)\n* [We don't teach frameworks. We teach building applications!](#we-don-t-teach-frameworks-we-teach-building-applications-)\n* [We want you to be strong on the fundamentals](#we-want-you-to-be-strong-on-the-fundamentals)\n* [Step By Step](#step-by-step)\n* [Efficient and Effective](#efficient-and-effective)\n* [Real Project Experiences](#real-project-experiences)\n* [Debugging and Troubleshooting skills](#debugging-and-troubleshooting-skills)\n* [Modules - Beginners and Experts!](#modules---beginners-and-experts-)\n* [Focus on Unit Testing](#focus-on-unit-testing)\n* [Code on Github](#code-on-github)\n* [Design and Architecture](#design-and-architecture)\n* [Modern Development Practices](#modern-development-practices)\n* [Interview Guides](#interview-guides)\n* [Bring the technology trends to you](#bring-the-technology-trends-to-you)\n* [Building a connect](#building-a-connect)\n* [Socially Conscious](#socially-conscious)\n* [We care for our learners](#we-care-for-our-learners)\n* [We love what we do](#we-love-what-we-do)\n\n## Continuous Learning\n\nTrends change. Period. \n\nYesterday it was REST, Spring, Spring MVC. Today it is Spring Boot, Microservices and Full Stack Development. Tomorrow it will be AI, Machine Learning and Big Data. \n\nIrrespective of the direction technology is heading, two characteristics seperate frontrunners\n- You are an expert at what you do\n- You are a continuous learner\n\n> You know what is happening. You keep learning every day. You know how to adapt when things go in a direction different from your expectations.\n\nWe believe that while you should work hard at your job and achieve great success with it, you should always have an eye towards \n- Getting better at what you do\n- Expanding your horizons\n\nInfact, this belief in continuous learning is what made me choose the name - in28Minutes.\n\n> I'm a great believer that if you spend 30 minutes every day taking a small step towards your dream, you will reach the top 5% of any path you choose. And that where the name in28Minutes comes from. Atleast 28 minutes of learning every day!\n\nAt in28Minutes we believe in Continous Learning. \n\n> We are learning with you and identifying things that you would want to learn. \n\nWe started with Spring and Spring MVC. We have expanded into Spring Boot and Spring Cloud and now have the best courses on building web applications, SOAP and RESTful web services, APIs and Microservices. \n\nWe also teach the finer aspects of programming - unit testing, mocking and modern development practices - TDD, 4 Principles of Simple Design and Refactoring.\n\n![](/images/in28Minutes-Java-Course-Roadmap.png)\n\nIn the next few months, we are expanding into \n- Front End\n- Automation Testing\n\nWe continuously work on creating awesome course experiences.  \n- Code and Complete Notes on Github (https://github.com/in28minutes/)\n- Course Companion Guides\n- Troubleshooting Guides (https://github.com/in28minutes/in28minutes-initiatives/tree/master/The-in28Minutes-TroubleshootingGuide-And-FAQ)\n- Modularity of Courses helping them cater to the needs of both Beginners and Experts\n- Increased Coverage of Topics\n\nWe spend time every day visualizing how we can make your course experiences better.\n\n> You are a 28Minuter if you spend atleast half an hour a day in making your dreams come a step closer. \n\n## Hands-on\n\nYou do not learn to drive by watching Tom Cruise drive at 300 kmph. You have to do it yourselves to learn. \n\nThe same applies to learning programming and learning to develop applications! You have to get your hands dirty. \n\nThat's how you learn the most and that's exactly how we design our courses! \n\n> We design them to be hands-on.\n\nIf you are one of our 1300 followers on GitHub (https://github.com/in28minutes/) , you will know that we start working on a course atleast 3-6 months ahead of the release. \n\nSometimes, it could be years before the course is live.\n\n> For Example, I've been working on a programming course for the last 2 years to enable you to learn  both object oriented programming and functional programming irrespective of the language. You might be wondering \"why 2 years?\". I want the course to teach programming, design, unit testing, great programming practices, high quality code and be a lot of fun. I want the course to create great programmers. The first version of the course with Java will be released soon. \n\nFollow us on Github (https://github.com/in28minutes/) to know what we are working on.\n\n> We believe that the best courses use the right examples to illustrate concepts. \n\nFinding the right example and fitting it into the hand-on approach is not an easy job. But that's the effort we put in to help you have an amazing learning experience.\n\nAnd here is a review that recognizes our efforts in the background to make a course just right!\n\n##### Master Microservices with Spring Boot and Spring Cloud\n> A lot of preparation work has taken place from the teacher and this is visible throughout the course.\n\nThe fun part is \"even our interview courses are full of code examples\"!\n\nWhen you learn something with a hands-on example, you retain the concepts for longer. And when you follow along with us and do it, you retain 200% more. \n\nThat's the secret recipe for our amazing reviews. \n\n##### Spring Master Class - Beginner to Expert \n\n> You do not get bored in long conversations and you get time to get your hands dirty at the end of each video\n\n> The instructor has  explained and demonstrated each single setting and covered so much!\n\n##### Java Servlets and JSP \n\n> The best part of it is the hands-on approach which the author maintained throughout the course as he had promised at the beginning of the lecture. He explains the concepts really well and also makes sure that there is not a single line of code you type without understanding what it really does. It was so engaging that it gets you interested in web development and kinda makes you want to learn more about it.\n\n> I got a working servlet! I got a working website!\n\n##### Learn Spring Boot in 100 Steps - Beginner to Expert \n\n> I also appreciate the mind and hands approach of teaching something and then having the student apply it.  It makes everything a lot clearer for the student and uncovers issues that we will face in our project early.\n\n## We don't teach frameworks. We teach building applications!\n\nProjects are not built with one framework. There is an eco system that's used to build a project. An ecosystem of tools, concepts and frameworks. There are finer aspects like architecture, design, unit testing, security, exception handling and unit testing which make a project great.\n\n> You do not become a great developer by understanding the framework. \n\nThat's why we teach how to build applications using frameworks.\n\nThe fundamentals of a web service, a web application or a microservice do not change. If you create a good web service, irrespective of the framework you use to build it, it has potential to evolve into a good microservice. \n\nThe frameworks you use might change but the applications will live for longer. We focus on helping you to learn to build great applications so that you can easily adapt to new frameworks.\n\nHere are some of the titles of our awesome courses and you can see that all of them are focused on building something using the framework. They help you understand the framework but more importantly - they help you build an application with the framework.\n  - Master Microservices with Spring Boot and Spring Cloud\n  - Master Web Services and REST API with Spring Boot\n  - Build Java EE(JEE) app in 25 Steps - Java Servlets and JSP\n  - Build Java Web App in 25 Steps - Spring MVC For Beginners\n\nHere are some of the reviews related to building awesome applications with a wide variety of frameworks and tools\n\n##### Spring MVC For Beginners : Build Java Web App in 25 Steps \n\n> I learned a lot practically building the web application and you guys have tried using new concepts like bootstrap, HTML 5 which helps us go through them as well.\n\n> This course covers quite a lot of subjects: Maven, Spring MVC, and Maven support for Bootstrap, Hibernate Validator, JSTL, jQuery, ...The author does a good job introducing all of these technologies.\n\n##### JUnit Tutorial for Beginners - Learn Java Unit Testing\n\n> This course starts and develops into more complex topics with clear explanations. It uses Eclipse and Maven so you can have the same tools available to use.\n\n##### Java Servlets and JSP - Build Java EE(JEE) app in 25 Steps\n\n> Simple, yet precise explanation. The course is also enabling in understanding how to use tools like eclipse, maven, tomcat.\n\n> You will learn the concepts of Servlets, JSP, Maven, TomCat, and bit of bootstrap and CSS also. A++++\n\n## We want you to be strong on the fundamentals\n\nWe think that understanding the fundametals of a tool, framework or a language is what makes you an expert. While you want to quickly learn how to use a framework, the key difference between an expert and a novice is \"How deep do you understand the framework?\". \n\nWe want you to learn the fundamentals. We want you to be able to make the different choices involved in choosing and using a framework. \n\nWe want you to understand not just the What and How. We would want you to understand the Why and When questions as well?\n- Why Microservices?\n- Why Spring? Why Spring Boot?\n- Why are we using Maven?\n- When should you use Mockito?\n- What magic happens behind Spring Boot?\n- What are the best practices in developing RESTful Web Services\n\nIn Spring MVC course, we teach you basics of JSPs and Servlets and then move to Spring MVC to ensure you understand why we are using Spring MVC.\n\nIn the Spring Boot course, we create examples using Spring Boot and without Spring Boot to help you understand what Spring Boot offers.\n\nIn the JPA and Hibernate course, we start with JDBC, Spring JDBC and iBatis to ensure you understand how things worked before JPA. And you know the advantages of JPA.\n\nLets look at a few of the reviews\n\n##### Master Java Web Services and REST API with Spring Boot \n\n> I was always confused about RESTful web services and kept away from it. This course opened my eyes. Thanks a lot!\n\n> I have worked on the webservices before, but did not know what was going behind the scene. Now i do and it makes lot easier to debug.\n\n##### Spring Master Class - Beginner to Expert \n\n> Amazing course. Explained super difficult concepts (that I have spent hours on the internet finding a good explanation) in under 5 minutes.\n\n> I've finaly undrestood the concept of DI and Autowiring ...\n\n> I love it,teaches me Spring like I am toddler.Fully detailed\n\n> You have really de-mystified dependency injection especially how it relates to Inversion of Control a concept that was failing to wrap around my mind, now i get it.!!!\n\n##### Spring MVC For Beginners : Build Java Web App in 25 Steps \n\n> I like the way of topic explaining: creating JSP/Servlet app and then editing it according to Spring MVC principles and functionality step-by-step.\n\n> Really complete Spring course for beginners, not only shows you the HOW to use Spring MVC but also the WHYs of every feature, snippet, configuration, design pattern and logic, not only for the Spring/Java related code but also HTML5, external libraries and maven\n\n## Step By Step\n\nAll our courses take a step by step approach. We build awesome web applications, web services and microservices step by step. \n\nWe believe that complex things should be explained by breaking them down into small understandable chunks and explained in small practical steps.\n\nYou can take a look at one of our recent courses for an example -  https://github.com/in28minutes/spring-microservices/tree/master/03.microservices\n\nLet's hear this being reflected in our reviews for our courses\n\n#### \"Spring Master Class - Beginner to Expert\" \n\n> Well-paced, clear, step-by-step explanation of a framework that is extremely complex if you try to absorb it all at once, but very intuitive when broken down.  The instructor breaks it down extremely well and the supplemental materials make it easy to play along.\n\n> A great course which simplifies learning the complex things in depth.\n\n> The course is structured in a very logical way and the instructor is well versed with whatever he is teaching. Liked it. A great experience!\n\n## Efficient and Effective\n\nWe value your time and our time. \n- We want our courses to be very efficient. \n- We want you to learn the most in the least possible time. \n- We want you to be able to pick and choose the modules you want to learn.\n\nOur courses use very efficient setup. \n- We use embedded Tomcat for all Spring Boot Courses! \n- We use maven tomcat plugin for our JSP Servlet and Spring MVC Course.\n- We use in memory databases where possible.\n- We use Unit Tests to illustrate examples.\n\nThat's why you would be able to learn a lot in a very short span of time!\n\nLet's hear this being reflected in our reviews\n\n##### Spring Master Class - Beginner to Expert\n\n> The course is good for a beginner in spring framework like me. It also focus on writing the effective programming  with the help of utilising all the options available in Eclipse and Maven.\n\n##### Java Servlets and JSP - Build Java EE(JEE) app in 25 Steps \n\n> I can see that you will be able to learn many advanced concepts very quickly and broadly within a short time frame. \n\n##### Spring MVC For Beginners : Build Java Web App in 25 Steps \n\n> It covers many many topics just in 6 hours! Even if I've lost something (but just because I wanted to follow all this dense course in one solution)  I can say that now I know many more things and I can go to study better what it has been explained. Thanks!\n\nBonus - Here are a couple of videos to help you become more efficient with Eclipse and Maven\n- 10 Maven Tips for Beginners - https://www.youtube.com/watch?v=exNl7USPfsg\n- 10 Eclipse Tips for Beginners - https://www.youtube.com/watch?v=dN9GYsG1v_c\n\n## Real Project Experiences\n\nWe replicate real project experiences by building all important application features and by using the tools which are used in projects today. We build features like Exception Handling, Security and use tools/frameworks like Maven, Tomcat, JUnit and Mockito.\n\nThis ensures that you can apply what you learnt directly in your project. \n\nThat's one of the most important goals we set when we start creating our course examples. \n\n> Make it as near to a real project experience as possible. \n\nAnd as always, our efforts reflect in our reviews.\n\n##### \"Master Java Web Services and REST API with Spring Boot\" \n\n> Course made by in28minutes are really excellent.  And it directly helpful in developing application .\n\n> Great course. The instructor has an easy way to explain exposing practical examples. Very straight. I definitely recommend!\n\n##### \"Spring MVC For Beginners : Build Java Web App in 25 Steps\" \n\n> After finishing, I'm confident I know eneough to start creating other MVC projects. \n\n> \"Thorough walk through, hitting on most of the tools that are used and needed for real world enterprise applications. Clear presentation and language.\"\n\n##### \"Master Hibernate and JPA with Spring Boot in 100 Steps\" \n\n> Great course!  I was able to apply what I learned immediately!  Thanks!\n\n##### Spring Master Class - Beginner to Expert \n\n> \"exactly the information I need for my project\"\n\n> This is a great course. It has practical examples. It is not too fast or slow.\n\n##### \"Spring MVC For Beginners : Build Java Web App in 25 Steps\" \n\n> The lecturer also uses more modern Java coding methodologies, whereas you still see older methodologies on other websites. \n\n## Debugging and Troubleshooting skills\n\nWithout great debugging skills, you cannot become a great programmer. Things go wrong when you put a project live and you want to find out why they went wrong and you want to find it quickly.\n\nHow can you develop great debugging skills?\n - Understand fundamentals\n - Learn step by step so that you know whats happening in the background\n - Ability to use logging effectively\n\nWe focus on enabling these during the courses. Let's hear this in the voice of our students.\n\n##### \"Master Microservices with Spring Boot and Spring Cloud\" \n\n> The course does a good job of explaining terms, it goes through debug logs to explain step by step what the framework does, and it gives you a few tips on how to troubleshoot.\n\n##### \"Master Java Web Services and REST API with Spring Boot\" \n\n> He sometimes (deliberately) make mistakes which is very helpful for newbies.\n\n> I have worked on the webservices before, but did not know what was going behind the scene. Now i do and it makes lot easier to debug.\n\n## Modules - Beginners and Experts!\n\nWe love modularization! We love building applications using a modular structure and the cool thing is we structure our courses around modules too!\n\nWe cater to the needs of Beginners and Experts with the same course by structuring our courses as independent modules.\n- This enables an intermediate/expert learner to directly jump into an advanced module.\n- This gives our learners the ability to pick and choose what they want to learn. \n- They can create their own learning paths based on their needs/experience/abilities.\n\nHere are the modules for one of our courses\n- Master Web Services and REST API with Spring Boot\n- Introduction To Web Services\n- Introduction to Spring Framework in 10 Steps\n- Introduction to Spring Boot in 10 Steps\n- SOAP Web Services with Spring and Spring Boot\n- RESTful Web Services with Spring and Spring Boot\n- Introduction to JPA in 10 Steps\n- Connecting RESTful Web Service to JPA\n- RESTful Web Services - Best Practices\n\nAn intermediate learner who is familiar with Spring and Spring Boot and wants to learn RESTful Services can skip the introduction and jump directly into to the specific section \"RESTful Web Services with Spring and Spring Boot\" directly.\n\nHere are a few awesome learning talking about this in their reviews.\n\n##### Master Java Web Services and REST API with Spring Boot\n\n> I love how he organized this course in a way that it is not related to each other, so you can go to the segment you want to learn.\n\n##### \"Master Microservices with Spring Boot and Spring Cloud\" \n\n> Each lesson is independent of the others so you can move to different lectures if needed.  I already have a lot of experience with programming and wanted to learn about specific examples.  This course provided that exactly. \n\n##### Learn Spring Boot in 100 Steps - Beginner to Expert \n\n> This course was perfect not only for beginners but for experienced engineers such as myself trying to get up to speed on spring boot quickly.\n\n## Focus on Unit Testing\n\nUnit Testing enables \n\t- Quick Feedback\n\t- Continuous Improvement of Code\n\nWe believe that great developers write great unit tests and we want all our learners to be great developers!\n\nWe have courses on JUnit (a free course) and Mockito to teach how to write great unit tests using mocks. And We ensure that all our web services and framework courses teach how to write great unit tests and integration tests.\n\nOur Spring Course has sections on JUnit, Mockito and teaches unit testing as an integral part of the course.\n\nHere are a few reviews on our unit testing courses\n\n##### Mockito Tutorial : Learn mocking with 25 Junit Examples \n\n> The best course of mockito and poweMockito that I have seen. Thanks for posting this great amount of great content to us.\n\n> Very good course. The approach is very systematic and step by step. I really like the combination of theory and practical goes hand by hand. The journey from JUnit to Mockito to Powermock is very well described.\n\n## Code on Github\n\nAll our code examples are open source and available on Github. We have 40+ repositories catering to the needs of wide range of courses and videos.\n\nWe have step by step details, step by step code and individual folder for each of the modules in our Github repository. \n\n> You can take a look at one of our recent courses for an example -  https://github.com/in28minutes/spring-microservices/tree/master/03.microservices\n\nLets take a quick look at a few screenshots from our Github repository.\n\n#### Step by Step Details\n![](/images/step-wise-details.png)\n\n#### Step by Step Code Backup\n![](/images/step-wise-backups.png)\n\n#### Complete Code Examples\n![](/images/complete-code-examples.png)\n\n## Design and Architecture\n\nWhile we belive in Evolutionary Design, we think its important to spend time to create the right architectural mindset. \n\nWe believe that the most important thing to do is to differentiate between Architecture and Design. Here's a great video to start off on Agile and Evolutionary Design - https://www.youtube.com/watch?v=gt6js9zl1Rs\n\nWe have created a few videos earlier on Design and Architecture. You can expect us to focus on this even more going forward.\n\nHere are few videos:\n\n- Introduction to Non Functional Requirements - https://www.youtube.com/watch?v=JTYxAcZC8Io\n- Should I be an expert at all Design Patterns? - https://www.youtube.com/watch?v=8lEfj1cmBJ4\n- Introduction to Design Patterns in 25 Minutes - https://www.youtube.com/watch?v=Vp7q_pE7Fzg\n- 4 Principles of Simple Design - https://www.youtube.com/watch?v=OwS8ydVTx1c&list=PL066F8F24976D837C\n- Web Service Design - REST - https://www.youtube.com/watch?v=dEL6762fj8M&list=PLBBog2r6uMCTsOXlw9xFpgONdKnT2ls3u\n\n\n\n## Modern Development Practices\n\n- We believe that following modern development practices is essential for a great developer. \n\nWe created a number of videos on our YouTube channel about these practices.  \n- Introduction to Modern Development Practices - https://www.youtube.com/watch?v=0Kqzfyp-w4s\n- Introduction to DevOps - https://www.youtube.com/watch?v=I-JkJZruWyU\n- How to become a good programmer? - https://www.youtube.com/watch?v=iJe1Ru4bJQo\n- TDD - https://www.youtube.com/watch?v=45T32_ImO2c&list=PLBBog2r6uMCSa9_mNISSpTcbTcKlMAe6t\n- Static Code Analysis - Best Practices - https://www.youtube.com/watch?v=rB_BaftN3nE\n- JUnit - https://courses.in28minutes.com/p/junit-tutorial-for-beginners\n- Introduction to Coding Standards - https://www.youtube.com/watch?v=XRKDpQ3b27M\n- Introduction to Code Quality - https://www.youtube.com/watch?v=M4Ip6joERv4\n- Code Review Best Practices - https://www.youtube.com/watch?v=hVJGu0xdXII\n- Unit Testing (JUnit) Best Practices - https://www.youtube.com/watch?v=BukAouJgEjo\n- Agile and Evolutionary Design - https://www.youtube.com/watch?v=gt6js9zl1Rs\n\n## Interview Guides\n\nWe believe that interviews should not be focused on whether the interviewee remembers the nuances (api or annotations) of a framework or a language. Interviews should be focused on the thought process of a interviewee - \"How would he/she approach a specific problem?\"\n\nHaving said that, it is important for you to revise your concepts and fill the gaps in your understanding before an interview. And that's exactly how we think about our Spring and Java Interview Guides.\n\nOur Interview Guides are \n- Aimed to help you quickly review important concepts and features\n- Hands-on and full of code examples\n\nHere are few reviews\n\n##### \"Spring Framework Interview Guide - 200+ Questions & Answers\" \n\n> Best course to refresh the spring concepts and syntax in short time to prepare the interviews.\n\n##### \"Java Interview Guide : 200+ Interview Questions and Answers\" \n\n> This is the best course to refresh or learn almost all the core java topics related to interview in few hours. Thanks for the awesome explanation Ranga it helped me a lot for changing my job.\n\n## Bring the technology trends to you\n\nThere is a lot of churn in the industry. There is new stuff happening all around the technology world. AI, IOT, Machine Learning, Big Data, Cloud and DevOps are the buzzwords today. \n\nWe would want to ensure that you are aware of the trends. We would give a new direction to our YouTube channel and help you whats happening with the buzzwords as well as the technologies where we are experts.\n- Microservices - Node JS/Spring Boot\n- Frontend Frameworks - Javascript/etc\n- Automation Testing\n- Mobile Development - Android/iPhone/Cross Platform\n\nWe would create more videos like these to help you understand our view of what's happending in the industry - Java Learning Roadmap and Trends - May 2017 - https://www.youtube.com/watch?v=6ObWpCUpGYc\n\nWe will help you get the expert view by connecting with the industry. More about it in the next section.\n\n## Building a connect\n\nWhile we are creating great learning experiences with our courses, we think a real mindset change happens only when a learner gets a chance to interact with experts - who are passionate and doing great work.\n\nWe want to bring the experts to you and help you understand their vision, their passion and knowledge. We believe, this will enable you to make the right choices in your technology career.\n\nYou can read more about this initiative in here - https://github.com/in28minutes/in28minutes-initiatives/tree/master/in28Minutes-connect\n\nWe want to promote online learning because we think Online Learning is a great socio economic leveller. \n\nWe want to give you\n - Behind the scenes look at experts - stories, lessons, beliefs and vision!\n - What's happening in the industry?\n - How can they adapt?\n\n## Socially Conscious\n\nWe would want an inclusive society where every one has an equal chance to succeed.\n\nWe are ready to offer our courses at substantial discounts and even for free for the right causes\n  - We are and would want to support initiatives like women back to work \n  - We want to help re-skilling for those who lost jobs.\n\nIf you are aware of organizations supporting these intiatives, do help us reach out to them and help them Re-skill.\n\nin28Minutes is proud of the great things that India has done on the technology front\n- We invented Zero and thats the base for everything we do in the programming world.\n- We created wonderful programmers.\n- We created wonderful world leaders for top technology organizations.\n\nHowever, we believe there is a lot of work to be done.\n\nAnd we would want to do our bit.\n\n###### Promote Online Learning in India\n\n> We think Online Learning is a great socio economic leveller. Online learning has come a long way in the last few years around the world. However, adoption in India remains slow and we want to increase adoption by bringing online learning at an early stage - college and industry entry level. We belive once you start learning online, it will remain your No 1 choice of learning.\n\n##### Create More Great Programmers from India\n\n> There are awesome programmers from India doing great work across the world. However, as a percentage of IT professionals, the number of awesome programmers remains miniscule.\n\nFor enabling this - we would create awesome free courses for entry level programmers to understand and love programming. \n\nWe would want to reduce the barriers in learning programming by creating programming courses in local languages\n  - c++ in telugu - https://www.youtube.com/watch?v=FzosXb-n3V8&list=PLB54DFFD608FDCCA5\n  - C in telugu - https://www.youtube.com/watch?v=0Asyny8Wto4&list=PLA8E0AD777C0B9827\n\n##### Support Re-skilling of Experienced Developers\n\n> Whethers its developers coming back to workforce or who lost their jobs, we would want to provide them the means to help them get back.\n\n## We care for our learners\n\nWe care for our learners. We ensure that their needs are addressed and we are creating awesome course and learning experiences. And they love us back :)\n\nHere are a few reviews show our learner's love for us\n\n##### Master Microservices with Spring Boot and Spring Cloud\n\n> Superb course! Very detailed and helpful\n\n> Its amazing to learn from this  course\n\n##### Learn Spring Boot in 100 Steps - Beginner to Expert\n\n> So clear, funny and easy to learn with you. A pleasure!\n\n> Lot lot, lot of great and quality stuff, as always with Ranga.\n\n> Honestly, this is the best Spring Boot course I've ever tried out. These things make even more sense to me, and I am enjoying every single moment of it. Super snazzy and flawless presentations, Ranga! Keep up the clean work!\n\n> I love this guy\n\n##### Java EE Made Easy - Patterns, Architecture and Frameworks\n\n> Excellent as usual\n\n##### Spring Master Class - Beginner to Expert\" \n\n> Excellent and amazing course!!! I've been searching for such a complete and awesome course on spring for a long time. It's a really comprehensive course and all concepts are explained in details.\n\n> The way he explains everything is just amazing. He understand very well the concepts and very meticulous explaining every concept \n\n##### Master Java Web Services and REST API with Spring Boot \n\n> Genius !!!\n\n> V V good and what else i should say  .. no word ..\n\n##### Master Hibernate and JPA with Spring Boot in 100 Steps \n\n> this is a big course , excelent teacher  , the best  hahahahha\n\n> We are lucky to have Ranga's courses published on Udemy so that we got opportunity to learn those in faster pace.\n\n##### Spring MVC For Beginners : Build Java Web App in 25 Steps \n\n> Brilliant! The best course ever!\n\n> \"Very Good lecture and I have not seen like this before I salute for you Sir\"\n\n> Excellent, fabulous. The way he has prepared the material and the way he teaches is really awesome. What an effort .. Thanks a million\n\n## We love what we do\n\nWe are helping shape the careers of our learners and that's what we love doing. Since we started teaching full time, we put in more effort to ensure you are having the best course experience possible. \n\nWe are venturing into Automation Testing and Full Stack Development next and we will bring the same level of expertise and commitment to those courses as well.\n\nWe want you to achieve what you want by making you experts and enjoy what you are learning.\n\n##### Master Microservices with Spring Boot and Spring Cloud\n\n> Its amazing to learn from this  course\n\n##### Learn Spring Boot in 100 Steps - Beginner to Expert\n\n> So clear, funny and easy to learn with you. A pleasure!\n\n> Lot lot, lot of great and quality stuff, as always with Ranga.\n\n##### Spring MVC For Beginners : Build Java Web App in 25 Steps \n\n> Wow, great coach!\n\n> By the time you complete the course, you realise that he has taught you all the most important Spring concepts in a fun, entertaining and easy to understand manner.\n\n> This guy is fantastic. Really. Wonderful teaching skills, and goes well out of his way to make sure that everything he is doing is fully understood. This is the kind of tutorial that gets me excited to work with a framework that I may otherwise not be.\n\n## The End\n\nWow! Wasn't it a wonderful read? We would love to hear your thoughts.  \nTo find out more about our courses visit http://www.in28minutes.com\n\nShare on Twitter - https://twitter.com/home?status=Having%20a%20great%20time!%20%0A%20%23in28Minutes%20%23ImLearningIn28Minutes\n\n#in28Minutes #ImLearningIn28Minutes #ImLovingIn28Minutes \n\nGood Luck and Keep Learning in28Minutes\n- Linked In : https://www.linkedin.com/in/rangakaranam/​\n- Facebook  : https://www.facebook.com/in28Minutes​\n- Twitter   : https://twitter.com/in28Minutes​\n- YouTube   : https://www.youtube.com/rithustutorials​\n​\n![](/images/udemy-courses.png)"
  },
  {
    "path": "_blog/articles/2019-02-03-spring-boot-maven-eclipse-troubleshooting-guide-and-faq.md",
    "content": "---\nlayout:     post\ntitle:      Spring Boot, Maven and Eclipse Errors and TroubleShooting Guide and FAQ\ndate:       2022-10-17 12:31:19\nsummary:    Troubleshoot your Spring, Spring Boot, Maven and Eclipse issues using this guide from in28Minutes. \ncategories: SpringBoot\npermalink:  /spring-boot-maven-eclipse-troubleshooting-guide-and-faq\n---\n\nWe love all our 100,000 learners. We want to help you in every way possible.\n\nWe do not want you to get stuck because of a simple error.\n\nThis 50 page troubleshooting guide and faq is our way of thanking you for choosing to learn from in28Minutes.\n\n## How to use this guide?\n\n### 1. Ensure You Have The Recommended Versions of Tools/Versions\n\nFirst of all - Make sure you are using the right versions. Here is the recommended versions and errors if you don't use them:\n\n| Recommended Version  | Errors with other versions | More Details |\n| -------------------- |:-----------------------------------------------:|--------------|\n| Java 8  | Unsupported major.minor version 52.0 |[Basics](#basics)|\n| Eclipse Java EE Oxygen | org.codehaus.plexus.archiver.jar.Manifest.write (java.io.PrintWriter)      |[Basics](#basics)|\n| Spring Boot 2.3.1.RELEASE    | Maven download issues. Hal Browser and Spring Boot Actuator are not working!|[Configure 2.3.1.RELEASE](#error---hal-browser-and-spring-boot-actuator-are-not-working)|\n\n\n### 2. Highly Probable Errors\n\nProblems a high proportionate of our learners face.\n\n| Error                | Solution Reference |\n| -------------------- |:-------------:|\n| Compilation failure [ERROR] No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?  |[Configure Eclipse to use JDK](#error---you-are-not-using-a-jdk) | \n| Could not transfer artifact           |[Check Maven Configuration](#error--you-are-not-connected-to-internet-or-you-are-behind-a-proxy) |\n|Hal Browser and Spring Boot Actuator are not working   |[Configure Spring Boot Version 2.3.1.RELEASE](#error---hal-browser-and-spring-boot-actuator-are-not-working)|\n|H2 Embedded Database - Cannot find tables |[Use the right database name](#error---table-is-not-created-automatically-in-h2-embedded-db-or-im-unable-to-see-the-tables) |\n| Failed to load class (or)Could not find or load main class or Failed to read Class-Path attribute from manifest    |[Redownload artifacts with Maven](#error--files-downloaded-by-maven-are-corrupt) |\n|java.net.BindException: Address already in use: JVM_Bind   |[Stop 8080 or Use Other Port](#q---what-should-i-do-when-some-other-application-is-using-default-port-8080) |\n|No mapping found for HTTP request   |[Check your component scan configuration](#q---how-do-i-solve-errors-related-to-component-scan) |\n|No qualifying bean of type   |[Check your component scan configuration](#q---how-do-i-solve-errors-related-to-component-scan) |\n|java.lang.NoClassDefFoundError: org/springframework/web/cors/CorsConfigurationSource|[Solution](#error---spring-security---javalangnoclassdeffounderror-orgspringframeworkwebcorscorsconfigurationsource) |\n|Unable to find setter method for attribute commandName   |[Use modelAttribute](#error---unable-to-find-setter-method-for-attribute-commandname) |\n\n### 3. Go for the complete list\n\nIf you are facing a exception or an error\n - Try searching with complete exception text\n - Try searching with a substring\n - Try searching with name of exception\n - Try searching with the direct cause of exception\n - Try searching for the framework and browse through the FAQ\n\n> If the troubleshooting guide does not help you solve your specific problem, raise a pull request with the problem and solution to improve the troubleshooting guide.\n\n> If you see a bug in the troubleshooting guide, raise a pull request to improve the troubleshooting guide.\n\nIf you are here for fun, continue reading. \n\nThis will be the best 20 minute investment you made in your programming career. You get an understanding of how you can troubleshoot a wide variety of issues.\n\nHappy Troubleshooting.\n\n- [Basics](#basics)\n\t- [Tip :  Ensure you have the right version of Java Installed](#tip---ensure-you-have-the-right-version-of-java-installed)\n\t- [Tip : Ensure you have the right version of Eclipse Installed](#tip--ensure-you-have-the-right-version-of-eclipse-installed)\n\t- [Tip : Troubleshooting Embedded Maven in Eclipse](#tip--troubleshooting-embedded-maven-in-eclipse)\n\t- [Error :  You are not using a JDK](#error---you-are-not-using-a-jdk)\n\t- [Error : You are not connected to internet or You are behind a proxy!](#error--you-are-not-connected-to-internet-or-you-are-behind-a-proxy)\n\t\t- [Configuring a Proxy](#configuring-a-proxy)\n\t- [Error : Files Downloaded by Maven are Corrupt](#error--files-downloaded-by-maven-are-corrupt)\n\t\t- [Force Update of Snapshots/Release](#force-update-of-snapshotsrelease)\n\t\t- [Purge Your Maven Repository](#purge-your-maven-repository)\n\t\t- [Delete your local repository](#delete-your-local-repository)\n\t- [Error :  org.codehaus.plexus.archiver.jar.Manifest.write\\(java.io.PrintWriter\\)](#error---orgcodehausplexusarchiverjarmanifestwritejavaioprintwriter)\n\t- [Error : Unsupported major.minor version 52.0](#error--unsupported-majorminor-version-520)\n\t- [Tip :  Your Project Maven configuration should be configured to compile at Java 8](#tip---your-project-maven-configuration-should-be-configured-to-compile-at-java-8)\n\t\t- [Approach 1 : Spring Boot Project](#approach-1--spring-boot-project)\n\t\t- [Approach 2: Non Spring Boot Project](#approach-2-non-spring-boot-project)\n\t- [Error :  On Maven > Update Project, Java 1.4 is auto selected](#error---on-maven--update-project-java-14-is-auto-selected)\n\t- [Error :  Changes you made are not reflected](#error---changes-you-made-are-not-reflected)\n\t- [Q :  What should I do when some other application is using default port 8080?](#q---what-should-i-do-when-some-other-application-is-using-default-port-8080)\n\t\t- [Option 1 - Kill](#option-1---kill)\n\t\t- [Option 2 - Switch Port](#option-2---switch-port)\n\t\t- [Option 1 - Kill](#option-1---kill-1)\n\t\t- [Option 2 - Switch Port](#option-2---switch-port-1)\n\t- [Q :  Do I need to install Tomcat seperately for this course?](#q---do-i-need-to-install-tomcat-seperately-for-this-course)\n\t- [Q :  Why do we use this specific project structure in all our courses?](#q---why-do-we-use-this-specific-project-structure-in-all-our-courses)\n\t- [Q :  What software do you use for your diagrams or Mind Maps?](#q---what-software-do-you-use-for-your-diagrams-or-mind-maps)\n\t- [Q :  How to debug the application?](#q---how-to-debug-the-application)\n\t- [Q :  How do I configure auto restarting the server whenever source code changes?](#q---how-do-i-configure-auto-restarting-the-server-whenever-source-code-changes)\n\t\t- [Approach 1 : Spring Boot Project](#approach-1--spring-boot-project-1)\n\t\t- [Approach 2: Non Spring Boot Project](#approach-2-non-spring-boot-project-1)\n\t- [Q :  Can I use jboss instead of tomcat server?](#q---can-i-use-jboss-instead-of-tomcat-server)\n\t- [Q :  How to get the projects to run in Tomcat 8 or 9?](#q---how-to-get-the-projects-to-run-in-tomcat-8-or-9)\n- [Maven](#maven)\n\t- [Q :  Why Maven?](#q---why-maven)\n\t- [Q :  What is ArtifactId and GroupId?](#q---what-is-artifactid-and-groupid)\n\t- [Q :  How to know the exact string and name of a dependency and its artifactid?](#q---how-to-know-the-exact-string-and-name-of-a-dependency-and-its-artifactid)\n\t- [Q :  What's the difference between scope and phase?](#q---whats-the-difference-between-scope-and-phase)\n\t- [Q :  Maven - How did a specific jar end up in our deployable?](#q---maven---how-did-a-specific-jar-end-up-in-our-deployable)\n\t- [Q :  What is a SNAPSHOT as in 0.0.1-SNAPSHOT?](#q---what-is-a-snapshot-as-in-001-snapshot)\n\t- [Q :  What is difference between runtime and provided scopes?](#q---what-is-difference-between-runtime-and-provided-scopes)\n\t- [Q :  How can you always exclude a specific jar using Maven Exclusions?](#q---how-can-you-always-exclude-a-specific-jar-using-maven-exclusions)\n\t- [Tip : Example of a multi layered maven project](#tip--example-of-a-multi-layered-maven-project)\n\t- [Error : java.lang.ClassNotFoundException](#error--javalangclassnotfoundexception)\n\t- [Q :  Why are we not using Gradle?](#q---why-are-we-not-using-gradle)\n- [Eclipse](#eclipse)\n\t- [Q :  How do I see the list of methods in a class?](#q---how-do-i-see-the-list-of-methods-in-a-class)\n\t- [Q :  How do I become more efficient developer?](#q---how-do-i-become-more-efficient-developer)\n\t- [Q :  How do you download source code to Eclipse so that you can see the code for frameworks?](#q---how-do-you-download-source-code-to-eclipse-so-that-you-can-see-the-code-for-frameworks)\n- [Intellij and/or Mac](#intellij-andor-mac)\n\t- [Q :  How to install Maven on MAC OS X?](#q---how-to-install-maven-on-mac-os-x)\n\t- [Q :  How do I import a Maven project into Intellij?](#q---how-do-i-import-a-maven-project-into-intellij)\n\t- [Q :  How do I create and run unit tests \\(JUnit\\) with Intellij?](#q---how-do-i-create-and-run-unit-tests-junit-with-intellij)\n\t- [Error :  I'm having a problem running jsps with Spring Boot in Intellij. What should I do?](#error---im-having-a-problem-running-jsps-with-spring-boot-in-intellij-what-should-i-do)\n\t- [Q :  Why does Hot reload not work with Spring Boot DevTools and Intellij?](#q---why-does-hot-reload-not-work-with-spring-boot-devtools-and-intellij)\n- [Spring](#spring)\n\t- [Q :  What is the need for a Component Scan?](#q---what-is-the-need-for-a-component-scan)\n\t- [Q :  How do you define a Component Scan?](#q---how-do-you-define-a-component-scan)\n\t\t- [Approach 1 : Spring Boot Project](#approach-1--spring-boot-project-2)\n\t\t- [Detailed Example](#detailed-example)\n\t\t- [Approach 2: Non Spring Boot Project](#approach-2-non-spring-boot-project-2)\n\t\t- [Java Application Context](#java-application-context)\n\t\t- [XML Application Context](#xml-application-context)\n\t- [Q :  How do I solve Errors related to Component Scan?](#q---how-do-i-solve-errors-related-to-component-scan)\n\t\t- [Solution](#solution)\n\t- [Q :  What is the difference between @Component and @ComponentScan?](#q---what-is-the-difference-between-component-and-componentscan)\n\t- [Q :  How do I choose between Spring and CDI?](#q---how-do-i-choose-between-spring-and-cdi)\n\t- [Q :  Why do we write a lot of unit tests in the Spring Master Class course?](#q---why-do-we-write-a-lot-of-unit-tests-in-the-spring-master-class-course)\n\t- [Q :  What is the use of an @Bean annotation?](#q---what-is-the-use-of-an-bean-annotation)\n\t- [Q :  What is the difference between @Bean and @Component?](#q---what-is-the-difference-between-bean-and-component)\n\t- [Q :  What is the difference between @Component, @Service and @Repository annotations?](#q---what-is-the-difference-between-component-service-and-repository-annotations)\n\t- [Q :  Can we use @Component annotation instead of @Service for Business Services?](#q---can-we-use-component-annotation-instead-of-service-for-business-services)\n\t- [Q :  What is the difference between web.xml and the Spring Context - servlet.xml?](#q---what-is-the-difference-between-webxml-and-the-spring-context---servletxml)\n\t- [Q :  Should we use XML or Annotation based wiring?](#q---should-we-use-xml-or-annotation-based-wiring)\n\t- [Q :  Can we do autowiring with Non Setter and Non Constructor Methods?](#q---can-we-do-autowiring-with-non-setter-and-non-constructor-methods)\n\t- [Q :  Where should we use Checked Exceptions?](#q---where-should-we-use-checked-exceptions)\n\t- [Q :  What is the difference between Cross Cutting Concerns and AOP?](#q---what-is-the-difference-between-cross-cutting-concerns-and-aop)\n\t- [Q :  What is difference between IOC and Application Context?](#q---what-is-difference-between-ioc-and-application-context)\n\t- [Q :  What is the difference between classPathXmlApplicationContext and annotationConfigApplicationContext ?](#q---what-is-the-difference-between-classpathxmlapplicationcontext-and-annotationconfigapplicationcontext-)\n\t- [Q :  When @Around aspect is introduced the value returned by@AfterReturning is lost. Why is this happening?](#q---when-around-aspect-is-introduced-the-value-returned-byafterreturning-is-lost-why-is-this-happening)\n\t- [Q :  How do you use which autowiring type to use - @Primary or @Qualifier?](#q---how-do-you-use-which-autowiring-type-to-use---primary-or-qualifier)\n\t- [Q :  What are the New Features in Spring Framework 5.0?](#q---what-are-the-new-features-in-spring-framework-50)\n\t- [Q :  What are the possible reasons of preDestroy not being called?](#q---what-are-the-possible-reasons-of-predestroy-not-being-called)\n\t- [Q :  Compare Application Context vs IOC Container vs Web Container vs EJB Container](#q---compare-application-context-vs-ioc-container-vs-web-container-vs-ejb-container)\n\t- [Notes :  Notes from Rodolfo](#notes---notes-from-rodolfo)\n\t- [Q :  How do we inject different bean depending on the configuration in application.properties?](#q---how-do-we-inject-different-bean-depending-on-the-configuration-in-applicationproperties)\n\t- [Error :  Log4j problems with Spring 5!](#error---log4j-problems-with-spring-5)\n\t- [Q :  What is the minimum baseline Java Version for Spring Boot 2 and Spring 5?](#q---what-is-the-minimum-baseline-java-version-for-spring-boot-2-and-spring-5)\n\t- [Error :  Getting SLF4J errors and not getting logger output in Lecture 41 - Step 19?](#error---getting-slf4j-errors-and-not-getting-logger-output-in-lecture-41---step-19)\n\t- [Error : No Spring WebApplicationInitializer types detected on classpath](#error--no-spring-webapplicationinitializer-types-detected-on-classpath)\n- [JSP Servlets and Spring MVC](#jsp-servlets-and-spring-mvc)\n\t- [Q :  What is the difference between @Controller and @RestController?](#q---what-is-the-difference-between-controller-and-restcontroller)\n\t- [Q :  Why is there no context root in the request url for each web application?](#q---why-is-there-no-context-root-in-the-request-url-for-each-web-application)\n\t- [Q :  What does tomcat7:run exactly mean?](#q---what-does-tomcat7run-exactly-mean)\n\t- [Q :  How is the URL decided with Spring MVC?](#q---how-is-the-url-decided-with-spring-mvc)\n\t- [Error : No plugin found for prefix 'tomcat7' in the current project](#error--no-plugin-found-for-prefix-tomcat7-in-the-current-project)\n\t- [Q :  Is this kind of Tomcat server usage what is commonly referred to as \"Embedded Tomcat Server\" ?](#q---is-this-kind-of-tomcat-server-usage-what-is-commonly-referred-to-as-embedded-tomcat-server-)\n\t\t- [Basic Spring MVC and JSP Servlet courses do not use embedded servers](#basic-spring-mvc-and-jsp-servlet-courses-do-not-use-embedded-servers)\n\t\t- [All our Spring Boot courses use Embedded Servers](#all-our-spring-boot-courses-use-embedded-servers)\n\t- [Q :  How do we handle errors to non existing URL Paths with Spring MVC?](#q---how-do-we-handle-errors-to-non-existing-url-paths-with-spring-mvc)\n\t- [Q :  How do we configure a welcome page?](#q---how-do-we-configure-a-welcome-page)\n\t- [Q :  Why do we teach JSP and Servlets in the first section of Spring MVC Course?](#q---why-do-we-teach-jsp-and-servlets-in-the-first-section-of-spring-mvc-course)\n\t- [Q :  Why do we use  @ResponseBody sometimes and ResponseEntity some other times?](#q---why-do-we-use--responsebody-sometimes-and-responseentity-some-other-times)\n\t\t- [Example 1](#example-1)\n\t\t- [Example 2](#example-2)\n\t- [Q :  What is difference between Spring 5 and Spring 4 in terms of developing web application in the course? Does it matter if a new version is used ?](#q---what-is-difference-between-spring-5-and-spring-4-in-terms-of-developing-web-application-in-the-course-does-it-matter-if-a-new-version-is-used-)\n\t- [Q :  What is the difference between Filters, Listeners and Interceptors?](#q---what-is-the-difference-between-filters-listeners-and-interceptors)\n\t- [Q :  What is the difference between ModelMap and ModelAndView?](#q---what-is-the-difference-between-modelmap-and-modelandview)\n\t- [Q :  What is the difference between model.put\\(\\) and model.addAttribute\\(\\)?](#q---what-is-the-difference-between-modelput-and-modeladdattribute)\n\t- [Q :  How do you pass values from Java Controller to JSP?](#q---how-do-you-pass-values-from-java-controller-to-jsp)\n\t- [Q :  What is Form Binding?](#q---what-is-form-binding)\n\t- [Q :  What is WEB-INF exactly? Why so we need it?](#q---what-is-web-inf-exactly-why-so-we-need-it)\n\t- [Q :  Why do we use Hibernate Validator?](#q---why-do-we-use-hibernate-validator)\n\t- [Q :  Are Model objects specific to a request?](#q---are-model-objects-specific-to-a-request)\n\t- [Q :  The groupid for jstl jar is jstl and not javax.servlet](#q---the-groupid-for-jstl-jar-is-jstl-and-not-javaxservlet)\n\t- [Q :  Why are we using request GET method for \"delete-todo\" request?](#q---why-are-we-using-request-get-method-for-delete-todo-request)\n\t- [Q :  Why do we need xmlns hyperlinks? like http://www.springframework.org/schema/bean](#q---why-do-we-need-xmlns-hyperlinks-like-httpwwwspringframeworkorgschemabean)\n\t- [Error : View is not resolving to a JSP](#error--view-is-not-resolving-to-a-jsp)\n\t- [Q :  How to use own CSS with Spring MVC?](#q---how-to-use-own-css-with-spring-mvc)\n\t- [Q :  Where should we place our static \\(css, js, html\\) resources in a Spring MVC application?](#q---where-should-we-place-our-static-css-js-html-resources-in-a-spring-mvc-application)\n\t- [Q :  How to add a custom login page in Spring Security?](#q---how-to-add-a-custom-login-page-in-spring-security)\n\t- [Q :  How can you authenticate by connecting to a database with Spring Security?](#q---how-can-you-authenticate-by-connecting-to-a-database-with-spring-security)\n\t- [Q :  Why is request method POST recommended compared to GET for sensitive data?](#q---why-is-request-method-post-recommended-compared-to-get-for-sensitive-data)\n\t- [Q :  We use ${todo.done} in JSP even though the name of the field in Todo.java is isDone. Shouldn't we be using ${todo.isDone}?](#q---we-use-tododone-in-jsp-even-though-the-name-of-the-field-in-todojava-is-isdone-shouldnt-we-be-using-todoisdone)\n\t- [Error : After adding security dependencies - java.lang.NoSuchMethodError: org.springframework.aop.framework.autoproxy.AutoProxyUtils.determineTargetClass](#error--after-adding-security-dependencies---javalangnosuchmethoderror-orgspringframeworkaopframeworkautoproxyautoproxyutilsdeterminetargetclass)\n\t- [Q :  How do I ensure that session attributes are not part of the request url?](#q---how-do-i-ensure-that-session-attributes-are-not-part-of-the-request-url)\n\t- [Error :  Spring Security - java.lang.NoClassDefFoundError: org/springframework/web/cors/CorsConfigurationSource](#error---spring-security---javalangnoclassdeffounderror-orgspringframeworkwebcorscorsconfigurationsource)\n\t- [Error :  Unable to find setter method for attribute commandName](#error---unable-to-find-setter-method-for-attribute-commandname)\n\t- [Q :  Can I have multiple parameters with the same name in a request?](#q---can-i-have-multiple-parameters-with-the-same-name-in-a-request)\n\t- [Error :  java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'todo' available as request attribute](#error---javalangillegalstateexception-neither-bindingresult-nor-plain-target-object-for-bean-name-todo-available-as-request-attribute)\n\t- [Error :  Request processing failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate \\[com.in28minutes.Todo.Todo\\]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.in28minutes.Todo.Todo.\\(\\)](#error---request-processing-failed-nested-exception-is-orgspringframeworkbeansbeaninstantiationexception-failed-to-instantiate-comin28minutestodotodo-no-default-constructor-found-nested-exception-is-javalangnosuchmethodexception-comin28minutestodotodo)\n\t- [Error :  Caused by: java.lang.IllegalArgumentException: The servlets named \\[com.in28minutes.LoginServlet\\] and \\[webapp.LoginServlet\\] are both mapped to the url-pattern \\[/login.do\\] which is not permitted](#error---caused-by-javalangillegalargumentexception-the-servlets-named-comin28minutesloginservlet-and-webapploginservlet-are-both-mapped-to-the-url-pattern-logindo-which-is-not-permitted)\n\t- [Q :  How is server picking up index.html and index.jsp even when they are not configured in web.xml?](#q---how-is-server-picking-up-indexhtml-and-indexjsp-even-when-they-are-not-configured-in-webxml)\n\t- [Q :  What is the benefit of using view resolver?](#q---what-is-the-benefit-of-using-view-resolver)\n\t\t- [Why am I not able to see todo's list on screen?](#why-am-i-not-able-to-see-todos-list-on-screen)\n\t- [Q :  What is @ControllerAdvice?](#q---what-is-controlleradvice)\n\t- [Q :  What Request method should be used for updating user details?](#q---what-request-method-should-be-used-for-updating-user-details)\n\t- [Q :  What is the difference between put and patch request methods?](#q---what-is-the-difference-between-put-and-patch-request-methods)\n- [Spring Boot](#spring-boot)\n\t- [Q :  What should be the first things I read about Spring Boot?](#q---what-should-be-the-first-things-i-read-about-spring-boot)\n\t- [What is the minimum baseline Java Version for Spring Boot 2 and Spring 5?](#what-is-the-minimum-baseline-java-version-for-spring-boot-2-and-spring-5)\n\t- [Q :  Is Spring Initializr the only way to create Spring Boot Projects?](#q---is-spring-initializr-the-only-way-to-create-spring-boot-projects)\n\t\t- [Setting up a maven project manually](#setting-up-a-maven-project-manually)\n\t- [Q :  Why am I not seeing code completion when updating application.properties in Eclipse?](#q---why-am-i-not-seeing-code-completion-when-updating-applicationproperties-in-eclipse)\n\t- [Q :  Why do we need spring-boot-maven-plugin?](#q---why-do-we-need-spring-boot-maven-plugin)\n\t- [Q :  Devtools helps me to restart the server automatically. But, I have a problem. The browser page is not auto refreshed.](#q---devtools-helps-me-to-restart-the-server-automatically-but-i-have-a-problem-the-browser-page-is-not-auto-refreshed)\n\t- [Q :  What and Why Embedded Servers?](#q---what-and-why-embedded-servers)\n\t- [Q :  How can I add custom JS code with Spring Boot?](#q---how-can-i-add-custom-js-code-with-spring-boot)\n\t- [Error :  HAL browser gives me unauthorized error - Full authentication is required to access this resource.](#error---hal-browser-gives-me-unauthorized-error---full-authentication-is-required-to-access-this-resource)\n\t\t- [Option 1 : Disable security](#option-1--disable-security)\n\t\t- [Option 2 : Search for password in the log and pass it in the request header](#option-2--search-for-password-in-the-log-and-pass-it-in-the-request-header)\n\t- [Error :  Hal Browser and Spring Boot Actuator are not working](#error---hal-browser-and-spring-boot-actuator-are-not-working)\n\t- [Q :  How does path=\"users\", collectionResourceRel=\"users\" work with Spring Data Rest?](#q---how-does-pathusers-collectionresourcerelusers-work-with-spring-data-rest)\n\t- [Q :  What is importance of {id} in ServletUriComponentsBuilder.fromCurrentRequest\\(\\).path\\(\"/{id}\"\\).buildAndExpand\\(returnQuestion.getId(\\)).toUri\\(\\);](#q---what-is-importance-of-id-in-servleturicomponentsbuilderfromcurrentrequestpathidbuildandexpandreturnquestiongetidtouri)\n\t- [Error :  java.lang.ClassCastException: org.springframework.boot.context.event.ApplicationReadyEvent cannot be cast](#error---javalangclasscastexception-orgspringframeworkbootcontexteventapplicationreadyevent-cannot-be-cast)\n\t- [Q :  What is difference between Spring 5 and Spring 4 in terms of developing web application in the course? Does it matter if a new version is used ?](#q---what-is-difference-between-spring-5-and-spring-4-in-terms-of-developing-web-application-in-the-course-does-it-matter-if-a-new-version-is-used--1)\n\t- [Q :  Why am I seeing an extra dialogue asking me to \"Select Java Application Type\" when I launch a Spring Boot Application?](#q---why-am-i-seeing-an-extra-dialogue-asking-me-to-select-java-application-type-when-i-launch-a-spring-boot-application)\n\t- [Q :  What happens in the background when a Spring Boot Application is \"Run as Java Application\"?](#q---what-happens-in-the-background-when-a-spring-boot-application-is-run-as-java-application)\n\t- [Q :  Can we use jetty instead of tomcat in spring-boot-starter-web?](#q---can-we-use-jetty-instead-of-tomcat-in-spring-boot-starter-web)\n\t- [Error :  Failure to transfer org.springframework.boot:spring-boot-starter-parent:pom:2.3.1.RELEASE from https://repo.spring.io/snapshot](#error---failure-to-transfer-orgspringframeworkbootspring-boot-starter-parentpom200build-snapshot-from-httpsrepospringiosnapshot)\n\t- [Q :  Why do we configure Spring Snapshot and milestone repositories?](#q---why-do-we-configure-spring-snapshot-and-milestone-repositories)\n\t- [Error :   java.lang.IllegalArgumentException: Sources must not be empty](#error----javalangillegalargumentexception-sources-must-not-be-empty)\n\t- [Q :  Can i use spring boot dev tools for a non spring boot project?](#q---can-i-use-spring-boot-dev-tools-for-a-non-spring-boot-project)\n\t- [Q :  What is the difference between Static and Dynamic filtering?](#q---what-is-the-difference-between-static-and-dynamic-filtering)\n\t- [Error :  No message found under code 'good.morning.message' for locale 'us'.](#error---no-message-found-under-code-goodmorningmessage-for-locale-us)\n\t- [Q :  How to generate a WAR file with Spring Boot?](#q---how-to-generate-a-war-file-with-spring-boot)\n\t- [Q :  How to deploy to a different server with with Spring Boot?](#q---how-to-deploy-to-a-different-server-with-with-spring-boot)\n\t- [Q :  What is the difference between RequestMapping and GetMapping?](#q---what-is-the-difference-between-requestmapping-and-getmapping)\n\t- [Q :  Why do we recommend not to use Spring Data Rest in real world applications?](#q---why-do-we-recommend-not-to-use-spring-data-rest-in-real-world-applications)\n\t- [Q :  How do I change the package name of a project in Spring Initializer?](#q---how-do-i-change-the-package-name-of-a-project-in-spring-initializer)\n\t- [Q :  Where can I find the complete list of properties that can be configured in application.properties?](#q---where-can-i-find-the-complete-list-of-properties-that-can-be-configured-in-applicationproperties)\n- [Hibernate, JPA and In-memory Database](#hibernate-jpa-and-in-memory-database)\n\t- [Q :  What is the difference between JPA and Hibernate?](#q---what-is-the-difference-between-jpa-and-hibernate)\n\t- [Q :  Compare Entity Manager vs SessionFactory](#q---compare-entity-manager-vs-sessionfactory)\n\t- [Q :  In which layer, should the boundary of a transaction start?](#q---in-which-layer-should-the-boundary-of-a-transaction-start)\n\t- [Q :  HQL vs JPQL](#q---hql-vs-jpql)\n\t- [Q :  What are the dependencies need to start up an in memory database H2 with Spring Boot?](#q---what-are-the-dependencies-need-to-start-up-an-in-memory-database-h2-with-spring-boot)\n\t- [Q :  How is Hibernate chosen as the default implementation for JPA without any configuration?](#q---how-is-hibernate-chosen-as-the-default-implementation-for-jpa-without-any-configuration)\n\t- [Q :  Why H2? And how does it work?](#q---why-h2-and-how-does-it-work)\n\t- [Q :  Where is the database connection info specified? How does it know to automatically connect to H2?](#q---where-is-the-database-connection-info-specified-how-does-it-know-to-automatically-connect-to-h2)\n\t- [Q :  How do we connect to a external database like MSSQL or oracle?](#q---how-do-we-connect-to-a-external-database-like-mssql-or-oracle)\n\t\t- [Step 1 - Add dependency for mqsql connector to pom.xml](#step-1---add-dependency-for-mqsql-connector-to-pomxml)\n\t\t- [Step 2 - Remove H2 Dependency from pom.xml](#step-2---remove-h2-dependency-from-pomxml)\n\t\t- [Step 3 - Setup your My SQL Database](#step-3---setup-your-my-sql-database)\n\t\t- [Step 4 - Configure your connection to My SQL Database](#step-4---configure-your-connection-to-my-sql-database)\n\t\t- [Step 5 - Restart and You are ready!](#step-5---restart-and-you-are-ready)\n\t- [Q :  What is the default h2 database name configured by Spring Boot? Why is the default database name testdb?](#q---what-is-the-default-h2-database-name-configured-by-spring-boot-why-is-the-default-database-name-testdb)\n\t- [Q :  What happens if H2 is not in the classpath?](#q---what-happens-if-h2-is-not-in-the-classpath)\n\t- [Q :  Why the data lost between restart?](#q---why-the-data-lost-between-restart)\n\t- [Error :  Table is not created automatically in h2 embedded db or I'm unable to see the tables](#error---table-is-not-created-automatically-in-h2-embedded-db-or-im-unable-to-see-the-tables)\n\t- [Error :  H2 Console is not Launched up?](#error---h2-console-is-not-launched-up)\n\t- [Q :  How did the insert query from data.sql run at application startup?](#q---how-did-the-insert-query-from-datasql-run-at-application-startup)\n\t- [Q :  How to define a Composite Primary Key or a Composite ID?](#q---how-to-define-a-composite-primary-key-or-a-composite-id)\n\t- [Q :  Why should we annotate EntityManager with @PersistenceContext and not just @Autowired?](#q---why-should-we-annotate-entitymanager-with-persistencecontext-and-not-just-autowired)\n\t- [Q :  How can we connect to Multiple Databases using Spring Boot?](#q---how-can-we-connect-to-multiple-databases-using-spring-boot)\n\t- [Q :  How did JdbcTemplate achieve connection details?](#q---how-did-jdbctemplate-achieve-connection-details)\n\t- [Q :  Can you give an example for ReadOnly as true in Transaction management?](#q---can-you-give-an-example-for-readonly-as-true-in-transaction-management)\n\t- [Error :  org.hibernate.loader.MultipleBagFetchException](#error---orghibernateloadermultiplebagfetchexception)\n\t- [Error :  BeanCreationException - java.lang.IllegalArgumentException: At least one JPA metamodel must be present](#error---beancreationexception---javalangillegalargumentexception-at-least-one-jpa-metamodel-must-be-present)\n\t- [Q :  Is it mandatory to specify @Repository on a repository which is extending JPARepository?](#q---is-it-mandatory-to-specify-repository-on-a-repository-which-is-extending-jparepository)\n\t- [Q :  JPA and Hibernate Course - Notes from Rodolfo](#q---jpa-and-hibernate-course---notes-from-rodolfo)\n\t- [Q :  How can we use a mysql database for running the application and use inmemory database H2 for unit tests?](#q---how-can-we-use-a-mysql-database-for-running-the-application-and-use-inmemory-database-h2-for-unit-tests)\n\t- [Q :  When is any primary or an id field annotated with @GeneratedValue autogenerated? Why are we passing the value for id in data.sql?](#q---when-is-any-primary-or-an-id-field-annotated-with-generatedvalue-autogenerated-why-are-we-passing-the-value-for-id-in-datasql)\n\t- [Q :  Field dao in SpringRestController required a bean of type 'CustomerDAO' that could not be found. Consider defining a bean of type 'CustomerDAO' in your configuration.](#q---field-dao-in-springrestcontroller-required-a-bean-of-type-customerdao-that-could-not-be-found-consider-defining-a-bean-of-type-customerdao-in-your-configuration)\n\t- [Error :  Detached object passed to persist](#error---detached-object-passed-to-persist)\n\t- [Error :  java.lang.NoClassDefFoundError: javax/wsdl/extensions/ExtensibilityElement](#error---javalangnoclassdeffounderror-javaxwsdlextensionsextensibilityelement)\n\t- [Q :  How do authentication with jwt to service REST??](#q---how-do-authentication-with-jwt-to-service-rest)\n- [Unit Testing](#unit-testing)\n\t- [Q :  What is a mockito answer?](#q---what-is-a-mockito-answer)\n\t- [Q :  How do you mock a private method that requires arguments?](#q---how-do-you-mock-a-private-method-that-requires-arguments)\n\t- [Q :  How to make JUnit run at regular intervals of time?](#q---how-to-make-junit-run-at-regular-intervals-of-time)\n\t- [Q :  Annotation Changes - JUnit 4 vs JUnit 5](#q---annotation-changes---junit-4-vs-junit-5)\n- [You and in28Minutes](#you-and-in28minutes)\n\t- [Q :  What should you do to make the best use of our courses?](#q---what-should-you-do-to-make-the-best-use-of-our-courses)\n\t- [Q :  Why should you learn from in28Minutes?](#q---why-should-you-learn-from-in28minutes)\n\t- [Q :  What is the focus of each of your courses?](#q---what-is-the-focus-of-each-of-your-courses)\n\t- [Q :  How to improve Logical Skills?](#q---how-to-improve-logical-skills)\n\n\n\n## Basics\n\nThis video can help with simple troubleshooting - https://www.youtube.com/watch?v=ZZw8XNz5N-c&t=6s\n\n### Tip :  Ensure you have the right version of Java Installed\n\nRecommended Java Version\n- Do not use Java 9. My recent tests show a few compatibility issues with Spring Boot 2.0+. Let's wait for these get resolved\n- Java 8 for Spring Boot 2.0+ or Spring 5.0+\n- Java 7/Java 8 for earlier versions\n\nJava JDK Version in Eclipse\nYou can use JavaSE-1.8 to develop Java 8 and any lower version of Java applications. You can control the version of an application through maven.\n\nhttps://maven.apache.org/plugins/maven-compiler-plugin/examples/set-compiler-source-and-target.html\n\n### Tip : Ensure you have the right version of Eclipse Installed\n\n> Recommended to use Eclipse Java EE version\n\nRecommended Eclipse Version\n- Oxygen https://www.eclipse.org/downloads/packages/release/Oxygen/\n- Eclipse Java EE version\n\n### Tip : Troubleshooting Embedded Maven in Eclipse\n\nThis video is good start for your troubleshoot embedded maven issues in Eclipse - https://www.youtube.com/watch?v=ZZw8XNz5N-c&list=PLBBog2r6uMCSmMVTW_QmDLyASBvovyAO3&index=5\n\n> In Windows, use Window -> Preferences for Preferences.\n\nThere are typically 4 reasons for errors with Embedded Maven in Eclipse\n\n### Error :  You are not using a JDK\n```\nFailed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.2:compile (default-compile) on project in28minutes-multi-module-model: Compilation failure [ERROR] No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?\n```\n\nFix - You would need to configure Eclipse to use JDK instead of JRE \n- Go to Your Eclipse > (Window/Eclipse) -> Preferences -> Java -> Installed JRE's\n- Change to use a JDK\n\nFollowing links will help you if you have questions\n- http://stackoverflow.com/questions/13635563/setting-jdk-in-eclipse\n- http://stackoverflow.com/questions/19655184/no-compiler-is-provided-in-this-environment-perhaps-you-are-running-on-a-jre-ra\n- http://stackoverflow.com/questions/21099072/eclipse-maven-error-no-compiler-is-provided-in-this-environment\n\n### Error : You are not connected to internet or You are behind a proxy!\n\nMaven downloads the dependencies (i.e. frameworks and libraries(jars)) from the Maven repository (repo.maven.apache.org). \n\nThis is the error you would see\n```\nPlugin org.apache.maven.plugins:maven-compiler-plugin:3.1 or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.apache.maven.plugins:maven-compiler-plugin:jar:3.1: Could not transfer artifact org.apache.maven.plugins:maven-compiler-plugin:pom:3.1 from/to central (https://repo.maven.apache.org/maven2): sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target -> [Help 1]\n```\n\nRun this command at command prompt or terminal\n```\ntelnet repo.maven.apache.org 80\n```\n\nIf you are able to connect you should see this. \n```\ntelnet repo.maven.apache.org 80\nTrying 151.101.200.215...\nConnected to maven.map.fastly.net.\nEscape character is '^]'.\n```\n\nIf you do not see above text ```Connected to maven.map.fastly.net.``` you would need to check your internet connection.\n\nIf you are trying this at work, you might be behind a proxy. \n\nYou need to talk to maven experts in your organization to figure out the right settings.\n- Here's a discussion which will be useful \n  - http://stackoverflow.com/questions/25911623/problems-using-maven-and-ssl-behind-proxy\n  - http://stackoverflow.com/questions/5074063/maven-error-failure-to-transfer\n- The section below shows how to configure a proxy in Eclipse\n\n###### Configuring a Proxy \nMaven plugin uses a settings file where the configuration can be set. Its path is available in Eclipse at Window -> Preferences -> Maven -> User Settings. If the file doesn't exist, create it and put on something like the example below:\n\n```\n<settings xmlns=\"http://maven.apache.org/SETTINGS/1.0.0\"\n  xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n  xsi:schemaLocation=\"http://maven.apache.org/SETTINGS/1.0.0\n                      http://maven.apache.org/xsd/settings-1.0.0.xsd\">\n  <localRepository/>\n  <interactiveMode/>\n  <usePluginRegistry/>\n  <offline/>\n  <pluginGroups/>\n  <servers/>\n  <mirrors/>\n  <proxies>\n    <proxy>\n      <id>myproxy</id>\n      <active>true</active>\n      <protocol>http</protocol>\n      <host>192.168.1.100</host>\n      <port>6666</port>\n      <username></username>\n      <password></password>\n      <nonProxyHosts>localhost|127.0.0.1</nonProxyHosts>\n    </proxy>\n  </proxies>\n  <profiles/>\n  <activeProfiles/>\n</settings>\n```\n\n### Error : Files Downloaded by Maven are Corrupt\nTypical Errors\n```\nException in thread \"main\" java.lang.NoClassDefFoundError: ch/qos/logback/classic/turbo/TurboFilter\nat java.lang.Class.getDeclaredConstructors0(Native Method)\nat java.lang.Class.privateGetDeclaredConstructors(Unknown Source)\nat java.lang.Class.getConstructor0(Unknown Source)\n\nCould not find or load main class com.springboot.app.Application\n\nException in thread \"main\" java.lang.IllegalStateException: Failed to read Class-Path attribute from manifest of jar file:/home/edas/.m2/repository/javax/servlet/jstl/1.2/jstl-1.2.jar\nAnd here is my the complete exception stack\n\nException in thread \"main\" java.lang.IllegalStateException: Failed to read Class-Path attribute from manifest of jar file:/C:/Users/pervacio/.m2/repository/org/springframework/security/spring-security-config/5.0.0.M3/spring-security-config-5.0.0.M3.jar\n\n```\n\nOptions that can be tried are listed below:\n\n###### Force Update of Snapshots/Release\n\n- Right click on your project -> Maven -> Update Project -> Use \"Force Update of Snapshots/Releases\" -> Check this checkbox\n\n###### Purge Your Maven Repository\n\nThis can be done in two ways\n\n- Inside Eclipse - Right click on the project > Run as Maven Build > dependency:purge-local-repository\n\n- From Command Prompt cd to the project of the folder\n   - ```mvn dependency:purge-local-repository```\n\n###### Delete your local repository\nThis will be last resort\n\n### Error :  org.codehaus.plexus.archiver.jar.Manifest.write(java.io.PrintWriter)\n\nReason - You are using an old version of Eclipse without the latest maven archiver plugin\n\nYou get this error\n```\norg.codehaus.plexus.archiver.jar.Manifest.write(java.io.PrintWriter)\n```\n\nRecommended Actions\n- Recommended - Download latest version of Eclipse\n- Other option - It might be a problem with your specific version of eclipse : https://github.com/tesla/m2eclipse-mavenarchiver/issues/9. You can try updating m2e.\n   - Eclipse > Goto Intall New Software then input https://otto.takari.io/content/sites/m2e.extras/m2eclipse-mavenarchiver/0.17.0/N/LATEST/ and continue.\n   - Go ahead and install the plugin\n\nFor more information read these\n- https://stackoverflow.com/questions/37936646/eclipse-2-0-2-and-maven-0-17-configuration\n- https://github.com/tesla/m2eclipse-mavenarchiver/issues/8\n\n### Error : Unsupported major.minor version 52.0\n\nReason - You are using an old version of JDK\n\nYou would get this error\n```\nUnsupported major.minor version 52.0\n```\n\nThis error happens when you try to run code compiled using JDK 8 in a lesser version of JDK or JRE.\n\nFix \n- If you do not have JDK 8, go ahead an install it.\n- Configure Eclipse to use JDK 8. Refer to \"You are not using a JDK\" section to find out how to configure JDK 8\n\n### Tip :  Your Project Maven configuration should be configured to compile at Java 8\n\nIf you are using Spring Boot, check configuration in Approach 1.\n\nIf you are doing a JSP/Servlet or a Spring MVC course without using Spring Boot use Approach 2.\n\n###### Approach 1 : Spring Boot Project\n\nIn pom.xml, the property java.version should be set to 1.8.\n\n```\n  <properties>\n    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>\n    <java.version>1.8</java.version>\n<maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>\n  </properties>\n```\n\n###### Approach 2: Non Spring Boot Project\n\nIn pom.xml, the source and target of maven-compiler-plugin should be set to 1.8\n\n```\n<project>\n  [...]\n  <build>\n    [...]\n    <plugins>\n      <plugin>\n        <groupId>org.apache.maven.plugins</groupId>\n        <artifactId>maven-compiler-plugin</artifactId>\n        <configuration>\n          <source>1.8</source>\n          <target>1.8</target>\n        </configuration>\n      </plugin>\n    </plugins>\n    [...]\n  </build>\n  [...]\n</project>\n```\n\n### Error :  On Maven > Update Project, Java 1.4 is auto selected\n\nEnsure that you have the latest version of Eclipse and Java installed.\n\n### Error :  Changes you made are not reflected\n\n- Did you restart the server?\n- Did you stop and start the server?\n- Did you reload your web page?\n\nChanges to configuration and web.xml are reflected only when you completely restart the server. \n\n### Q :  What should I do when some other application is using default port 8080?\n\n```\nEmbedded servlet container failed to start. Port 8080 was already in use.\n```\n\nYou have two options\n- Option 1 - Identify and stop the process that's listening on port 8080 or\n- Option 2 - Configure this application to listen on another port.\n\n###### Option 1 - Kill\n\n- In Eclipse console tab, on the right hand side, click the double cross icon (Kill all terminated launches). You should see the running program highlighted by a red terminate button. You can kill the red button to kill the running application.\n- In windows, Use Ctrl + Shift + Esc to launch windows task manager. Kill all java.exe or javaw.exe\n- In Mac, You can use one of these commands to find the PID of process using 8080\n```\nnetstat -vanp tcp | grep 8080\nsudo lsof -i tcp:8080\n```\n- After you have the PID, execute the command below:\n```\nkill -9 <PID>\n```\n\n###### Option 2 - Switch Port\n\nAdd a property in application.properties\n\n```\nserver.port = 8081\n```\n\n```\njava.net.BindException: Address already in use: JVM_Bind <null>:8080. \n```\n\nYou have two options\n- Option 1 - Identify and stop the process that's listening on port 8080 or\n- Option 2 - Configure this application to listen on another port.\n\n###### Option 1 - Kill\n\n- In Eclipse console tab, on the right hand side, click the double cross icon (Kill all terminated launches). You should see the running program highlighted by a red terminate button. You can kill the red button to kill the running application.\n- In windows, Use Ctrl + Shift + Esc to launch windows task manager. Kill all java.exe or javaw.exe\n- In Mac, You can use one of these commands to find the PID of process using 8080\n```\nnetstat -vanp tcp | grep 8080\nsudo lsof -i tcp:8080\n```\n- After you have the PID, execute the command below:\n```\nkill -9 <PID>\n```\n\n###### Option 2 - Switch Port\n\nOption 2a - change pom.xml. port is changed to 8081.\n\n```\n <plugin>\n            <groupId>org.apache.tomcat.maven</groupId>\n            <artifactId>tomcat7-maven-plugin</artifactId>\n            <version>2.2</version>\n            <configuration>\n                <port>8081</port>\n            </configuration>\n        </plugin>\n\n```\n\nOption 2b - Instead of tomcat7:run use the command below to run the application. This will run it on port 8081\n\n```\n-Dmaven.tomcat.port=8081 tomcat7:run\n```\n\n### Q :  Do I need to install Tomcat seperately for this course?\n\nDuring the course we would configure a tomcat plugin or embedded tomcat (in Spring Boot courses), which will download tomcat 7 and use it. \n\nYou don't need Tomcat installed on your system.\n\n### Q :  Why do we use this specific project structure in all our courses?\n\nWe follow maven standard project structure. \n\nWe recommend you spend sometime understanding this directory layout \n- https://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html.\n\n### Q :  What software do you use for your diagrams or Mind Maps?\n\nIts called MindMup. https://www.mindmup.com/\n\nI loved the first version of it. And am finding it difficult to adapt to the second version. But as usual, we programmers find a way :)\n\n### Q :  How to debug the application?\n\nInstead of Run as -> Maven application, use Debug as -> Maven application. Add your breakpoints. You should be all set.\n\nIf you are using Spring Boot and Running using Run as -> Java application, then you can use Debug as -> Java Application. Add your breakpoints. You should be all set.\n\n### Q :  How do I configure auto restarting the server whenever source code changes?\n\nIf you are using Spring Boot, check configuration in Approach 1.\n\nIf you are doing a JSP/Servlet or a Spring MVC course without using Spring Boot use Approach 2.\n\n###### Approach 1 : Spring Boot Project\n\nIn pom.xml, add a dependency on devtools and restart the server. You are all set.\n\n> If you are using Intellij, there is one more configuration you need. Check out the intellij faq section.\n\n```\n<dependency>\n      <groupId>org.springframework.boot</groupId>\n      <artifactId>spring-boot-devtools</artifactId>\n      <scope>runtime</scope>\n    </dependency>\n```\n\n###### Approach 2: Non Spring Boot Project\n\nUse ```<contextReloadable>true</contextReloadable>``` in your pom.xml maven plugin configuration. Restart the server. You are all set.\n\n```\n<plugin>\n    <groupId>org.apache.tomcat.maven</groupId>\n    <artifactId>tomcat7-maven-plugin</artifactId>\n    <version>2.2</version>\n    <configuration>\n        <path>/</path>\n        <contextReloadable>true</contextReloadable>\n        <port>8080</port>\n    </configuration>\n</plugin>\n```\n\n### Q :  Can I use jboss instead of tomcat server?\nYeah. You can find more details of how to use the jboss maven plugin at https://docs.jboss.org/jbossas/7/plugins/maven/latest/examples/deployment-example.html.\n\n### Q :  How to get the projects to run in Tomcat 8 or 9?\nI’ve done a quick search to find the plugins for tomcat 8 and tomcat 9. Here’s the best I could find \n- http://jtuts.com/2016/09/14/run-embedded-tomcat8-maven/\n\nSee also here: https://stackoverflow.com/questions/26883836/tomcat-8-maven-plugin-for-java-8\n\n\n## Maven\n\n### Q :  Why Maven?\n\nYou don’t want to store all the libraries in your project!\n\nYou want to tell I need A, B, C and you would want the tool to download the libraries and make them available to you.\n\nThat's Maven. The tool which you use to manage the libraries.\n\nIf you need a new version of the library, you can change the version and your project is ready!\n\nAlso, You don't need to worry about what libraries your library needs to work. For example, Spring might need other libaries - logging, xml etc. \n\nOnce you declare a dependency on Spring, Maven would download\n- Spring\n- And all dependencies of Spring\n\nIsn't that cool?\n\n### Q :  What is ArtifactId and GroupId?\n\nYou don’t want to store all the libraries in your project!\n\nSo, you define dependencies in your pom.xml. \n\nMaven would download the dependencies and make them available for use in your project.\n\nBut, how does Maven know what dependency to download?\n\nYou need to tell it by giving the details of the dependency. \n\nJust like you can identify a Java class with a class name and a package name, you can identify a maven artifact by a GroupId and an ArtifactId.\n\n### Q :  How to know the exact string and name of a dependency and its artifactid?\n\nYou can either google or you can visit our Github repository.\n\nYou can find it on the home page of the section on github\n\n(Details would have been explained in the introduction video of the section)\n\n- For example - https://github.com/in28minutes/spring-web-services/tree/master/restful-web-services\n\n```\n  <dependency>\n      <groupId>org.springframework.boot</groupId>\n      <artifactId>spring-boot-starter-hateoas</artifactId>\n    </dependency>\n```\n\n### Q :  What's the difference between scope and phase?\n\nA scope specifies areas of the application, a dependency can be used.  I can use the dependency in tests or I can used it in source code or I can use it when I run the application.\n\nPhase - Different steps in the build life cycle. You compile code first. Then compile test code. Then you run unit tests, Then you run integration tests and so on..\n\n### Q :  Maven - How did a specific jar end up in our deployable?\n\nIn Maven terminology, what you are trying to see is called a dependency tree.\n\nYou can type in the command mvn dependency:tree to figure it out.\n\nIn eclipse. Right click on Project > Run as > Maven Build > dependency:tree\n\n### Q :  What is a SNAPSHOT as in 0.0.1-SNAPSHOT?\n\nA project in development uses a snapshot version. Once you have completed developing a version you would release it as 0.0.1 or 0.0.1-RELEASE. \n\nThe next version in development will be 0.0.2-SNAPSHOT.\n\nVersioning convention is MAJOR.MINOR.FIX\n\nYou can read more about it here : http://books.sonatype.com/mvnref-book/reference/pom-relationships-sect-pom-syntax.html\n\n\n### Q :  What is difference between runtime and provided scopes?\n\nProvided is when you expect the runtime environment to provide the dependency. For example, the Java ee api will be provided by tomcat or web sphere. We declare it as provided. \n\nLet’s say you want to use a specific class from a jar in your code. However, you don’t want that jar to be part of your deployable unit. You want this jar to be provided by the runtime server - say tomcat or web sphere or web logic. In those cases, we use a scope of provided to indicate that \n- It is NOT included in Deployable unit\n- It is available while compiling code\n\nLet's say We would want a jar to be only available when running the app and not when compiling it. We would use scope of runtime. \n- For example - business layer wants to use the api of data layer but not the implementation of data layer. We will make the implementation dependency of data layer as having a scope of runtime.\n\n```\n<dependency>\n  <groupId>javax</groupId>\n  <artifactId>javaee-web-api</artifactId>\n  <version>6.0</version>\n  <scope>provided</scope>\n</dependency>\n```\n\n### Q :  How can you always exclude a specific jar using Maven Exclusions?\n\nMaven exclusion is an awesome feature to exclude dependencies that we would not want to be part of our deployable\n\n```\n<dependency>\n    <groupId>org.springframework.boot</groupId>\n    <artifactId>spring-boot-starter-web</artifactId>\n    <exclusions>\n        <exclusion>\n            <groupId>org.springframework.boot</groupId>\n            <artifactId>spring-boot-starter-tomcat</artifactId>\n        </exclusion>\n    </exclusions>\n</dependency>\n```\nA good example of using dependency exclusion is logging with Spring Boot.  Default logging framework is logback. However, if I want to use log4j, I can exclude logback and add log4j. \n- You can read about it here : https://docs.spring.io/spring-boot/docs/current/reference/html/howto-logging.html#howto-configure-log4j-for-logging\n\nHowever, there is no concept of general exclusion in Maven. \n\nDependency exclusion is specific to the dependency where it is declared. \n\nYou have to exclude a jar in all the dependencies where it is declared as a dependency.\n\n### Tip : Example of a multi layered maven project\n\nhttps://github.com/in28minutes/MavenIn28Minutes/tree/\nmaster/4.web-application-with-maven\n\n### Error : java.lang.ClassNotFoundException\n\n```\nCaused by: java.lang.ClassNotFoundException: org.springframework.beans.factory.config.BeanDefinitionCustomizer\n```\n\nWhen ever you get this kind of exception. Find out which jar this class belongs to by doing a google - org.springframework.beans.factory.config.BeanDefinitionCustomizer\n\nIn this example I'm missing spring-beans. So, find the right version and add it in. You are all set.\n\n```\n<dependency>\n <groupId>org.springframework</groupId>\n <artifactId>spring-beans</artifactId>\n <version>4.3.10.RELEASE</version>\n</dependency>\n```\n\n### Q :  Why are we not using Gradle?\n\nGradle is awesome. \n\nIf Gradle came before Maven, that is what I would have used for this course :)\n\nMaven has the first mover advantage and has retained it and hence the choice for this course. But, if Gradle become more popular, I would be the first one to switch :)\n\nIf you want to create a Spring Boot app with Gradle, this should help you get started - https://spring.io/guides/gs/gradle/\n\n## Eclipse\n\n### Q :  How do I see the list of methods in a class?\n\nIts called outline. Short cut is Ctrl + O.\n\n### Q :  How do I become more efficient developer? \n\nFirst Step. Use Keyboard Shortcuts :)\n\n- Eclipse - https://shortcutworld.com/Eclipse/win/Eclipse-Helios_Shortcuts\n- Intellij - https://www.jetbrains.com/help/idea/keyboard-shortcuts-you-cannot-miss.html\n\n### Q :  How do you download source code to Eclipse so that you can see the code for frameworks?\n\nIts easy. Three Options.\n- Ctrl + Click on the Class Name and see if the jar is auto downloaded. \n- Right click on your project and go to Maven -> Download JavaDoc, you can also select Maven -> Download Sources\n- In Eclipse menus, open Window -> Preferences -> Maven and there you check the box with download sources and download javadoc as well.\n\n\n## Intellij and/or Mac\n\n### Q :  How to install Maven on MAC OS X?\n\nRecommended Reading\n- Updating PATH environment variable - https://www.mkyong.com/maven/install-maven-on-mac-osx/\n\n### Q :  How do I import a Maven project into Intellij?\n\nHere's a starting guide \n- https://www.jetbrains.com/help/idea/2016.1/importing-project-from-maven-model.html\n\nA few tips:\n- When importing project, check the option to \"Search for projects recursively\"\n\t- https://s31.postimg.org/gadu5g7l7/Options.png\n- After importing the project, wait for all background tasks to complete - \"Resolving Maven dependencies\" etc.....\n\t- https://s31.postimg.org/z448g6v6z/Resolving_Dependencies.png\n\n### Q :  How do I create and run unit tests (JUnit) with Intellij?\nHere's the complete guide \n- https://www.jetbrains.com/help/idea/creating-tests.html\n\nThis can be another option for setting up a unit test\n- https://stackoverflow.com/questions/19330832/setting-up-junit-with-intellij-idea\n\n### Error :  I'm having a problem running jsps with Spring Boot in Intellij. What should I do?\n\nChanged the scope of the embedded Tomcat dependency to required. Hope this helps anyone using IntelliJ.\n\n<dependency>\n    <groupId>org.apache.tomcat.embed</groupId>\n    <artifactId>tomcat-embed-jasper</artifactId>\n    <scope>required</scope> <!-- 'provided' for Eclipse, 'required' for IntelliJ -->\n</dependency>\n\n### Q :  Why does Hot reload not work with Spring Boot DevTools and Intellij?\n\nHere's a quick summary of what you have to do\n- Settings --> Build-Execution-Deployment --> Compiler --> enable \"Make Project Automatically\".\n- Press ctrl+shift+A and search for the registry. Enable following configuration ```compiler.automake.allow.when.app.running```\n- Restart IntelliJ.\n\nRecommended Reading\n- https://dzone.com/articles/spring-boot-application-live-reload-hot-swap-with\n\n\n```\n<dependency>\n   <groupId>org.springframework.boot</groupId>\n   <artifactId>spring-boot-devtools</artifactId>\n</dependency>\n```\n\n## Spring\n\n### Q :  What is the need for a Component Scan?\n\n> If you understand component scan, you understand Spring.\n\nThe first step of defining Spring Beans is by adding the right annotation - @Component or @Service or @Repository. \n\nHowever, Spring does not know about the bean unless it knows where to search for it. This part of \"telling Spring where to search\" is called a Component Scan. You define the packages that have to be scanned.\n\nOnce you define a Component Scan for a package, Spring would search the package and all its sub packages for components.\n\n### Q :  How do you define a Component Scan?\n\nDefining a Component Scan\n- If you are using Spring Boot, check configuration in Approach 1.\n- If you are doing a JSP/Servlet or a Spring MVC course without using Spring Boot use Approach 2.\n\n###### Approach 1 : Spring Boot Project\n\nExecutive Summary\n- If your other packages hierarchies are below your main app with the @SpringBootApplication annotation, you're covered by implicit components scan.\n- if the other packages do not reside under the main package, you should manually add them as @ComponentScan\n\n###### Detailed Example\n\nConsider the class below:\n\n```\npackage com.in28minutes.springboot.basics.springbootin10steps;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.ConfigurableApplicationContext;\n\n@SpringBootApplication\npublic class SpringbootIn10StepsApplication {\n\n\tpublic static void main(String[] args) {\n\t\tApplicationContext applicationContext = \n\t\t\t\tSpringApplication.run(SpringbootIn10StepsApplication.class, args);\n\t\t\n\t\tfor (String name : applicationContext.getBeanDefinitionNames()) {\n\t\t\tSystem.out.println(name);\n\t\t}\n\t}\n}\n```\n\n```@SpringBootApplication``` is defined on ```SpringbootIn10StepsApplication class``` which is package ```com.in28minutes.springboot.basics.springbootin10steps.```\n\n```@SpringBootApplication``` defines an automatic component scan on package ```com.in28minutes.springboot.basics.springbootin10steps```.\n\nYou are fine if all your components are defined in the above package or a sub-package.\n\nHowever, let's say one of the components is defined in a package ```com.in28minutes.springboot.somethingelse```\n\nIn this case, you would need add the new package into component scan.\n\nTwo Options\n-  Define @ComponentScan(“com.in28minutes.springboot”) - This would scan the entire parent tree of com.in28minutes.springboot.\n- Or Define two specific Component Scans by using an array. \n   - @ComponentScan({\"com.in28minutes.springboot.basics.springbootin10steps\",\"com.in28minutes.springboot.somethingelse\"})\n\nOption 1\n```\n@ComponentScan(“com.in28minutes.springboot”)\n@SpringBootApplication\npublic class SpringbootIn10StepsApplication {\n```\n\nOption 2\n```\n@ComponentScan({\"com.in28minutes.springboot.basics.springbootin10steps\",\"com.in28minutes.springboot.somethingelse\"})\n@SpringBootApplication\npublic class SpringbootIn10StepsApplication {\n```\n\n###### Approach 2: Non Spring Boot Project\n\nIn a non Spring Boot Project, we would typically define the component scan explicitly in an XML application context or a Java Application Context.\n\n###### Java Application Context\n\nOption 1\n```\n@ComponentScan(“com.in28minutes)\n@Configuration\npublic class SpringConfiguration {\n```\n\nOption 2\n```\n@ComponentScan({\"com.in28minutes.package1\",\"com.in28minutes.package2\"})\n@Configuration\npublic class SpringConfiguration {\n```\n\n###### XML Application Context\n\n```\n<context:component-scan base-package=\"com.in28minutes\" />\n```\n\nor Specific Multiple Packages\n\n```\n<context:component-scan base-package=\"com.in28minutes.package1, com.in28minutes.package2\" />\n```\n\n### Q :  How do I solve Errors related to Component Scan?\n\nTypical errors are shown below:\n\nError Type 1 : \n\nServer starts up fine but\n- My URL is not working\n- My login url is not working\n- My todo url is not working\n\nError Type 2\n```\nWARNING: No mapping found for HTTP request with URI [/spring-mvc/login] in DispatcherServlet with name 'dispatcher'\nWARNING: No mapping found for HTTP request with URI [/login] in DispatcherServlet with name 'dispatcher'\nWARNING: No mapping found for HTTP request with URI [/list-todos] in DispatcherServlet with name 'dispatcher'\n\n```\n\nOR \n\nError Type 3\n```\nNo qualifying bean of type [com.in28minutes.springboot.jpa.UserRepository] found for dependency [com.in28minutes.springboot.jpa.UserRepository]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}\n\n```\n\n###### Solution\n\nThree possible mistakes\na. You have not added the right annotation - @Controller, @Repository or @Controller\nb. You have not added a component scan. \nc. The package of your component is not defined in component scan.\n\nYou have two options\n1) Add the annotation or component scan\n2) Move the component to a package already under component scan\n\n### Q :  What is the difference between @Component and @ComponentScan? \n\n@Component and @ComponentScan are for different purposes.\n- @Component indicates that a class might be a candidate for creating a bean. Its like putting a hand up.\n- @ComponentScan is searching packages for Components. Trying to find out who all put their hands up.\n\n### Q :  How do I choose between Spring and CDI?\n\nIt's a choice between \n- A framework which popularised DI  and IOC (Spring)​ vs \n- A Java EE standard(CDI) that came up as a result of the framework .\n\nI go for the framework, in this case, because it is cutting edge and provides me with more options. There are a lot of guys out there who prefer the standard (CDI) because - well - it is a standard.​\n\nThe interesting part of the equation is Hibernate vs JPA brings up the same question. However, in Hibernate vs JPA, I prefer JPA.\n\n> Summary : There is no choice which is perfect. This is a 55-45 choice. Evaluate what your needs are and make a choice. The good thing is you cannot go wrong with either of the choices.\n\n\n### Q :  Why do we write a lot of unit tests in the Spring Master Class course?\n\nThink it this way. Functionally, does Spring allow you to do anything that you were not able to do earlier? The answer is NO. Almost everything that we are doing with Spring today could have been done without Spring 10 years back. So, what does Spring really bring to the table?\n\nAnswer is better Design and Testability through Dependency Injection.\n\nTo get into the right mindset with Spring, you need to think Testability and Loose Coupling.\n\n### Q :  What is the use of an @Bean annotation?\nWithin a Spring Configuration Class , @Bean is used to define beans with custom configuration. You define the beans to be created!\n\n### Q :  What is the difference between @Bean and @Component?\n\nHere's a quick fire answer\n- @Bean is used in Spring Configuration Files and Classes. It is used to directly instantiate or configure spring beans.\n- @Component is used with everything that you want Spring to manage. When Spring sees @Component, it creates a bean for you!\n\n@Component and @Bean do two quite different things, and shouldn't be confused.\n\nRecommended Reading\n- https://stackoverflow.com/questions/10604298/spring-component-versus-bean\n\nAn Extract\n- @Component (and @Service and @Repository) are used to auto-detect and auto-configure beans using classpath scanning. There's an implicit one-to-one mapping between the annotated class and the bean (i.e. one bean per class). Control of wiring is quite limited with this approach, since it's purely declarative.\n- @Bean is used to explicitly declare a single bean, rather than letting Spring do it automatically as above. It decouples the declaration of the bean from the class definition, and lets you create and configure beans exactly how you choose\n\n### Q :  What is the difference between @Component, @Service and @Repository annotations?\n\nAt the core, all of these define spring beans. However, you can further classify them based on the layer you are using them. \n- @Component - Generic Component\n- @Repository - encapsulating storage, retrieval, and search behavior typically from a relational database\n- @Service - Business Service Facade\n- @Controller - Controller in MVC pattern\n\nIn addition, these can be used at later point to add additional behaviour using AOP, for example. \n- For example, in case of @Repository, Spring automatically wires in JDBC Exception translation features.\n\nBy using a specific annotation, you are giving more information to the framework about your intentions.\n\n### Q :  Can we use @Component annotation instead of @Service for Business Services?\n\nHeres an extract from spring documentation. Since we were creating a business layer service, we used @Service. \n\n> \"@Component serves as a generic stereotype for any Spring-managed component; whereas, @Repository, @Service, and @Controller serve as specializations of @Component for more specific use cases (e.g., in the persistence, service, and presentation layers, respectively). What this means is that you can annotate your component classes with @Component, but by annotating them with @Repository, @Service, or @Controller instead, your classes are more properly suited for processing by tools or associating with aspects. For example, these stereotype annotations make ideal targets for pointcuts. Of course, it is also possible that @Repository, @Service, and @Controller may carry additional semantics in future releases of the Spring Framework. Thus, if you are making a decision between using @Component or @Service for your service layer, @Service is clearly the better choice. Similarly, as stated above, @Repository is already supported as a marker for automatic exception translation in your persistence layer.\"\n\n### Q :  What is the difference between web.xml and the Spring Context - servlet.xml?\n\nShort Answer:\n- web.xml - Java EE Web application Standard. Meta data and configuration of any Java EE compliant web application is stored in web.xml.\n- todo-servlet.xml - Spring Configuration file. Specific to Spring Framework.\n\nLong Answer:\n\nweb.xml is a default Web Application configuration descriptor, it's a core part of any WAR (Web application ARchive) and it is not really related to Spring, it's more like a Web App standard. You usually provide all the servlet related mappings/configuration in this file, then this file is picked up and used by the Web Server (like Tomcat) to set up your application. Again, it has little to do with Spring, you can map any kind of servlet in there not necessarily Springs DispatcherServlet.\n\ntodo-servlet.xml is a Spring specific configuration file used to launch up the Application Context.  Application Context is the core spring component implementing IoC (Inversion of Control). The xml contains Spring bean declarations, annotation-enabling configuration, etc.\n\nSo basically, web.xml defines the servlet and specifies which Spring application context file should be associated with this servlet (you can have different servlets use different app contexts), and the Spring application context defines the concrete configuration for this servlet and it's environment, e.g. which ViewResolver should it use and with what prefixes/suffixes.\n\n### Q :  Should we use XML or Annotation based wiring?\n\nWhich is better depends on a) context b) preference of the team.\n\nIf the configuration is specific to a bean, that is part of the current project code base - for example @Service, @Component, @Autowired - I prefer annotations.\n\nHowever, when it comes to some application related configuration or a common configuration example @ComponentScan, I do not really have a preference. I would leave it to the team. However, I would definitely want the entire team to discuss and agree what they prefer. \n\n### Q :  Can we do autowiring with Non Setter and Non Constructor Methods?\nYes you can. \n\n@Autowired annotation can be used with constructor, setter method or just any other method. Whenever Spring finds @Autowired annotation it will try to find beans matching to method parameters and will invoke that method. If multiple methods (setter or non-setter) have @Autowiredannotation, all will be invoked by Spring after bean instantiation.\n\nWhenever you use an @Autowired on a method in the bean, it will be called after bean instantiation. So, this method would be called and Spring would auto wire the matching objects from the Spring Context.\n\nHere's a recommended reading:\n- http://stackoverflow.com/questions/30188262/spring-autowired-for-setter-methods-vs-non-setter-methods\n\n### Q :  Where should we use Checked Exceptions?\n\nI've a simple philosophy!\n\nIf you can do something about an Exception other than showing an error page to the user, then consider Checked Exceptions. You want the consumer of the method to do something about that exception!\n\nIn all other scenarios where there is nothing a programmer can do - other than showing an error page - use Unchecked exceptions. \n\nI love keeping exception handling code to a bare minimum!\n\nThat's what Spring enables by converting most Checked exceptions into Runtime (also called Unchecked) exceptions.\n\n### Q :  What is the difference between Cross Cutting Concerns and AOP?\n\nA quick fire answer\n- Cross Cutting Concerns are features or functionality that you would need in multiple layers - logging, performance management, security etc.\n- AOP is one of the preferred approaches to implement Cross Cutting Concerns.\n\n### Q :  What is difference between IOC and Application Context?\n\nIOC is a concept - Inversion of Control. Instead of the programmer injecting dependencies, the framework takes the responsibility of auto wiring.\n\nApplicationContext is the Spring implementation of IOC.\n\nBean Factory is the basic version of IOC Container. \n\nApplication Context adds in all the features that are typically needed by enterprise applications. \n\n### Q :  What is the difference between classPathXmlApplicationContext and annotationConfigApplicationContext ?\n\n- classPathXmlApplicationContext > You want to load an application context using an Spring Config XML present in the class path.\n- annotationConfigApplicationContext > You want to load an application context using a Java Config class.\n\n\n### Q :  When @Around aspect is introduced the value returned by@AfterReturning is lost. Why is this happening?\nThe around method should return an Object - value returned by joinpoint.proceed(). \n\n```\n@Around(\"com.in28minutes.spring.aop.springaop.aspect.CommonJoinPointConfig.trackTimeAnnotation()\")\npublic Object around(ProceedingJoinPoint joinPoint) throws Throwable{\n    long startTime = System.currentTimeMillis();\n \n    Object retVal = joinPoint.proceed();\n \n    long timeTaken = System.currentTimeMillis() - startTime;\n    logger.info(\"Time taken by {} is equal to {}\",joinPoint, timeTaken);\n \n    return retVal;\n}\n```\n### Q :  How do you use which autowiring type to use - @Primary or @Qualifier?\n\nIf there is a default bean (a bean you prefer over all others) that you want to use most of the times, then go for @Primary and use @Qualifier for non-default scenarios.\n\nIf all of the beans have same priority, we would go with @Qualifier always.\n\nIf you want to select a bean at runtime, thats business logic - Not auto wiring.\n\nYou would need to create a separate class for Selector which has both the sorting algorithms auto wired. It should have the business logic to choose the appropriate algorithm.\n\n\n### Q :  What are the New Features in Spring Framework 5.0?\n\nI’ve recently wrote a book on Mastering Spring 5.0.\n\nImportant features in Spring 5.0 are Functional Web Framework, Kotlin and Reactive Programming support. But none of these are mainstream yet. \n\nhttps://github.com/spring-projects/spring-framework/wiki/What%27s-New-in-the-Spring-Framework#whats-new-in-spring-framework-5x \n\n### Q :  What are the possible reasons of preDestroy not being called?\n- Replace ApplicationContext with ConfigurableApplicationContext and call applicationContext.close() at the end.\n\n### Q :  Compare Application Context vs IOC Container vs Web Container vs EJB Container\n\nDo we need a Web Container to run a Spring Boot Application?\n\nBasically spring runs anywhere where we have a JVM because that JVM will have capability to run some sort of a container or capability to run an application. Difference would be that the mechanism to load application context would be different based on where it runs. e.g. 2  high level categories - ApplicationContext for Web and Applicationcontext for standalone and again in those 2 categories we will choose \"how\" and \"from where\" we want to load that metadata for those applicationContext. \n\nWeb Container & EJB Containers are part of the application/web servers - Tomcat, Websphere, Weblogic. They run what ever application is given to them. Java EE defines a contract for web applications (web.xml etc etc) and these are the implementations of that contract.\n\nSpring Container is part of the application you are building - the jar or the war. It can run inside a web container, EJB container or even without them :) You can launch it as a java application or you can even run it in an embedded server.\n\n### Notes :  Notes from Rodolfo\nLink to this file:\nhttps://s3.amazonaws.com/espanol-libros/AllLinks.rtf\n\nSpring Master Class:\n\nhttps://s3.amazonaws.com/espanol-libros/Spring/Section+03+Eclipse+in+5+Steps.rtf\n\nhttps://s3.amazonaws.com/espanol-libros/Spring/Section+04+Maven+in+5+Steps.rtf\n\nhttps://s3.amazonaws.com/espanol-libros/Spring/Section+09+Basic+Web+Application.rtf\n\nhttps://s3.amazonaws.com/espanol-libros/Spring/Section+12+Databases.rtf\n\n### Q :  How do we inject different bean depending on the configuration in application.properties?\n\nConsider the example\n\n```\ninterface GreetingService {\npublic String sayHello();\n}\n```\n\nTwo components\n```\n@Component(value=\"real\")\nclass RealGreetingService implements GreetingService {\n\tpublic String sayHello() {\n\t\treturn \"I'm real\";\n\t}\n}\n\n \n@Component(value=\"mock\")\nclass MockGreetingService implements GreetingService {\n\tpublic String sayHello() {\n\t\treturn \"I'm mock\";\n\t}\n}\n```\n\napplication.properties\n```\napplication.greeting: real \n```\n\nAdding @Resource with the name of the property\n\n```\n@RestController\npublic class WelcomeController {\n \n@Resource(name=\"${application.greeting}\")\nprivate GreeterService service1;\n```\n\n### Error :  Log4j problems with Spring 5!\n- TODO\n\n### Q :  What is the minimum baseline Java Version for Spring Boot 2 and Spring 5?\n\nSpring 5.0 and Spring Boot 2.0 requires Java 8 or later. Java 6 and 7 are no longer supported.\n\nRecommended Reading \n- https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.0.0-M1-Release-Notes\n\n### Error :  Getting SLF4J errors and not getting logger output in  Step 19?\n\n```\nSLF4J: Failed to load class \"org.slf4j.impl.StaticLoggerBinder\".\nSLF4J: Defaulting to no-operation (NOP) logger implementation\nSLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.\n```\nAs we start removing Spring Boot and bringing in Spring core,in Step 19 of Spring In Depth Section, you would see \n- A few SLF4J errors\n- Logging does not work\n\nDo not worry about them. We will fix them in the next step Step 20 by adding logback as the logging framework.\n\n### Error : No Spring WebApplicationInitializer types detected on classpath\n\nIt usually happens when you are having conflicts in Java and Spring versions.\n-  Please refer http://stackoverflow.com/questions/22938689/info-no-spring-webapplicationinitializer-types-detected-on-classpath. \n\n## JSP Servlets and Spring MVC\n\n### Q :  What is the difference between @Controller and @RestController?\n\n@RestController = @Controller + @ResponseBody\n\nThe response from the @RestController are directly returned as a response after conversion to JSON or XML.\n\nIn Summary\n- @Controller : Uses a view resolver to find the view. You are returning either the View, View Name or Model and View.\n- @RestController : You are returning a bean. The bean would be converted to a JSON using a Jackson message converter.\n\n\n```\n@Controller\n@ResponseBody\npublic class MyController { }\n \n@RestController\npublic class MyRestController { }\n```\n### Q :  Why is there no context root in the request url for each web application? \n\nGreat question. The magic is in path configuration of tomcat7 maven plugin. We use ```/``` as the path. Therefore, there is no need for a context root. You can configure a path of your choice and that becomes the context root for your web app.\n\n```\n<plugin>\n    <groupId>org.apache.tomcat.maven</groupId>\n    <artifactId>tomcat7-maven-plugin</artifactId>\n    <version>2.2</version>\n    <configuration>\n        <path>/</path>\n        <contextReloadable>true</contextReloadable>\n    </configuration>\n</plugin>\n```\n\n### Q :  What does tomcat7:run exactly mean? \n\nWe use a maven plugin for integrating with tomcat7. The plugin would take care of downloading tomcat and installing the war in it. \n```\n<plugin>\n    <groupId>org.apache.tomcat.maven</groupId>\n    <artifactId>tomcat7-maven-plugin</artifactId>\n    <version>2.2</version>\n    <configuration>\n        <path>/</path>\n        <contextReloadable>true</contextReloadable>\n    </configuration>\n</plugin>\n```\n\nYou can find more documentation here \n- http://tomcat.apache.org/maven-plugin-trunk/tomcat7-maven-plugin/plugin-info.html\n\nYou can read more down here as well\n- http://stackoverflow.com/questions/7823346/mvn-tomcat7run-how-does-it-work\n- http://tomcat.apache.org/maven-plugin-trunk/tomcat7-maven-plugin/run-mojo.html\n\n### Q :  How is the URL decided with Spring MVC?\n\nFirst things are the port and the context root. We use the default port - 8080 and we set path to /. So, the initial url is http://localhost:8080.\n\npom.xml\n```\n<plugin>\n    <groupId>org.apache.tomcat.maven</groupId>\n    <artifactId>tomcat7-maven-plugin</artifactId>\n    <version>2.2</version>\n    <configuration>\n        <path>/</path>\n        <contextReloadable>true</contextReloadable>\n    </configuration>\n</plugin>\n```\n\nWe configured dispatcher servlet with a url-pattern /. So, it handles all request to http://localhost:8080\n\nweb.xml\n```\n<servlet>\n    <servlet-name>dispatcher</servlet-name>\n    <servlet-class>\n        org.springframework.web.servlet.DispatcherServlet\n    </servlet-class>\n    <init-param>\n        <param-name>contextConfigLocation</param-name>\n        <param-value>/WEB-INF/todo-servlet.xml</param-value>\n    </init-param>\n    <load-on-startup>1</load-on-startup>\n</servlet>\n\n<servlet-mapping>\n    <servlet-name>dispatcher</servlet-name>\n    <url-pattern>/</url-pattern>\n</servlet-mapping>\n```\n\nThe ```showWelcomePage``` method is mapped with a path of \"/\". So, a request to http://localhost:8080 will be handled by this method.\n\n```\n@Controller\npublic class WelcomeController {\n\n    @RequestMapping(value = \"/\", method = RequestMethod.GET)\n    public String showWelcomePage(ModelMap model) {\n        model.put(\"name\", getLoggedInUserName());\n        return \"welcome\";\n    }\n```\n\n```TodoController``` ```showTodosList``` method is used to display the list of todos. The uri configured is /list-todos. So, it handles requests to http://localhost:8080/list-todos.\n\n```\n@Controller\npublic class TodoController {\n\n    @RequestMapping(value = \"/list-todos\", method = RequestMethod.GET)\n    public String showTodosList(ModelMap model) {\n        String user = getLoggedInUserName();\n        model.addAttribute(\"todos\", service.retrieveTodos(user));\n        return \"list-todos\";\n    }\n```\n\n### Error : No plugin found for prefix 'tomcat7' in the current project\nNo plugin found for prefix 'tomcat7' in the current project and in the plugin groups [org.apache.maven.plugins, org.codehaus.mojo] when trying to run the application using run with Maven tomcat7:run\n\nFirst thing I would check is if maven plugin configured in your pom.xml as mentioned in https://github.com/in28minutes/SpringMvcStepByStep/blob/master/Step01.md\n\n```\n<plugin>\n    <groupId>org.apache.tomcat.maven</groupId>\n    <artifactId>tomcat7-maven-plugin</artifactId>\n    <version>2.2</version>\n    <configuration>\n        <path>/</path>\n        <contextReloadable>true</contextReloadable>\n    </configuration>\n</plugin>\n```\n\nIf it is configured correctly then I would check these two links if they are of any use\n- http://stackoverflow.com/questions/24311383/maven-no-plugin-found-for-prefix-tomcat7-in-the-current-project-and-in-the-p\n- http://stackoverflow.com/questions/21073123/maven-no-plugin-found-for-prefix-tomcat7-in-the-current-project\n\n### Q :  Is this kind of Tomcat server usage what is commonly referred to as \"Embedded Tomcat Server\" ?\n\n> This answer applies only to our Basic JSP Servlets and Spring MVC Courses. For all the courses using Spring Boot we use an embedded tomcat server.\n\nThink about what you would need to be able to deploy your application (typically) on a virtual machine.\n- Step 1 : Install Java\n- Step 2 : Install the Web/Application Server (Tomcat/Websphere/Weblogic etc)\n- Step 3 : Deploy the application war\n\nWhat if we want to simplify this?\n\nHow about making the server a part of the application? \n\n> You would just need a virtual machine with Java installed and you would be able to directly deploy the application on the virtual machine. Isn't it cool?\n\nThis idea is the genesis for Embedded Servers.\n\nWhen we create an application deployable, we would embed the server (for example, tomcat) inside the deployable. \n> For example, for a Spring Boot Application, you can generate an application jar which contains Embedded Tomcat. You can run a web application as a normal Java application!\n\nEmbedded server is when our deployable unit contains the binaries for the server (example, tomcat.jar).\n\n###### Basic Spring MVC and JSP Servlet courses do not use embedded servers\n\nIn our basic Spring MVC and JSP Servlet courses, we use the age old approach of generating wars. However, we use a tomcat maven plugin to simplify deployment. \n\nThe plugin will take care of downloading Tomcat and deploying the war to it. One less thing for you to worry about. \n\nHowever, this is not really an embedded server.  This is midway between an external server and an embedded server.\n\n###### All our Spring Boot courses use Embedded Servers\nAll our Spring Boot courses use embedded Tomcat server.\n\n### Q :  How do we handle errors to non existing URL Paths with Spring MVC?\n\nYou can add an error page for 404 in your web.xml.\n\n```\n<error-page>\n    <error-code>404</error-code>\n    <location>/error404.jsp</location>\n</error-page>\n```\n\n### Q :  How do we configure a welcome page?\n\nLet's say your Login Controller is mapped to login.do and you would want that to be default page to be rendered when you type in http://localhost:8080.\n\nThis can be achieved by having a welcome file list configured in the web.xml.\n\n```\n<welcome-file-list>\n    <welcome-file>login.do</welcome-file>\n</welcome-file-list>\n```\n\n### Q :  Why do we teach JSP and Servlets in the first section of Spring MVC Course?\n\nI would recommend you to read \"The in28Minutes Way\" - https://github.com/in28minutes/in28minutes-initiatives/tree/master/The-in28Minutes-Way#we-want-you-to-be-strong-on-the-fundamentals\n\n> We think that understanding the fundametals of a tool, framework or a language is what makes you an expert. While you want to quickly learn how to use a framework, the key difference between an expert and a novice is \"How deep do you understand the framework?\".\n\nIn Spring MVC course, we teach you basics of JSPs and Servlets and then move to Spring MVC to ensure you understand why we are using Spring MVC.\n\n### Q :  Why do we use  @ResponseBody sometimes and ResponseEntity<T> some other times?\n\nQuick Answer - You use ResponseEntity when you want to customize the Response Status. In all other situations, we use @ResponseBody.\n\n###### Example 1\n@GetMapping(value=\"/resource\")\n@ResponseBody\npublic Resource sayHello() { \n   return resource;\n}\n\n###### Example 2\n@PostMapping(value=\"/resource\")\npublic ResponseEntity<String> createResource() {\n    ....\n    ....\n    return ResponseEntity.created(resource).build();\n}\n\nThere are a variety of HTTP Response Status Codes that you can return with your response.\n\n- 200 - SUCCESS\n- 201 - CREATED\n- 404 - RESOURCE NOT FOUND\n- 400 - BAD REQUEST\n- 401 - UNAUTHORIZED\n- 500 - SERVER ERROR\n\nWith @ResponseBody the only response type that goes out is SUCCESS (Example 1). (or 500 if a server error happens)\n\nLet's say you are creating a resource. You would want to send a status of 201 CREATED. In this case, we use ResponseEntity as in Example 2.\n\n### Q :  What is difference between Spring 5 and Spring 4 in terms of developing web application in the course? Does it matter if a new version is used ?\n\nThere will be one problem you will face when you use Spring 5. \n\nWhen you get to /src/main/webapp/WEB-INF/views/todo.jsp - You should use modelAttribute instead of commandName\n\nInstead of\n```\n<form:form method=\"post\" commandName=\"todo\">\n```\nUse\n```\n<form:form method=\"post\" modelAttribute=\"todo\">\n```\nYou can read more about this here :\n\nhttps://stackoverflow.com/questions/21495616/difference-between-modelattribute-and-commandname-atributes-in-form-tag-in-sprin\n\n\n\n### Q :  What is the difference between Filters, Listeners and Interceptors?\n\nConceptually similar. Servlet filters can intercept only HTTPServlets. Listeners can intercept a few specific events. How do you intercept events which are neither of the above.\n\nBoth filters and interceptors do the same things - They intercept something and do something before/after an action is performed.\n\nJava EE uses the term filter (in web.xml) and Spring calls them Interceptors.\n\nThats where AOP comes in. You can intercept calls to any object with AOP. \n\nMore Reading\n- http://www.programering.com/a/MzM3EDNwATY.html\n\n### Q :  What is the difference between ModelMap and ModelAndView?\n\nModel is an interface while ModelMap is a class.\n\nModelAndView is just a container for both a ModelMap and a View object. It allows a controller to return both as a single value.\n\nI usually like ModelAndView to return the model and view from a controller. However, there is an option where you can just add values to ModelMap and return viewname from the controller method. \n\nMore Reading\n- http://stackoverflow.com/questions/16951609/when-to-use-modelandview-vs-model-in-spring \n\n### Q :  What is the difference between model.put() and model.addAttribute()? \n\nCode for addAttribute method is listed below. It does an additional null check before calling a put. Doesn't really matter which one you use. \n\nI like addAttribute because you are separated from underlying data structure (```put``` implies you are using a hashmap).\n\n/**\n     * Add the supplied attribute under the supplied name.\n     * @param attributeName the name of the model attribute (never <code>null</code>)\n     * @param attributeValue the model attribute value (can be <code>null</code>)\n     */\n    public ModelMap addAttribute(String attributeName, Object attributeValue) {\n        Assert.notNull(attributeName, \"Model attribute name must not be null\");\n        put(attributeName, attributeValue);\n        return this;\n    }\n\nOne more difference is that addAttribute returns the ModelMap back. So, you can chain calls.\n\nmodel.addAttribute(\"attribute1\",\"value1\").addAttribute(\"attribute2\",\"value2\");\n\n### Q :  How do you pass values from Java Controller to JSP?\n\nThis is done through Model. You put a value in the model object in your Controller. Spring MVC makes it available to the JSP. \n\nPut a list with name \"todos\" in the model. Spring MVC makes it available with name \"todos\" in the JSP.  \n\nWe can access the value in the JSP using ```${todos}```\n\n```<c:forEach items =\"${todos}\" var= \"todo\">``` - In this forEach var=\"todo\" declares a variable todo. \n\nYou can think of it similar to Java Enhanced for loop - \"for(Todo todo:todos)\" ). \n\n### Q :  What is Form Binding?\nWe want to take values from screen and store them to the database. The value on the HTML form needs to be transferred to the bean on the Controller. \n\nIf you use the Spring MVC form tags, Spring MVC automatically takes care of the binding the values in the HTML form to the bean.\n- I would recommend you to do a View Source on the browser and see the html that is generated with the form tags\n\nYou need a form to bind the value to a bean. \n\nYou can look up the documentation for Spring MVC Form Tags for more details.\n\nI would recommend you to start looking at each of the things thats happening in the browser. See the html that is generated (view source), look at what are the values in the request when you click the submit button on the screen (Look at the network tab : http://code.tutsplus.com/articles/chrome-dev-tools-networking-and-the-console--net-28167)\n\nCouple of Sources which might be useful for you\n- Spring MVC Documentation : http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#mvc\n- Spring MVC Code : https://github.com/spring-projects/spring-framework/tree/master/spring-webmvc/src\n\n### Q :  What is WEB-INF exactly? Why so we need it?\n\nFrom the specification, \"A special directory exists within the application hierarchy named WEB-INF. This directory contains all things related to the application that aren’t in the document root of the application. The WEB-INF node is not part of the public document tree of the application. No file contained in the WEB-INF directory may be served directly to a client by the container. However, the contents of the WEB-INF directory are visible to servlet code using the getResource and getResourceAsStream method calls on the ServletContext, and may be exposed using the RequestDispatcher calls.\"\n\nMore Reading\n- http://stackoverflow.com/questions/19786142/what-is-web-inf-used-for-in-a-java-ee-web-application\n\n### Q :  Why do we use Hibernate Validator?\n\nHibernate Validator is not related to Database. It is a validation framework.\n\nHibernate Validator 5.x is the reference implementation Bean Validation 1.1! \n\nActually, you can use any implementation of Bean Validation API.  However, there are really no other popular options.\n\nAs you can see at http://beanvalidation.org/2.0/, Hibernate Validator is the only one which is certified!\n\n### Q :  Are Model objects specific to a request?\n\nYes. They are specific to a request.\n\nModel objects cannot be shared across requests. So, 2 different requests mean 2 different model objects.\n\nIf you look at the jsp for a todo page, it shares the responsibility of creating a new todo and modifying an existing todo. And the todo object is binded to the form. \n\nTo display todo page for new todo, we need a model with no values. That's the first model object that's created.\n- This is used only for the display of new todo page. \n\nOnce the page is displayed, the first model does not exist anymore. \n\nWhen user fills in the values and clicks submit, the values in the form gets bound to a new model object - the second one.\n\n### Q :  The groupid for jstl jar is jstl and not javax.servlet\n\nYeah. There seems to be some confusion around this. As I understand java.servlet is recommended.\n\nRecommended Reading\n- http://stackoverflow.com/questions/2276083/include-jstl-dependency-with-maven\n\nIts not a recommendation I give often, but feel free to use whatever works in this specific scenario\n\n\n### Q :  Why are we using request GET method for \"delete-todo\" request? \n\n> Question Continued - Shouldn't we be using DELETE request method? \n\nThe data we use to execute the DELETE is just an id. It is not sensitive information. We can add a check to see if the user has permission on the id to execute a delete before executing a delete. Changing it to POST does not give us any added advantages.\n\nHowever, when we create RESTful services, we should use DELETE. \n\n### Q :  Why do we need xmlns hyperlinks? like http://www.springframework.org/schema/bean\n\nThese are generic and would work with all version of Spring Framework. Otherwise we would need to change the version every time we upgrade Spring Framework.\n- http://stackoverflow.com/questions/11610790/what-difference-does-an-xmlns-definition-make-in-a-spring-configuration-file\n\n### Error : View is not resolving to a JSP\nIn your web.xml, ensure your url-pattern is set to /spring-mvc/\n\n```\n<servlet-mapping>\n    <servlet-name>dispatcher</servlet-name>\n    <url-pattern>/spring-mvc/</url-pattern>\n</servlet-mapping>\n```\n\n> If you have /* dispatcher servlet would handle requests to the views as well. We don't want that!\n\n### Q :  How to use own CSS with Spring MVC?\n\nSpring Configuration XML\n<mvc:resources mapping=\"/resources/**\" location=\"/WEB-INF/resources/\" />\n\nJSP\n<link href=\"resources/css/main.css\" rel=\"stylesheet\">\n\n### Q :  Where should we place our static (css, js, html) resources in a Spring MVC application?\n\nFor the Java script, I would have separate java script files and include them into your jsp.\n\nHere's a small discussion where static files should be located:\n- https://stackoverflow.com/questions/7836930/where-do-css-and-javascript-files-go-in-a-maven-web-app-project\n\n\n### Q :  How to add a custom login page in Spring Security?\n\nComplete example down here \n- http://docs.spring.io/spring-security/site/docs/current/guides/html5/form-javaconfig.html\n\nOther Recommended Reading\n- https://docs.spring.io/spring-security/site/docs/3.2.0.RELEASE/guides/form.html\n- http://www.concretepage.com/spring-4/spring-4-mvc-security-custom-login-form-and-logout-example-with-csrf-protection-using-annotation-and-xml-configuration\n\n### Q :  How can you authenticate by connecting to a database with Spring Security?\n\nComplete example down here : \n- https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-web-secure-jdbc\n\n### Q :  Why is request method POST recommended compared to GET for sensitive data?\n\nFollowing are the steps that happen when you interact with a web page\n- Browser : You enter the details\n- Browser : Creates a POST request where details are put into the request (and encrypted if you are using https)\n- Routers and Network : The POST request is sent through multiple routers before it reaches the destination\n\nIn the case of a get request and post request, in steps a and b you can see the details on the browser. The real change is in step c. \n\n> Important Question to ask is \"What is going across the network?\"\n\nIn the case of GET request, your details are part of url and all routers can see those details. However, in the case of POST, the details are sent as part of the body of the request and hence more safe.\n\n### Q :  We use ${todo.done} in JSP even though the name of the field in Todo.java is isDone. Shouldn't we be using ${todo.isDone}?\n\nIsn't it tricky? Welcome to the fun of Java Beans. \n\nYou can try renaming the variable to done or what ever you want. The important thing is what is the name of getters and setters.\n\nJava Beans work based on the names of your getters and setters. The setter is named setDone. So, we use ${todo.done}.\n\nI would recommend playing with getters and setters to understand this further.\n\n```\npublic boolean isDone() {\n    return isDone;\n}\n\npublic void setDone(boolean isDone) {\n    this.isDone = isDone;\n}\n```\n\n\n### Error : After adding security dependencies - java.lang.NoSuchMethodError: org.springframework.aop.framework.autoproxy.AutoProxyUtils.determineTargetClass\n\n```\nHTTP Status 500 - Servlet.init() for servlet dispatcher threw exception\njava.lang.NoSuchMethodError: org.springframework.aop.framework.autoproxy.AutoProxyUtils.determineTargetClass(Lorg/springframework/beans/factory/config/ConfigurableListableBeanFactory;Ljava/lang/String;)Ljava/lang/Class;\nat org.springframework.context.event.EventListenerMethodProcessor.afterSingletonsInstantiated(EventListenerMethodProcessor.java:78)\n```\n\nIts a compatibility issue between Hibernate Validator and Spring.\n\nSolution - Change your 4.2.3.RELEASE dependency to 4.2.2.RELEASE and change Hibernate version 5.0.4.Final to 5.0.2.Final\n\nRecommended Reading\n- http://stackoverflow.com/questions/34053170/spring-4-2-3-release-and-hibernate-5-0-4-final-compatibility-issue\n\n\n### Q :  How do I ensure that session attributes are not part of the request url?\n\nWhen we use model.put(\"name\", name) and name is a session attribute, these parameters are shown in redirected page as parameters in url. \n\nTo avoid this, we can use flash attributes.\n\nAn example below:\n\n```\n@RequestMapping(value=\"/Login\",method = RequestMethod.POST)\npublic ModelAndView loginValidate(HttpServletRequest req, RedirectAttributes redir){\n...\n \n    modelAndView.setViewName(\"redirect:welcome\");\n    redir.addFlashAttribute(\"USERNAME\",uname);\n    return modelAndView;\n}\n```\n\n\n### Error :  Spring Security - java.lang.NoClassDefFoundError: org/springframework/web/cors/CorsConfigurationSource\n\nTypically this happens because the schemas in your application context xml are referring to a different Spring Version\n\nExample : You use Spring 5 and your schema's are referring to Spring 4.0\n```\nxsi:schemaLocation=\"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd\n http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd\n http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd\">\n```\n\nSolving the error - Recommendation is to use generic schema definitions. \n```\n<beans xmlns=\"http://www.springframework.org/schema/beans\"\n    xmlns:context=\"http://www.springframework.org/schema/context\"\n    xmlns:mvc=\"http://www.springframework.org/schema/mvc\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n    xsi:schemaLocation=\"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd\n        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd\n        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd\">\n```\n\n\n### Error :  Unable to find setter method for attribute commandName\n\n```\norg.apache.jasper.JasperException: /WEB-INF/jsp/todo.jsp (line: [12], column: [1]) Unable to find setter method for attribute: [commandName]\n\n```\ncommandName is deprecated and is replaced with modelAttribute.\n\nAll you have to do is modify the form line within todo.jsp (getting rid of commandName=\"todo\"), as follows:\n\n```\n <form:form method=\"post\" modelAttribute=\"todo\">  \n```\n\nThis is further explained in the last step of Spring Boot course in section \"Connecting to JPA\" - Step 33: Upgrading to Spring Boot 2 and Spring 5\n\n\n### Q :  Can I have multiple parameters with the same name in a request?\n\nLet's take an example\n\nhttp://localhost:8080/login?name=Ranga&name=Ravi&name=Sathish\n\nYou can accept all values using an array in the controller method.\n\nHere's a snippet!\n\n```\npublic String method(@RequestParam(value=\"name\") String[] names){\n \n    //if length of names is not 1, throw an error!\n \n    //Continue processing.\n \n}\n```\n\n### Error :  java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'todo' available as request attribute\n\nThis is a problem with using ToDo as the bean class name instead of Todo.\n\n```\nresult.hasErrors()\n\nwhen I try to add less than 6 chars, error occurs which says:\n\njava.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'todo' available as request attribute\n\n```\n2 Possible Solutions\n- Rename your ToDo.java to Todo.java (OR)\n- Change your method signature to include @ModelAttribute\n\npublic String addTodo(ModelMap model, @ModelAttribute(\"toDo\") @Valid ToDo todo, BindingResult result) {\n\nSpring MVC makes assumptions about your beans. If your class is ToDo, it expects the name of the object to be toDo. since, we are using todo as the name we need to add in a ModelAttribute annotation. \n\n### Error :  Request processing failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.in28minutes.Todo.Todo]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.in28minutes.Todo.Todo.<init>()\n\nNo default constructor found;\n\nYou would need a default constructor\n\npublic void Todo() {} \n\n### Error :  Caused by: java.lang.IllegalArgumentException: The servlets named [com.in28minutes.LoginServlet] and [webapp.LoginServlet] are both mapped to the url-pattern [/login.do] which is not permitted \n\nProblem is because there are two servlets with same url pattern.\n\nTo fix it, you can delete one of the LoginServlet classes.\n\n### Q :  How is server picking up index.html and index.jsp even when they are not configured in web.xml?\n\nThese are present in the default web.xml present on the tomcat server. Thats why even when you don't provide a web.xml , these are picked up.\n\n<welcome-file-list>\n        <welcome-file>index.html</welcome-file>\n        <welcome-file>index.htm</welcome-file>\n        <welcome-file>index.jsp</welcome-file>\n    </welcome-file-list>\n\n\n### Q :  What is the benefit of using view resolver?\nQuestion Continued - Will it not take more time to process a request.\n\nIt all boils down to good design!\n\nDo one thing very well. \n\nView Resolver maps a logical view name to a physical view (JSP).\n\nAs far as Java is concerned, more method calls does not mean bad performance.\n\n###### Why am I not able to see todo's list on screen?\nMake sure you use the right user name in the code to retrieve the list of todos.\n\n```\nmodel.put(\"todos\", service.retrieveTodos(\"in28Minutes\"));\n```\n\n### Q :  What is @ControllerAdvice?\n@ControllerAdvice is common to all the controllers.\n\nAll logic that is common to all the controllers is implemented in Controller Advice classes.\n\nException handling etc.\n\n### Q :  What Request method should be used for updating user details?\nYou would  need to use a PUT method for updating a user. You can use a @PutMapping.\n\n### Q :  What is the difference between put and patch request methods?\n- PUT : When you update the entire resource - when you want to update all/most of the fields of a resource.\n- PATCH: When you want to update specific details of the resource. All other details remain unchanged. \n\n## Spring Boot\n\nSpring Boot is the best Java framework for microservices We recommend you to become an expert at Spring Boot!\n\n### Q :  What should be the first things I read about Spring Boot?\nHere are a list of articles for you to get started with understanding Spring Boot.\n- [Spring Boot vs Spring vs Spring MVC](http://www.springboottutorial.com/spring-boot-vs-spring-mvc-vs-spring)\n- Basics of Spring Boot - [Auto Configuration](http://www.springboottutorial.com/spring-boot-auto-configuration), [Spring Boot Starter Projects](http://www.springboottutorial.com/spring-boot-starter-projects), [Spring Boot Starter Parent](http://www.springboottutorial.com/spring-boot-starter-parent), [Spring Boot Initializr](http://www.springboottutorial.com/spring-initialzr-bootstrap-spring-boot-applications)\n- Rest Services - [Basic Rest Service with Spring Boot](http://www.springboottutorial.com/creating-rest-service-with-spring-boot), [Unit Testing](http://www.springboottutorial.com/unit-testing-for-spring-boot-rest-services), [Integration Testing](http://www.springboottutorial.com/integration-testing-for-spring-boot-rest-services)\n- Web Application - [Create Basic Web Application with Spring Boot](http://www.springboottutorial.com/creating-web-application-with-spring-boot)\n- Spring Boot Starter Security - [Secure Your Rest Services with Spring Boot](http://www.springboottutorial.com/securing-rest-services-with-spring-boot-starter-security)\n\n### What is the minimum baseline Java Version for Spring Boot 2 and Spring 5?\n\nSpring Boot 2.0 requires Java 8 or later. Java 6 and 7 are no longer supported.\n\nRecommended Reading \n- https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.0.0-M1-Release-Notes\n\n\n### Q :  Is Spring Initializr the only way to create Spring Boot Projects?\n\nNo.\n\nSpring Initializr makes it easy to create Spring Boot Projects. But you can setup a maven project and add the right dependencies to start off. \n\nIn our Spring course, we use 2 approaches to create projects. \n- The first one is start.spring.io. \n- The other one - setting up a project manually is used in the Section titled - “Basic Web Application”\n\n###### Setting up a maven project manually\n\nHere are the important steps:\n- In Eclipse, Use File -> New Maven Project to create a new project.\n- Add dependencies.\n- Add the maven plugins!\n- Add the Spring Boot Application class\n\nYou are ready to go!\n\n### Q :  Why am I not seeing code completion when updating application.properties in Eclipse?\n\nYou would need to install the Spring Eclipse plugin. \n- https://marketplace.eclipse.org/content/spring-ide#group-external-install-button\n\n### Q :  Why do we need spring-boot-maven-plugin?\n\nspring-boot-maven-plugin provides a few commands which enable you to package the code as a jar or run the application\n- spring-boot:run runs your Spring Boot application.\n- spring-boot:repackage repackages your jar/war to be executable.\n- spring-boot:start and spring-boot:stop to manage the lifecycle of your Spring Boot application (i.e. for integration tests).\n- spring-boot:build-info generates build information that can be used by the Actuator.\n\n### Q :  Devtools helps me to restart the server automatically. But, I have a problem. The browser page is not auto refreshed.\n\nDevtool helps the server pick up the change automatically. However, you have to refresh the page manually to execute a new request.\n\nIf you would want to auto load the page as well, you can look at LiveReload \n- http://www.logicbig.com/tutorials/spring-framework/spring-boot/boot-live-reload/.\n\nIn my trials, we found LiveReload buggy. Do let us know if you have a better experience with it. \n\n### Q :  What and Why Embedded Servers?\n\nThink about what you would need to be able to deploy your application (typically) on a virtual machine.\n- Step 1 : Install Java\n- Step 2 : Install the Web/Application Server (Tomcat/Websphere/Weblogic etc)\n- Step 3 : Deploy the application war\n\nWhat if we want to simplify this?\n\nHow about making the server a part of the application? \n\n> You would just need a virtual machine with Java installed and you would be able to directly deploy the application on the virtual machine. Isn't it cool?\n\nThis idea is the genesis for Embedded Servers.\n\nWhen we create an application deployable, we would embed the server (for example, tomcat) inside the deployable. \n> For example, for a Spring Boot Application, you can generate an application jar which contains Embedded Tomcat. You can run a web application as a normal Java application!\n\nEmbedded server is when our deployable unit contains the binaries for the server (example, tomcat.jar).\n\n### Q :  How can I add custom JS code with Spring Boot? \n\nCreate a folder called static under resources folder. You can put your static content in that folder.\n\nFor your example the path to myapp.js would be resources\\static\\js\\myapp.js\n\nYou can refer to it in jsp using\n\n```\n<script src=\"/js/myapp.js\"></script>\n```\n\n### Error :  HAL browser gives me unauthorized error - Full authentication is required to access this resource.\n\n```\n{\n  \"timestamp\": 1488656019562,\n  \"status\": 401,\n  \"error\": \"Unauthorized\",\n  \"message\": \"Full authentication is required to access this resource.\",\n  \"path\": \"/beans\"\n}\n```\n\nTwo options\n\n###### Option 1 : Disable security\n\napplication.properties\n```\nmanagement.security.enabled: FALSE \n```\n###### Option 2 : Search for password in the log and pass it in the request header\n\n### Error :  Hal Browser and Spring Boot Actuator are not working\n\nQuestion Continued - You can only get a json response. /application, /application/status and /application/info\n\nWith 2.0.0.M4 Spring Boot is making a lot of changes to Actuator. \n\n> Do not use SNAPSHOT versions\n\nFor now we recommend using 2.3.1.RELEASE with all courses. I will wait for the changes that are introduced with M4 to stabilize before incorporating into the course.\n\nRecommmended Reading\n- https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.0.0-M4-Release-Notes\n\nSolution : Update your pom.xml\n\n```\n<parent>\n\t<groupId>org.springframework.boot</groupId>\n\t<artifactId>spring-boot-starter-parent</artifactId>\n\t<version>2.3.1.RELEASE</version>\n\t<relativePath /> <!-- lookup parent from repository -->\n</parent>\n```\nIf you are using Milestone (M1, M2, M3...) or SNAPSHOT version you need this configuration\n\n```\n<repositories>\n\t\t<repository>\n\t\t\t<id>spring-snapshots</id>\n\t\t\t<name>Spring Snapshots</name>\n\t\t\t<url>https://repo.spring.io/snapshot</url>\n\t\t\t<snapshots>\n\t\t\t\t<enabled>true</enabled>\n\t\t\t</snapshots>\n\t\t</repository>\n\t\t<repository>\n\t\t\t<id>spring-milestones</id>\n\t\t\t<name>Spring Milestones</name>\n\t\t\t<url>https://repo.spring.io/milestone</url>\n\t\t\t<snapshots>\n\t\t\t\t<enabled>false</enabled>\n\t\t\t</snapshots>\n\t\t</repository>\n\t</repositories>\n \n\t<pluginRepositories>\n\t\t<pluginRepository>\n\t\t\t<id>spring-snapshots</id>\n\t\t\t<name>Spring Snapshots</name>\n\t\t\t<url>https://repo.spring.io/snapshot</url>\n\t\t\t<snapshots>\n\t\t\t\t<enabled>true</enabled>\n\t\t\t</snapshots>\n\t\t</pluginRepository>\n\t\t<pluginRepository>\n\t\t\t<id>spring-milestones</id>\n\t\t\t<name>Spring Milestones</name>\n\t\t\t<url>https://repo.spring.io/milestone</url>\n\t\t\t<snapshots>\n\t\t\t\t<enabled>false</enabled>\n\t\t\t</snapshots>\n\t\t</pluginRepository>\n\t</pluginRepositories>\n```\n\n### Q :  How does path=\"users\", collectionResourceRel=\"users\" work with Spring Data Rest?\n\n```\n@RepositoryRestResource(collectionResourceRel = \"users\", path = \"users\")\n\npublic interface UserRestRepository extends\nPagingAndSortingRepository<User, Long>\n```\n\n- path - The path segment under which this resource is to be exported.\n- collectionResourceRel - The rel value to use when generating links to the collection resource. This is used when generating HATEOAS links.\n\n### Q :  What is importance of {id} in ServletUriComponentsBuilder.fromCurrentRequest().path(\"/{id}\").buildAndExpand(returnQuestion.getId()).toUri(); \n\nThe name of the variable in the path does not really matter. \n\nYou can read more about UriComponentsBuilder here :  http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/util/UriComponentsBuilder\n\n### Error :  java.lang.ClassCastException: org.springframework.boot.context.event.ApplicationReadyEvent cannot be cast\n```\ns.c.e.SimpleApplicationEventMulticaster : Non-matching event type for listener: org.springframework.boot.web.context.ServerPortInfoApplicationContextInitializer$$Lambda$69/128359175@5e82df6a\njava.lang.ClassCastException: org.springframework.boot.context.event.ApplicationReadyEvent cannot be cast to org.springframework.boot.web.context.WebServerInitializedEvent\n\norg.springframework.boot.context.event.ApplicationReadyEvent cannot be cast to org.springframework.boot.web.context.WebServerInitializedEvent \n```\n\nApplicationReadyEvent is sub-class of SpringApplicationEvent. So, it cannot be type casted to WebServerInitializedEvent.\n\nThe code which is triggering the exception is below\n```\ntry {\n    listener.onApplicationEvent(event);\n}\ncatch (ClassCastException ex) {\n    String msg = ex.getMessage();\n    if (msg == null || msg.startsWith(event.getClass().getName())) {\n        // Possibly a lambda-defined listener which we could not resolve the generic event type for\n        Log logger = LogFactory.getLog(getClass());\n        if (logger.isDebugEnabled()) {\n            logger.debug(\"Non-matching event type for listener: \" + listener, ex);\n        }\n    }\n    else {\n        throw ex;\n    }\n}\n```\n\nAs you can see the exception is being suppressed based on the exception message. I guess this is a scenario which the developer expected.\n\nI could not figure anything more about this code other than the fact that this event is trigged when application is ready to accept requests.\n\n\"Event published as late as conceivably possible to indicate that the application is ready to service requests. The source of the event is the {@link SpringApplication} itself, but beware of modifying its internal state since all initialization steps will have been completed by then.\"\n\nI dont expect this to cause a problem. Especially because this is logged at debug level.\n\n### Q :  What is difference between Spring 5 and Spring 4 in terms of developing web application in the course? Does it matter if a new version is used ?\n\nThere will be one problem you will face when you use Spring 5. \n\nWhen you get to /src/main/webapp/WEB-INF/views/todo.jsp - You should use modelAttribute instead of commandName\n\nInstead of\n```\n<form:form method=\"post\" commandName=\"todo\">\n```\nUse\n```\n<form:form method=\"post\" modelAttribute=\"todo\">\n```\nYou can read more about this here :\n\nhttps://stackoverflow.com/questions/21495616/difference-between-modelattribute-and-commandname-atributes-in-form-tag-in-sprin\n\n### Q :  Why am I seeing an extra dialogue asking me to \"Select Java Application Type\" when I launch a Spring Boot Application?\n\nThe best way to run is to right click on the Java Class File you want to run (SpringBootTutorialApplication) > Run As > Java Application.\n\n> When you do it on a project, Eclipse finds all the java classes with main methods and asks you to choose among them\n\n### Q :  What happens in the background when a Spring Boot Application is \"Run as Java Application\"?\n\nIf you are using Eclipse IDE, Eclipse maven plugin ensures that as soon as you add a dependency or make a change to the class file, it is compiled and ready in the target folder! And after that its just like any other Java application. \n\nWhen you launch the java application, then the spring boot auto configuration magic kicks in. \n- It launches up tomcat when it sees that you are developing a web application!\n\n### Q :  Can we use jetty instead of tomcat in spring-boot-starter-web?\n\nRemove the existing dependency on spring-boot-starter-web and add these in.\n\n```\n<dependency>\n    <groupId>org.springframework.boot</groupId>\n    <artifactId>spring-boot-starter-web</artifactId>\n    <exclusions>\n        <exclusion>\n            <groupId>org.springframework.boot</groupId>\n            <artifactId>spring-boot-starter-tomcat</artifactId>\n        </exclusion>\n    </exclusions>\n</dependency>\n<dependency>\n    <groupId>org.springframework.boot</groupId>\n    <artifactId>spring-boot-starter-jetty</artifactId>\n</dependency>\n```\n\n### Error :  Failure to transfer org.springframework.boot:spring-boot-starter-parent:pom:2.3.1.RELEASE from https://repo.spring.io/snapshot\n\nSNAPSHOT versions are versions under development. Of late, there are a few issues with some of the SNAPSHOT version of Spring Boot 2. We recommend using 2.3.1.RELEASE for now.\n\nIn you pom.xml, you can change the version in the parent as shown below:\n\n```\n<parent>\n\t<groupId>org.springframework.boot</groupId>\n\t<artifactId>spring-boot-starter-parent</artifactId>\n\t<version>2.3.1.RELEASE</version>\n\t<relativePath/> <!-- lookup parent from repository -->\n</parent>\n```\nIf you are using Milestone (M1, M2, M3...) or SNAPSHOT version you need this configuration\n\n```\n<repositories>\n\t\t<repository>\n\t\t\t<id>spring-snapshots</id>\n\t\t\t<name>Spring Snapshots</name>\n\t\t\t<url>https://repo.spring.io/snapshot</url>\n\t\t\t<snapshots>\n\t\t\t\t<enabled>true</enabled>\n\t\t\t</snapshots>\n\t\t</repository>\n\t\t<repository>\n\t\t\t<id>spring-milestones</id>\n\t\t\t<name>Spring Milestones</name>\n\t\t\t<url>https://repo.spring.io/milestone</url>\n\t\t\t<snapshots>\n\t\t\t\t<enabled>false</enabled>\n\t\t\t</snapshots>\n\t\t</repository>\n\t</repositories>\n \n\t<pluginRepositories>\n\t\t<pluginRepository>\n\t\t\t<id>spring-snapshots</id>\n\t\t\t<name>Spring Snapshots</name>\n\t\t\t<url>https://repo.spring.io/snapshot</url>\n\t\t\t<snapshots>\n\t\t\t\t<enabled>true</enabled>\n\t\t\t</snapshots>\n\t\t</pluginRepository>\n\t\t<pluginRepository>\n\t\t\t<id>spring-milestones</id>\n\t\t\t<name>Spring Milestones</name>\n\t\t\t<url>https://repo.spring.io/milestone</url>\n\t\t\t<snapshots>\n\t\t\t\t<enabled>false</enabled>\n\t\t\t</snapshots>\n\t\t</pluginRepository>\n\t</pluginRepositories>\n```\n\n\n### Q :  Why do we configure Spring Snapshot and milestone repositories? \n\nIf you are using Milestone (M1, M2, M3...) or SNAPSHOT version you need this configuration\n\n```\n<repositories>\n\t\t<repository>\n\t\t\t<id>spring-snapshots</id>\n\t\t\t<name>Spring Snapshots</name>\n\t\t\t<url>https://repo.spring.io/snapshot</url>\n\t\t\t<snapshots>\n\t\t\t\t<enabled>true</enabled>\n\t\t\t</snapshots>\n\t\t</repository>\n\t\t<repository>\n\t\t\t<id>spring-milestones</id>\n\t\t\t<name>Spring Milestones</name>\n\t\t\t<url>https://repo.spring.io/milestone</url>\n\t\t\t<snapshots>\n\t\t\t\t<enabled>false</enabled>\n\t\t\t</snapshots>\n\t\t</repository>\n\t</repositories>\n \n\t<pluginRepositories>\n\t\t<pluginRepository>\n\t\t\t<id>spring-snapshots</id>\n\t\t\t<name>Spring Snapshots</name>\n\t\t\t<url>https://repo.spring.io/snapshot</url>\n\t\t\t<snapshots>\n\t\t\t\t<enabled>true</enabled>\n\t\t\t</snapshots>\n\t\t</pluginRepository>\n\t\t<pluginRepository>\n\t\t\t<id>spring-milestones</id>\n\t\t\t<name>Spring Milestones</name>\n\t\t\t<url>https://repo.spring.io/milestone</url>\n\t\t\t<snapshots>\n\t\t\t\t<enabled>false</enabled>\n\t\t\t</snapshots>\n\t\t</pluginRepository>\n\t</pluginRepositories>\n```\n\n\n### Error :   java.lang.IllegalArgumentException: Sources must not be empty\n\nMake sure you are running the right Java class. Go to your class containing @SpringBootApplication and right click > Run as Java Application. \n\nIn the example below SpringbootIn10StepsApplication has the @SpringBootApplication annotation. So, it is the one you should run as Java Application.\n\n```\npackage com.in28minutes.springboot.basics.springbootin10steps;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.ConfigurableApplicationContext;\n\n@SpringBootApplication\npublic class SpringbootIn10StepsApplication {\n\n\tpublic static void main(String[] args) {\n\t\tApplicationContext applicationContext = \n\t\t\t\tSpringApplication.run(SpringbootIn10StepsApplication.class, args);\n\t\t\n\t\tfor (String name : applicationContext.getBeanDefinitionNames()) {\n\t\t\tSystem.out.println(name);\n\t\t}\n\t}\n}\n```\n\n### Q :  Can i use spring boot dev tools for a non spring boot project?\n\nI would recommend you to try JRebel. \n\n### Q :  What is the difference between Static and Dynamic filtering?\n\nImagine the same bean being used in two different RESTful services. And these two services want to send out different set of fields in the response. \n\nIf we add the @JsonIgnoreProperties annotation on the bean, then we cannot have different set of fields in the responses.  Thats why this is called static filtering. \n\nHowever with dynamic filtering, shown below, you can create two request methods, each having different attributes being sent.\n\n```\nSimpleBeanPropertyFilter filter = SimpleBeanPropertyFilter.filterOutAllExcept(\"field1\", \"field2\");\n \nFilterProvider filters = new SimpleFilterProvider().addFilter(\"SomeBeanFilter\", filter);\n\nMappingJacksonValue mapping = new MappingJacksonValue(someBean);\n\nmapping.setFilters(filters);\n\nreturn mapping;\n```\n\n\n### Error :  No message found under code 'good.morning.message' for locale 'us'.\n\nEnsure that the name of ResourceBundleMessageSource is the same in both the files related to internationalization.\n- In the examples below, we use messageSource as the @Autowired bean name and the @Bean method name.\n\n```\n@Autowired\nprivate MessageSource messageSource;\n```\n\n```\n@Bean\npublic ResourceBundleMessageSource messageSource() {\n\tResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();\n\tmessageSource.setBasename(\"messages\"); \n\treturn messageSource;\n}\n```\n\n### Q :  How to generate a WAR file with Spring Boot?\n\nRecommended Reading\n- https://spring.io/guides/gs/convert-jar-to-war/\n\nHere’s the direct link to spring documentation \n- https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#build-tool-plugins-maven-packaging\n\n### Q :  How to deploy to a different server with with Spring Boot?\n\nYou would need to do 2 Steps\n- Generate a war from the project. \n- Deploy it to your favourite server (Websphere or Weblogic or Tomcat or ...).\n\nStep 1 : This getting started guide should help - https://spring.io/guides/gs/convert-jar-to-war/\n\nStep 2 : Depends on your server\n\n### Q :  What is the difference between RequestMapping and GetMapping?\n- RequestMapping is generic - you can use with GET, POST, PUT or any of the other request methods using the method attribute on the annotation.\n- GetMapping is specific to GET request method. It’s just an extension of RequestMapping to improve clarity. \n\n### Q :  Why do we recommend not to use Spring Data Rest in real world applications?\n\nWe think Spring Data Rest is Good for quick prototyping! Be cautious about using this in Big applications!\n\nWith Spring Data REST you are exposing your database entitities directly as REST Services. \n\nWhen you design RESTful services, Best design practices suggests that your interface should consider two important things\n- Your Domain Model\n- Your Consumers\n\nWith Spring Data REST, you are not considering either of those. You just expose entities as REST Services.\n\nThats why we suggest to use it for quick prototyping or the initial evolution of a project. It may not be a great idea for a fully evolved project.\n\n### Q :  How do I change the package name of a project in Spring Initializer?\n\nGood news is you can customise it. Click the link “Switch to the full version.“. You would be able to configure the package name you would want!\n\n### Q :  Where can I find the complete list of properties that can be configured in application.properties?\n\nHere’s the complete guide \n- https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html\n\n\n## Hibernate, JPA and In-memory Database\n\n### Q :  What is the difference between JPA and Hibernate?\n\nShort Story\n- JPA is a specification/Interface \n- Hibernate is one of JPA implementations\n\nWhen we use JPA, we use the annotation and interfaces from javax.persistence package, without using the hibernate import packages.\n\nWe recommend using JPA annotations as we are not tied to Hibernate as implementation. Later (I know - <1% Chance), we can use another JPA implementation.\n\n### Q :  Compare Entity Manager vs SessionFactory\nNotes\n- Entity Manager and SessionFactory are similar, have very similar responsibilities. \n- JPA specifies EntityManager while Hibernate can work with both SessionFactory and EntityManager.\n\nWe recommend using pure JPA  i.e. EntityManager. You would not want to be tied to Hibernate as the JPA implementation - Hence avoid SessionFactory. \n\n### Q :  In which layer, should the boundary of a transaction start?\n\nWe recommend managing transactions in the Service layer. Logic for business transactions is in the business/service layer and you would want to enforce transaction management at that level.\n\n### Q :  HQL vs JPQL\nJPQL is a Java EE Standard. Once you use JPQL you can switch between any JPA implementation - Hibernate or Toplink or …  \n\nHQL is specific to Hibernate. If you use HQL, you are tied to Hibernate for your lifetime.\n\nWhile this might seem not to be such a important choice now, what if there is a more popular JPA implementation in 5 years and you want to switch away from Hibernate. Applications using JPQL will be easier to migrate than those using HQL.\n\n\n### Q :  What are the dependencies need to start up an in memory database H2 with Spring Boot?\n\nIn a Spring Boot project, you should be able to launch up H2 Console as long as you ensure the following dependencies are on the class path.\n- web starter\n- h2  \n- data jpa starter\n\nThe exact dependencies are shown below:\n```\n<dependency>\n    <groupId>org.springframework.boot</groupId>\n    <artifactId>spring-boot-starter-web</artifactId>\n</dependency>\n\n<dependency>\n    <groupId>org.springframework.boot</groupId>\n    <artifactId>spring-boot-starter-data-jpa</artifactId>\n</dependency>\n\n<dependency>\n    <groupId>com.h2database</groupId>\n    <artifactId>h2</artifactId>\n    <scope>runtime</scope>\n</dependency>\n```\n\nA few tips:\n- An in-memory database is live only during the time of execution of the application. It is an efficient way to learn a framework.\n- This is not how you want your real world applications to behave.\n- We explain how to connect to a database of your choice in the answer to the question \"How do we connect to a external database?\".\n\n\n### Q :  How is Hibernate chosen as the default implementation for JPA without any configuration?\nAgain - Spring Boot Auto Configuration.\n\nThis is the dependency we added in \n\n```\n<dependency>\n            <groupId>org.springframework.boot</groupId>\n            <artifactId>spring-boot-starter-data-jpa</artifactId>\n        </dependency>\n```\n\nThe Starter spring-boot-starter-data-jpa has a transitive dependency on Hibernate and JPA.\n\nWhen Spring Boot sees Hibernate in the class path, it auto configures it as the default JPA Implementation.\n\n### Q :  Why H2? And how does it work?\n\nFirst and most important thing - Spring Boot is intelligent.\n\nIf you are talking to an in memory db, by default, it looks at the entities and creates the database and the tables.\n\nHowever, if you connect to a mysql database, Spring Boot knows that its a permanent database. By default, it expects you to set up the database, set up the tables and it uses the connection that you established.\n\nHere are the details \n- http://www.springboottutorial.com/spring-boot-auto-configuration\n- https://docs.spring.io/spring-boot/docs/current/reference/html/howto-database-initialization.html\n\n### Q :  Where is the database connection info specified? How does it know to automatically connect to H2?\n\nThats Spring Boot Autoconfiguration magic.\n\nFrom https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-auto-configuration.html\n\n\"Spring Boot auto-configuration attempts to automatically configure your Spring application based on the jar dependencies that you have added. For example, If HSQLDBis on your classpath, and you have not manually configured any database connection beans, then we will auto-configure an in-memory database.\n\nMore Reading\n- http://www.springboottutorial.com/spring-boot-auto-configuration\n\n### Q :  How do we connect to a external database like MSSQL or oracle? \n\nLet's consider one of those as an example - MySQL\n\n###### Step 1 - Add dependency for mqsql connector to pom.xml \n```\n<dependency>\n    <groupId>mysql</groupId>\n    <artifactId>mysql-connector-java</artifactId>\n</dependency>\n```\n\n###### Step 2 - Remove H2 Dependency from pom.xml\nOr atleast make its scope as test\n\n```\n<!--\n<dependency>\n    <groupId>com.h2database</groupId>\n    <artifactId>h2</artifactId>\n    <scope>test</scope>\n</dependency>\n-->\n```\n\n###### Step 3 - Setup your My SQL Database\n- For more check out - https://github.com/in28minutes/jpa-with-hibernate#installing-and-setting-up-mysql\n\n###### Step 4 - Configure your connection to My SQL Database\nConfigure application.properties\n```\nspring.jpa.hibernate.ddl-auto=none\nspring.datasource.url=jdbc:mysql://localhost:3306/todo_example\nspring.datasource.username=todouser\nspring.datasource.password=YOUR_PASSWORD\n```\n\n###### Step 5 - Restart and You are ready!\nThat's it\n\n### Q :  What is the default h2 database name configured by Spring Boot? Why is the default database name testdb?\n\nThis is where all the default values in application.properties are listed\n- https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html\n\nLook for the property below\n```\nspring.datasource.name=testdb # Name of the datasource.\n```\n\nIf you are using an H2 in-memory database, thats exactly the name that Spring Boot uses to setup your H2 database.\n\n\n### Q :  What happens if H2 is not in the classpath?\n\nYou get this error\n```\nCannot determine embedded database driver class for database type NONE\n````\n\nAdd H2 to the pom.xml and Restart your server\n```\n<dependency>\n\t<groupId>com.h2database</groupId>\n\t<artifactId>h2</artifactId>\n\t<scope>runtime</scope>\n</dependency>\n```\n\n### Q :  Why the data lost between restart?\n\nH2 is an in memory database. Its not a persisted database. \n\nH2 is a great tool for learning because you need zero setup.\n\n\nWhile we dont recommend this , it interesting to note that H2 has a persisted database mode. \n- With this configuration, the data is not lost even after spring boot restart and computer restart. \n- You would find H2 being very rarely used in this way. If you are really interested in a persistent database, I would recommend MySQL\n\napplication.properties\n```\nspring.datasource.name=yourdbname\nspring.datasource.driverClassName=org.h2.Driver\n \nspring.datasource.initialize=false\nspring.datasource.url=jdbc:h2:file:~/yourdbname;DB_CLOSE_ON_EXIT=FALSE;IFEXISTS=TRUE;DB_CLOSE_DELAY=-1;\n \nspring.jpa.hibernate.ddl-auto = update\n```\n\n### Error :  Table is not created automatically in h2 embedded db or I'm unable to see the tables\n\nUsually, the table's are created but the url used in H2 GUI Console is wrong.\n\nIn the browser, change the database url to jdbc:h2:mem:testdb (Shown in the screen below).\n\n![](/images/h2-solution-image.png)\n\nYou should be good to go!\n\n### Error :  H2 Console is not Launched up?\n\nTry enabling it in the application.properties\n\n```\nspring.h2.console.enabled=true\n```\n\n### Q :  How did the insert query from data.sql run at application startup? \n\nThats the magic of Spring Boot Autoconfiguration again. You can read more here. \n- http://www.springboottutorial.com/spring-boot-auto-configuration\n- https://docs.spring.io/spring-boot/docs/current/reference/html/howto-database-initialization.html\n\n### Q :  How to define a Composite Primary Key or a Composite ID?\n\nYou can use a structure similar to below:\n\n```\n@Entity\npublic class Project {\n    @EmbeddedId ProjectId id;\n\n}\n```\n \n```\n@Embeddable\nclass ProjectId implements Serializable{\n    int departmentId;\n    long projectId;\n}\n```\n\n### Q :  Why should we annotate EntityManager with @PersistenceContext and not just @Autowired?\n\nIt is actually recommended to use @PersistenceContext. It is a JPA Specific Specialization. \n\nYou can read more here \n- https://docs.oracle.com/javaee/7/api/javax/persistence/PersistenceContext.html\n\n### Q :  How can we connect to Multiple Databases using Spring Boot?\n\nHere’s a good article showing how to connect to multiple databases\n- http://www.baeldung.com/spring-data-jpa-multiple-databases\n\nYou have to do all the work now. You cannot depend on auto configuration :)\n\nHere’s another good read:\n- https://medium.com/@joeclever/using-multiple-datasources-with-spring-boot-and-spring-data-6430b00c02e7\n\n### Q :  How did JdbcTemplate achieve connection details?\n\nIts down to Spring Boot Auto Configuration!\n\nFirst thing you would need to understand is Spring Boot Auto Configuration. \n\nHere’s a good read \n- http://www.springboottutorial.com/spring-boot-auto-configuration\n\nAs far as H2 is concerned, as soon as Spring Boot sees H2 in the class path, it auto configures something similar to what you see below:\n\n```\nspring.datasource.url=jdbc:h2:mem:testdb\nspring.datasource.driverClassName=org.h2.Driver\nspring.datasource.username=sa\nspring.datasource.password=\n\nspring.jpa.database-platform=org.hibernate.dialect.H2Dialect\n```\nIt knows that you are using an inmemory database H2 and It knows the default url if you don’t provide one.\n\n### Q :  Can you give an example for ReadOnly as true in Transaction management?\n- When you read stuff from the database, user details or any other details, you wanna set read only on the transaction so that Hibernate does not need to check for changes to the entities. This is more efficient.\n\n### Error :  org.hibernate.loader.MultipleBagFetchException\n```\nCaused by: org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags: [com.mypackage.jpa.hibernate.jpahibernate.entity.Student.courses, com.mypackage.jpa.hibernate.jpahibernate.entity.Course.reviews]\n```\n\nIt looks like this is a bug with Hibernate. Hibernate doesn't like two collections with FetchType.EAGER\n\nThis thread is a good start for more approaches - https://stackoverflow.com/questions/4334970/hibernate-cannot-simultaneously-fetch-multiple-bags\n\n### Error :  BeanCreationException - java.lang.IllegalArgumentException: At least one JPA metamodel must be present\n\n```\norg.springframework.beans.factory.BeanCreationException: Error creating bean with name ' ': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: At least one JPA metamodel must be present!\n```\n\nThis is because of conflicts with older version of Hibernate.\n\nEnsure you are using the recommended version of Spring Boot - 2.3.1.RELEASE\n\n\n### Q :  Is it mandatory to specify @Repository on a repository which is extending JPARepository?\n\n- Ideally you don’t need to have an @Repository. But, I faced a few issues sometimes - better be safe than sorry.\n\n\n### Q :  JPA and Hibernate Course - Notes from Rodolfo\n\nLink to this file:\nhttps://s3.amazonaws.com/espanol-libros/AllLinks.rtf\n\nhttps://s3.amazonaws.com/espanol-libros/JPA/Section+5+JPA+and+Hibernate+in+Depth.rtf\n\nhttps://s3.amazonaws.com/espanol-libros/JPA/Section+6+Establishing+Relationship+with+JPA+and+Hibernate+OneToOne.rtf\n\nhttps://s3.amazonaws.com/espanol-libros/JPA/Section+7+Review+with+FAQs.rtf\n\nhttps://s3.amazonaws.com/espanol-libros/JPA/Section+8+Establishing+relationships+with+JPA+and+Hibernate+ManyToOne.rtf\n\n### Q :  How can we use a mysql database for running the application and use inmemory database H2 for unit tests?\n\nThe standard properties file that Spring Boot picks up automatically when running an application is called application.properties and resides in the src/main/resources folder.\n\nIf we want to use different properties for tests, then we can override the properties file in the main folder by placing another file with the same name in src/test/resources.\n\nThe application.properties file in src/test/resources folder should contain the standard key-value pairs necessary for configuring a in memory connection.\n\nFirst add the dependencies for your database driver (mysql in the example below) and make the dependency for h2 test scoped.\n\n```\n<dependency>\n    <groupId>mysql</groupId>\n    <artifactId>mysql-connector-java</artifactId>\n</dependency>\n\n<dependency>\n    <groupId>com.h2database</groupId>\n    <artifactId>h2</artifactId>\n    <scope>test</scope>\n</dependency>\n```\n\nUse the mysql database for your real code\n\nsrc\\main\\resources\\application.properties\n```\nspring.jpa.hibernate.ddl-auto=none\nspring.datasource.url=jdbc:mysql://localhost:3306/person_example\nspring.datasource.username=personuser\nspring.datasource.password=YOUR_PASSWORD\n```\n\nUse in memory database for your unit tests\n\nsrc\\test\\resources\\application.properties\n```\nspring.datasource.driver-class-name=org.h2.Driver\nspring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1\nspring.datasource.username=sa\nspring.datasource.password=sa\n```\n\n### Q :  When is any primary or an id field annotated with @GeneratedValue autogenerated? Why are we passing the value for id in data.sql?\n\nLet's consider a simple example:\n\n```\n@Entity\npublic class Course {\n\n    @Id\n    @GeneratedValue\n    private Long id;\n```\n\nId is generated only when you insert it using entity manager.\n\n```\nCourse course1 = new Course(\"Web Services in 100 Steps\");\nem.persist(course1);\n```\n\nWhen we use data.sql to insert the data we have to provide all the details as entity manager is not involved.\n\n```\ninsert into course(id, name, created_date, last_updated_date,is_deleted) \nvalues(10001,'JPA in 50 Steps', sysdate(), sysdate(),false);\n```\n\n### Q :  Field dao in SpringRestController required a bean of type 'CustomerDAO' that could not be found. Consider defining a bean of type 'CustomerDAO' in your configuration.\n\nTwo things that are typically a problem\n- Annotate repository class with @Repository\n- Try adding the annotation @EnableJpaRepositories(basePackageClasses = ...) with the right value for basePackageClasses next to @SpringBootApplication on the Spring Boot Application class.\n\n### Error :  Detached object passed to persist\n\nConsider the code\n```\npublic void playWithEntityManager() {\n    Course course = new Course( 200L, \"Some Course\" );\n    em.persist( course);\n}\n```\n\nThis is because an id on the Course is set - 200L.  To fix it you can create a new constructor without an id and use it!\n\n> Hibernate distinguishes between transient and detached objects and persist works only with transient objects. If persist concludes the object is detached (which it will because the ID is set), it will return the \"detached object passed to persist”\n\n### Error :  java.lang.NoClassDefFoundError: javax/wsdl/extensions/ExtensibilityElement\n\n```\nSOAP Web Service - ationConfigEmbeddedWebApplicationContext\nException encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'courses' defined in class path resource [com/ashwani/CustomerDetailsService/WebServiceConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.ws.wsdl.wsdl11.DefaultWsdl11Definition]: Factory method 'defaultWsdl11Definition' threw exception; nested exception is java.lang.NoClassDefFoundError: javax/wsdl/extensions/ExtensibilityElement\n```\n\nMake sure you have this dependency in the pom.xml\n\n```\n<dependency>\n\t<groupId>wsdl4j</groupId>\n\t<artifactId>wsdl4j</artifactId>\n</dependency>\n```\n\n### Q :  How do authentication with jwt to service REST??\n\nI’m working on a course for Full Stack Developer with REST APIs (on Spring Boot) connecting to a frontend (Angular and React) and this is exactly the stuff that needs attention.\n\nHere’s a good reference - https://medium.com/@nydiarra/secure-a-spring-boot-rest-api-with-json-web-token-reference-to-angular-integration-e57a25806c50\n\n\n## Unit Testing\n\n### Q :  What is a mockito answer?\n\nHere's a great starting point https://testing.googleblog.com/2014/03/whenhow-to-use-mockito-answer.html\n\n### Q :  How do you mock a private method that requires arguments?\n\n```\nPowerMockito.when(SomeClass.class, \"somePrivateMethodName\", argument1, argument2).thenReturn(returnValue);\n```\n\n### Q :  How to make JUnit run at regular intervals of time?\n\nI love Infinitest - https://infinitest.github.io/\n\nThis keeps running your unit tests in the back ground. You can focus on your code.\n\n### Q :  Annotation Changes - JUnit 4 vs JUnit 5\nAnnotation Changes in JUnit 5\n\n- @Before annotation is renamed to @BeforeEach\n- @After annotation is renamed to @AfterEach\n- @BeforeClass annotation is renamed to @BeforeAll\n- @AfterClass annotation is renamed to @AfterAll\n- @Ignore annotation is renamed to @Disabled\n\n## You and in28Minutes\n\n### Q :  What should you do to make the best use of our courses?\n\nWhat is the use of all these numbers?\n- 99000+ - Students!\n- 7000+ - 5 Star Reviews on our Courses\n- More than 100 Hours of Course Content\n\nNot useful unless you make the best use of these.\n\nLearn something new for atleast half an hour every day! \n\nIf you do it for 100 days consecutively, it becomes a habit. Good Habits are great things to have.\n\n> If you are not able to commit time on the courses, then read this - \"The in28Minutes Way\" - https://github.com/in28minutes/in28minutes-initiatives/tree/master/The-in28Minutes-Way\n\nOpen up your mobile and set a daily reminder now!\n\n### Q :  Why should you learn from in28Minutes?\n\nRead this - \"The in28Minutes Way\" - https://github.com/in28minutes/in28minutes-initiatives/tree/master/The-in28Minutes-Way\n\nSome facts\n- 75% - Percentage of New Java Projects/Microservices using Spring/Spring Boot\n- 300% - Increase in Microservices using Spring Boot in the last two years!\n- 70% - Percentage of Real World projects using Maven\n- 70% - Percentage of Real World Projects using Git as Version Control. Fork, Like and Play!\n- 10+ - We are in the world of Microservices. We create a number of small microservices. That means understand how to set up projects is a very important skill. We help you learn that by creating a number of small projects during this course.\n- 80/20 - Most Important Rule that dictates things for in28Minutes. \n\n> Remember if you Listen, Watch, Do and Repeat. You Retain More of What you learn.\n\nOnce you realize the importance of what you are learning, committing to your goal becomes easy. Think and find at least 28 minutes in your day for doing this. Good Luck. \n\n### Q :  What is the focus of each of your courses?\n\nHere are the courses and their focus areas:\n\n- Master Microservices with Spring Boot & Spring Cloud\n  - Expert - Microservices with Spring Cloud\n    - Setup Centralized Microservices Configuration with Spring Cloud Config Server\n    - Implement client side load balancing (Ribbon), Dynamic scaling(Eureka Naming Server) and an API Gateway (Zuul)\n    - Distributed tracing for microservices with Spring Cloud Sleuth and Zipkin\n    - Fault Tolerance for microservices with Hystrix\n  - Expert - RESTful API and Web Services with Spring Boot\n    - Best Practices in Designing RESTful web services\n    - Implement Exception Handling, Validation, HATEOAS and filtering for RESTful Web Services\n    - Version and Document (using Swagger) Your RESTful Web Services\n  - Introduction Modules \n    - Spring Boot \n    - JPA\n- Master Web Services and REST API with Spring Boot\n  - Expert - SOAP Web Services with Spring Boot\n    - Understand WSDL, SOAP Header, SOAP Body, SOAP Fault, XSD, JAXB and EndPoint\n    - Use Contract First Approach to Develop Web Services\n  - Expert - Design and Develop RESTful API and Web Services with Spring Boot\n    - Best Practices in Designing RESTful web services\n    - Implement Exception Handling, Validation, HATEOAS and filtering for RESTful Web Services\n    - Version and Document (using Swagger) Your RESTful Web Services\n    - Connect web services to JPA/Hibernate\n  - Introduction Modules \n    - Spring Boot\n- Master Hibernate & JPA with Spring Boot in 100 Steps\n  - Expert - JPA & Hibernate with Spring Boot\n    - Fundametals - Entities, Relationships, Inheritance Mappings and Annotations\n    - Relationships in depth - One to One, Many to One and Many to Many\n    - Querying data - JPQL, Criteria API and Native Queries\n    - Caching - First Level Cache and Second Level Cache with EhCache\n    - Performance tuning your JPA application with Hibernate - Solve N+1 Queries Issue\n  - Introduction Modules \n    - Spring, Spring Boot, Spring JDBC, Spring Data JPA and Spring Data REST\n- Learn Spring Boot in 100 Steps - Beginner to Expert\n  - Expert - Fundamentals of Spring Boot\n    - Magic of Spring Boot - Auto Configuration, Spring Initializr and Starter Projects\n    - Develop a Web Application connecting to JPA/Hibernate Step by Step with Spring MVC and Spring Boot\n    - Understand Spring MVC in depth - DispatcherServlet , Model, Controllers and ViewResolver\n    - Externalise application configuration using Spring Boot Profiles and Dynamic Configuration\n    - Monitoring\n    - Write great Unit and Integration tests using Spring Boot Starter Test\n    - Use a wide variety of Spring Boot Starter Projects - Spring Boot Web, Spring Boot Test, Spring Boot Data JPA, Spring Boot Data REST\n    - Explore the embedded servlet container options provided by Spring Boot - Tomcat, Jetty and Undertow\n    - Make best use of Spring Boot Actuator and Spring Boot Developer Tools\n  - Introduction Modules \n    - Spring, JUnit and Mockito.\n- Spring Master Class - Beginner to Expert in 100 Steps\n  - Expert - Fundamentals of Spring Framework\n    - Dependency Injection, IOC Container, Application Context and Bean Factory.\n    - Spring Annotations - @Autowired, @Component, @Service, @Repository, @Configuration, @Primary\n    - Unit tests with XML, Java Application Contexts and Mockito\n  - Introduction Modules\n    - Maven, JUnit, Mockito and Spring Boot\n\n### Q :  How to improve Logical Skills?\nLogical skills are difficult to acquire but are among the things which will help you through out your programming career.\n\nThere are three ways - Practice, Practice and More Practice.\n\nI would suggest joining a programming contest like CodeChef or TopCoder for a start. Once you start being active there, you will understand everything else.\n\n"
  },
  {
    "path": "_blog/articles/2019-02-03-spring-boot-tutorials-for-beginners.md",
    "content": "---\nlayout:     post\ntitle:      Spring Boot Tutorials for Beginners\ndate:       2020-01-03 12:31:19\nsummary:    At in28Minutes, we are creating a number of tutorials with videos, articles &amp; courses on Spring Boot for Beginners and Experienced Developers. This resources will help you learn and gain expertise at Spring Boot.\ncategories:  SpringBoot\npermalink:  /spring-boot-tutorials-for-beginners\nimage: /images/spring-boot-category.png\n---\n\nThis guide will help you understand the different resources (tutorials, videos and courses) we are creating for beginners to learn and gain expertise at Spring Boot. \n\n\n\n\n\n## Articles\n- [Spring Boot vs Spring vs Spring MVC](http://www.springboottutorial.com/spring-boot-vs-spring-mvc-vs-spring){:target=\"_blank\"}\n- Basics of Spring Boot - [Auto Configuration](http://www.springboottutorial.com/spring-boot-auto-configuration){:target=\"_blank\"}, [Spring Boot Starter Projects](http://www.springboottutorial.com/spring-boot-starter-projects){:target=\"_blank\"}, [Spring Boot Starter Parent](http://www.springboottutorial.com/spring-boot-starter-parent){:target=\"_blank\"}, [Spring Boot Initializr](http://www.springboottutorial.com/spring-initialzr-bootstrap-spring-boot-applications){:target=\"_blank\"}\n- Rest Services - [Basic Rest Service with Spring Boot](http://www.springboottutorial.com/creating-rest-service-with-spring-boot){:target=\"_blank\"}, [Unit Testing](http://www.springboottutorial.com/unit-testing-for-spring-boot-rest-services){:target=\"_blank\"}, [Integration Testing](http://www.springboottutorial.com/integration-testing-for-spring-boot-rest-services){:target=\"_blank\"}\n- Web Application - [Create Basic Web Application with Spring Boot](http://www.springboottutorial.com/creating-web-application-with-spring-boot){:target=\"_blank\"}\n- Spring Boot Starter Security - [Secure Your Rest Services with Spring Boot](http://www.springboottutorial.com/securing-rest-services-with-spring-boot-starter-security){:target=\"_blank\"}\n\n\n## Code Examples - Maven Projects\n\n> Our Github repository has all the code examples - [https://github.com/in28minutes/in28minutes.github.io/tree/master/code-zip-files](https://github.com/in28minutes/in28minutes.github.io/tree/master/code-zip-files){:target=\"_blank\"}\n\n- Rest Services with Unit and Integration Tests\n    - Website-springbootrestservices-simplerestserviceswithunitandintegrationtests.zip\n- Spring Security Example\n    - Website-SpringSecurityStarterWebApplication_Final.zip\n- All other examples related to Restful Web Services\n    - Website-springbootrestservices-all-examples.zip\n"
  },
  {
    "path": "_blog/articles/2019-02-18-064-Monolith-To-Microservice.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Breaking a Monolith into Microservices - Best Practices and Challenges\r\ndate:    2022-11-04 00:00:00\r\nsummary:  In this article, we will describe the first steps, in taking an architecture from monolith to microservice. \r\ncategories:  SpringBootMicroservices\r\npermalink:  /breaking-a-monolith-into-microservices\r\nimage: /images/microservices-category.png\r\n---\r\n\r\nIn this article, we will describe the first steps, in taking an architecture from monolith to microservice. \r\n \r\n## You will learn\r\n- What are the important features of microservices architectures?\r\n- What are the important challenges?\r\n- How do you break a monolith to microservices?\r\n\r\nLet's start with the basics of a monolith architecture,  understand the microservices architecture, and figure out what should you do to migrate from the former to the latter.\r\n\r\n\r\n\r\n### Monolith Architecture\r\n\r\nThe salient features of monolith applications are:\r\n\r\n*  Released, or taken to production, once every few week or months or years\r\n*  Generally have a wide range of features and functionality\r\n*  Have a development team of over 50 people working on them\r\n*  Debugging problems that arise in them, is a huge challenge\r\n*  It is almost impossible to bring in new technologies and technical processes, midway through the lifetime of such an application\r\n\r\n> Monolith applications are typically huge, with them having a million lines of code on average. \r\n\r\nA monolithic application would look something like the following:\r\n\r\n![image info](/images/Capture-064-02.PNG)\r\n\r\nYou have a large application talking to a large database.\r\n\r\n### Microservices Architecture\r\n\r\nIn microservices architectures, instead of building a large application, we build a number of smaller microservices. \r\n\r\nHere is how you would split up the monolith MovieApplication:\r\n\r\n![image info](/images/Capture-064-03.PNG)\r\n\r\n> As you can see here, the databases are also separated out. \r\n\r\nMicroservices architecture involves a number of small, well-designed microservices, that exchange messages among themselves:\r\n![image info](/images/Capture-059-02.png)\r\n\r\n### Microservices Architecture Is Tough\r\n\r\nWhile a microservices architecture looks very easy at a high level, implementing it is not a trivial process at all. \r\n\r\n> There are a number of important decisions to make for moving to Microservices Architectures\r\n\r\nExamples: \r\n* What are the boundaries of the individual microservices? \r\n* How small should a microservice be, and what functionality should go into it?\r\n* What all data needs to go into the database that a particular microservice talks to extensively? \r\n* How should the microservices communicate with each other?\r\n\r\n### Challenges with the Microservices Architectures\r\n\r\nThe challenges that need to be tacked when setting up a microservices architecture are described below.\r\n\r\n#### Quick Setup Needed\r\n\r\nYou can NOT spend a month setting up each microservice. You should be able to setup a microservice quickly. \r\n\r\n#### Automation\r\n\r\nBecause there are a number of smaller components instead of a monolith, there needs to be automation in every activity, such as builds, deployment, monitoring, etc. \r\n\r\n#### Visibility\r\n\r\nYou have a potentially large number of smaller components to deploy and maintain. This number could be 100 today, and a 1000 tomorrow. You should be able to monitor and identify problems automatically. You need great visibility around all the components.\r\n\r\n#### Bounded Context\r\n\r\nDeciding the boundaries of a microservice is not an easy task. Applying Bounded Context principles from Domain Driven Design is usually a good starting point. \r\n\r\nYour understanding of the domain evolves over a period of time. You need to ensure that the microservice boundaries evolve with time. \r\n\r\n#### Configuration Management\r\n\r\nYou need to maintain configurations for hundreds of components across environments. It would be best to have a configuration management solution. \r\n\r\n#### Dynamic Scale Up And Scale Down\r\n\r\nThe advantages of a microservices architecture can be realized only of the application can scale up and scale down easily in the cloud. \r\n\r\n#### Pack Of Cards\r\n\r\nIf the microservice at the bottom of a call chain fails, it can have knock on effects on all the other microservices. Microservices should be fault tolerant by design.\r\n\r\n#### Debugging\r\n\r\nWhen there is a problem that needs investigation, you might need to look into multiple services across different components. Centralized logging ans dashboards are essential to make it easy to debug problems.\r\n\r\n#### Consistency\r\n\r\nYou cannot have a wide range of tools solving the same problem. While it is important to encourage innovation, it is also essential to have decentralized governance around the languages, platforms, technologies and tools used for implementing, deploying and monitoring microservices.\r\n\r\n### Going from Monolith To Microservices - It is Not A Switch\r\n\r\nYou may have noticed that after describing monolith applications, we directly jumped into the challenges of microservices. \r\n\r\n>The reason we did not first talk about the advantages of microservices, is that you need a reality check when you migrate from one architecture to another. You need to realize this is not something you can do in a few weeks or months. \r\n\r\n> Getting a microservices architecture right involves a few years of work. It's not a switch, but a journey. \r\n\r\nDuring that journey, both architectures live side by side. \r\n\r\n> You would hope that number of applications using the microservices architecture grows over time. \r\n\r\n#### Ask Why are you migrating From Monolith To Microservices \r\n\r\nThis is the most important question to ask! Don't do microservices because it is a buzzword. Do it because your business needs it.\r\n\r\n> Why are you migrating from Monolith to Microservices?\r\n\r\nWhat do you want to achieve?\r\n* Do you want to be able to adopt new technologies and processes, in a faster manner?\r\n* Do you want faster release cycles for your application?\r\n* Do you want to scale more easily in the cloud?\r\n\r\nYou need to be very aware of which of these reasons is the biggest one, for your migration. \r\n\r\n> The approach you use to actually migrate would differ, based on the exact reason for migration. \r\n\r\nLet's look at these approaches in a little more detail.\r\n\r\n##### If your reason is - to Adopt New Technologies\r\n\r\nLet's say the reason is the ability to adopt newer technologies. In that case, you can start off with designing microservices for the next set of features you intend to implement. In other words, all the requirements for new feature implementation in the monolith application, are the best candidates to become microservices. \r\n\r\nYou need to answer questions such as:\r\n* How do you design the database?\r\n* How do make sure the communication between the old monolith and the new components, is proper?\r\n\r\n##### If your reason is - to have Faster Release Cycles\r\n\r\nYour business may not be happy with the pace at which new features are being released to production. In that scenario, you first need to identify those parts of the application, where there are frequent changes.\r\n\r\nOnce you do this, you can extract the fast moving parts and create microservices around them. \r\n\r\n> The idea behind this is , when there is a change, only release the related microservice.\r\n\r\n##### If your reason is - to Scale With The Cloud\r\n\r\nIf the driving force behind the migration is scaling with the cloud, then you need to analyze what needs to be done to put your application in the cloud. \r\n\r\nStart with research and Proof-of-Concept prototypes to understand the dependencies involved. You need to find out which dependencies are important to break, and anticipate the problems you may face on making the application cloud-native.\r\n\r\n##### More than one\r\n\r\nYour business might need more that one of the above. Prioritize them and get started with the most important ones. \r\n\r\n> Clearly, the path to migration will not be the same for all. However, with whatever microservices that you design in your journey, make sure they address the challenges that we saw earlier, in an effective manner.\r\n\r\nDo check out our video on this:\r\n\r\n[![image info](/images/Capture-064-01.PNG)](https://www.youtube.com/watch?v=d_wVZ6sgVbs)\r\n\r\n### Summary\r\n\r\nIn this article, we had a good look at the activities involved in moving from a monolith to a microservices architecture. We observed that it is not an easy journey, as the though process involved in designing the two kinds of systems, is radically different. \r\n\r\nThe actual journey of your migration will heavily depend upon the exact reason why you want to do it. Ultimately, with whatever microservices you come up with, make sure they effectively address the challenges that exist in such a system.\r\n\r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-03-27-spring-boot-react-crud-full-stack-with-maven-top20.md",
    "content": "---\nlayout:     post\ntitle:      Creating Spring Boot and React Java Full Stack Application with Maven\ndate:       2020-01-02 12:31:19\nsummary:    This guide helps you create a Java full stack application with all the CRUD (Create, Read, Update and Delete) features using React as Frontend framework and  Spring Boot as the backend REST API. We use Maven as the build tool.\ncategories:  SpringBootFullStack\npermalink:  /spring-boot-react-full-stack-crud-maven-application\nimage: /images/spring-boot-application.png\n---\n \n![Image](/images/full-stack-application-with-spring-boot-screenshot.png \"Spring Boot Full Stack Application\") \n\nThis guide helps you create a Java full stack application with all the CRUD (Create, Read, Update and Delete) features using React as Frontend framework and  Spring Boot as the backend REST API. We will be using JavaScript as the frontend language and Java as the backend language.\n\n![Image](/images/react_00_architecture.png \"Architecture of Spring Boot React Full Stack Application\")\n\n## You will learn\n\n- What is a full stack application?\n- Why do we create full stack applications?\n- How do you use React as a Frontend Framework?\n- How do you use Spring to create Backend REST Service API?\n- How do you call Spring Boot REST API from React using the axios framework?\n- How and When to use different REST API Request Methods - GET, POST, PUT and DELETE?\n- How do you perform CRUD (Create, Read, Update and Delete) operations using React as Frontend framework and  Spring Boot as the backend REST API?\n- How do you create a form in React using Formik?\n\n\n## Step 0: Get an overview of the Full Stack Application\n\n### Understanding Basic Features of the Application\n\nFollowing screenshot shows the application we would like to build: \n\nIt is a primary instructor portal allowing instructors to maintain their courses.\n\n![Image](/images/full-stack-application-with-spring-boot-screenshot.png \"Spring Boot Full Stack Application\") \n\n![Image](/images/full-stack-application-with-spring-boot-screenshot-2.png \"Spring Boot Full Stack Application\") \n\n### Understanding Full Stack Architecture\n\nFollowing Screenshot shows the architecture of the application we would create:\n\n![Image](/images/react_00_architecture.png \"Architecture of Spring Boot React Full Stack Application\")\n\nImportant points to note:\n- REST API is exposed using Spring Boot\n- REST API is consumed from React Frontend to present the UI\n- The Database, in this example, is a hardcoded in-memory static list.\n\nYou can find more details about Full Stack Architecture here - [Full Stack Application Architecture - Spring Boot and React](https://youtu.be/TTWH_Q7uSlY){:target=\"_blank\"}\n\n### Getting an overview of Spring Boot REST API Resources\n\nIn this guide, we will create these services using proper URIs and HTTP methods:\n\n- ```@GetMapping(\"/instructors/{username}/courses\")``` : Get Request Method exposing the list of courses taught by a specific instructor\n- ```@GetMapping(\"/instructors/{username}/courses/{id}\")``` : Get Request Method exposing the details of a specific course taught by a specific instructor\n- ```@DeleteMapping(\"/instructors/{username}/courses/{id}\")``` : Delete Request Method to delete a course belonging to a specific instructor\n- ```@PutMapping(\"/instructors/{username}/courses/{id}\")``` : Put Request Method to update the course details of a specific course taught by a specific instructor\n- ```@PostMapping(\"/instructors/{username}/courses\")``` : Post Request Method to create a new course for a specific instructor\n\n> The REST API can be enhanced to interact with other microservices infrastructure components and act as microservices.\n\n### Downloading the Complete Maven Project With Code Examples\n\nFollowing GitHub repository hosts the complete frontend and backend projects - https://github.com/in28minutes/spring-boot-react-fullstack-examples/tree/master/spring-boot-react-crud-full-stack-with-maven\n\n> Our Github repository has all the code examples - https://github.com/in28minutes/spring-boot-react-examples/\n\n### Understanding Spring Boot REST API Project Structure\n\nFollowing screenshot shows the structure of the Spring Boot project we create.\n\n![Image](/images/project-structure-spring-boot-fullstack-crud-maven.png \"Spring Boot Rest Service - Project Structure\") \n\nA few details:\n\n- `CourseResource.java` - Rest Resource exposing all the service methods discussed above.\n- `Course.java, CoursesHardcodedService.java` - Business Logic for the application. CoursesHardcodedService exposes a few methods we would invoke from our Rest Resource.\n- `SpringBootFullStackCrudFullStackWithMavenApplication.java` - Launcher for the Spring Boot Application. To run the application, launch this file as Java Application.\n- `pom.xml` - Contains all the dependencies needed to build this project. We use Spring Boot Starter Web and Spring Boot DevTools.\n\n\n## Understanding React Frontend Project Structure\n\nFollowing screenshot shows the structure of the React project we create.\n\n![Image](/images/project-structure-react-fullstack-crud-maven.png \"React Frontend - Project Structure\") \n\n> Quick Tip: You can get a high-level overview of all files in the React Project Structure watching this video [React Project Structure](https://youtu.be/wI5G8FNFrto){:target=\"_blank\"}\n\nA few details:\n- `InstructorApp.jsx` : React Component representing the high-level structure of the application. Routing is defined in this file.\n- `ListCoursesComponent.jsx` - React Component for listing all the courses for an instructor.\n- `CourseComponent.jsx` - React Component for editing Course Details and creating a new course\n- `CourseDataService.js` - Service using axios framework to make the Backend REST API Calls.\n\n\n### Understanding the tools you need to build this project\n\n- Maven 3.0+ for building Spring Boot API Project\n- npm, webpack for building frontend\n- Your favorite IDE. We use Eclipse for Java and Visual Studio Code for Frontend - JavaScript, TypeScript, Angular and React.\n- JDK 1.8+\n- Node v8+\n- Embedded Tomcat, built into Spring Boot Starter Web\n\n#### Installing Node Js (npm) & Visual Studio Code \n\n- Playlist - [Click to see video Playlist](https://www.youtube.com/playlist?list=PLBBog2r6uMCQN4X3Aa_jM9qVjgMCHMWx6\n- Steps){:target=\"_blank\"}\n  - Step 01 - Installing NodeJs and NPM - Node Package Manager\n  - Step 02 - Quick Introduction to NPM\n  - Step 03 - Installing Visual Studio Code - Front End JavaScript Editor\n\n#### Installing Java, Eclipse & Embedded Maven\n\n- Playlist - [Click to see video Playlist](https://www.youtube.com/playlist?list=PLBBog2r6uMCSmMVTW_QmDLyASBvovyAO3\n- Steps){:target=\"_blank\"}\n  - 0 - Overview - Installation Java, Eclipse and Maven\n  - 1 - Installing Java JDK\n  - 2 - Installing Eclipse IDE\n  - 3 - Using Embedded Maven in Eclipse\n  - 4 - Troubleshooting Java, Eclipse and Maven\n\n### Creating Full Stack CRUD application with React and Spring Boot - Step By Step Approach\n\nWe will use a step by step approach to creating the full stack application\n- Create a Spring Boot Application with Spring Boot Initializr\n- Create a React application using Create React App\n- Create the Retrieve Courses REST API and Enhance the React Front end to retrieve the courses using the axios framework\n- Add feature to delete a course in React front end and Spring Boot REST API\n- Add functionality to update course details in React front end and Spring Boot REST API\n- Add feature to create a course in React front end and Spring Boot REST API\n\n> You can get an introduction to REST down here - [Introduction to REST API](http://www.springboottutorial.com/creating-rest-service-with-spring-boot){:target=\"_blank\"}\n\n## Step 1: Bootstrapping Spring Boot REST API with Spring Initializr\n\nCreating a REST service with Spring Initializr is a cake walk. We will use Spring Web MVC as our web framework.  \n\nSpring Initializr [http://start.spring.io/](http://start.spring.io/){:target=\"_blank\"} is great tool to bootstrap your Spring Boot projects.\n\n![Image](/images/spring-boot-full-stack-with-web-and-dev-tools.png \"Spring Boot Project with Web and Developer Tools\")\n\nAs shown in the image above, the following steps have to be done\n\n- Launch Spring Initializr and choose the following\n  - Choose `com.in28minutes.fullstack.springboot.maven.crud` as Group\n  - Choose `spring-boot-fullstack-crud-full-stack-with-maven` as Artifact\n  - Choose following dependencies\n    - Web\n    - DevTools\n- Click Generate Project.\n- Import the project into Eclipse. File -> Import -> Existing Maven Project. For more details about creating Spring Boot Projects, you can read - [Creating Spring Boot Projects](http://www.springboottutorial.com/creating-spring-boot-project-with-eclipse-and-maven){:target=\"_blank\"}\n\n\n> If you are new to Spring Boot, we recommend watching this video - [Spring Boot in 10 Steps](https://www.youtube.com/watch?v=PSP1-2cN7vM){:target=\"_blank\"}\n\n\n## Step 2 - Bootstrapping React Frontend with Create React App\n\n[Create React App](https://github.com/facebook/create-react-app){:target=\"_blank\"} is an amazing tool to bootstrap your React applications. \n\nCreating React Frontend Applications with Create React App is very simple. \n\nLaunch up your terminal/command prompt. Make sure that you have node installed.\n\n```\nnpx create-react-app frontend-spring-boot-react-crud-full-stack-with-maven\n```\n\n> You can find more information about using Create React App here - [Create React App - Create and Launch a React Application](https://youtu.be/PR1pXhesetg){:target=\"_blank\"}\n\n> You can get a high-level overview of all files in the React Project Structure here - [React Project Structure](https://youtu.be/wI5G8FNFrto){:target=\"_blank\"}\n\n\n\n### Launching up React Frontend\n\nYou would need to cd to the project we created and execute `npm start`\n\n```\ncd frontend-spring-boot-react-crud-full-stack-with-maven\nnpm start\n```\nYou would see the screen below:\n\n![Image](/images/npm-start-new-react-app.png \"Starting a React Project\")\n\nWhen you launch up the application in the browser at ```http://localhost:3000/```, you would see the following welcome screen.\n\n![Image](/images/react-on-load-screenshot.png \"New React Project on the Browser\")\n\nYou can import the created project into Visual Studio Code by using ```File > Open > Select the project created earlier```. You can find more details here - [Importing React App into Visual Studio Code](https://youtu.be/Cw-bSD6Q8xI){:target=\"_blank\"}\n\n\n> Cool! You are all set to rock and roll with React.\n\n## Step 3 - Creating REST API for Retrieve All Courses and Connecting React Frontend\n\nWe would want to start building the screen shown below:\n\n![Image](/images/full-stack-application-with-spring-boot-screenshot.png \"Spring Boot Full Stack Application\") \n\nLet's start with building the course listing screen.\n\nTo be able to do that, we need to\n- Create REST API for retrieving a list of courses.\n- Connect the React Frontend to the backend REST API\n\n### Create REST API for retrieving a list of courses\n\nWeb Services, REST and Designing REST API, are pretty deep concepts. We would recommend to check this out for more - [Designing Great REST API](https://www.youtube.com/watch?v=NzgFdEGI8sI){:target=\"_blank\"}\n\nWe will create\n- A model object  ```Course.java```\n- A Hardcoded Business Service ```CoursesHardcodedService.java```\n- A Resource to expose the REST API ```CourseResource.java```\n\nWe will start with creating a model object ```Course.java```. The snippet below shows the content of the model class. For the complete listing, refer ```course/Course.java``` in the complete code example at the end of this article.\n\n```\npublic class Course {\n  private Long id;\n  private String username;\n  private String description;\n  //no arg constructor\n  //constructor with 3 args\n  //getters and setters\n  //hashcode and equals\n```\n\nNext, let's create a Business Service. In this article, we will use hardcoded data.\n\n```\n@Service\npublic class CoursesHardcodedService {\n\n  private static List<Course> courses = new ArrayList<>();\n  private static long idCounter = 0;\n\n  static {\n    courses.add(new Course(++idCounter, \"in28minutes\", \"Learn Full stack with Spring Boot and Angular\"));\n    courses.add(new Course(++idCounter, \"in28minutes\", \"Learn Full stack with Spring Boot and React\"));\n    courses.add(new Course(++idCounter, \"in28minutes\", \"Master Microservices with Spring Boot and Spring Cloud\"));\n    courses.add(new Course(++idCounter, \"in28minutes\",\n        \"Deploy Spring Boot Microservices to Cloud with Docker and Kubernetes\"));\n  }\n\n  public List<Course> findAll() {\n    return courses;\n  }\n}\n```\nFew things to note\n- Data is hardcoded\n- findAll returns the complete list of courses\n- You can see that the API of the Service is modelled around the Spring Data Repository interfaces. If you are familiar with JPA and Spring Data, you can easily replace this with a Service talking to a database.\n\nNext, let create the REST Resource to retrieve the list of courses for an instructor.\n\n```\n@RestController\npublic class CourseResource {\n\n  @Autowired\n  private CoursesHardcodedService courseManagementService;\n\n  @GetMapping(\"/instructors/{username}/courses\")\n  public List<Course> getAllCourses(@PathVariable String username) {\n    return courseManagementService.findAll();\n  }\n}\n```\n\nFew things to note:\n- ```@RestController : Combination of @Controller and @ResponseBody``` - Beans returned are converted to/from JSON/XML.\n- ```@Autowired private CoursesHardcodedService courseManagementService``` - Autowire the CoursesHardcodedService so that we can retrieve details from business service.\n\nIf you launch up the Spring boot application and go to ```http://localhost:8080/instructors/in28minutes/courses``` in the browser, you would see the response from the API.\n\n```\n[\n   {\n      \"id\": 1,\n      \"username\": \"in28minutes\",\n      \"description\": \"Learn Full stack with Spring Boot and Angular\"\n   },\n   {\n      \"id\": 2,\n      \"username\": \"in28minutes\",\n      \"description\": \"Learn Full stack with Spring Boot and React\"\n   },\n   {\n      \"id\": 3,\n      \"username\": \"in28minutes\",\n      \"description\": \"Master Microservices with Spring Boot and Spring Cloud\"\n   },\n   {\n      \"id\": 4,\n      \"username\": \"in28minutes\",\n      \"description\": \"Deploy Spring Boot Microservices to Cloud with Docker and Kubernetes\"\n   }\n]\n```\n\nWe have the REST API up and running. Its time to focus on the Frontend.\n\n### Enhancing React App to consume the REST API\n\nTo be able to enhance the React Application to consume the REST API, we would need to \n- Create an Application Component - to represent the structure of the complete application and include it in ```App.jsx``` - ```InstructorApp.jsx```\n- Add the frameworks need to call the REST API - axios, display a form - formik and support routing - react-router-dom\n- Create a view component for showing a list of course details and include it in the Application Component - ```ListCoursesComponent.jsx```\n- Invoking Retrieve Courses REST API from React Component - To enable this we will create a service to call the REST API using the axios framework - ```CourseDataService.js```. ```ListCoursesComponent.jsx``` will make use of ```CourseDataService.js```\n\nLet's start with creating an Application Component - ```InstructorApp.jsx```\n\n/src/component/InstructorApp.jsx\n\n```\nimport React, { Component } from 'react';\n\nclass InstructorApp extends Component {\n    render() {\n        return (\n              <h1>Instructor Application</h1>\n        )\n    }\n}\n\nexport default InstructorApp\n```\n\nFew things to note:\n- One of the first things you would need to understand about React is the concept of the component. You can find more about a react component here - [React Components](https://youtu.be/OmwcVGZWM98){:target=\"_blank\"}\n- ```class InstructorApp extends Component``` - Every React Class Component should extend a class called Component.\n- ```render()``` - The render() method of a component returns what needs to be displayed as part of the component\n- ```export default InstructorApp``` - Each JavaScript file is a module. If you wanted elements from a JavaScript module to be used in other JavaScript modules, we would need to export them. Here, we are making ```InstructorApp``` available for import in other components.\n\nLet's update the ```App.js``` to display the InstructorApp component.\n\nsrc/App.js\n\n```js\nimport React, { Component } from 'react';\nimport './App.css';\nimport InstructorApp from './component/InstructorApp';\n\nclass App extends Component {\n  render() {\n    return (\n      <div className=\"container\">\n        <InstructorApp />\n      </div>\n    );\n  }\n}\n\nexport default App;\n```\n\nFew things to note:\n- ```import InstructorApp from './component/InstructorApp'``` - Importing the InstructorApp component class\n- ```<InstructorApp />``` - Display the Instructor App component.\n\nLet's update the App.css to use Bootstrap framework:\n\n/src/App.css\n\n```css\n@import url(https://unpkg.com/bootstrap@4.1.0/dist/css/bootstrap.min.css)\n```\n\nWhen you launch the React app in the browser, it will appear as shown below:\n\n![Image](/images/react-initial-instructor-component.png \"Initial View of Instructor Component\")\n\n#### Adding Frameworks to React Application\n\nIn this project, we will make use of axios to execute REST APIs, react-router-dom to do the Routing between pages and formik to create forms. Let's stop the front end app running in the command prompt and execute these commands.\n\n```\nnpm add axios\n```\n\n```\nnpm add react-router-dom\n```\n\n```\nnpm add formik\n```\n\nWhen commands execute successfully, you would see new entries in ```package.json```\n\n```\n    \"axios\": \"^0.18.0\",\n    \"formik\": \"^1.5.1\",\n    \"react-router-dom\": \"^5.0.0\",\n```\n\nYou can run 'npm start' to relaunch the front end app loading up all the new frameworks.\n\n#### Creating a List Courses Component\n\nLet's create a new component for showing the List of courses - `ListCoursesComponent.jsx`. For now, let's hardcode a course into the course list.\n\n/src/component/ListCoursesComponent.jsx\n\n```\nclass ListCoursesComponent extends Component {\n\n    render() {\n        return (\n            <div className=\"container\">\n                <h3>All Courses</h3>\n                <div className=\"container\">\n                    <table className=\"table\">\n                        <thead>\n                            <tr>\n                                <th>Id</th>\n                                <th>Description</th>\n                            </tr>\n                        </thead>\n                        <tbody>\n                            <tr>\n                                <td>1</td>\n                                <td>Learn Full stack with Spring Boot and Angular</td>\n                            </tr>\n                        </tbody>\n                    </table>\n                </div>\n            </div>\n        )\n    }\n}\n\nexport default ListCoursesComponent\n```\nThings to Note:\n- It's a simple component. Returning a hardcoded table displaying a list of courses.\n\nLet's update the InstructorApp component to display the ListCoursesComponent.\n\n/src/component/InstructorApp.jsx\n\n```\nclass InstructorApp extends Component {\n    render() {\n        return (<>\n              <h1>Instructor Application</h1>\n              <ListCoursesComponent/>\n            </>\n        )\n    }\n}\n\nexport default InstructorApp\n```\n\nWe are importing the ListCoursesComponent and displaying it in the InstructorApp.\n\nWhen you launch the React app in the browser, it will appear as shown below:\n\n![Image](/images/react-second-stage-hardcoded-instructor-component.png \"Hardcoded Instructor Component\")\n\n#### Invoking Retrieve Courses REST API from React Component\n\nWe had created the REST API for retrieving the list of courses earlier. To call the REST API we would need to use a framework called axios. \n\n> Axios is a Promise based HTTP client for the browser and node.js\n\nAxios is a frontend framework that helps you make\n- REST API calls with different request methods including GET, POST, PUT, DELETE etc\n- Intercept Front end REST API calls and add headers and request content\n\nLet's create a data service method to call the REST API.\n\n/src/service/CourseDataService.js\n\n```js\nimport axios from 'axios'\n\nconst INSTRUCTOR = 'in28minutes'\nconst COURSE_API_URL = 'http://localhost:8080'\nconst INSTRUCTOR_API_URL = `${COURSE_API_URL}/instructors/${INSTRUCTOR}`\n\nclass CourseDataService {\n\n    retrieveAllCourses(name) {\n        return axios.get(`${INSTRUCTOR_API_URL}/courses`);\n    }\n}\n\nexport default new CourseDataService()\n\n```\n\nImportant points to note:\n- ```const INSTRUCTOR_API_URL = `${COURSE_API_URL}/instructors/${INSTRUCTOR}` ``` - We are forming the URL to call in a reusable way.\n- ```axios.get(`${INSTRUCTOR_API_URL}/courses`)``` - Call the REST API with the GET method. \n- ```export default new CourseDataService()``` - We are creating an instance of CourseDataService and making it available for other components.\n\nTo make the REST API call, we would need to call the CourseDataService - retrieveAllCourses method from the ListCoursesComponent\n\nImportant snippets are shown below:\n\n```\nclass ListCoursesComponent extends Component {\n\n    constructor(props) {\n        super(props)\n        this.refreshCourses = this.refreshCourses.bind(this)\n    }\n\n    componentDidMount() {\n        this.refreshCourses();\n    }\n\n    refreshCourses() {\n        CourseDataService.retrieveAllCourses(INSTRUCTOR)//HARDCODED\n            .then(\n                response => {\n                    console.log(response);\n                }\n            )\n    }\n    ....\n}\n\n```\n\nThings to note:\n- ```componentDidMount()``` - React defines a component lifecycle. componentDidMount will be called as soon as the component is mounted. We are calling refreshCourses as soon as a component is mounted.\n- ```this.refreshCourses = this.refreshCourses.bind(this)``` - Any method in a react component should be bound to this.\n-```CourseDataService.retrieveAllCourses(INSTRUCTOR).then``` - This would make the call to the REST API. You can define how to process the response in the then method.\n\n\nWhen you run the react app in the browser right now, you would see the following errors in the console\n```\n[Error] Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin.\n[Error] XMLHttpRequest cannot load http://localhost:8080/instructors/in28minutes/courses due to access control checks.\n[Error] Failed to load resource: Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin. (courses, line 0)\n[Error] Unhandled Promise Rejection: Error: Network Error\n  (anonymous function) (0.chunk.js:1097)\n  promiseReactionJob\n```\n\nThe Backend Spring Boot REST API is running on http://localhost:8080, and it is not allowing requests from other servers - http://localhost:3000, in this example. \n\nLet's configure Rest Resource to allow access from specific servers.\n\n\n```\n@CrossOrigin(origins = { \"http://localhost:3000\", \"http://localhost:4200\" })\n@RestController\npublic class CourseResource {\n\n```\nAn important thing to note\n- @CrossOrigin(origins = { \"http://localhost:3000\", \"http://localhost:4200\" }) - Allow requests from specific origins\n- We will use 3000 to run React and Vue JS apps, and we use 4200 to run Angular apps. Hence we are allowing requests from both ports.\n\nIf you refresh the page again, you would see the response from server printed in the console. \n\nWe would need to use the data from the response and show it on the component. \n\n> In React, we use the state to do that.\n\nFollowing snippet highlights the significant changes\n\n```\nclass ListCoursesComponent extends Component {\n\n    constructor(props) {\n        super(props)\n        this.state = {\n            courses: [],\n            message: null\n        }\n        this.refreshCourses = this.refreshCourses.bind(this)\n    }\n\n    componentDidMount() {\n        this.refreshCourses();\n    }\n\n    refreshCourses() {\n        CourseDataService.retrieveAllCourses(INSTRUCTOR)//HARDCODED\n            .then(\n                response => {\n                    console.log(response);\n                    this.setState({ courses: response.data })\n                }\n            )\n    }\n    ....\n}\n\n```\n\nImportant things to note:\n- ```this.state = {courses: [],message: null}``` - To display courses, we need to make them available to the component. We add courses to the state of the component and initialize it in the constructor.\n- ```response => {this.setState({ courses: response.data })}``` - When the response comes back with data, we update the state.\n\nWe have data in the state. How do we display it? \n\nWe need to update the render method.\n\n```\n    render() {\n        return (\n            <div className=\"container\">\n                <h3>All Courses</h3>\n                <div className=\"container\">\n                    <table className=\"table\">\n                        <thead>\n                            <tr>\n                                <th>Id</th>\n                                <th>Description</th>\n                            </tr>\n                        </thead>\n                        <tbody>\n                            {\n                                this.state.courses.map(\n                                    course =>\n                                        <tr key={course.id}>\n                                            <td>{course.id}</td>\n                                            <td>{course.description}</td>\n                                        </tr>\n                                )\n                            }\n                        </tbody>\n                    </table>\n                </div>\n            </div>\n        )\n    }\n\n```\n\nImportant things to note\n- ```this.state.courses.map(``` - Allow you to loop around a list of items and define how each item should be displayed.\n- ```key={course.id}``` - A key is used to uniquely identify a row.\n- ```{course.id}``` - In JSX, we use {} to execute JavaScript code.\n\nWhen you launch the React app in the browser, it will appear as shown below:\n\n![Image](/images/react-third-stage-getting-course-listing-from-rest-api.png \"Course Listing Component Retrieving from REST API\")\n\n> Congratulations! You have successfully integrated React with a REST API. Time to celebrate!\n\n## Step 4: Adding Delete Feature to List Courses Page\n\nTo be able to do this\n- We need a REST API in Spring Boot Backend for deleting a course\n- We would need to update React frontend to use the API\n\n### Adding Delete Method in the Backend REST API\n\nIt should be easy.\n\nSnippets below show how we create a simple deleteById method in CoursesHardcodedService and expose it from CourseResource. \n\n```\n@Service\npublic class CoursesHardcodedService {\n\n  public Course deleteById(long id) {\n    Course course = findById(id);\n\n    if (course == null)\n      return null;\n\n    if (courses.remove(course)) {\n      return course;\n    }\n\n    return null;\n  }\n\n```\n\n```\npublic class CourseResource {\n\n  @DeleteMapping(\"/instructors/{username}/courses/{id}\")\n  public ResponseEntity<Void> deleteCourse(@PathVariable String username, @PathVariable long id) {\n\n    Course course = courseManagementService.deleteById(id);\n\n    if (course != null) {\n      return ResponseEntity.noContent().build();\n    }\n\n    return ResponseEntity.notFound().build();\n  }\n```\n\nImportant things to note:\n- ```@DeleteMapping(\"/instructors/{username}/courses/{id}\")``` - We are mapping the Delete Request Method with two path variables\n- ```@PathVariable String username, @PathVariable long id``` - Defining the variables for Path Variables\n- ```ResponseEntity.noContent().build()``` - If Request is successful, return no content back\n- ```ResponseEntity.notFound().build()``` - If delete failed, return error - resource not found.\n\n\n### Enhancing React app with Delete Course Feature\n\nLet's add `deleteCourse` method to `CourseDataService`. As you can see it execute the delete request to specific course api url.\n\n```\ndeleteCourse(name, id) {\n    //console.log('executed service')\n    return axios.delete(`${INSTRUCTOR_API_URL}/courses/${id}`);\n}\n```\n\nWe can add a delete button corresponding to each of the courses:\n\n```\n<td><button className=\"btn btn-warning\" onClick={() => this.deleteCourseClicked(course.id)}>Delete</button></td>\n```\n\nOn click of the button we are calling the `deleteCourseClicked` method passing the course `id`. The implementation for `deleteCourseClicked` is shown below:\n\nWhen we get a successful response for delete API call, we set a `message` into state and refresh the courses list.\n\n```\ndeleteCourseClicked(id) {\n    CourseDataService.deleteCourse(INSTRUCTOR, id)\n        .then(\n            response => {\n                this.setState({ message: `Delete of course ${id} Successful` })\n                this.refreshCourses()\n            }\n        )\n\n}\n```\nWe display the message just below the header\n\n```\n<h3>All Courses</h3>\n{this.state.message && <div class=\"alert alert-success\">{this.state.message}</div>}\n```                \n\nOf course - we have to  ensure that the method is bound to `this` in the constructor.\n\n```\nthis.deleteCourseClicked = this.deleteCourseClicked.bind(this)\n```\n\nComplete `ListCoursesComponent`, at this stage, is shown below:\n\n```\nclass ListCoursesComponent extends Component {\n    constructor(props) {\n        super(props)\n        this.state = {\n            courses: [],\n            message: null\n        }\n        \n    }\n\n    render() {\n        console.log('render')\n        return (\n            <div className=\"container\">\n                <h3>All Courses</h3>\n                {this.state.message && <div class=\"alert alert-success\">{this.state.message}</div>}\n                <div className=\"container\">\n                    <table className=\"table\">\n                        <thead>\n                            <tr>\n                                <th>Id</th>\n                                <th>Description</th>\n                                <th>Delete</th>\n                            </tr>\n                        </thead>\n                        <tbody>\n                            {\n                                this.state.courses.map(\n                                    course =>\n                                        <tr key={course.id}>\n                                            <td>{course.id}</td>\n                                            <td>{course.description}</td>\n                                            <td><button className=\"btn btn-warning\" onClick={() => this.deleteCourseClicked(course.id)}>Delete</button></td>\n                                        </tr>\n                                )\n                            }\n                        </tbody>\n                    </table>\n                </div>\n            </div>\n        )\n    }\n\n```\nWhen you launch the React app in the browser, it will appear as shown below:\n\n![Image](/images/react-course-listing-with-delete.png \"Course Listing Component Retrieving from REST API and Delete Button\")\n\nWhen you click the delete button, the course will be deleted.\n\n\n### Updating Course Details\n\nTo be able to update the course details, we would need to create a new component to represent the todo form. \n\nLet's start with creating a simple component.\n\n/src/component/CourseComponent.jsx\n```\nclass CourseComponent extends Component {\n      render() {\n        return (\n              <h1>Course Details</h1>\n        )\n    }\n\n}\n\nexport default CourseComponent\n```\n\n#### Implementing Routing\n\nWhen the user clicks the update course button on the course listing page, we would want to route to the course page. How do we do it? That's where Routing comes into the picture.\n\n/src/component/InstructorApp.jsx\n\n```\nclass InstructorApp extends Component {\n    render() {\n        return (\n            <Router>\n                <>\n                    <h1>Instructor Application</h1>\n                    <Switch>\n                        <Route path=\"/\" exact component={ListCoursesComponent} />\n                        <Route path=\"/courses\" exact component={ListCoursesComponent} />\n                        <Route path=\"/courses/:id\" component={CourseComponent} />\n                    </Switch>\n                </>\n            </Router>\n        )\n    }\n}\n\nexport default InstructorApp\n```\n\nWe are defining a Router around all the components and configuring paths to each of them.\n- ```http://localhost:3000/``` takes you to home page\n- ```http://localhost:3000/courses``` takes you to course listing page\n- ```http://localhost:3000/courses/2``` takes you to course page\n\nWhen you launch the React app in the browser using this URL ```http://localhost:3000/courses/2```, it will appear as shown below:\n\n![Image](/images/react-1-course-details.png \"Course Component First Version\")\n\n#### Adding Update Button to Course Listing Page\n\nLet's add update button to the course listing page.\n\n/src/component/ListCoursesComponent.jsx\n```\n.....\n\n<th>Update</th>\n\n....\n<td><button className=\"btn btn-success\" onClick={() => this.updateCourseClicked(course.id)}>Update</button></td>\n```\n\nWe can create the add ```updateCourseClicked``` method to redirect to Course Component and add the binding in the constructor method.\n\n```\n...\nthis.updateCourseClicked = this.updateCourseClicked.bind(this)\n\n...\nupdateCourseClicked(id) {\n    console.log('update ' + id)\n    this.props.history.push(`/courses/${id}`)\n}\n```\n\n#### Adding Add button to Course Listing Page\n\nLet's add an Add button at the bottom of Course Listing Page.\n\n/src/component/ListCoursesComponent.jsx\n```\n<div className=\"row\">\n    <button className=\"btn btn-success\" onClick={this.addCourseClicked}>Add</button>\n</div>\n```\n\nLet's add the appropriate binding and the method to handle click of Add button.\n\n```\n//In constructor\nthis.addCourseClicked = this.addCourseClicked.bind(this)\n```\n\n```\naddCourseClicked() {\n    this.props.history.push(`/courses/-1`)\n}\n```\n\nWhen you launch the React app in the browser using this URL ```http://localhost:3000```, it will appear as shown below:\n\n![Image](/images/full-stack-application-with-spring-boot-screenshot.png \"Course listing page final version\")\n\nClicking any of the Update or Add buttons would take you to the Course Component.\n\n#### Create API to Retrieve Specific Course Details\n\nNow that we have the course component beinging rendered on the click of update button, let's start focusing on getting the course details from the REST API.\n\nLet's add `findById` method to `CoursesHardcodedService`. It retrieves the details of a specific course based on it.\n\n```\npublic Course findById(long id) {\n  for (Course course: courses) {\n    if (course.getId() == id) {\n      return course;\n    }\n  }\n  return null;\n}\n```\n\nLet's add `getCourse` method to `CourseResource` class. It exposes the GET method to get the details of a specific course based on id.\n\n```\n@GetMapping(\"/instructors/{username}/courses/{id}\")\npublic Course getCourse(@PathVariable String username, @PathVariable long id) {\n  return courseManagementService.findById(id);\n}\n\n```\n\n#### Invoking the API from Course Component\n\n> How do we invoke the retrieve course details from the React frontend?\n\nLet's add `retrieveCourse` method to `CourseDataService`\n\n```\nretrieveCourse(name, id) {\n    return axios.get(`${INSTRUCTOR_API_URL}/courses/${id}`);\n}\n```\nWe would want to call the retrieveCourse method in CourseDataService on the load of CourseComponent.\n\n> How do we do it?\n\n> Yes. componentDidMount is the right solution.\n\nBefore we get to it we would need to be able to get the course id from the URL. In the course details page, we are redirecting to the url `/courses/${id}`. From the path parameter, we would want to capture the id. We can use `this.props.match.params.id` to get the id from path parameters.\n\nThe code listing below shows the updated CourseComponent.\n\n```\nimport React, { Component } from 'react'\nimport { Formik, Form, Field, ErrorMessage } from 'formik';\nimport CourseDataService from '../service/CourseDataService';\n\nconst INSTRUCTOR = 'in28minutes'\n\nclass CourseComponent extends Component {\n\n    constructor(props) {\n        super(props)\n\n        this.state = {\n            id: this.props.match.params.id,\n            description: ''\n        }\n\n    }\n\n    componentDidMount() {\n\n        console.log(this.state.id)\n\n        // eslint-disable-next-line\n        if (this.state.id == -1) {\n            return\n        }\n\n        CourseDataService.retrieveCourse(INSTRUCTOR, this.state.id)\n            .then(response => this.setState({\n                description: response.data.description\n            }))\n    }\n\n    render() {\n\n        let { description, id } = this.state\n\n        return (\n            <div>\n                <h3>Course</h3>\n                <div>{id}</div>\n                <div>{description}</div>\n            </div>\n        )\n    }\n}\n\nexport default CourseComponent\n```\n\nWe are setting the details of the course into state.  \n\nWe are initializing state in the constructor.\n\n```\nthis.state = {\n    id: this.props.match.params.id,\n    description: ''\n}\n```\n\nIn `componentDidMount`, we are calling the `CourseDataService.retrieveCourse` to get the details for a course. Once we have the details, we are updating the state.\n\n```\nCourseDataService.retrieveCourse(INSTRUCTOR, this.state.id)\n    .then(response => this.setState({\n        description: response.data.description\n    }))\n```\n\nWe are updating the `render` method to show the course details from component `state`.\n\n```\nrender() {\n\n    let { description, id } = this.state\n\n    return (\n        <div>\n            <h3>Course</h3>\n            <div>{id}</div>\n            <div>{description}</div>\n        </div>\n    )\n}\n```\n\n`let { description, id } = this.state` is called destructing. This is similar to writing code shown below.\n\n```\nlet description = this.state.description\nlet id = this.state.id\n```\n\nWhen you try to update a course, you would see the screen below.\n\n![Image](/images/react-2-course-details-update.png \"Course Component Second Version\")\n\nWhen you try to create a course, you would see the screen below.\n\n![Image](/images/react-3-course-details-create.png \"Course Component Second Version\")\n\nThis is because of the logic in `componentDidMount` to not invoke the course API for a new todo.\n\n```\nif (this.state.id == -1) {\n    return\n}\n```\n\n#### Create a Form using Formik\n\nNow that we have loaded up the details of a specific course, let's shift out our attention to editing them and saving them back to the database.\n\nTo edit course details, we need a form. The most popular form framework with React is formik. We already added formik to our `package.json` using the command `npm add formik`.\n\nLet's now create a simple form using formik.\n\n```\nrender() {\n\n    let { description, id } = this.state\n\n    return (\n        <div>\n            <h3>Course</h3>\n            <div className=\"container\">\n                <Formik\n                    initialValues={% raw %}{{ id, description }}{% endraw %}\n                >\n                    {\n                        (props) => (\n                            <Form>\n                                <fieldset className=\"form-group\">\n                                    <label>Id</label>\n                                    <Field className=\"form-control\" type=\"text\" name=\"id\" disabled />\n                                </fieldset>\n                                <fieldset className=\"form-group\">\n                                    <label>Description</label>\n                                    <Field className=\"form-control\" type=\"text\" name=\"description\" />\n                                </fieldset>\n                                <button className=\"btn btn-success\" type=\"submit\">Save</button>\n                            </Form>\n                        )\n                    }\n                </Formik>\n\n            </div>\n        </div>\n    )\n}\n```\n\nFollowing are some of the important details:\n- `let { description, id } = this.state` - Creating local variable using destructuring\n- `{% raw %}<Formik initialValues={{ id, description }}>{% endraw %}` - Initialing Formik with the values loaded from state\n- `<Field className=\"form-control\" type=\"text\" name=\"id\" disabled />` - Creating a disabled text element for id. The name of element should match the name in state.\n- `<Field className=\"form-control\" type=\"text\" name=\"description\" />` - Creating a text element for description. The name of element should match the name in state.\n- `<button className=\"btn btn-success\" type=\"submit\">Save</button>` - Adding a submit button.\n\nWhen you try to update a course, you would see the screen below.\n\n![Image](/images/react-4-course-details-form.png \"Course Component Fourth Version\")\n\n#### Adding Handling of Submit Event\n\nLet's try to handle the Submit event now.\n\nLet's create an onSubmit method to log the values\n\n```\nonSubmit(values) {\n    console.log(values);\n}\n```\n\nLet's bind the `onSubmit` method to `this` in the constructor.\n\n```\nthis.onSubmit = this.onSubmit.bind(this)\n```\n\nIt's time to tie up the form with the onSubmit method. The key snippet is `onSubmit={this.onSubmit}`.\n\n```\n<Formik\n      initialValues={% raw %}{{ id, description }}{% endraw %}\n      onSubmit={this.onSubmit}\n                    >\n```\n\nWhen you click Submit, the form details are now printed to the console.\n\n```\n{id: \"2\", description: \"Learn Microservices\"}\n```\n\n#### Adding Validation using Formik\n\nWhat's a form without validation?\n\nLet's add a validate method.\n```\nvalidate(values) {\n    let errors = {}\n    if (!values.description) {\n        errors.description = 'Enter a Description'\n    } else if (values.description.length < 5) {\n        errors.description = 'Enter atleast 5 Characters in Description'\n    }\n\n    return errors\n}\n```\n\nWe are adding two validations:\n- check for empty description\n- check for a minimum length of 5\n\nYou can add other validations as you need.\n\n\nAs usual, let's bind it to `this` in the constructor.\n\n```\nthis.validate = this.validate.bind(this)\n```\n\nLet's ties this up with the form. The key snippet is `validate={this.validate}`. We do not want to validate on change of value or on blur of the field. Let's keep things simple. `enableReinitialize={true}` is needed to ensure that we can reload the form for existing todo.\n\n```\n<Formik\n      initialValues={% raw %}{{ id, description }}{% endraw %}\n      onSubmit={this.onSubmit}\n      validateOnChange={false}\n      validateOnBlur={false}\n      validate={this.validate}\n      enableReinitialize={true}>\n\n```\n\nIf you run the page right now and submit invalid description, you would see that validations prevent the form from getting submitted. \n\n> How do we see validation messages on the screen? \n\nFormik provides ErrorMessage.\n\nLet's add error message to the field:\n\n```\n<ErrorMessage name=\"description\" component=\"div\"\n    className=\"alert alert-warning\" />\n```\n\nWhen you try to update a course, you would see the screen below.\n\n![Image](/images/react-5-course-details-validation-error.png \"Course Component Fifth Version\")\n\n### Updating Course Details on click of submit\n\nNow that the form is ready, we would want to call the backend API to save the course details.\n\nLet's quickly create the API to Update and Create Courses.\n\n#### Create API to Update Course\n\nLet's add a `save` method to `CoursesHardcodedService` to handle creation and updation of course.\n\n```\npublic Course save(Course course) {\n  if (course.getId() == -1 || course.getId() == 0) {\n    course.setId(++idCounter);\n    courses.add(course);\n  } else {\n    deleteById(course.getId());\n    courses.add(course);\n  }\n  return course;\n}\n```\n\nLet's add a method to the Resource class to update the course. We are using PUT method to update the course. On course updation, we are returning 200 status with updaated course details in the body.\n\n```\n  @PutMapping(\"/instructors/{username}/courses/{id}\")\n  public ResponseEntity<Course> updateCourse(@PathVariable String username, @PathVariable long id,\n      @RequestBody Course course) {\n\n    Course courseUpdated = courseManagementService.save(course);\n\n    return new ResponseEntity<Course>(courseUpdated, HttpStatus.OK);\n  }\n```\n\n#### Adding API to Create Course\n\nLet's add a method to the Resource class to create the course. We are using POST method to create the course. On course updation, we are returning a status of CREATED.\n\n```\n  @PostMapping(\"/instructors/{username}/courses\")\n  public ResponseEntity<Void> createCourse(@PathVariable String username, @RequestBody Course course) {\n\n    Course createdCourse = courseManagementService.save(course);\n\n    // Location\n    // Get current resource url\n    /// {id}\n    URI uri = ServletUriComponentsBuilder.fromCurrentRequest().path(\"/{id}\").buildAndExpand(createdCourse.getId())\n        .toUri();\n\n    return ResponseEntity.created(uri).build();\n  }\n```\n\n#### Invoking Update and Create APIs from Course Screen\n\nNow that the REST API is ready, let's create the frontend methods to call them.\n\nLet's create respective methods in the `CourseDataService`. `updateCourse` uses a `put` and `createCourse` uses `post`.\n\n```\nclass CourseDataService {\n  updateCourse(name, id, course) {\n      return axios.put(`${INSTRUCTOR_API_URL}/courses/${id}`, course);\n  }\n\n  createCourse(name, course) {\n      return axios.post(`${INSTRUCTOR_API_URL}/courses/`, course);\n  }\n```\n\nLet's update the `CourseComponent` to invoke the right service on the click of the submit button.\n\n```\n    onSubmit(values) {\n        let username = INSTRUCTOR\n\n        let course = {\n            id: this.state.id,\n            description: values.description,\n            targetDate: values.targetDate\n        }\n\n        if (this.state.id === -1) {\n            CourseDataService.createCourse(username, course)\n                .then(() => this.props.history.push('/courses'))\n        } else {\n            CourseDataService.updateCourse(username, this.state.id, course)\n                .then(() => this.props.history.push('/courses'))\n        }\n\n        console.log(values);\n    }\n\n```\n\nWe are creating a course object with the updated details and calling the appropriate method on the `CourseDataService`. Once the request is successful, we are redirecting the user to the course listing page using `this.props.history.push('/courses')`.\n\n\n\n### Downloading the Complete Maven Project With Code Examples\n\nFollowing GitHub repository hosts the complete frontend and backend projects - https://github.com/in28minutes/spring-boot-react-fullstack-examples/tree/master/spring-boot-react-crud-full-stack-with-maven\n\n> Our Github repository has all the code examples - https://github.com/in28minutes/spring-boot-react-examples/\n"
  },
  {
    "path": "_blog/articles/2019-04-10-Architecture-Goal-Of-An-Architect.md",
    "content": "---\r\nlayout:  post\r\ntitle:  What Is The Goal Of a Software Architect?\r\ndate:    2019-04-09 12:31:19\r\nsummary:  In this article, we have a close look at what your goal as an architect should be. Before reading any further, take a piece of paper and put down the list of goals from your perspective. \r\ncategories: SwArchitecture\r\npermalink:  /what-is-the-goal-of-an-software-architect\r\nimage: /images/architecture.png\r\n---\r\n\r\nIn this article, we have a close look at what your goal as an architect should be. Before reading any further, take a piece of paper and put down the list of goals from your perspective.\r\n\r\n\r\n\r\nThis is the second article in the following series of articles on Software Architecture :\r\n- [1 - Quick Introduction To Software Architecture](/introduction-to-software-architecture){:target='_blank'}\r\n- [2 - What Is The Goal Of a Software Architect?](/what-is-the-goal-of-an-software-architect){:target='_blank'}\r\n- [3 - 5 Qualities of a Great Software Architect](/five-important-qualities-of-a-software-architect){:target='_blank'}\r\n- [4 - 5 Important Responsibilities of a Software Architect](/five-important-responsibilities-of-a-software-architect){:target='_blank'}\r\n- [5 - Software Architecture - Why do we use Layered Architectures?](/software-architecture-why-should-we-use-layered-architecture){:target='_blank'}\r\n\r\n\r\n### Technology Enables/Supports Business\r\n\r\nThe most important point to understand is that technology enables and supports businesses. That is the primary reason why we build awesome applications and frameworks. \r\n\r\nFor example, Netflix built an excellent microservices architecture, in order to support its business and consumer needs. Netflix's architecture enables them to provide an out-of-this-world movie streaming experience to all their customers. Simply having great technology will not help them survive. \r\n\r\nYour role as an architect is very similar - architect applications that support business needs. \r\n\r\n### What Are These Business Needs?\r\n\r\nThe business needs can be put into the following categories:\r\n\r\n#### Functional Requirements\r\n\r\nNetflix might say it needs a web page where all the available movies are listed. A user should then be able to select a movie by clicking on it, and watch it. This is an example of a functional requirement. All businesses have them.\r\n\r\n#### Non Functional Requirements\r\n\r\nNetflix might put down a condition that the application needs to support over 100,000 users. The amount of time needed to load a page should not exceed 2 seconds. Also, application should be very secure. In addition, the system should be available 99.9999% of the time. These are all non functional requirements.\r\n\r\n#### Quick Feature Releases\r\n\r\nIn general, if you get a fresh requirement today, you don't want it be delivered 6 months down the line. There is a need for early delivery of features. \r\n\r\nHigh performance organizations such as Facebook, Twitter, Amazon and Netflix do multiple feature releases in a single day. \r\n\r\n#### Early Feedback\r\n\r\nAnother thing that all businesses need is early feedback. If a system is down, a particular feature is not working as expected, or if a large number of users don't like a particular feature, the business wants to know of it as early as possible. \r\n\r\n#### Quick Troubleshooting And Support   \r\n\r\nIn today's customer-centered world, it is of high importance that you have teams to deliver quick troubleshooting, and excellent customer support services. You also need to solve any problems that customers raise, very quickly.\r\n\r\n### Focus On The Right Things as an Architect\r\n\r\nA lot of technology folks are obsessed with technology - tools, frameworks, languages and stuff like that. These are very important in their own right, without a doubt. \r\n\r\nHowever, the problems comes when we forget the very reason why the application is being built - to enable a business to succeed. \r\n\r\nAs an architect, your unwavering focus should be on the business entirely, and look to reach business goals using the right technology solutions.\r\n\r\nDo check out our video on this:\r\n\r\n[![image info](/images/Capture-042-01.png)](https://www.youtube.com/watch?v=kpGG-GxM2DA)\r\n\r\n### Summary\r\n\r\nIn this article, we focused on what the goals of an architect should be. We saw that most developers focus on the technology, but lose sight of the business goals. Applications are enablers of businesses. We then saw the five categories of business goals that an architect should try to meet through the application design.\r\n\r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-04-10-Architecture-Introduction-To-Software-Architecture.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Quick Introduction To Software Architecture - What, Why and How?\r\ndate:    2019-04-09 12:31:19\r\nsummary: Good Software Architecture is essential to building great software. What is Software Architecture all about?\r\ncategories: SwArchitecture\r\npermalink:  /introduction-to-software-architecture\r\nimage: /images/architecture.png\r\n---\r\n\r\nGood Software Architecture is essential to building great software. What is Software Architecture all about?\r\n\r\n## You will learn\r\n- What Is Software Architecture?\r\n- What do Software Architects do?\r\n- What are some of the important decisions software architects make?\r\n- Why do we need Software Architecture?\r\n\r\n\r\n\r\nThis is the first article in the following series of articles on Software Architecture :\r\n- [1 - Quick Introduction To Software Architecture](/introduction-to-software-architecture){:target='_blank'}\r\n- [2 - What Is The Goal Of a Software Architect?](/what-is-the-goal-of-an-software-architect){:target='_blank'}\r\n- [3 - 5 Qualities of a Great Software Architect](/five-important-qualities-of-a-software-architect){:target='_blank'}\r\n- [4 - 5 Important Responsibilities of a Software Architect](/five-important-responsibilities-of-a-software-architect){:target='_blank'}\r\n- [5 - Software Architecture - Why do we use Layered Architectures?](/software-architecture-why-should-we-use-layered-architecture){:target='_blank'}\r\n\r\n\r\n### What Is Software Architecture?\r\n\r\nTo understand what software architecture is all about, let us look at the following diagram:\r\n\r\n![image info](images/Capture-087-02.png)\r\n\r\nThis application architecture has multiple microservices - Microservice1, Microservice2 and Microservice3. There are a set of common components that handle functionality such as security, logging, archetype creation, and the like. You also have components to handle common infrastructure concerns/ These include an API Gateway, a naming server, and a centralized logging system. \r\n\r\n#### Answering Some Important Questions\r\n\r\n* Who made the decision that there need to be three microservices, and assigned specific responsibility to each one of them?\r\n* Who decided that certain functionalities of the application need to be handled by common components? \r\n* Who designed the mode of interaction between the microservices and the common components?\r\n* Who classifies the common infrastructure components, and designs their interfaces with each of the microservices?\r\n\r\n#### Architecture Is All About Making Decisions\r\n\r\nDesigning an application architecture is all about making such important decisions. It involves staring from a level that involves these decisions:\r\n\r\n* What are the applications? What are their individual boundaries?\r\n* What are the interactions between the individual applications? In other words, the services of which other applications are needed by a particular application?\r\n* What are the common functionalities that can be identified in the system? How do you design them as components, and how to interface them with the other applications/components?\r\n* What services of the system need to be abstracted into the common infrastructure? How do you decide on how to make these services available to the rest of the system?\r\n\r\n\r\n### Why Do We Need Software Architecture?\r\n\r\nA few decades earlier, software programs built were small and simple. However, things have changed dramatically. \r\n\r\nSoftware has become quite complex, with the advent of cloud computing, microservices, big data, and what not.\r\n\r\nFactors that have contributed to this complexity include:\r\n\r\n* **Distributed Systems**: Even a single web page that you may view online, might be driven by a cluster of hundreds of systems.\r\n* **Device Explosion**: Earlier, devices owned by users were limited to a single PC or laptop per person. Nowadays, you have a choice of mobile phones, tablets, IoT devices, and what not! Software that needs to run on  more than one device, will be complex\r\n* **Enormous Scale**: The load or the scale of users that an enterprise application needs to support has also gone up significantly\r\n* **Technology Evolution**: The languages, frameworks, tools and processes used in software development continuously undergo change, and applications need to keep pace with them\r\n* **Non Functional Requirements**: It is very important to ensure that all non functional requirements are adhered to when designing your applications.\r\n\r\nThe challenge in such a dynamic scenario, is to develop applications that work today, and adapt to stay relevant tomorrow. This is the puzzle that architects try to solve. \r\n\r\nThat's also the reason why you need to pay attention to the architecture, when you develop applications. \r\n\r\nDo check out our video on the same topic:\r\n\r\n[![image info](images/Capture-087-01.png)](https://www.youtube.com/watch?v=RxNNPU7pz_s)\r\n[![image info](/images/Capture-023-01.png)](https://www.youtube.com/watch?v=RALT8z8Ya0w)\r\n\r\n### Summary\r\n\r\nSoftware architecture is all about making decisions. It mainly involves identifying applications and components, and clearly demarcating their boundaries. \r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-04-10-Architecture-Top-Architect-Responsibilities.md",
    "content": "---\r\nlayout:  post\r\ntitle:  5 Important Responsibilities of a Software Architect\r\ndate:    2019-04-09 12:31:19\r\nsummary:  In this article, we look at some of the important responsibilities that an architect is expected to handle. Although we chiefly focus on application architects, most of these also hold true for enterprise architects as well.\r\ncategories: SwArchitecture\r\npermalink:  /five-important-responsibilities-of-a-software-architect\r\nimage: /images/architecture.png\r\n---\r\n\r\nIn this article, we look at some of the important responsibilities that an architect is expected to handle. Although we chiefly focus on application architects, most of these also hold true for enterprise architects as well.\r\n\r\nFive Responsibilities Of Architects that we look at are\r\n- Clean And Simple Architecture\r\n- Clear Standards\r\n- Proper Governance\r\n- Best Engineering Practices\r\n- Awesome Technical Processes\r\n\r\n\r\n\r\nThis is the fourth article in the following series of articles on Software Architecture :\r\n- [1 - Quick Introduction To Software Architecture](/introduction-to-software-architecture){:target='_blank'}\r\n- [2 - What Is The Goal Of a Software Architect?](/what-is-the-goal-of-an-software-architect){:target='_blank'}\r\n- [3 - 5 Qualities of a Great Software Architect](/five-important-qualities-of-a-software-architect){:target='_blank'}\r\n- [4 - 5 Important Responsibilities of a Software Architect](/five-important-responsibilities-of-a-software-architect){:target='_blank'}\r\n- [5 - Software Architecture - Why do we use Layered Architectures?](/software-architecture-why-should-we-use-layered-architecture){:target='_blank'}\r\n\r\n\r\n### Clean And Simple Architecture\r\n\r\nAny application that you work on needs to have a very clean and simple architecture. There must be great clarity in the organization on application layers, the use of specific frameworks at each layer, and patterns in communication with external applications. \r\n\r\n### Clear Standards\r\n\r\nThere needs to be clarity on the sets of standards followed in design, development, deployment and operations. \r\n\r\n### Governance\r\n\r\nArchitects needs to ensure proper governance around the various standards, and on the creation of common components. In any enterprise application, it always adds great value to have common components that are frequently reused across different applications and application layers. \r\n\r\n### Best Engineering Practices\r\n\r\nIt is very important to adhere to engineering best practices over the lifetime of an application. Interesting examples are Test Driven Development, Behavior Driven Development, DevOps. Such practices also involve use of consistent build and deployment tools and processes. \r\n\r\nThe question you need to ask yourself frequently is - Are you are making the best possible use of these practices, to achieve business goals?\r\n\r\n### Awesome Technical Processes\r\n\r\nYou need to make sure that you have great processes in place for the following:\r\n\r\n* Development\r\n* Deployment\r\n* Continuous Integration\r\n* Immediate Defect Feedback\r\n\r\nYou need to have complete control over such issues. \r\n\r\nDo check out our video on this:\r\n\r\n[![image info](/images/Capture-044-01.png)](https://www.youtube.com/watch?v=QAUa41CXsrk)\r\n\r\n### Summary\r\n\r\nIn this article, we looked at the some of the important responsibilities of a software architect.\r\n\r\nFive Responsibilities Of Architects that we looked at are\r\n- Clean And Simple Architecture\r\n- Clear Standards\r\n- Proper Governance\r\n- Best Engineering Practices\r\n- Awesome Technical Processes\r\n\r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-04-10-Architecture-Top-Qualities-Great-Architects.md",
    "content": "---\r\nlayout:  post\r\ntitle:  5 Qualities of a Great Software Architect\r\ndate:    2019-04-09 12:31:19\r\nsummary:  In this article, we look at some of the important qualities of a great software architect. While we focus on application architects, most of these are applicable for enterprise architects as well.\r\ncategories: SwArchitecture\r\npermalink:  /five-important-qualities-of-a-software-architect\r\nimage: /images/architecture.png\r\n---\r\n\r\nIn this article, we look at some of the important qualities of a great software architect. Although we chiefly focus on application architects, most of these also hold true for enterprise architects as well.\r\n\r\nFive Qualities Of Architects that we look at are\r\n- Great Communication\r\n- Great Technical Skills\r\n- Forward Thinker\r\n- Super Diagnostic Skills\r\n- Hands-on\r\n\r\n\r\n\r\nThis is the third article in the following series of articles on Software Architecture :\r\n- [1 - Quick Introduction To Software Architecture](/introduction-to-software-architecture){:target='_blank'}\r\n- [2 - What Is The Goal Of a Software Architect?](/what-is-the-goal-of-an-software-architect){:target='_blank'}\r\n- [3 - 5 Qualities of a Great Software Architect](/five-important-qualities-of-a-software-architect){:target='_blank'}\r\n- [4 - 5 Important Responsibilities of a Software Architect](/five-important-responsibilities-of-a-software-architect){:target='_blank'}\r\n- [5 - Software Architecture - Why do we use Layered Architectures?](/software-architecture-why-should-we-use-layered-architecture){:target='_blank'}\r\n\r\n\r\n### Great Communication\r\n\r\nArchitecture is all about conveying your vision to every member of the team. There are multiple stakeholders who are interested in knowing how we achieve business needs. Within a business, there are architects at multiple levels:\r\n\r\n* Enterprise Architects\r\n* Application Architects\r\n* Core Architects\r\n\r\nApart from them, there are other stakeholders such as:\r\n\r\n* Development Team\r\n* QA Team\r\n* Operations Team\r\n\r\nIt is vital that all these stakeholders have a clear view of the future direction of the business and technology.\r\n\r\n### Great Technical Skills\r\n\r\nYou being an architect, it is but natural for us to expect a great understanding of technology from you. You need to have a good grasp of concepts such as tools, languages, frameworks and tools used in the application. \r\n\r\n> This is something taken as a given!\r\n\r\n### Forward Thinker\r\n\r\nAs an architect, you need to be forward thinking and proactive. You need to understand where technology is heading, what kinds of architectures are trending, what programming languages are becoming popular, in what direction is the business headed, and what could be the business needs of the future. \r\n\r\nYou need to be able to have a plan of how to evolve the application to meet future business needs. \r\n\r\nIn the modern world of Agile practices, you should be able to break down these future expectations into manageable chunks, in order to evolve the application.  \r\n\r\n### Super Diagnostic Skills\r\n\r\nYou need to be able to resolve real world problems the application might face. This is not just about handling exceptions. If the application has a security, scalability or performance issue, then the architect needs to get involved and work out a solution. This requires the ability to look at the big picture, and at the same time understand the minor details. \r\n\r\n### Hands-On\r\n\r\nWhen needed, architects should be able to get the system up and running, checking out code from the repository, and start fixing bugs. \r\n\r\nI loved working in organizations where even Enterprise Architects could get their hands dirty when needed. At a minimum, atleast the application architects should be able to write production code. \r\n\r\nDo check out our video on this:\r\n\r\n[![image info](/images/Capture-043-01.png)](https://www.youtube.com/watch?v=M4A532ksLow)\r\n\r\n### Summary\r\n\r\nIn this article, we looked at the top 5 qualities of a great software architect has. Those are great communication, great technical skills, forward thinking, great diagnostic skills, and being hands-on.\r\n\r\n\r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-04-10-Architecture-Why-Have-Multiple-Layers.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Software Architecture - Why do we use Layered Architectures?\r\ndate:    2019-04-09 12:31:19\r\nsummary:  In this article, we explore the reasons why we build applications with several layers. We also look at different options for each layer in the Java world.\r\ncategories: SwArchitecture\r\npermalink:  /software-architecture-why-should-we-use-layered-architecture\r\nimage: /images/spring-boot-application.png\r\n---\r\n\r\nIn this article, we explore the reasons why we build applications with several layers. We also look at different options for each layer in the Java world.\r\n\r\n### You will Learn\r\n- Why Have Multiple Layers?\r\n- What are typical layers and their responsiblities?\r\n- What are the typical frameworks used in each layer in the Java world?\r\n\r\n\r\n\r\nThis is the fifth article in the following series of articles on Software Architecture :\r\n- [1 - Quick Introduction To Software Architecture](/introduction-to-software-architecture){:target='_blank'}\r\n- [2 - What Is The Goal Of a Software Architect?](/what-is-the-goal-of-an-software-architect){:target='_blank'}\r\n- [3 - 5 Qualities of a Great Software Architect](/five-important-qualities-of-a-software-architect){:target='_blank'}\r\n- [4 - 5 Important Responsibilities of a Software Architect](/five-important-responsibilities-of-a-software-architect){:target='_blank'}\r\n- [5 - Software Architecture - Why do we use Layered Architectures?](/software-architecture-why-should-we-use-layered-architecture){:target='_blank'}\r\n\r\n\r\n### Why Have Multiple Layers?\r\n\r\nWhen we build any large application, such as a web application or service, we try to organize it into multiple layers. We could go for layers such as Web, Business, Access, among others:\r\n\r\n![image info](/images/Capture-038-02.png)\r\n\r\nThe reason we go to such lengths is a very important underlying principle : **separation of concerns**. \r\n\r\nEach of the layers above have different responsibilities. Web layer is responsible for presenting information to the user. The Business layer is responsible for application's business logic. The Data layer is responsible for taking care of the data access, and configuring and talking to the data stores. You might also have an additional access layer to talk to external applications, or queueing messages for dispatch.\r\n\r\nBy defining each layer to have a separate responsibility, you ensure high cohesion with-in each such layer. \r\n\r\n### Layers In Enterprise Java\r\n\r\nWhen it comes to the Java world, the typical organization of enterprise applications follows this schematic:\r\n\r\n![image info](/images/Capture-038-03.png)\r\n\r\n\r\n### Implementing The Web Layer\r\n\r\nEarlier, the web layer of a Java EE application is responsible for rendering the final view to the user with technologies like JSPs and variety of templating languages.  With the advent of RESTful web services and evolution of JavaScript SPA frameworks, this has changed drastically. \r\n\r\nToday, we expose a REST API from the Java Web layer, and a front-end framework (such as AngularJS or ReactJS) handles the user presentation.\r\n\r\nThe main responsibility of a web layer is to talk to business layer and send a proper response to REST API calls.\r\n\r\nAnother responsibility that a web layer typically handles is authentication and authorizations using a module like Spring Security.\r\n\r\n![image info](/images/Capture-038-04.png)\r\n \r\n\r\nA few important decisions when designing your web layer are\r\n- Should the application have state? If yes, you need to store session information about the user. Ideally, you should not.\r\n- Which framework to use? The popular options are Spring Boot (MVC), JAX-RS(REST), JAX-WS(SOAP).\r\n\r\n### Implementing The Business Layer\r\n\r\n![image info](/images/Capture-038-05.png)\r\n\r\nLets look at the important business layer responsibilities:\r\n\r\n#### Transaction Management\r\n\r\nThis is taken care of by Java Transaction API (JTA) and Spring Transactions. \r\n\r\n### Implementing The Access Layer\r\n\r\n![image info](/images/Capture-038-06.png)\r\n\r\nThe following are the responsibilities of the Access layer:\r\n\r\n#### Communicating with Data Store\r\n\r\nIf your application communicates with an external database, JPA might be a good choice. If very complex database queries are needed, then you might want to use JDBC or MyBatis. \r\n\r\n> Spring Data JPA might be a good starting point for using JPA and Hibernate.\r\n\r\n#### Communication With External Interfaces\r\n\r\nThis layer provides interface with the JMS module. It also communicates with AMQP implementations.\r\n\r\n### Other Layers\r\n\r\n![image info](/images/Capture-038-07.png)\r\n\r\nOne of the most important aspects that needs to be handled in any system is Cross Cutting Concerns. This includes tasks such as logging, performance and security. \r\n\r\nTypically these are implemented using Aspect Oriented Programming. AspectJ and Spring AOP are options to consider.\r\n\r\n### Unit Testing\r\n\r\nUnit testing of the application is another important concern. Typical frameworks that are provided include JUnit, Mockito and Spring Unit.\r\n\r\nDo check out our video on this:\r\n\r\n[![image info](/images/Capture-038-01.png)](https://www.youtube.com/watch?v=fS2JnypQKWs)\r\n\r\n### Summary\r\n\r\nIn this article, we understood why we need to have multiple layers in an application. We looked at the layers in a typical Java web application, along with framework options available. We then had a look at the makeup of the individual Data, Business and Access layers of a typical Java web application.\r\n"
  },
  {
    "path": "_blog/articles/2019-04-10-Component-Scan.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Spring Framework - What Is Component Scan?\r\ndate:   2019-04-10 12:31:19\r\nsummary: Spring framework identifies the beans and their dependencies, creates the beans and injects the dependencies into beans. How does the Spring Framework know where to search for beans and dependencies? How does Spring Boot make it easier?\r\ncategories:  SpringFramework\r\npermalink:  /spring-and-spring-boot-what-is-component-scan\r\nimage: /images/spring-framework-category.png\r\n---\r\n\r\nSpring framework identifies the beans and their dependencies, creates the beans and injects the dependencies into beans. How does the Spring Framework know where to search for beans and dependencies? How does Spring Boot make component scan easier?\r\n \r\n## You will learn\r\n- Why do we need Component Scan in Spring?\r\n- How can you configure a Component Scan in Spring with XML and Java Annotation based configuration?\r\n- How does Spring Boot provide an automatic Component Scan?\r\n- How do you solve problems with Component Scan?\r\n\r\nIn this article, we understand a little bit about component scan in the context of the Spring framework. We also see how component scan works with the Spring Boot framework.\r\n\r\n\r\n### Spring Framework\r\n\r\nThis is the fourth article in a series of articles on Spring Framework:\r\n\r\n- [1 - Introduction To Spring Framework](/introduction-to-the-spring-framework){:target='_blank'}\r\n- [2 - What Is A Dependency?](/spring-framework-what-is-a-dependency){:target='_blank'}\r\n- [3 - What Is Dependency Injection?](/spring-framework-dependency-injection-inversion-of-control){:target='_blank'}\r\n- [4 - What Is Component Scan?](/spring-and-spring-boot-what-is-component-scan){:target='_blank'}\r\n- [5 - Architecture of Spring Framework - Modularity and Spring Modules](/spring-framework-architectures-and-modules){:target='_blank'}\r\n- [6 - What Are Spring Projects?](/spring-projects-with-examples){:target='_blank'}\r\n- [7 - Introduction To Spring Batch](/spring-basics-introduction-to-spring-batch){:target='_blank'}\r\n\r\n\r\n### Functionality Of The Spring Framework?\r\n\r\nWhat is the fundamental functionality of the Spring framework? It is dependency injection. \r\n\r\nSpring framework identifies the beans and their dependencies, finds them and injects the dependencies into beans. \r\n\r\nHave a look at the following example:\r\n\r\n```java\r\n\r\n\t@Component\r\n\tpublic class ComplexAlgorithmImpl {\r\n\t\t@Autowired\r\n\t\tprivare SortAlgorithm sortAlgorithm;\r\n\t\t//...\r\n\t}\r\n\r\n\tpublic interface SortAlgorithm {\r\n\t\tpublic int[] sort(int[] numbers);\r\n\t}\r\n\r\n\t@Component\r\n\tpublic class QuickSortAlgorithm implements SortAlgorithm {\r\n\t\t//...\r\n\t}\r\n\r\n```\r\n\r\nLet's quickly look at what Spring Framework needs to do get the autowiring working.\r\n\r\nSpring framework needs to create instances of ```ComplexAlgorithmImpl``` and ```QuickSortAlgorithm```. \r\n\r\nSince ```QuickSortAlgorithm``` is the only implementation of ```SortAlgorithm``` available, it needs to be auto-wired into the ```sortAlgorithm``` field of ```ComplexAlgorithmImpl```. \r\n\r\n### How Does Spring Search For Beans?\r\n\r\nLet's look at a few questions?\r\n- How does Spring know where to look for the beans? \r\n- How does it know where it needs to search for classes with annotations such as ```@Component``` and ```@Service```?  \r\n\r\nA typical application could have hundreds of JARS, and as a result, thousands of classes. Therefore, it is not practical for Spring to search in all the classes present in the ```CLASSPATH```.\r\n\r\n### Enter Component Scan\r\n\r\nClearly, Spring needs to be given inputs to identify the packages of the beans and dependencies. This is where component scan comes into the picture. \r\n\r\nYou declare a component scan by passing in a list of packages where the scan needs to take place:\r\n\r\n```java\r\n\r\n\t@Configuration\r\n\t@ComponentScan(basePackages = {\r\n\t\t\t\"com.in28minutes.spring.example1.businessservice\",\r\n\t\t\t\"com.in28minutes.spring.example1.dataservice.stub\"})\r\n\r\n\tclass SpringContext {\r\n\t}\r\n\r\n```\r\n\r\nThe packages mentioned above are the locations where the beans and their dependencies are defined. This ```@ComponentScan``` gives a clue to the Spring framework on where to search.\r\n\r\n\r\n### Component Scan With XML Configuration\r\n\r\nThe thing is, component scan an also be done with XML configuration:\r\n\r\n![image info](images/Capture-092-02.png)\r\n\r\nFor this, use the ```<context:component-scan>``` tag, and specify the packages that are the locations. \r\n\r\n### How does Auto Configuration work with Spring Boot?\r\n\r\nSpring Boot tries to automate a lot of stuff. Consider the code example below:\r\n\r\n```java\r\n\r\n\tpackage com.in28minutes.spring.basics.springin5steps;\r\n\r\n\t@SpringBootApplication\r\n\tpublic class SpringIn5StepsApplication {\r\n\t\t//...\r\n\t}\r\n\r\n```\r\n\r\n```java\r\n\r\n\tpackage com.in28minutes.spring.basics.springin5steps;\r\n\t\r\n\t@RunWith(SpringRunner.class)\r\n\r\n\t@SpringBootTest\r\n\tpublic class SpringIn5StepsApplicationTests {\r\n\t\t//...\r\n\t}\r\n\r\n``` \r\n\r\nAs soon as Spring Boot sees the annotation ```@SpringBootApplication```, it does an automatic scan on the current package, which is ```com.in28minutes.spring.basics.springin5steps```. \r\n\r\nYou don't need to explicitly define a component scan. If all the components that you need are present in the same package as ```SpringIn5StepsApplication```, you don't need to explicitly specify component scan.\r\n\r\n### Troubleshooting Component Scan In Spring Boot\r\n\r\nHave a look at the following Spring Boot application:\r\n\r\n![image info](images/Capture-092-03.png)\r\n\r\nSince ```SpringbootIn10StepsApplication``` has a ```@SpringBootApplication``` annotation attached to it, an automatic component scan in the package ```com.in28minutes.springboot.basics.springbootin10steps```, and all its sub-packages. \r\n\r\nHowever, what would happen if you have one of the components defined in a different package, say ```com.in28mnutes.springboot.somethingelse```? \r\n\r\nIn this case, you need to add that package to the component scan. There are a couple of options available for doing this.\r\n\r\n### Explicit Component Scan In Spring Boot\r\n\r\nThere are two ways of doing an explicit component scan:\r\n\r\n#### Scan a parent package\r\n\r\nThis would scan the entire parent package tree of ```com.in28minutes.springboot```. \r\n\r\n```java\r\n\r\n\t@ComponentScan(\"com.in28minutes.springboot\")\r\n\t\r\n\t@SpringBootApplication\r\n\tpublic class SpringBootApllicationIn10Steps {\r\n\t\t//...\r\n\t}\r\n\r\n``` \r\n\r\n\r\n#### Define explicit scans\r\n\r\nIn this case, we explicitly mention a list of specific packages within the tree. Therefore, only those two paths in the package tree will now get scanned.\r\n\r\n```java\r\n\r\n\t@ComponentScan({\r\n\t\t\"com.in28minutes.springboot.basics.springbootin10steps\",\r\n\t\t\"com.in28minutes.springboot.somethingelse\"})\r\n\t\r\n\t@SpringBootApplication\r\n\tpublic class SpringBootApllicationIn10Steps {\r\n\t\t//...\r\n\t}\r\n\r\n```\r\n\r\n\r\nAs soon as you explicitly define a component scan, you are taking complete control. The default automatic scan that generally happens with Spring Boot will not longer take place. You need to specify the default package, as well as other packages.\r\n\r\n### Errors Related To Component Scan\r\n\r\nLet's look at some of the errors related to component scan and how you can solve them.\r\n\r\n#### Typical Errors\r\n\r\nWhen the controllers are not scanned, the URLs would not work. You would observe behaviors like this:\r\n\r\n![image info](images/Capture-092-04.png)\r\n\r\nThe other kind of error is when Spring does not find the dependencies. A typical error looks like this:\r\n\r\n![image info](images/Capture-092-05.png)\r\n\r\nThis means Spring expects at least one bean to auto-wire a dependency, but is not able to locate them. \r\n\r\n### Solving Errors With Component Scan\r\n\r\nHere are some of the things to look fo:\r\n* Make sure that you have the right annotation for the concerned bean - ```@Controller```, ```@Repository```, ```@Component```.\r\n* Make sure that the package that a component is present in, is part of the component scan.\r\n\r\nDo check out our video on the same topic:\r\n\r\n[![image info](images/Capture-092-01.png)](https://www.youtube.com/watch?v=L1Y5pwy09Vw)\r\n\r\n### Summary\r\n\r\nIn this article, we talked about component scan in the context of Spring and Spring Boot frameworks.The ```@ComponentScan``` annotation is used to specify packages to locate components in Spring. This is automatically done in the default package, in the case of Spring Boot.\r\n"
  },
  {
    "path": "_blog/articles/2019-04-10-Dependency-Injection.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Spring Basics - Dependency Injection and Inversion of Control\r\ndate:   2019-04-10 12:31:19\r\nsummary: Developers starting with the Spring framework often get confused with terminology - Dependency, Dependency Injection and Inversion Of Control. In this article, we introduce you to the concepts of Dependency Injection and Inversion Of Control.\r\ncategories:  SpringFramework\r\npermalink:  /spring-framework-dependency-injection-inversion-of-control\r\nimage: /images/spring-features.png\r\n---\r\n \r\nDevelopers starting with the Spring framework often get confused with terminology - Dependency, Dependency Injection and Inversion Of Control. In this article, we introduce you to the concepts of Dependency Injection and Inversion Of Control.\r\n\r\n## You will learn\r\n- What Is Dependency Injection?\r\n- Why do you need Dependency Injection?\r\n- What Is tight coupling?\r\n- What Is de-coupling?\r\n- How does Spring Framework provide Dependency Injection?\r\n- What Is Inversion Of Control?\r\n- What are good examples of inversion of control?\r\n- How does Spring Framework implement Inversion of Control?\r\n- Why Is Inversion of Control Important and what are its advantages?\r\n\r\n\r\n\r\n### Spring Framework\r\n\r\nThis is the third article in a series of articles on Spring Framework:\r\n\r\n- [1 - Introduction To Spring Framework](/introduction-to-the-spring-framework){:target='_blank'}\r\n- [2 - What Is A Dependency?](/spring-framework-what-is-a-dependency){:target='_blank'}\r\n- [3 - What Is Dependency Injection?](/spring-framework-dependency-injection-inversion-of-control){:target='_blank'}\r\n- [4 - What Is Component Scan?](/spring-and-spring-boot-what-is-component-scan){:target='_blank'}\r\n- [5 - Architecture of Spring Framework - Modularity and Spring Modules](/spring-framework-architectures-and-modules){:target='_blank'}\r\n- [6 - What Are Spring Projects?](/spring-projects-with-examples){:target='_blank'}\r\n- [7 - Introduction To Spring Batch](/spring-basics-introduction-to-spring-batch){:target='_blank'}\r\n\r\n\r\n### What Is Dependency Injection?\r\n\r\nDependency injection is the core feature of the Spring Framework.  Dependency injection is a concept that is borrowed from the Dependency Inversion Principle (DIP). \r\n\r\n#### Tight Coupling\r\n\r\nHave a look at the following examples of code:\r\n\r\n##### Example-1\r\n\r\n```java\r\n\r\n\tpublic class TodoBusinessService {\r\n\t\tTodoDataServiceImpl dataService = new TodoDataServiceImpl();\r\n\t\t//... \r\n\t}\r\n\r\n```  \r\n\r\n```TodoBusinessService``` is directly creating an instance of ```TodoDataServiceImpl``` within itself. \r\n\r\n##### Example-2\r\n\r\n```java\r\n\r\n\tpublic class ComplexAlgorithmImpl {\r\n\t\tBubbleSortAlgorithm bubbleSortAlgorithm = new BubbleSortAlgorithm();\r\n\t\t//...\r\n\t}\r\n\r\n``` \r\n\r\n```ComplexAlgorithmImpl``` is meant to perform a lot of complex logic, and one of the things it does is sorting. here, it is directly creating an instance of ```BubbleSortAlgorithm``` within itself.\r\n\r\nThese two examples highlight code with tight coupling. \r\n\r\nImagine what you need to do, if you want to change the sort algorithm to quicksort. You need to change the relevant code within ```ComplexAlgorithmImpl```. \r\n\r\nHence, ```ComplexAlgorithmImpl``` is tightly coupled to ```BubbleSortAlgorithm```, a specific sort algorithm.\r\n\r\n#### Decoupling ```ComplexAlgorithmImpl```\r\n\r\nHow do we decouple ```ComplexAlgorithmImpl``` from the specific sort algorithm? \r\n\r\nWe want it to be used with bubble sort, or quick sort, or radix sort, or any other sort. The solution is to make use of an interface.\r\n\r\nHave a look at the following code:\r\n\r\n```java\r\n\r\n\tpublic interface SortAlgorithm {\r\n\t\tpublic int[] sort(int[] numbers);\r\n\t}\r\n\r\n\t@Component\r\n\tpublic class ComplexAlgorithmImpl {\r\n\t\t@Autowired\r\n\t\tprivate SortAlgorithm sortAlgorithm;\t\r\n\t\t//...\r\n\t}\r\n\r\n\tpublic class BubbleSortAlgorithm implements SortAlogrithm {\r\n\t\t//...\r\n\t}\r\n\r\n\tpublic class QuickSortAlgorithm implements SortAlogrithm {\r\n\t\t//...\r\n\t}\r\n\r\n``` \r\n#### Decoupling Explained\r\n\r\nWe have created an interface named ```SortAlgorithm``` that has ```sort()``` method defined. Specific sort algorithms all implement ```SortAlgorithm``` by overriding ```sort()```. Here, ```ComplexAlgorithmImpl``` makes use of ```SortAlgorithm``` as a dependency by declaring it as a member. However, the actual implementation of ```SortAlgorithm``` needs to be passed in as a parameter to its constructor, or a setter method. The user decides which specific sort algorithm ```ComplexAlgorithmImpl``` gets to use.\r\n\r\nWhichever class wants to make use of ```ComplexAlgorithmImpl``` needs to write code such as this:\r\n\r\n```java\r\n\r\n\tCompexAlgorithmImpl binarySearch = new ComplexAlgorithmImpl(new QuickSortAlgorithm());\r\n\r\n```\r\n\r\nOther classes may choose to pass in ```SortAlgorithm``` implementations for bubble sort, heap sort or radix sort. \r\n\r\n#### Inversion of Control with ```ComplexAlgorithmImpl```\r\n\r\nLook at it from the perspective of ```ComplexAlgorithmImpl```. \r\n\r\nIn the first approach, it took up the responsibility of selecting the specific sort algorithm. As a result, the specific ```BubbleSortAlgorithm``` was hard-coded.\r\n\r\nIn the second approach, the class which uses ```ComplexAlgorithmImpl``` gets to decide which specific sort algorithm is to be used. \r\n\r\nThere is a clear inversion of responsibility taking place. This is also called Inversion of Control or **dependency inversion**.\r\n\r\nDependency inversion results in **loose coupling**.  ```ComplexAlgorithmImpl``` is not tied to a specific sort algorithm.\r\n\r\n### Dependency Injection In Spring\r\n\r\nNow where does Spring framework come into picture?\r\n\r\nLets look at the code below:\r\n\r\n```java\r\n\r\n\tCompexAlgorithmImpl binarySearch = new ComplexAlgorithmImpl(new QuickSortAlgorithm());\r\n\r\n```\r\n\r\nIn the above piece of code, we are manually creating the objects and tying them up with dependencies. In a typical application, we might have thousands of objects. Do you want to write the code for all it manually. How about having a framework that does this for you?\r\n\r\nLet's consider the following example:\r\n\r\n```java\r\n\r\n\t@Component\r\n\tpublic class ComplexAlgorithmImpl {\r\n\t\t@Autowired\r\n\t\tprivate SortAlgorithm sortAlgorithm;\t\r\n\t\t//...\r\n\t}\r\n\r\n```\r\n\r\nWhen this code is run - Spring creates an instance of ```QuickSortAlgorithm``` which implements ```SortAlgorithm``` interface, and wires it into an instance of ```ComplexAlgorithmImpl```. \r\n\r\nThis process, where the Spring framework identifies the beans, identifies the dependencies, and populates the dependencies inside the beans is called **dependency injection**. \r\n\r\n#### Dependency Inversion And Dependency Injection\r\n\r\nSo far in this article, we have discussed two important concepts:\r\n\r\n* Dependency Inversion : We create loosely couple code by explicitly declaring dependencies, and introducing interfaces for them. \r\n* Dependency Injection : The Spring framework identifies beans and dependencies, and wires dependencies inside beans.\r\n\r\nDo check out our video on the same topic:\r\n\r\n[![image info](images/Capture-091-01.png)](https://www.youtube.com/watch?v=4sD_3BzxJOo)\r\n\r\n### Summary\r\n\r\nIn this article, we talked about dependency injection. Dependency injection has its roots in a core SOLID principle of object oriented programming, named the Dependency Inversion principle. We saw how dependency inversion transforms tightly couple code into a loosely coupled one. Dependencies are explicitly identified, and classes that use them become flexible.\r\n\r\nDependency injection is a mechanism based on dependency inversion. The Spring framework identifies beans and dependencies, and autowires the dependencies into beans.\r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-04-10-Introduction-To-Spring-Boot.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Introduction To Spring Boot Framework - A Quick Tutorial for Beginners\r\ndate:   2022-04-10 12:31:19\r\nsummary: In this article, we understand the basics of Spring Boot framework. We look at the important features of Spring Boot and how it is different from the Spring framework.\r\ncategories:  SpringBoot\r\npermalink:  /introduction-to-spring-boot\r\nimage: /images/spring-boot-feature.png\r\n---\r\n\r\nIn this article, we understand the basics of Spring Boot framework. We look at the important features of Spring Boot and how it is different from the Spring framework.\r\n\r\n![image info](images/Capture-085-03.png)\r\n\r\n## You will learn\r\n- What is Spring Boot?\r\n- What are the problems in developing Spring Based Applications?\r\n- How does Spring Boot help in solving these problems?\r\n- What are important concepts to understand in Spring Boot?\r\n- What are the best practices in using Spring Batch?\r\n- What is Spring Boot Auto Configuration?\r\n- What are Spring Boot Starter Projects?\r\n\r\n\r\n### What Is Spring Boot?\r\n\r\nHere's the official definition of Spring Boot from the Spring Boot Web Site.\r\n\r\n> Spring Boot makes it easy to create stand-alone, production-ready Spring-based application that is ready to run. Most Spring Boot applications need very little Spring configuration.  \r\n\r\nWhat does it mean? Let's start with looking at Spring Framework.\r\n\r\n### Spring Framework\r\n\r\nThe core feature of Spring framework is **dependency injection**. Spring alsoe provides great integration with other frameworks, like Hibernate. Spring provides a few frameworks of its own - for example, Spring MVC for developing web applications and REST API.\r\n\r\n### Problem with Spring Based Applications\r\n\r\nIf you look at any Spring-based application, such as a Spring MVC application:\r\n\r\n![image info](images/Capture-085-02.png)\r\n\r\nYou need to configure a lot of components within it:\r\n\r\n![image info](images/Capture-085-03.png)\r\n\r\nYou also end up configuring a data source and a transaction manager: \r\n\r\n![image info](images/Capture-085-04.png)\r\n\r\nThe configuration story is the same for any Spring-based application. \r\n\r\n### Spring Boot To The Rescue\r\n\r\nSpring Boot asks the question: \r\n\r\n> Why do we need to do the exact same thing for every project involving Spring? \r\n\r\nWhy not just abstract it away, and help the developer build applications quicker?\r\n\r\n#### Spring Boot Auto Configuration\r\n\r\nSpring Boot Auto Configuration looks to bring more intelligence into application configuration. \r\n\r\nFor example, it looks to build a few patterns, identify what JAR files are available, and looks to auto-configure a lot of the things.\r\n\r\nSpring Boot ensures that a developer can build a new Spring project in a few minutes, instead of hours. \r\n\r\n#### Spring Boot And Frameworks\r\n\r\nSpring Boot takes care of the typical things you normally do in Sprint 0 of a project. In addition, Spring Boot helps the developer in the following areas:\r\n* Integration with several frameworks\r\n* Configuration management\r\n* Logging\r\n* Transaction management\r\n* Error/Exception handling\r\n* Monitoring and health checks\r\n* Integrating unit testing and mocking frameworks\r\n\r\nAll we need to do is provide the frameworks that are needed by the application, and Spring Boot magically auto configures them. \r\n\r\n#### Spring Boot And Version Management\r\n\r\nSpring Boot also takes the responsibility of managing versions of dependent libraries. \r\n\r\nYou just need to migrate to the latest version of Spring Boot, and the corresponding compatible versions of all the frameworks being used are directly available for you. \r\n\r\n### Why Do You Need Spring Boot?\r\n\r\n#### Reducing Project Start-up Time\r\n\r\nSpring Boot reduces the startup time in creating new projects. You can add frameworks and Spring Boot automatically configures them for you. In the world of microservices, as we create a number of smaller microservices instead of a large monolith, Spring Boot helps us start up projects quickly. \r\n\r\n#### Spring Boot Provides Starter Projects\r\n\r\nSpring Boot provides a feature called Starter Projects, which helps you quickly add specific features to your application. Important ones include:\r\n* spring-boot-starter-web-services: Quickly build SOAP Web Services.\r\n* spring-boot-starter-web: Useful to build RESTful web applications, using Spring MVC. It uses Tomcat as the default embedded container.\r\n* spring-boot-starter-test: Used for testing Spring Boot applications, using libraries such as JUnit, Hamcrest, and Mockito.\r\n* spring-boot-starter-hateoas: Useful for building hypermedia-based RESTful web applications, using Spring MVC and Spring HATEOAS.\r\n* spring-boot-starter-jersey: An alternative to string-boot-starter-web. Useful for building RESTful web applications using JAX-RS and Jersey\r\n* spring-boot-starter-security: Useful for using Spring Security\r\n* spring-boot-starter-jpa: Used for Spring data JPA with hibernate\r\n* spring-boot-starter-data-rest: A stater for exposing Spring Data repositories over REST, using Spring Data REST\r\n\r\n#### Spring Boot Provides Developer Tools\r\n\r\nSpring Boot makes the life of a developer a lot easier by providing important debug and deployment tools. \r\n\r\nDo check out our video on the same topic:\r\n\r\n[![image info](images/Capture-085-01.png)](https://www.youtube.com/watch?v=sKdD3wYP9SM)\r\n\r\n### Summary\r\n\r\nIn this article, we had a quick look at the Spring Boot Framework. We saw that the Spring framework is very useful to developers, but Spring projects had a large configuration overhead. Spring Boot adds some intelligence with autoconfiguration. It greatly reduces project startup time and provides easier mechanism - called starter projects - for developing different kinds of applications."
  },
  {
    "path": "_blog/articles/2019-04-10-Introduction-To-Spring-Data-REST.md",
    "content": "---\r\nlayout:  post\r\ntitle: Introduction To Spring Data Rest - Quick Tutorial for Beginners\r\ndate:   2022-04-10 12:31:19\r\nsummary: Spring Data project provides common abstractions to integrate with different kinds of data stores. Spring Data Rest is part of the umbrella of Spring Data projects. It makes it easy to build hypermedia-driven REST web services, on top of Spring Data repositories.\r\ncategories:  SpringBoot\r\npermalink:  /spring-boot-introduction-to-spring-data-rest\r\nimage: /images/spring-boot-application.png\r\n---\r\n\r\nSpring Data project provides common abstractions to integrate with different kinds of data stores. Spring Data Rest is part of the umbrella of Spring Data projects. It makes it easy to build hypermedia-driven REST web services, on top of Spring Data repositories.\r\n\r\n![image info](images/Capture-082-03.png)\r\n\r\n## You will learn\r\n- What is Spring Data Rest?\r\n- How does Spring Data Rest make building REST API easier?\r\n- How to integration Spring Data Rest with Spring Data JPA?\r\n- What are important features of Spring Data Rest?\r\n- How to execute REST API created using Spring Data Rest?\r\n\r\n\r\n### What Does Spring Data Rest Do?\r\n\r\nIt does all of the following:\r\n* Exposes REST services around the Spring Data, without having to write a lot of code. \r\n* Supports both SQL-based and No SQL-based databases.\r\n* Supports Pagination\r\n* Enables Filtering\r\n* Allows for Sorting\r\n* Supports HATEOAS\r\n\r\n### Why Spring Data Rest\r\n\r\nSpring Data Rest is ideal for simple projects, that quickly want to get started with creating REST API. \r\n\r\nLet's look at a quick example of using Spring Data Rest to build a REST API.\r\n\r\n#### Generate your project\r\n\r\nThe easiest way to bring such projects up, would be to use the Spring Initializr:\r\n\r\n![image info](images/Capture-082-03.png)\r\n\r\nNote that we have included the dependencies such as Web, JPA and Rest Repositories.You can generate the project, and then import it as a maven project into Eclipse IDE.\r\n\r\n#### Create Entity\r\n\r\nOnce you have the project imported into eclipse, lets create a JPA Entity - Todo:\r\n\r\n![image info](images/Capture-082-04.png)\r\n\r\n```@Entity``` ```Todo``` has an Id, and has a few fields and methods. \r\n\r\n#### Create RepositoryRestResource\r\n\r\nOnce you have an entity, you can create a RepositoryRestResource for it.\r\n\r\n```java\r\n\r\n\t@RepositoryRestResource(collectionResourceRel=\"todos\", path=\"todos\")\r\n\tpublic interface TodoRepository \r\n\t\t\t\t\textends PagingAndSortingRepository<Todo, Long> {\r\n\t\tList<Todo> findByUser(@Param(\"user\") String user);\r\n\t}\r\n\t\r\n``` \r\n\r\n#### Testing REST API\r\n\r\nOnce you have the Entity and RepositoryRestResource, you are ready to fire your requests.\r\n\r\nFor example, you can send a POST request to a URL to create a resource:\r\n\r\n![image info](images/Capture-082-05.png)\r\n\r\nYou can see that the link of the created resource is returned to you. \r\n\r\nAnother thing you can do is go to the URL and see what resources are currently stored there:\r\n![image info](images/Capture-082-06.png)\r\n\r\nYou can also access a specific todo stored in the repository:\r\n![image info](images/Capture-082-07.png)\r\n\r\nYou can do a search on the repository by typing in a query such as:\r\n```https://localhost:8080/todos?user=\"Jill\"```\r\n\r\nYou can also do a search by directly invoking the repository method:\r\n```https://localhost:8080/search/findByUser?user=\"Jill\"```\r\n\r\n### When to use Spring Data Rest?\r\n\r\nRemember to use Spring Data Rest only for simple projects. It is great to use when you are building a prototype for your application. However, when it comes to production applications, you need to think twice before using Spring Data Rest.\r\n\r\nDo check out our video on the same topic:\r\n\r\n[![image info](images/Capture-082-01.png)](https://www.youtube.com/watch?v=prtat_cKUVA)\r\n\r\n### Summary\r\n\r\nIn this article, we had a look at Spring Data Rest, which is a framework used to build REST services around Spring Data repositories. It is ideal to use with simple applications or prototypes."
  },
  {
    "path": "_blog/articles/2019-04-10-Introduction-To-Spring-Framework.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Introduction To Spring Framework - Quick Tutorial For Beginners\r\ndate:   2019-04-10 12:31:19\r\nsummary: In this article, we look to get an introduction to what the Spring framework is, and why it is so widely used.\r\ncategories:  SpringFramework\r\npermalink:  /introduction-to-the-spring-framework\r\nimage: /images/spring-framework-category.png\r\n---\r\n\r\nIn this article, we look to get an introduction to what the Spring framework is, and why it is so widely used. \r\n\r\n![image info](images/Capture-081-02.png)\r\n \r\n## You will learn\r\n- What is Spring Framework?\r\n- What are the important problems that Spring Framework solves?\r\n- How does Spring Framework make building enterprise applications easier?\r\n- What are important features of Spring Framework?\r\n- What are important concepts to understand in Spring Framework?\r\n- Why Is The Spring Framework Important?\r\n- What are the best practices in using Spring Framework?\r\n- What are Spring Projects?\r\n- What are Spring Modules?\r\n\r\n\r\n### Spring Framework\r\n\r\nThis is the first article in a series of articles on Spring Framework:\r\n\r\n- [1 - Introduction To Spring Framework](/introduction-to-the-spring-framework){:target='_blank'}\r\n- [2 - What Is A Dependency?](/spring-framework-what-is-a-dependency){:target='_blank'}\r\n- [3 - What Is Dependency Injection?](/spring-framework-dependency-injection-inversion-of-control){:target='_blank'}\r\n- [4 - What Is Component Scan?](/spring-and-spring-boot-what-is-component-scan){:target='_blank'}\r\n- [5 - Architecture of Spring Framework - Modularity and Spring Modules](/spring-framework-architectures-and-modules){:target='_blank'}\r\n- [6 - What Are Spring Projects?](/spring-projects-with-examples){:target='_blank'}\r\n- [7 - Introduction To Spring Batch](/spring-basics-introduction-to-spring-batch){:target='_blank'}\r\n\r\n### What Is Spring?\r\n\r\nHere's the description from the Spring web site:\r\n\r\n> The Spring framework provides comprehensive infrastructural support to develop Java applications.  Spring handles the infrastructure, so you can develop your application. \r\n\r\nWhat does this mean?\r\n\r\nLet's look at some of the important features of Spring framework with examples.\r\n\r\n### Writing Loosely Coupled Code\r\n\r\nWhen we write application code, we don't want it to be tightly coupled.\r\n\r\n#### What Is Tight Coupling?\r\n\r\nTightly coupled code could look like the following:\r\n\r\n```java\r\n\r\n\tpublic class ComplexAlgorithmImpl {\r\n\t\tBubbleSortAlgorithm bubbleSortAlgorithm = new BubbleSortAlgorithm();\r\n\t\t//...\r\n\t}\r\n\r\n```\r\n\r\n```ComplexAlgorithmImpl``` is tightly coupled to the ```BubbleSortAlgorithm```. \r\n\r\nIf you need to change the sort algorithm from ```BubbleSortAlgorithm``` to ```QuickSortAlgorithm```, then the code of ```ComplexAlgorithmImpl``` needs to change as well.\r\n\r\n#### What Is Loose Coupling?\r\n\r\nIs there a better way to manage change, than what we see over here?  turns out there is - use an interface named ```SortAlgorithm```:\r\n\r\n```java\r\n\r\n\tpublic interface SortAlgorithm {\r\n\t\tpublic int[] sort(int[] numbers);\r\n\t}\r\n\r\n\tpublic class BubbleSortAlgorithm implements SortAlgorithm {\r\n\t\t//...\r\n\t}\r\n\r\n\tpublic class QuickSortAlgorithm implements SortAlgorithm {\r\n\t\t//...\r\n\t}\r\n\r\n\t@Component\r\n\tpublic class ComplexAlgorithmImpl {\r\n\t\t@Autowired\r\n\t\tprivate SortAlgorithm sortAlgorithm;\r\n\t\t//...\r\n\t}\r\n\r\n```\r\n\r\n```ComplexAlgorithmImpl``` is no longer tightly coupled to any particular sort algorithm. \r\n\r\nWhenever you need to instantiate a ```ComplexAlgorithmImpl```, this is how  you proceed:\r\n\r\n```java\r\n\r\n\tComplexAlgorithmImpl binarySearch = new ComplexAlgorithmImpl(new QuickSortAlgorithm());\r\n\r\n```\r\n\r\nThe exact sort algorithm to be used can be passed as an input parameter to the constructor.  \r\n\r\n#### What does the Spring Framework do?\r\n\r\nWhere does the Spring framework come into the picture? \r\n\r\nLook at the snippet below:\r\n\r\n\r\n```java\r\n\r\n\t@Component\r\n\tpublic class ComplexAlgorithmImpl {\r\n\t\t@Autowired\r\n\t\tprivate SortAlgorithm sortAlgorithm;\r\n\t\t//...\r\n\t}\r\n\r\n```\r\n\r\n```java\r\n\t@Component\r\n\tpublic class QuickSortAlgorithm implements SortAlgorithm {\r\n\t\t//...\r\n\t}\r\n```\r\n\r\nWe defined the components and identified their dependencies by using Spring specific annotations.\r\n\r\nWe are defining ```ComplexAlgorithmImpl``` as a spring bean, and ```SortAlgorithm``` as a dependency. We are also providing an implementation of ```SortAlgorithm``` - ```QuickSortAlgorithm``` as a spring bean.\r\n\r\nWhen Spring Framework looks at this code, it create a QuickSortAlgorithm bean and injects it into ComplexAlgorithmImpl bean. This is called **Dependency Injection**. \r\n\r\n### Advantages Of Loose Coupling\r\n\r\nIf you want to switch to a new ```SortAlgorithm``` implementation, then loose coupling makes it very easy to make the change. The code inside ```ComplexAlgorithmImpl``` does not need to change at all.\r\n\r\nYou need to remove the ```@Component``` annotation from ```QuickSortAlgorithm``` and place it at the definition of the new implementation. \r\n\r\nThe other thing you are now able to do is write a unit test for ```ComplexAlgorithmImpl```, without worrying about the sort logic. \r\n\r\nYou can create a stub algorithm that implements ```SortAlgorithm```, and use that in tests for ```ComplexAlgorithmImpl```. The test would now focus on the business logic of the component, not its dependencies.\r\n\r\n### Another Example Of Loose Coupling\r\n\r\nHave a look at the following code:\r\n\r\n```java\r\n\r\n\t@RestController\r\n\tpublic class WelcomeController {\r\n\t\tprivate WelcomeService service = new WelcomeService();\r\n\t\t\r\n\t\t@RequestMapping(\"/welcome\")\r\n\t\tpublic String welcome() {\r\n\t\t\treturn service.retrieveWelcomeMessage();\r\n\t\t}\r\n\t}\r\n\r\n```\r\n\r\nThe ```WelcomeController``` is directly creating an instance of the ```WelcomeService```, and so it is tightly coupled to it. \r\n\r\nIf you were to use the Spring framework to decouple the two, you do something like:\r\n\r\n```java\r\n\r\n\t@Component\r\n\tpublic class WelcomeService {\r\n\t\t//...\r\n\t}\r\n\r\n\t@RestController\r\n\tpublic class Welcome Controller {\r\n\t{\r\n\t\t@Autowired\r\n\t\tWelcomeService service;\r\n\r\n\t\t@RequestMapping(\"/welcome\")\r\n\t\tpublic String welcome() {\r\n\t\t\treturn service.retrieveWelcomeMessage();\r\n\t\t}\t\t\r\n\t}\t\r\n\r\n``` \r\n\r\nNow, Spring auto-wires in the ```WelcomeService``` dependency to the ```WelcomeController``` component. When writing a unit test for this component, we can use a ```WelcomeService``` stub instead of an actual dependency. \r\n\r\n### Solving Other Problems Using Spring\r\n\r\nThe Spring framework can be used to solve a host of other problems in Java applications.\r\nLet's look at a few of them.\r\n\r\n#### Reducing Duplication In Code\r\n\r\nSpring provides a whole range of modules such as:\r\n\r\n* SpringMVC\r\n* SpringJDBC\r\n* SpringORM\r\n* SpringAOP\r\n* SpringJMS\r\n* SpringTest\r\n\r\nAll these frameworks make it easy to write your Java code. They bring in a set of abstractions, that reduce boilerplate code.  \r\n\r\n#### Improving Integration With Other Frameworks\r\n\r\nSpring does not try to provide solutions for problems that have already been solved. It provides excellent integration with frameworks such as \r\n* Hibernate for ORM\r\n* iBatis for object mapping\r\n* JUnit and Mockito for unit testing\r\n\r\n### What Does The Spring Framework Do?\r\n\r\nThe Spring framework facilitates the following:\r\n\r\n* Allows the programmers to focus on the business logic. The key feature is dependency management, and it provides excellent interfacing with external frameworks, by adding layers on top of them. \r\n* Enables testability, as it enables us to write decoupled code.\r\n* Allows for inversion of control, through dependency injection. A component is no longer tied to specific dependencies. Instead, the dependency is injected in from outside, during instantiation of the component. The Spring framework takes care of the actual injection.\r\n\r\n### Best Practices With Spring\r\n\r\n#### Use Spring Initializr\r\n\r\nSpring Initializr is a Spring project generation tool. Visit the following website - start.spring.io:\r\n\r\n![image info](images/Capture-081-02.png)\r\n\r\nYou only need to provide the Group Id, the Artifact Id, and the framework dependencies of the project. After that, you can generate the project and get started with Spring.\r\n\r\n#### Consider Spring Boot\r\n\r\nSpring Boot makes it very easy to use the Spring framework.\r\n\r\n#### Write Unit Tests\r\n\r\nAlways make sure you write great unit tests, because Spring makes it easy for you.\r\n\r\n### Challenges With Spring Framework\r\n\r\nSpring is difficult for a starting programmer to understand. However, once you understand it, you cannot stop using it!\r\n\r\n### Understand Spring Modules\r\n\r\nModules in Spring offer specialized functionality which can be used within a Spring application. Popular ones are:\r\n\r\n* SpringMVC\r\n* SpringJDBC\r\n* SpringORM\r\n* SpringAOP\r\n* SpringJMS\r\n* SpringTest\r\n\r\n### Explore Spring Projects\r\n\r\nThere are a wide variety of projects that have been done, under the umbrella of the Spring Framework. Popular ones include Spring Cloud, and Spring Web Services. \r\n\r\nDo check out our video on the same topic:\r\n[![image info](images/Capture-081-01.png)](https://www.youtube.com/watch?v=6xB-uXqbOqo)\r\n\r\n### Summary\r\n\r\nIn this article, we had an introductory look at the Spring Framework. We saw that Spring is a Java framework that makes life easy for a programmer. Spring improves the testability of the application code, and also makes it easy to interface it with external frameworks. Spring comes with its own umbrella of projects, and a rich set of modules as well.\r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-04-10-Introduction-To-spring-Data.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Spring Data and Spring Data JPA - Quick Tutorial for Beginners\r\ndate:   2022-04-10 12:31:19\r\nsummary: In this article, we take a look at Spring Data and Spring Data JPA.\r\ncategories:  SpringBoot\r\npermalink:  /introduction-to-spring-data-and-spring-data-jpa\r\nimage: /images/spring-data-category.png\r\n---\r\n\r\nIn this article, we take a look at Spring Data and Spring Data JPA.\r\n\r\n![image info](images/Capture-081-02.png)\r\n\r\n### You will Learn\r\n\r\n- What are the challenges with existing data store integration solutions?\r\n- What is Spring Data?\r\n- What are the aims of Spring Data?\r\n- How does Spring Data abstract talking to different data stores?\r\n- What is Spring Data JPA?\r\n- How does Spring Data JPA help in making JPA easier?\r\n\r\n\r\n### Challenges with Existing Data Store solutions\r\n\r\nLet's start with looking at problems with some of the existing solutions for storing data to data stores.\r\n\r\n#### Duplication of Code\r\n\r\nLet's start with looking at one of the important challenges with JPA - Duplicate code.\r\n\r\nLet's look at a couple of data layer classes to manage Passport and Student entities.\r\n\r\n#### Passport\r\n\r\n```java\r\n\r\n\t@PersistenceContext\r\n\tprivate EntityManager entityManager;\r\n\t\r\n\tpublic Passport getPassport(final long id) {\r\n\t\treturn entityManager.find(Passport.class, id);\r\n\t}\r\n\r\n\tpublic Passport createPassport(Passport passport) {\r\n\t\treturn entityManager.merge(passport);\r\n\t}\r\n\r\n```   \r\n\r\n#### Student\r\n\r\n```java\r\n\r\n\t@PersistenceContext\r\n\tprivate EntityManager entityManager;\r\n\r\n\tpublic Student retrieveStudent(final long id) {\r\n\t\treturn entityManager.find(Student.class, id);\r\n\t}\r\n\r\n\tpublic Student createStudent(Studetn student) {\r\n\t\treturn entityManager.merge(student);\r\n\t}\r\n\r\n```\r\n\r\nWhen we look at the above two snippets of code, we can see that there is a lot of similarity in the code structurally. Any additional methods written for the two entities would be very similar.\r\n\r\nA straightforward approach to deal with such duplication would be to create a common interface to extract the functionality, and implement that interface in an application.\r\n\r\n#### Explosion Of Data Stores\r\n\r\nNowadays, we are not confined to talking to just relational databases. We have a variety of data stores including NoSQL data stores such as MongoDB, Hadoop and Cassandra.\r\n\r\n### Spring Data\r\n\r\nSpring Data provides common abstractions to store and retrieve data from a data store. This eliminates the need to connect and interact differently, with different types of data stores. \r\n\r\nSuch abstractions allow you to connect in the same way to relational databases and NO-SQL databases. It enables you to switch effortlessly between data stores.\r\n\r\n### Spring Data JPA\r\n\r\nSpring Data JPA is an extension of Spring Data, to connect to JPA - concerned with talking with relational databases. \r\n\r\n#### Using Spring Data JPA\r\n\r\nThis is how you go about using this framework:\r\n\r\n```java\r\n\r\n\tpublic interface StudentRepository extends CrudRepository<Student, Long> {\r\n\t\t//...\r\n\t}\r\n\r\n\tpublic interface PassportRepository extends CrudRepository<Passport, Long> {\r\n\t\t//...\r\n\t}\r\n\r\n```\r\n\r\nEach of the repositories extends the base ```CrudRepository```, which is a repository that supports the CRUD operations - Create, read, Update and Delete.\r\n\r\n#### CrudRepository Interface\r\n\r\nLet's look at some of the methods in ```CrudRepository``` ```interface```:\r\n\r\n```java\r\n\r\n\tpublic interface Crudrepository<T, ID> extends Repository<T, ID> {\r\n\t\t<S extends T> S save(Entity s);\r\n\t\tOptional<T> findById(ID id);\r\n\t\tboolean existsById(ID id);\r\n\t\tIterable<T> findAll();\r\n\t\tvoid deleteById(ID id);\r\n\t\tlong count();\r\n\t\t//Other methods\r\n\t}\r\n\r\n```\r\n\r\n### Exploring Other Repositories\r\n\r\nThe ```CrudRepository``` is a very useful interface, and there are other repositories built on top of this. Let's look at a few of them.\r\n\r\n#### The PaginationAndSortingRepository\r\n\r\n```java\r\n\r\n\tpublic interface PaginationAndSortingRepository<T, ID> extends CrudRepository<T,ID> {\r\n\t\tIterable<T> findAll(Sort sort);\r\n\t\tPage<T> findAll(Pageable pageable);\r\n\t}\r\n\r\n```\r\n\r\nIf you wanted to access a particular page in a set of search results, or want them sorted in a specific order, then this repository is of good use. \r\n\r\nDo check out our video on the same topic:\r\n\r\n[![image info](images/Capture-083-01.png)](https://www.youtube.com/watch?v=bg0_9FsOI64)\r\n\r\n### Summary\r\n\r\nIn this article, we talked about Spring Data, and Spring Data JPA. \r\n\r\nSpring Data offers common abstractions, which allows us to talk to different data stores, both relational and otherwise. It is independent of any kind of data store. Spring Data JPA is an Spring Data Extension to work with JPA relational data stores.\r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-04-10-Inversion-Of-Control.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Spring Framework Basics - What Is Inversion Of Control?\r\ndate:   2019-04-10 12:31:19\r\nsummary: Developers starting with the Spring framework often get confused with terminology - Dependency, Dependency Injection and Inversion Of Control. In this article, we introduce you to the concept of Inversion of Control.\r\ncategories:  SpringFramework\r\npermalink:  /spring-framework-what-is-inversion-of-control\r\nimage: /images/spring-features.png\r\n---\r\n\r\nDevelopers starting with the Spring framework often get confused with terminology - Dependency, Dependency Injection and Inversion Of Control. In this article, we introduce you to the concept of Inversion of Control.\r\n \r\n## You will learn\r\n- What Is Inversion Of Control?\r\n- What are good examples of inversion of control?\r\n- How does Spring Framework implement Inversion of Control?\r\n- Why Is Inversion of Control Important and what are its advantages?\r\n\r\n\r\n### What Is Inversion Of Control?\r\n\r\n#### Approach-1\r\n\r\nHave a look at the following implementation of ```ComplexAlgorithmImpl```:\r\n\r\n```java\r\n\r\n\tpublic class ComplexAlgorithmImpl {\r\n\t\tBubbleSortAlgorithm bubbleSortAlgorithm = new BubbleSortAlgorithm();\r\n\t\t//...\r\n\t}\r\n\r\n``` \r\n\r\nOne of the numerous things that ```ComplexAlgorithmImpl``` does is sorting. It creates an instance of ```BubbleSortAlgorithm``` directly within its code. \r\n\r\n#### Approach-2\r\n\r\nNow look at this implementation for a change:\r\n\r\n```java\r\n\r\n\tpublic interface SortAlgorithm {\r\n\t\tpublic int[] sort(int[] numbers);\r\n\t}\r\n\r\n\t@Component\r\n\tpublic class ComplexAlgorithmImpl {\r\n\t\t@AutoWired\r\n\t\tprivate SortAlgorithm sortAlgorithm;\r\n\t\t//...\r\n\t}\r\n\r\n```\r\n\r\n```ComplexAlgorithmImpl``` here makes use of the ```SortAlgorithm``` interface. It also provides a constructor or a setter method, where you can set the ```SortAlgorithm``` instance into it. The user tells ```ComplexAlgorithmImpl``` which sort algorithm to make use of.\r\n\r\n### Comparing Approach-1 and Approach-2\r\n\r\n#### Approach-1\r\n\r\n* ```ComplexAlgorithmImpl``` can only use ```BubbleSortAlgorithm```, it is **tightly coupled**. \r\n* If we need to change ```ComplexAlgorithmImpl``` to use quicksort, the relevant code needs to be changed entirely.\r\n* The control over the ```BubbleSortAlgorithm``` dependency is with the ```ComplexAlgorithmImpl``` class. \r\n\r\n\r\n#### Approach-2\r\n\r\n* ```ComplexAlgorithmImpl``` is open to using any implementation of ```SortAlgorithm```, it is **loosely coupled**.\r\n* We only need to change the parameter we pass to the constructor or setter of ```ComplexAlgorithmImpl```.\r\n*  The control over the ```SortAlgorithm``` dependency is with the user of ```ComplexAlgorithmImpl```. \r\n\r\n### Inversion Of Control At Play!\r\n\r\nIn Approach-1, ```ComplexAlgorithmImpl```  is tied to a specific sort algorithm. \r\n\r\nIn Approach-2, it say's - give me any sort algorithm and I will work with it. \r\n\r\nThis is **inversion of control**. \r\n\r\nInstead of creating its own dependencies, a class declares its dependencies. The control now shifts from the class to the user of the class to provide the dependency.\r\n\r\n### Why Is Inversion of Control Important?\r\n\r\nOnce you wrote code with inversion of control, you can use frameworks like Spring to do Dependency Injection and wire up beans and dependencies.\r\n\r\n### Advantages Of Inversion Of Control\r\n* Inversion of control makes your code loosely coupled\r\n* Inversion of control makes it easy for the programmer to write great unit tests\r\n\r\nDo check out our video on the same topic:\r\n\r\n[![image info](images/Capture-090-01.png)](https://www.youtube.com/watch?v=oLxsTnH_peI)\r\n\r\n### Summary\r\n\r\nIn this article, we talked about inversion of control. Instead of a class creating an instance of its own dependency, it leaves it to the user of class to pass it in. Inversion of control makes code loosely coupled. \r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-04-10-Spring-Batch.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Spring Batch Tutorial for Beginners\r\ndate:   2022-04-10 12:31:19\r\nsummary: Spring Batch is a lightweight, comprehensive batch framework that is designed for use in developing robust batch applications. \r\ncategories:  SpringBoot\r\npermalink:  /spring-basics-introduction-to-spring-batch\r\nimage: /images/spring-boot-category.png\r\n---\r\n\r\nSpring Batch is a lightweight, comprehensive batch framework that is designed for use in developing robust batch applications. \r\n\r\n![image info](images/Capture-086-02.png)\r\n \r\n## You will learn\r\n- What is Spring Batch?\r\n- How does Spring Batch make building batch programs easier?\r\n- What are important features of Spring Batch?\r\n- What are important concepts to understand in Spring Batch?\r\n- What are the best practices in using Spring Batch?\r\n\r\n\r\n### Spring Framework\r\n\r\nThis is the seventh article in a series of articles on Spring Framework:\r\n\r\n- [1 - Introduction To Spring Framework](/introduction-to-the-spring-framework){:target='_blank'}\r\n- [2 - What Is A Dependency?](/spring-framework-what-is-a-dependency){:target='_blank'}\r\n- [3 - What Is Dependency Injection?](/spring-framework-dependency-injection-inversion-of-control){:target='_blank'}\r\n- [4 - What Is Component Scan?](/spring-and-spring-boot-what-is-component-scan){:target='_blank'}\r\n- [5 - Architecture of Spring Framework - Modularity and Spring Modules](/spring-framework-architectures-and-modules){:target='_blank'}\r\n- [6 - What Are Spring Projects?](/spring-projects-with-examples){:target='_blank'}\r\n- [7 - Introduction To Spring Batch](/spring-basics-introduction-to-spring-batch){:target='_blank'}\r\n\r\n\r\n### What Is Spring Batch?\r\n\r\nSpring Batch is a lightweight, comprehensive batch framework that is designed for use in developing robust batch applications. \r\n\r\n### Why Is Spring Batch Useful?\r\n\r\nThe requirements of typical batch programs are very similar:\r\n\r\n* **Restartability**: It is normally required to restart a batch program from where it had failed\r\n* **Different readers and writers**: You need the ability to talk to different kinds of data sources and sinks. These include talking to a database, an external messaging service such as JMS, and many others. \r\n* **Chunk Processing**:  If for instance there are a million records to be written to storage, it is a practical idea to split it into manageable chunks of 1000 records each, and write these chinks one at a time. Even if one such chink fails, the other operations are not affected.\r\n* **Ease Of Transaction Management**: Transaction management should be simple to implement properly, even when using chunk processing. \r\n* **Ease of parallel processing**: It should be possible to run the batch tasks using parallel processing. For this, it is important that the configuration be simple, so that overhead is minimized.  \r\n\r\n### Understanding Spring Batch\r\n\r\nA **Job** in Spring Batch is nothing but a sequence of **Steps**. Each Step can be configured before execution, with the following attributes:\r\n\r\n* **next**: The next Step to execute\r\n* **tasklet**: The task that needs to be done as part of this Step.\r\n* **decision**: This decides in which situations this Step needs to be run\r\n\r\n#### The Job Instance\r\n\r\nA Job Launcher is used in order to execute a Spring Batch Job. Note the following points about a Job thus created:\r\n\r\n* Each execution of a Job is called a Job Instance. Each Job Instance is provided with a unique execution id, which is useful to restart the job if it fails.\r\n* A Job can be configured with parameters. These can be passed to it from the Job Launcher.\r\n\r\n#### How Spring Batch Works\r\n\r\nA typical Job would look like the following:\r\n\r\n![image info](images/Capture-086-02.png)\r\n\r\nEach Job can have multiple Steps, and sometimes it is useful to organize the Steps into Flows. Different flows can usually be run in parallel, and the rest of the steps are run in strict sequential order. \r\n\r\nSpring Batch 3.0 supports JSR-352 - a Java specification for batch processing.\r\n\r\n### Best Practices For Spring Batch\r\n\r\nThe following are the recommended practices when using Spring Batch:\r\n\r\n* Be careful about exception handling and transaction management. These become the most critical issues with managing batch programs.\r\n* Deploy your batch programs as near to the data as possible. This improves their performance greatly, and that of the entire enterprise.\r\n* Allocate enough memory. \r\n* Stress test the application from the start of the project.    \r\n\r\nDo check out our video on the same topic:\r\n\r\n[![image info](images/Capture-086-01.png)](https://www.youtube.com/watch?v=eohUc-kRUPw)\r\n\r\n### Summary\r\n\r\nIn this article, we had a good look at Spring Batch, a framework for crating robust enterprise-level batch applications. The needs of most enterprise batch applications are fairly the same. Spring Batch implements several best practices in developing batch applications."
  },
  {
    "path": "_blog/articles/2019-04-10-Spring-Projects.md",
    "content": "---\r\nlayout:  post\r\ntitle:  What Are Spring Projects?\r\ndate:   2022-04-10 12:31:19\r\nsummary: There are several important Spring Projects solving the needs of enterprises today. What are Spring Projects and how are they different from Spring Modules?\r\ncategories:  SpringBoot\r\npermalink:  /spring-projects-with-examples\r\nimage: /images/spring-framework-category.png\r\n---\r\n\r\nThere are several important Spring Projects solving the needs of enterprises today. What are Spring Projects and how are they different from Spring Modules?\r\n\r\n![image info](images/Capture-095-03.png)\r\n \r\n## You will learn\r\n- What are Spring Projects?\r\n- What are examples of Spring Projects?\r\n- How are Spring Projects different from Spring Modules?\r\n\r\n\r\n### Spring Framework\r\n\r\nThis is the sixth article in a series of articles on Spring Framework:\r\n\r\n- [1 - Introduction To Spring Framework](/introduction-to-the-spring-framework){:target='_blank'}\r\n- [2 - What Is A Dependency?](/spring-framework-what-is-a-dependency){:target='_blank'}\r\n- [3 - What Is Dependency Injection?](/spring-framework-dependency-injection-inversion-of-control){:target='_blank'}\r\n- [4 - What Is Component Scan?](/spring-and-spring-boot-what-is-component-scan){:target='_blank'}\r\n- [5 - Architecture of Spring Framework - Modularity and Spring Modules](/spring-framework-architectures-and-modules){:target='_blank'}\r\n- [6 - What Are Spring Projects?](/spring-projects-with-examples){:target='_blank'}\r\n- [7 - Introduction To Spring Batch](/spring-basics-introduction-to-spring-batch){:target='_blank'}\r\n\r\n\r\n### What Are Spring Projects?\r\n\r\nWithin the Spring framework, there are a variety of different Spring modules - JDBC, AOP, Beans, Context. All Spring Modules share the same release version as the Spring framework. They are part of the same project.\r\n\r\nApart from the Spring framework and its various modules, there are other frameworks called Spring Projects. These projects provide solutions to other issues faced by enterprise applications. \r\n\r\nThese projects are versioned differently from the Spring framework. For example, the current version of Spring Framework is 5.x.x and that of Spring Boot (one of the Spring Projects) is 2.x.x.\r\n\r\n#### Spring Boot\r\n\r\nSpring Boot is one of the most popular framework to develop microservices today. Spring Boot makes it easy to develop applications quickly. It has important features such as starter projects, auto configuration and actuator, it is a cakewalk to develop microservices. \r\n\r\n### Spring Cloud\r\n\r\nWorld is moving towards the cloud. Everyone wants to deploy their application in the cloud. If you develop a microservice using Spring Boot, you could use Spring Cloud to make it cloud-enabled. \r\n\r\n### Spring Data\r\n\r\nSpring Data provides a provides mechanisms for consistent data access. \r\n\r\nA few years earlier, there were only one kind of database an application could connect to - the SQL based relational databases.  Today, we also have at our disposal a wide variety of databases including the NoSQL databases. \r\n\r\nSpring Data ensures that the way we access data from all these sources remains consistent.\r\n\r\n### Spring Integration\r\n\r\nSpring Integration on the other hand, addresses the issues of application integration. \r\n\r\nSpring Integration provides implementations for recommended architecture patterns in Enterprise Application Integration. \r\n\r\n### Spring Batch\r\n\r\nNot all processing is done online, and a lot is also accomplished through batch applications. \r\n\r\nBatch applications have their own unique set of requirements. For instance, it is important to be able to restart a batch job from the point where it had failed earlier. It may also be necessary to track down accurately what is happening in the back ground when a batch job executes. \r\n\r\nSpring Batch provides a great option to develop batch applications.\r\n\r\n### Spring Security\r\n\r\nSecurity is one of the most important non functional requirements of an application's development. Any application that you develop, be it a web application, a REST service or any other, you want it to be secure. \r\n\r\nSpring Security provides features for securing the applications that you develop. It has support for basic authentication, OAuth1 and OAuth2 authentication. \r\n\r\n### Spring HATEOAS\r\n\r\nWith RESTful services, it is not sufficient if you simply return the data for a resource. It is also recommended to return related actions you can perform on the resource. This is called HATEOAS. Spring HATEOAS enables you to develop HATEOAS compatible REST API.\r\n\r\nDo check out our video on the same topic:\r\n\r\n[![image info](images/Capture-094-01.png)](https://www.youtube.com/watch?v=gsqYVsVh7iM)\r\n\r\n### Summary\r\n\r\nWe have looked at seven of the available Spring projects. This is an evolving space and there are new Spring projects every year to solve emerging enterprise problems.\r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-04-10-SpringModules.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Architecture of Spring Framework - Modularity and Spring Modules\r\ndate:   2019-04-10 12:31:19\r\nsummary: One of the most important features of the Spring framework is its modularity. It is not one big monolith framework. What are Spring Modules? How are they organized? What is the architecture of Spring Framework?\r\ncategories:  SpringFramework\r\npermalink:  /spring-framework-architectures-and-modules\r\nimage: /images/spring-features.png\r\n---\r\n\r\n![image info](images/Capture-095-03.png)\r\n\r\nOne of the most important features of the Spring framework is its modularity. It is not one big monolith framework. What is the architecture of Spring Framework? What are Spring Modules? How are they organized?\r\n \r\n![image info](images/Capture-095-02.png)\r\n\r\n## You will learn\r\n- What is the architecture of Spring Framework?\r\n- How is Spring Framework Modularized?\r\n- What are different Spring Modules?\r\n- Which modules provide which Spring Features like Dependency Injection and Auto wiring?\r\n- How can you develop applications with multiple layers with Spring?\r\n\r\n\r\n### Spring Framework\r\n\r\nThis is the fifth article in a series of articles on Spring Framework:\r\n\r\n- [1 - Introduction To Spring Framework](/introduction-to-the-spring-framework){:target='_blank'}\r\n- [2 - What Is A Dependency?](/spring-framework-what-is-a-dependency){:target='_blank'}\r\n- [3 - What Is Dependency Injection?](/spring-framework-dependency-injection-inversion-of-control){:target='_blank'}\r\n- [4 - What Is Component Scan?](/spring-and-spring-boot-what-is-component-scan){:target='_blank'}\r\n- [5 - Architecture of Spring Framework - Modularity and Spring Modules](/spring-framework-architectures-and-modules){:target='_blank'}\r\n- [6 - What Are Spring Projects?](/spring-projects-with-examples){:target='_blank'}\r\n- [7 - Introduction To Spring Batch](/spring-basics-introduction-to-spring-batch){:target='_blank'}\r\n\r\n\r\n### Spring Architecture and Modules\r\n\r\nLet's look at the modules that are present in a typical Spring Project.\r\n![image info](images/Capture-095-02.png)\r\n\r\nIt is not organized as one big JAR file. It is composed of a large number of smaller JAR files. \r\n\r\nSpring is organized into modules. Here is how Spring is organized conceptually:\r\n![image info](images/Capture-095-03.png)\r\n\r\n### Container\r\n\r\nThis is the most heavily used part of the Spring framework. This includes modules such as:\r\n* Beans: To manage the application dependencies\r\n* Core\r\n* Context: To maintain the application context\r\n\r\n### Database Access And Integration\r\n\r\nSpring provide excellent options for implementing data and integration layers. \r\n\r\nThe important data access modules are:\r\n* **JDBC** : To talk to relational database using JDBC\r\n* **ORM** : Provides good integration with all ORM (Object Relational Mapping) frameworks, such as Hibernate and MyBatis. \r\n* **JMS** : If you want to talk to another application over a queue, JMS provides an excellent option. Spring has good integration with JMS. \r\n* **OXM** : This module provides good integration in scenarios where object to XML mappings are required.\r\n* **Transactions** : Transaction management is an important part of data access integration functionality. Ideally, you want the transaction to be fully successful, or completely rolled back. If a transaction has 4 steps and failed at the third step, the previous two successful steps must also be rolled back. Spring has great support for transaction management.\r\n\r\n### Web\r\n\r\nSpring has very good support to develop your web layer: \r\n* Spring MVC : It is Spring's own web framework\r\n* Struts : Spring provides good integration with Struts. \r\n\r\n### Cross Cutting Features\r\n\r\nAn application is typically developed in multiple layers. For example, a web application is often designed to have three layers: web, business and data:\r\n\r\n![image info](images/Capture-095-04.png)\r\n\r\nThere are many things that are applicable to more than one layer. Those are called **cross cutting concerns**. \r\n\r\n#### Unit Testing\r\n\r\nOne important cross cutting concern is unit testing. We want to be able to unit test code in all the three layers mentioned above. Spring Test framework provides good support for unit testing.\r\n\r\n#### AOP\r\n\r\nAOP stands for Aspect oriented programming. This module is useful for implementing features such as security and logging. Spring AOP provides basic AOP features.\r\n\r\nSpring provides good integration with the AspectJ framework to do advanced AOP.  \r\n\r\nDo check out our video on the same topic:\r\n\r\n[![image info](images/Capture-095-01.png)](https://www.youtube.com/watch?v=Lbz7yGXe_EM)\r\n\r\n### Summary\r\n\r\nIn this article, we had a brief look at the modular structure of the Spring framework. It is not a single monolith, but is organized as a set of small modules.\r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-04-10-What-Is-A-Dependency.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Spring Basics - What Is A Dependency?\r\ndate:   2019-04-10 12:31:19\r\nsummary: Most important feature of Spring Framework is Dependency Injection. To understand Dependency Injection, you need to understand the concept of a Dependency.\r\ncategories:  SpringFramework\r\npermalink:  /spring-framework-what-is-a-dependency\r\nimage: /images/spring-features.png\r\n---\r\n\r\nMost important feature of Spring Framework is Dependency Injection. To understand Dependency Injection, you need to understand the concept of a Dependency.\r\n \r\n## You will learn\r\n- What is a Dependency?\r\n- How are applications built? How is one layer dependent on another?\r\n- How is a class dependent on another?\r\n- How does the Spring Framework do Dependency Injection?\r\n\r\nIn this article, we have a look at what a dependency is in general terms, and then in the context of the Spring framework.\r\n\r\n\r\n### Spring Framework\r\n\r\nThis is the second article in a series of articles on Spring Framework:\r\n\r\n- [1 - Introduction To Spring Framework](/introduction-to-the-spring-framework){:target='_blank'}\r\n- [2 - What Is A Dependency?](/spring-framework-what-is-a-dependency){:target='_blank'}\r\n- [3 - What Is Dependency Injection?](/spring-framework-dependency-injection-inversion-of-control){:target='_blank'}\r\n- [4 - What Is Component Scan?](/spring-and-spring-boot-what-is-component-scan){:target='_blank'}\r\n- [5 - Architecture of Spring Framework - Modularity and Spring Modules](/spring-framework-architectures-and-modules){:target='_blank'}\r\n- [6 - What Are Spring Projects?](/spring-projects-with-examples){:target='_blank'}\r\n- [7 - Introduction To Spring Batch](/spring-basics-introduction-to-spring-batch){:target='_blank'}\r\n\r\n### Dependencies At A High Level\r\n\r\nWe build enterprise applications in multiple layers:\r\n![image info](images/Capture-093-02.png)\r\n\r\nA typical Java application will have three layers in its architecture: web, business and data.\r\n* The web layer\r\n* The business layer\r\n* The data layer\r\n\r\nIn the above scenario:\r\n- Web Layer depends on Business Layer. The business layer is a dependency for the web layer.\r\n- Business layer depends on Data Layer. The data layer is a dependency for the business layer.\r\n\r\n### Dependencies At Class Level\r\n\r\nLet's look at an example:\r\n\r\n```java\r\n\r\n\t@Service\r\n\tpublic class ClientBOImpl implemented ClientBO {\r\n\t\t@Autowired\r\n\t\tProductDO productDO;\r\n\t\t@Autowired\r\n\t\tClientDO clientDo;\r\n\r\n\t\t@Override\r\n\t\tpublic Amount getClientProductsSum(long cliendId) {\r\n\t\t\t//...\r\n\t\t}\r\n\r\n\t\t@Override\r\n\t\tpublic void saveChangedProducts(long clientId,\r\n\t\t\t\t\t\t\t\t\t\tList<Product> userEnteredProducts) {\r\n\t\t\t//...\r\n\t\t}\r\n\r\n\t\t//...\r\n\t}\r\n\r\n```\r\n\r\n```ClientBOImpl``` is the business class, and it makes use of two data layer classes - ```ProductDO``` and ```ClientDO```. \r\n\r\nLet's now have a look at the business logic within ````ClientBOImpl```:\r\n\r\n* ```getClientProductsSum()``` : This returns the sum of all products for a given client.  \r\n* ```saveChangedProducts()``` : When products are modified on the application page, this method is called. \r\n\r\nBoth methods in ClientBOImpl need either ```ProductDO``` or ```ClientDO```. ```ProductDO``` and ```ClientDO``` are dependencies of ClientBOImpl.\r\n\r\n### Inputs/Outputs Are Not Dependencies\r\n\r\nIf you look at ```public Amount getClientProductsSum(long clientId)```, clientId is merely an input, not a dependency. Similarly, the total calculated amount returned by ```getClientProductsSum``` is an output, not a dependency.\r\n\r\n### A Few More Examples Of Dependencies\r\n\r\n#### Example-1\r\n\r\nHave a look at the following code:\r\n\r\n```java\r\n\r\n\t@Component\r\n\tpublic class ComplexAlgorithmImpl {\r\n\t\t@Autowired\r\n\t\tprivate SortAlgorithm sortAlgorithm;\t\r\n\t\t//...\r\n\t}\r\n\r\n\tpublic interface SortAlgorithm {\r\n\t\tpublic int[] sort(int[] numbers);\r\n\t}\r\n\r\n\t@Component\r\n\tpublic class QuickSortAlgorithm implements SortAlogrithm {\r\n\t\t//...\r\n\t}\r\n\r\n``` \r\n\r\n```ComplexAlgorithmImpl``` performs a lot of complex logic, and sorting is one of the steps. \r\n\r\nThe ```SortAlgorithm``` is a dependency of ```ComplexAlgorithmImpl```. \r\n\r\nSince ```SortAlgorithm``` is an interface, you can easily change the actual sort algorithm used by ```ComplexAlgorithmImpl```, without changing its code. \r\n\r\n#### Example-2\r\n\r\nConsider the following code:\r\n\r\n```java\r\n\r\n\timport java.sql.ResultSet;\r\n\r\n\t@Repository\r\n\tpublic class PersonJdbcDao {\r\n\t\t@Autowired\r\n\t\tJdbcTemplate jdbcTemplate;\r\n\r\n\t\tclass PersonRowMapper implements RowMapper<Person> {\r\n\t\t\t@Override\r\n\t\t\tpublic Person mapRow(ResultSet rs, int rowNum) throws SQLException {\r\n\t\t\t\t//...\r\n\t\t\t}\r\n\t\t\t//...\r\n\t\t}\r\n\t}\r\n\r\n```\r\n\r\nTo execute a query on the database, ```PersonJdbcDao``` needs ```JdbcTemplate```. Therefore, ```JdbcTemplate``` is a dependency of ```PersonJdbcDao```. \r\n\r\nLet's look at a simple method:\r\n\r\n```java\r\n\r\n\tpublic Person findById(int id) {\r\n\t\treturn jdbcTemplate.queryForObject(//...);\r\n\t}\r\n\r\n```\r\n\r\n```id``` is the input for this method, and the output returned is of type ```Person```. \r\n\r\nIn the above method, we are making use of a dependeny ```jdbcTemplate``` . The inputs and outputs are not dependencies.\r\n\r\nDo check out our video on the same topic:\r\n\r\n[![image info](images/Capture-093-01.png)](https://www.youtube.com/watch?v=4VajgnSHwOw)\r\n\r\n### Summary\r\n\r\nIn this article, we focused on the most important concept in Spring Framework - a dependency.\r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-04-10-What-Is-A-Profile.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Spring Profile - Quick Tutorial for Beginners\r\ndate:   2019-04-10 12:31:19\r\nsummary: When we develop applications, we would want to be able to provide different application configuration in different environments? How do you achieve it with Profiles?\r\ncategories:  SpringBoot\r\npermalink:  /spring-boot-profiles-tutorial\r\nimage: /images/spring-boot-feature.png\r\n---\r\n\r\nWhen we develop applications, we would want to be able to provide different application configuration in different environments? How do you achieve it with Profiles?\r\n\r\n## You will learn\r\n\r\n- What is a Profile?\r\n- How do you provide different application configuration in different environments using Profiles?\r\n- How do you activate beans based on Profiles?\r\n- What is the default profiles with Spring Boot?\r\n\r\n\r\n### What Is A Profile?\r\n\r\nWhen we create an application, we need to deploy it in different kinds of environments, such as development, QA, staging and production. \r\n\r\nThe application configuration in each of these environments will be different. \r\n\r\nOne of the approaches to handling application configuration is to create something called a **profile**. Spring Boot has the concept of a profile built in. \r\n\r\n> A Profile answers the question of *\"How to have different configurations in different environments?\"* \r\n\r\n### Spring Boot Profiles \r\n\r\nYou can define default configuration in application.properties. Environment specific overrides can be configured in specific files:\r\n* application-dev.properties\r\n* application-qa.properties\r\n* application-stage.properties\r\n* application-prod.properties\r\n\r\n### Setting A Spring Boot Profile\r\n\r\n\r\nHere are a couple of ways of setting the active profile:\r\n* At the time of launching the Java application \r\n\t- ```-Dspring.profiles.active=qa``` - in the VM properties, OR\r\n* Do the following in the application.properties file \r\n\t- ```spring.application.profiles=qa```.\r\n\r\nDepending on which profile is currently the active, the appropriate configuration is picked up. \r\n\r\n### Using Profiles In Code\r\n\r\nA profile can be used in code to define your beans. For example, have a look at the following piece of code:\r\n\r\n```java\r\n\r\n\t@Profile(\"dev\")\r\n\t@Bean\r\n\tpublic String devBean() {\r\n\t\treturn \"I will be available in profile dev\";\r\n\t}\r\n\r\n\t@Profile(\"prod\")\r\n\t@Bean\r\n\tpublic String prodBean() {\r\n\t\treturn \"I will be available in profile prod\";\r\n\t}\r\n\r\n``` \r\n\r\nThe bean ```devBean()``` will only be available with the ```dev``` profile, as it has been annotated with ```@Profile(\"dev\")```. Similarly, the bean ```prodBean()``` is only available with the profile ```prod```.\r\n\r\nDo check out our video on the same topic:\r\n\r\n[![image info](images/Capture-097-01.png)](https://www.youtube.com/watch?v=XXCNe4HiLYI)\r\n\r\n### Summary\r\n\r\nSpring Boot Profiles provides a simple option to have environment specific configuration."
  },
  {
    "path": "_blog/articles/2019-04-17-Software-Design-001-FiveThings-DesignReview.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Software Design - Five Things To Look Out For In A Design Review\r\ndate:    2019-04-16 12:31:19\r\nsummary: Doing a software design review is never a straightforward task, with a number of things to look out for. In this short article, we look at five such aspects, which will help you structure your review process in a better way.\r\ncategories: SwDesign\r\npermalink:  /software-design-five-things-design-review\r\nimage: /images/design-category.png\r\n---\r\n\r\nYou are invited to do a design review for an important project.  \r\n- Where do you start? \r\n- What do you look for?\r\n\r\nDoing a software design review is never a straightforward task, with a number of things to look out for. In this short article, we look at five such aspects, which will help you structure your review process in a better way.\r\n\r\n\r\n\r\n### Software Design\r\n\r\nThis is the last article in a series of articles on Software Design:\r\n\r\n- [1 - How do you keep your design simple?](/software-design-keep-your-design-simple){:target='_blank'}\r\n- [2 - Design Patterns For Beginners - with Java Examples](/design-patterns-for-beginners-with-java-examples){:target='_blank'}\r\n- [3 - What is Abstraction?](/software-design-what-is-abstraction){:target='_blank'}\r\n- [4 - Encapsulation - with examples](/software-design-encapsulation-with-examples){:target='_blank'}\r\n- [5 - Coupling - with examples](/software-design-coupling-with-examples){:target='_blank'}\r\n- [6 - Cohesion - with examples](/software-design-cohesion-with-examples){:target='_blank'}\r\n- [7 - Introduction to Evolutionary Design](/software-design-introduction-to-evolutionary-design){:target='_blank'}\r\n- [8 - Software Design - Five Things To Look Out For In A Design Review](/software-design-five-things-design-review){:target='_blank'}\r\n\r\n\r\n## Do you have good high level architecture?\r\n\r\nI would start with looking at the high level architecture. Understand the business context of the application. Understand Choice Of Layers And Responsibilities\r\n\r\n* Are we making the *right choice* in number of software layers\r\n* Does each layer have its *own responsibility*?\r\n* Do we have *too few layers*?\r\n* Are we making the *design too complex*?\r\n* Are we making the *right choice of responsibility* for each layer?\r\n* Are we creating *good APIs*? Are we exposing functionality in the *right way*?\r\n\r\n## Are you choosing the right frameworks and tools?\r\n\r\nThe second thing I would look at is the choice of frameworks and tools. \r\n* Are we choosing the best framework options?\r\n* Does it fit in with the enterprise guidelines of the organization?\r\n* Are the chosen frameworks *appropriate for the domain* in which the software is being developed?\r\n* Are we making the *best use* of those frameworks?\r\n\r\n## Do you have Great Unit Tests?\r\n\r\n> This might be a surprise but I'm a great believer that great applications have great unit tests. \r\n\r\nIn order have the design of your software to be always evolving, you need an awesome set of unit tests. \r\n\r\n> Unit Testing Golden Rule : Are you able to understand the scenario being tested in less than a minute? \r\n\r\nIf you are, that's awesome. If you are not, this might indicate\r\n* Lack of Single Responsibility\r\n* Complex Dependencies or \r\n* Bad Unit Tests \r\n\r\nAny of the above is a bad omen. \r\n\r\n## Is the readability of code good?\r\n\r\nThe next thing I would look at is the readability of source code. Am I able to look at a piece of code and understand it quickly?\r\n\r\nIf you are, that's awesome. If you are not, this might indicate\r\n* Bad Coding Practices\r\n* Lack of Single Responsibility\r\n* Complex Dependencies\r\n\r\n## Are you using and creating reusable components?\r\n\r\nThe last thing I would focus on is Reusability. You don't want to build everything on your own. Do you? You want to use open source frameworks and also frameworks available in your enterprise. And you might also want to contribute to the frameworks in your enterprise.\r\n\r\nHere are somethings look at?\r\n* Can I *use other common components* present in the enterprise?\r\n* Can some part of what we are building (for example authentication, database framework etc) be *re-used across the enterprise*? Can we create a common component?\r\n* Are we making the *right use* of such common components?\r\n\r\nDo check out our video on this:\r\n\r\n[![image info](/images/Capture-01-02.png)](https://www.youtube.com/watch?v=idgO7_Dvdm0)\r\n\r\n### Summary\r\n\r\nIn this article, we looked at how you can do a quick design review for a new project.\r\n\r\nDo you look for anything else in a quick review? Leave a comment.\r\n\r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-04-17-Software-Design-003-EvolutionaryDesign.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Software Design - Introduction to Evolutionary Design\r\ndate:    2019-04-16 12:31:19\r\nsummary: With extreme programming and agile, the focus is being lean and doing just in time design. In this context, how do you ensure that your design remains good and evolves along with the application requirements? \r\ncategories: SwDesign\r\npermalink:  /software-design-introduction-to-evolutionary-design\r\nimage: /images/design-category.png\r\n---\r\n\r\nWith extreme programming and agile, the focus is being lean and doing just in time design. In this context, how do you ensure that your design remains good and evolves along with the application requirements? \r\n\r\n### What will you learn?\r\n* What is Evolutionary Design?\r\n* Why is it important?\r\n* How can you use Evolutionary Design in the best way possible?\r\n* What Are The Advantages Of Evolutionary Design?\r\n* How does Evolutionary Design fit in with agile?\r\n* What are the best practices with Evolutionary Design?\r\n\r\n\r\n\r\n### Software Design\r\n\r\nThis is the last article in a series of articles on Software Design:\r\n\r\n- [1 - How do you keep your design simple?](/software-design-keep-your-design-simple){:target='_blank'}\r\n- [2 - Design Patterns For Beginners - with Java Examples](/design-patterns-for-beginners-with-java-examples){:target='_blank'}\r\n- [3 - What is Abstraction?](/software-design-what-is-abstraction){:target='_blank'}\r\n- [4 - Encapsulation - with examples](/software-design-encapsulation-with-examples){:target='_blank'}\r\n- [5 - Coupling - with examples](/software-design-coupling-with-examples){:target='_blank'}\r\n- [6 - Cohesion - with examples](/software-design-cohesion-with-examples){:target='_blank'}\r\n- [7 - Introduction to Evolutionary Design](/software-design-introduction-to-evolutionary-design){:target='_blank'}\r\n\r\n\r\n\r\n### Waterfall Model In Perspective\r\n\r\nOne of the first software implementation model was the **Waterfall Model**. Before we start with Evolutionary Design, lets look at how design was done in a Waterfall Model.\r\n\r\nThe Waterfall Model typically involves the following project stages:\r\n* Architecture\r\n* Design\r\n* Programming/Coding\r\n* Testing \r\n\r\nThe duration of each of these phases could be a month, two months or even three months. \r\n\r\nBefore you can get to the programming step, you need to be involved for a long time in the architecture and design phases. The result of this is that you have the components of your program fully specified - the classes, methods among others - before you even start coding.\r\n\r\nThis model assumes that you can design software just like you design your buildings or bridges.\r\n\r\nHowever, there were several problems with this approach and we quickly moved on to other design approaches as new sotware development models evolved. \r\n\r\n### Introducing Evolutionary Design\r\n\r\nIn the waterfall model, we architect and design the entire system before we even start coding. \r\n\r\nEvolutionary Design adopts a radically different approach. It focuses on having a simple design that works to start with. Now, what is simple design? \r\n\r\nA software application is said to have a simple design if it:\r\n\r\n* **Runs all tests** : There are good unit tests and all tests succeed all the time.\r\n* **Contains no duplication** : There is no duplication of code or intent.\r\n* **Expresses intent of programmers** : Code is clear, easy to read and simple. \r\n* **Minimizes number of classes and methods** : Architecture and Design are as simple as possible to get things dones. Classes and Methods are as small as possible without losing clarity or performance.\r\n\r\nThe thought process behind Evolution Design is that once the design is simple, you can enhance it easily to meet future needs.\r\n\r\n### Evolutionary Design and Agile\r\n\r\nEvolution design fits very well with the agile way of working. \r\n\r\nAgile focuses on getting things done in small cycles. You design a little. You code a little. You test a little. You move your code to production often. Focusing on 4 principles of Simple Design helps you in keeping the design simple and evolve design over a period of time instead of a one time design.\r\n\r\n### Architecture vs Design\r\n\r\nWhile the focus of agile is on just in time design, it is important to distinguish between design decisions and architectural decisions. \r\n\r\nSome decision are difficult to change, once you made the choice. For example:\r\n* What frameworks to use to build your application?\r\n* How do you integrate with other applications?\r\n* What is the boundary of the application you are building?\r\n\r\nThese decisions are what I call - architectural decisions. It is important to take time while making architectural decisions and involve your architecture team as well. \r\n\r\n### How Evolutionary Design Works\r\n\r\nIn Evolutionary design, we follow an iterative approach:\r\n1. Does your feature involve an architectural decision? If not, go to next step. Otherwise, get your architecture team involved and possibly do a prototype to test your architecural decision.\r\n2. Code the feature\r\n3. Refactor code to meet 4 Principles of Simple Design\r\n4. Repeat\r\n\r\n### What Are The Advantages Of Evolutionary Design?\r\n\r\nThe following are the stand-out advantages of Evolutionary Design:\r\n\r\n* **Avoids over-design** : When we follow older design methods, we tend to prepare our software to handle future requirements. This is a classic case of over-design.\r\n* **Avoids wastage of effort**: This could happen when we design for future requirements that never happen\r\n* **Designs just-in-time**: It follows an iterative cycle of development, where the focus is on current requirements, delivering current value, and incorporating relevant feedback.\r\n\r\n### What Challenges Arise With Evolutionary Design?\r\n\r\nThe following are the significant challenges posed by Evolutionary Design:\r\n\r\n#### Needs a clear separation between Architecture and Design \r\n\r\nAll design cannot be done in the nick of time; architecture decisions are difficult to change and time must be devoted to those. You may want to create a separate category of user story, or even a separate process sprint to cover the architecture decisions. Also, everyone in the project needs to be clear about these two kinds of decisions for the project.\r\n\r\n#### Need for skilled and experienced architects and developers\r\n\r\nA group of inexperienced or less experienced developers cannot pull off a well-designed software application, using evolutionary design. You need guidance from experienced people.\r\n\r\n#### Need for Continuous Integration\r\n\r\nContinuous Integration is essential for Evolutionary Design is effective:\r\n\r\n * To be sure your tests are running regularly\r\n * To ensure that code quality is under check\r\n\r\n#### Needs High Quality Tests\r\n\r\nYour unit tests need to be really top-class. If these unit tests are not good, then refactoring the code is out of question. This leads to the design getting stagnated, as the \r\ndevelopers are reluctant to refactor the code. Now, the design is no longer evolutionary!\r\n\r\n### Understanding The Best Practices\r\n\r\nThe two major points to stress on here are:\r\n\r\n#### Use Test-Driven Development (TDD)\r\n\r\nThis is the best way to ensure that your low-level design is good. With TDD, your focus before you write any code is how you will go about testing it. For example, you start thinking about how someone will use your class and its methods, before you write the method. You thus have an *outside-in* perspective, and that's always good to have as a developer. This results in the software having a good and robust API. \r\n\r\nAnother things that results from TDD is you have great unit tests! \r\n\r\nWhen following TDD, you first write a unit test, make it fail, and then write the code to make it pass. So, you have more reliable tests.\r\n\r\n#### Use Continuous Integration\r\n\r\nAs we saw a short while ago, we need to make sure we keep running the tests we write, regularly. This ensures you get immediate feedback if something has gone wrong. \r\n\r\n### How To Learn Evolutionary Design?\r\n\r\nThe best way to learn this is by using **pair programming**: pair with good, experienced programmers. This will give you insights into how to evolve your program's design, over a period of time. \r\n\r\n### Summary\r\n\r\nIn this article, we gave you an insight into Evolutionary Design. Evolutionary Design helps us avoid over design and keeps our design simple.\r\n\r\nDo check out our video on this:\r\n\r\n[![image info](/images/Capture-03-01.png)](https://www.youtube.com/watch?v=9yXtlEegx90)\r\n\r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-04-17-Software-Design-006-WhatIsCoupling.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Software Design - Coupling - with examples\r\ndate:    2019-04-16 12:31:19\r\nsummary: Software architects and programmers love low coupling. What is coupling? Why is coupling important? Let's get started.\r\ncategories: SwDesign\r\npermalink:  /software-design-coupling-with-examples\r\nimage: /images/design-category.png\r\n---\r\n\r\nSoftware architects and programmers love low coupling. What is coupling? Why is coupling important? Let's get started.\r\n\r\n### You will learn\r\n\r\n* What is coupling?\r\n* What are common examples of coupling in software?\r\n* How can we reduce the amount of coupling between classes, between components, and the like?\r\n\r\n\r\n\r\n### Software Design\r\n\r\nThis is the fifth article in a series of articles on Software Design:\r\n\r\n- [1 - How do you keep your design simple?](/software-design-keep-your-design-simple){:target='_blank'}\r\n- [2 - Design Patterns For Beginners - with Java Examples](/design-patterns-for-beginners-with-java-examples){:target='_blank'}\r\n- [3 - What is Abstraction?](/software-design-what-is-abstraction){:target='_blank'}\r\n- [4 - Encapsulation - with examples](/software-design-encapsulation-with-examples){:target='_blank'}\r\n- [5 - Coupling - with examples](/software-design-coupling-with-examples){:target='_blank'}\r\n- [6 - Cohesion - with examples](/software-design-cohesion-with-examples){:target='_blank'}\r\n- [7 - Introduction to Evolutionary Design](/software-design-introduction-to-evolutionary-design){:target='_blank'}\r\n\r\n\r\n\r\n### Example of Couping\r\n\r\nLet's start with an example.\r\n\r\nLet's say a friend of mine is developing a Java component, in the form of a JAR file, for me to use. However, there is an implicit constraint imposed here - I need to use Java (or a JVM Based language) to use the utility JAR file! In other words, developing the component as a Java JAR has **coupled** me to using Java as well. To break free, I need to **decouple**. \r\n\r\n#### How to Decouple? An Example:\r\n\r\nInstead of providing me with a JAR, I could ask my friend to create a web service interface for me to access the same functionality. The concept would look something like this:\r\n\r\n![image info](/images/Capture-06-01.png)\r\n\r\nThe web service is created around the JAR, and can be accessed from a Java, a PHP, or a .NET application. We can use any kind of application to invoke the web service. \r\n\r\nThis implies we have effectively decoupled from the underlying technology of the component. We are no longer affected by the fact that the component was developed in Java.\r\n\r\n### Another Example for Low Coupling - Spring Framework\r\n\r\nSpring Framework has a highly modular structure: \r\n\r\n![image info](/images/Capture-06-03.png)\r\n\r\nSuppose we want to use a specific module from this framework; for instance, the Spring JDBC module. \r\n\r\nWhat would happen if Spring tells you that you can only use Spring JDBC if you also use the Beans and Context modules? \r\n\r\nYou would probably not use it at all, because it introduces additional dependencies such as configuration etc. \r\n\r\nSpring does get this right; it does not force you to use Beans or Context along with JDBC. In other words, Spring modules are not coupled with the other ones.\r\n\r\n### Class-level coupling - The ```Order``` class\r\n\r\nLet's now go one level deeper. Let's look at Coupling at the level of classes.\r\n\r\nLet's look at a simple shopping cart example:\r\n\r\n```java\r\n\r\n\tclass ShoppingCartEntry {\r\n\t\tpublic float price;\r\n\t\tpublic int quantity;\r\n\t}\r\n\r\n\tclass ShoppingCart {\r\n\t\tpublic ShoppingCartEntry[] items;\r\n\t}\r\n\r\n\tclass Order {\r\n\t\tprivate ShoppingCart cart;\r\n\t\tprivate float salesTax;\r\n\r\n\t\tpublic Order(ShoppingCart cart, float salesTax) {\r\n\t\t\tthis.cart = cart;\r\n\t\t\tthis.salesTax = salexTax;\r\n\t\t}\r\n\r\n\t\tpublic float orderTotalPrice() {\r\n\t\t\tfloat cartTotalPrice = 0;\r\n\r\n\t\t\tfor(int i=0; i<cart.items.length; i++) {\r\n\t\t\t\tcartTotalPrice += cart.items[i].price * cart.items[i].quantity;\r\n\t\t\t}\r\n\t\t\tcartTotalPrice += cartTotalPrice * salesTax;\r\n\t\t\treturn cartTotalPrice;\r\n\t\t}\r\n\t}\r\n\r\n```  \r\n\r\nYou would observe that ```orderTotalPrice()``` knows the internal details of the ```ShoppingCart``` and ```ShoppingCartEntry``` classes:\r\n\r\n* It accesses the ```items``` field of ```ShoppingCart``` directly\r\n* It accesses the ```price``` and ```quantity``` fields of ```ShoppingCartEntry```, also directly\r\n\r\nScenario : Try and imagine a situation where we change the name of the ```price``` field of ```ShoppingCartEntry```, to something else. \r\n\r\nApproach : Code within ```orderTotalPrice()``` would also need to change. \r\n\r\nIf you change the type of the ```items``` array (possibly to a list) within ```ShoppingCart```, that would also lead to a change within ```orderTotalPrice()```.  \r\n\r\n```Order``` class is **tightly coupled** to the ```ShoppingCart``` and ```ShoppingCartEntry``` classes. \r\n\r\nHow do we decouple them?\r\n\r\n#### Decoupling the ```Order``` class Example\r\n\r\nHere is one way of achieving this:\r\n\r\n```java\r\n\r\n\tclass ShoppingCartEntry {\r\n\t\tfloat price;\r\n\t\tint quantity;\r\n\r\n\t\tpublic float getTotalPrice() {\r\n\t\t\treturn price*quantity;\r\n\t\t}\r\n\t}\r\n\r\n\tclass CartContents {\r\n\t\tShoppingCartEntry[] items;\r\n\r\n\t\tpublic float getTotalPrice() {\r\n\t\t\tfloat totalPrice = 0;\r\n\r\n\t\t\tfor(ShoppingCartEntry item:items) {\r\n\t\t\t\ttotalPrice += item.getTotalPrice();\r\n\t\t\t}\r\n\t\t\treturn totalPrice;\r\n\t\t}\r\n\t}\r\n\r\n\tclass Order {\r\n\t\tCartContents cart;\r\n\t\tfloat salesTax;\r\n\r\n\t\tpublic Order(CartContents cart, float salesTax) {\r\n\t\t\tthis.cart = cart;\r\n\t\t\tthis.salesTax = salesTax;\r\n\t\t}\r\n\r\n\t\tpublic float totalPrice() {\r\n\t\t\treturn cart.getTotalPrice * (1.0f + salesTax);\r\n\t\t}\r\n\t}\r\n\r\n```\r\n\r\nNote the following points:\r\n\r\n* Instead of making the ```price``` and ```quantity``` fields accessible, ```ShoppingCartEntry``` now makes a method named ```getTotalPrice()``` available to ```CartContents```.\r\n* The ```CartContents``` class does something very similar, by also providing a ```getTotalPrice()``` method for ```Order``` to use.\r\n* The ```Order``` class now only invokes the ```getTotalPrice()``` methhod exposed by ```CartContents```, to compute the total cart value in ```totalPrice()```.\r\n\r\nNow,\r\n\r\n* If the ```price``` field in ```ShoppingCartEntry``` has its name changed, only ```getTotalPrice()``` within the same class would be affected\r\n* If the type of ```items``` within ```CartContents``` is changed from an array to a list, again only the ```CartContents``` ```getTotalPrice()``` method needs to be altered.\r\n* The code within ```Order``` is not affected by either of these changes at all.\r\n\r\nWe have now completely decoupled ```Order``` from both ```ShoppingCartEntry``` and ```CartContents```.\r\n\r\n### Another Coupling Example with Spring Framework\r\n\r\nConsider the following body of code:\r\n\r\n```java\r\n\r\n\tpublic class BinarySearchImpl {\r\n\t\tpublic int binarySearch(int[] numbers, int numberToSearchFor) {\r\n\t\t\tBubbleSortAlgorithm bubbleSortAlgorthm = new BubbleSortAlgorithm();\r\n\t\t\tint[] sortedNumbers = bubbleSortAlgorithm.sort(numbers);\r\n\r\n\t\t\t//...\r\n\t\t}\r\n\t}\r\n\r\n```   \r\n\r\nYou would notice that the ```BinarySearchImpl``` class is directly dependent on the ```BubbleSortAlgorithm``` class. If we need to change the actual sort algorithm, to use quicksort for instance, then a lot of code within ```BinarySearchImpl``` needs to change.\r\n\r\nWe can solve this issue by making use of **interfaces**. Here is how our modified code would look like:\r\n\r\n```java\r\n\r\n\tpublic intrface SortAlgorithm {\r\n\t\tpublic int[] sort(int[] numbers);\r\n\t}\r\n\r\n```\r\n\r\nIf you use the Spring framework, you could use the ```@Autowired``` annotation with the ```BinarySearchImpl``` class, to automatically fetch an implementation of an available sort algorithm:\r\n\r\n```java\r\n\r\n\t@Component\r\n\tpublic class BinarySearchImpl {\r\n\t\t@Autowired\r\n\t\tprivate SortAlgorithm sortAlgorithm;\r\n\r\n\t\tpublic BinarySearchImpl(SortAlgorithm sortAlgorithm) {\r\n\t\t\tsuper();\r\n\t\t\tthis.sortAlgorithm = sortAlgorithm;\r\n\t\t}\r\n\r\n\t\tpublic int[] binarySearch(int[] numbers, int numberToSearchFor) {\r\n\t\t\tint[] sortedNumbers = sortAlgorithm.sort(numbers);\r\n\t\t\t//...\r\n\t\t}\r\n\t}\r\n\r\n```\r\n\r\nWhat we have achieved here is reduce the coupling between ```BinarySeacrhImpl``` and a specific sort algorithm.\r\n\r\n### A Practical Viewpoint of Coupling\r\n\r\nA good way of thinking about coupling, is if you change the inner details of a class or a component, do you need to make changes elsewhere as well? \r\n\r\nSuch dependencies are not desirable. If you intend to reuse code from one place to another, the related dependencies should be as few as possible.\r\n\r\nCoupling can occur at multiple levels in an application:\r\n* Class-level\r\n* API-level\r\n* Component-level\r\n\r\nLet's look at an example of coupling at component level:\r\n\r\n### Component-Level Coupling\r\n\r\nConsider the following organization of an enterprise web application:\r\n\r\n![image info](/images/Capture-05-02.png)\r\n\r\nIf the Security component were coupled with the Logging component, then wherever we need Security, we would also need to access Logging. That's not good.\r\n\r\n### Coupling With Layers\r\n\r\nLet's look at an example of a layered web application:\r\n\r\n![image info](/images/Capture-06-04.png)\r\n\r\nIt is organized into these three layers. Also assume that from the Web layer Controller, I need to call multiple methods from the Business layer. Let's say five different methods need to be called for a single such requirement. This is a clear case of coupling. \r\n\r\nA very effective way to avoid such layer-to-layer coupling is to use the **Facade Pattern**. You can create a Facade component on top of the Business layer, that manages calls to these five methods. The web layer can then make do with calling a  single method from the Facade component.\r\n\r\n*All in all, decoupling makes the code more reusable and testable.*\r\n\r\nDo check out our video on this:\r\n\r\n[![image info](/images/Capture-06-05.png)](https://www.youtube.com/watch?v=f32UZn8fQiw)\r\n\r\n### Summary\r\n\r\nIn this article, we looked at the concept of coupling at multiple levels: at the class, the component, the API and the layer level. We also looked at how to get around this factor through decoupling, at each of these levels. We identified the key question to ask about coupling:  \"If something changes at a particular place, would other things need to change as well? And If I use something, would I be forced to use something else as well?\"\r\n\r\n\r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-04-17-Software-Design-008-Cohesion.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Software Design - Cohesion - with examples\r\ndate:    2019-04-16 12:31:19\r\nsummary: High Cohesion is one of the important aims when your architect and design your software. What is it all about?\r\ncategories: SwDesign\r\npermalink:  /software-design-cohesion-with-examples\r\nimage: /images/architecture.png\r\n---\r\n\r\nHigh Cohesion is one of the important aims when your architect and design your software. What is it all about?\r\n\r\n# You will learn\r\n* What is Cohesion?\r\n* Why is Cohesion important?\r\n* What are the different parts of applications that need high Cohesion?\r\n* How do we acheive high cohesion?\r\n\r\n\r\n\r\n### Software Design\r\n\r\nThis is the sixth article in a series of articles on Software Design:\r\n\r\n- [1 - How do you keep your design simple?](/software-design-keep-your-design-simple){:target='_blank'}\r\n- [2 - Design Patterns For Beginners - with Java Examples](/design-patterns-for-beginners-with-java-examples){:target='_blank'}\r\n- [3 - What is Abstraction?](/software-design-what-is-abstraction){:target='_blank'}\r\n- [4 - Encapsulation - with examples](/software-design-encapsulation-with-examples){:target='_blank'}\r\n- [5 - Coupling - with examples](/software-design-coupling-with-examples){:target='_blank'}\r\n- [6 - Cohesion - with examples](/software-design-cohesion-with-examples){:target='_blank'}\r\n- [7 - Introduction to Evolutionary Design](/software-design-introduction-to-evolutionary-design){:target='_blank'}\r\n\r\n\r\n\r\n### What Is Cohesion?\r\n\r\nCohesion is all about grouping related things in your software, together, at one place. \r\n\r\nDrawing from a real-life example, there would be a thousand things in your home. But if asked to fetch your tennis racket, you can get it in a matter of minutes, if not seconds. If you are asked to get a cooking utensil, you immediate go the the kitchen. How is it that you are able to retreive things quickly? Because you have organized them in a highly cohesive way. You have put all the related things together.\r\n\r\nThat is cohesion at play in real life.\r\n\r\n### Levels Of Cohesion\r\n\r\nCohesion in software is applicable at multiple levels:\r\n\r\n* Methods: We group related methods together to create a class\r\n* Classes: We group related classes and create a package\r\n* Packages: We group related packages to probably create a component\r\n* Components\r\n* Applications\r\n* Microservices\r\n\r\n### Cohesion: A First Example\r\n\r\nHave a look at the following code:\r\n\r\n```java\r\n\r\n\tclass DownloadAndStore {\r\n\t\tvoid downloadFromInternet() {\r\n\t\t\t//...\r\n\t\t}\r\n\t\tvoid parseData() {\r\n\t\t\t//...\r\n\t\t}\r\n\t\tvoid storeIntoDatabase() {\r\n\t\t\t//...\r\n\t\t}\r\n\t\tvoid doEverything() {\r\n\t\t\tdownloadFromInternet();\r\n\t\t\tparseData();\r\n\t\t\tstoreIntoDatabase();\r\n\t\t}\r\n\t}\r\n\r\n``` \r\n\r\n```DownloadAndStore``` has the responsibility of doing three tasks, and has methods to do each one of them:\r\n\r\n* ```downloadFromInternet()``` connects to a server and downloads a file\r\n* ```parseData()``` needs an understanding of the data format to get the data from this file\r\n* ```saveToDatabase()``` needs to talk to a database server to save the data\r\n \r\nTo perform them at one go, it defines another method, aptly named ```doEverything()``` to call the other three. \r\n\r\n```DownloadAndStore``` is a prime example of a class that has **very low cohesion**. Each of the listed three methods is doing something totally unrelated to the others. \r\n\r\n#### An Improved Solution\r\n\r\nA better solution would be to have an implementation like the following:\r\n\r\n```java\r\n\r\n\tclass InternetDownloader {\r\n\t\tpublic void downloadFromInternet() {\r\n\t\t\t//...\r\n\t\t}\r\n\t}\r\n\r\n\tclass DataParser {\r\n\t\tpublic void parseData() {\r\n\t\t\t//...\r\n\t\t}\r\n\t}\r\n\r\n\tclass DatabaseStorer {\r\n\t\tpublic void storeIntoDatabase() {\r\n\t\t\t//...\r\n\t\t}\r\n\t}\r\n\r\n\tclass DownloadAndStore {\r\n\t\tpublic void doEverything() {\r\n\t\t\tnew InternetDownloader().downloadFromInternet();\r\n\t\t\tnew DataParser().parseData();\r\n\t\t\tnew DatabaseStorer().storeToDatabase();\r\n\t\t}\r\n\t}\r\n\r\n```\r\n\r\nIn this code organization:\r\n\r\n* Classes named ```InternetDownloader```, ```DataParser``` and ```DatabaseStorer``` are defined, each with a single important thing to do\r\n* Methods of these classes are invoked to accomplish what is needed, within an external class, ```DownloadAndStore```.\r\n\r\nThis is a better solution, because it increases the possibilities of code reuse. Let's explore this a little further.\r\n\r\n### Layered Architecture And Cohesion\r\n\r\nConsider a simple web application, that is organized into three layers:\r\n\r\n![image info](/images/Capture-08-01.png)\r\n\r\nOrganizing an application into layers helps to allocate responsibility clearly and separately. Here, \r\n* All the UI logic would be confined to the Web layer\r\n* All the business logic would be the responsibility of the Business layer\r\n* All the data storage and retrieval would be taken up by the Data layer\r\n\r\nThis is an example of cohesion at the application layer level. Each layer is highly cohesive, because it does one specific thing, whether large or small. \r\n\r\n### Component-Level Cohesion\r\n\r\nAnother instance where cohesion comes into play when you design components to be used in an enterprise application:\r\n\r\n![image info](/images/Capture-05-02.png)\r\n\r\nAuthorization and Authentication approaches might be similar across the microservices in your enterprise. Hence, you could define a common security component. The security component only bothers about whether a given user has the right access and the right credentials - nothing else. It can be easily reused across multiple microservices. It is highly cohesive. It does security and it does it very well.\r\n\r\nNote that if you try to enhance the features of the Security component by adding a logging capability as well, then its reusability goes down greatly. Both security and logging are better off implemented separately, as  independent cohesive reusable components.\r\n\r\n### Example: The Spring Framework\r\n\r\nOne of the best examples of cohesion popularly in use is the Spring Framework:\r\n\r\n![image info](/images/Capture-06-03.png)\r\n\r\nThe framework is not implemented as one big component. It is organized as a set of modules, each one of which can be composed of smaller components. Here is how it is organized, in brief:\r\n\r\n* **Core Container**: The core feature of Spring is ***Dependency Injection***. This module is composed of core components such as Beans, Core, Context, and SpEL.\r\n* **AOP, Aspects, Instrumentation and Messaging** are separate, smaller components\r\n* **The Spring MVC Framework** is a separate module with components that handle web application needs\r\n* The **Data Access and Integration** module has components such as JDBC, ORM, Transactions and others\r\n* With the evolution of microservices, **Spring Cloud** is an additional module that has been designed to contain a set of cohesive components\r\n\r\n#### Leveraging Cohesion In Spring\r\n\r\nEach component has its own boundary; it is concerned with taking up a single responsibility, and doing it well. The more cohesive a component is, the more reusable it becomes. \r\n\r\nThe modular structure of the Spring framework enables a programmer to pull in only those components that she actually needs. If she needs just the core functionality, the Core components sufficient. If database integration is necessary, then she can make use of the JDBC components, for instance.\r\n\r\n### How To Make Software More Cohesive?\r\n\r\nThe guiding light that you need to follow to improve the cohesion in your software, is the **Single Responsibility Principle (SRP)**. \r\n\r\nWhen you look at your method/class/package/component, take to a minute to also think about its **responsibility**. If you can describe it in a single phrase or sentence, then you've done a good job defining it. \r\n\r\nHowever, if you end up joining together many phrases and sentences with several \"and\"s, then you violate the SRP. Your software could end up have low cohesion. \r\n\r\n\r\nDo check out our video on this:\r\n\r\n[![image info](/images/Capture-08-02.png)](https://www.youtube.com/watch?v=Gx2N-kkO4FU)\r\n     \r\n\r\n### Summary\r\n\r\nIn this video, we talked about cohesion in significant detail. Cohesion is all about grouping related things together. Cohesion is applicable at multiple levels in a single application, such as method/class/package/component/application. You group related methods into a class, related classes into a package, and related packages perhaps into a component. \r\n\r\nWe also examined the fact that cohesive classes and components are highly reusable. In addition, organizing an application into multiple layers also improves their cohesion. Then, we observed how the Spring Framework is organized into cohesive modules, each with a single responsibility. Finally, we looked at how Single Responsibility Principle can be used to build cohesive software.\r\n\r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-04-17-Software-Design-012-What-Is-Abstraction.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Software Design - What is Abstraction?\r\ndate:    2019-04-16 12:31:19\r\nsummary: Abstraction is one of the fundamental concepts of software engineering. It is all about hiding complexity while building your application. \r\ncategories: SwDesign\r\npermalink:  /software-design-what-is-abstraction\r\nimage: /images/architecture.png\r\n---\r\n\r\nAbstraction is one of the fundamental concepts of software engineering. It is all about hiding complexity in building various parts of your application. \r\n\r\n# You will learn\r\n\r\nIn this guide, we look at:\r\n* What is Abstraction?\r\n* A few examples of abstraction\r\n* Why is Abstraction Important in Software Design?\r\n* How can you introduce good abstractions?\r\n\r\n\r\n\r\n### Software Design\r\n\r\nThis is the third article in a series of articles on Software Design:\r\n\r\n- [1 - How do you keep your design simple?](/software-design-keep-your-design-simple){:target='_blank'}\r\n- [2 - Design Patterns For Beginners - with Java Examples](/design-patterns-for-beginners-with-java-examples){:target='_blank'}\r\n- [3 - What is Abstraction?](/software-design-what-is-abstraction){:target='_blank'}\r\n- [4 - Encapsulation - with examples](/software-design-encapsulation-with-examples){:target='_blank'}\r\n- [5 - Coupling - with examples](/software-design-coupling-with-examples){:target='_blank'}\r\n- [6 - Cohesion - with examples](/software-design-cohesion-with-examples){:target='_blank'}\r\n- [7 - Introduction to Evolutionary Design](/software-design-introduction-to-evolutionary-design){:target='_blank'}\r\n\r\n\r\n\r\n### What Is Abstraction?\r\n\r\nAbstraction is one of the fundamental concepts of software engineering.\r\n\r\n#### An Example Of Abstraction\r\n\r\nConsider a real-world analogy. Let's say you want to ride a motor bike. All you need to start the motor bike is to put the key on, push the start button, and use the accelerator. While riding, you may need to use the brake as well. \r\n\r\nYou are not really concerned about how the engine, accelerator and brake are working during the ride. All that is **abstract** to you, and you are not concerned with it (unless you are mechanic). \r\n\r\n#### Another Example\r\n\r\nTake another example - printing a document from your computer. You just open the document, click on the \"print\" command, and in a short while, the printed document is ready. You are not really bothered about how the computer stores the document in 0s and 1s, nor about hoe it is transferred to the printer. \r\n\r\n### Abstraction In Your Application\r\n\r\nWhenever we build applications, we do so in layers. Here is the layered architecture of a simple web application:\r\n\r\n![image info](/images/Capture-012-01.png)\r\n\r\nAn advantage of doing so is that the Web layer does not need to know anything about the Data layer. It is **abstracted away** from the Data layer. All that it needs to be concerned with, is that it can delegate requests to the Business layer, and the business layer would take care of rest of the flow. Layering in an application is, in a way, abstracting away complexity. \r\n\r\n### Abstraction In Programming\r\n\r\nLet's go one level deeper and look at what happens underneath the hood when we write computer programs.\r\n\r\n#### Programming In High-Level Languages\r\n\r\nHave you ever written an assembly language program? Those funny ones with 1s and 0s. Actually, thats the only language that your computer would understand.\r\n\r\nIf you want to develop a web service, will we use Assembly Language? Far from it. We would instead use a high-level language such as Java or Python, to do that. These are human readable languages, that spare us the task of programming in 0s and 1s. \r\n\r\nThe high level programming languages are an abstraction on top of machine or assembly language.\r\n\r\n#### Writing SQL Queries\r\n\r\nThink of how you write SQL queries to interact with a database. You just write what data you are concerned with, without paying heed to how it is stored in, or retrieved from the database. We expect the database to take care of all that. \r\n\r\nSQL is an abstraction layer for retrieving data from your database.\r\n\r\n#### Calling Built-In Methods\r\n\r\nIn a high level programming language, calling built in utility methods available in its packages is another example of abstraction. Here is an example in Python:\r\n\r\n```py\r\n\r\n\t>>> 'Hello World'.endswith('World')\r\n\tTrue\r\n\t>>> 'Hello'.islower()\r\n\tFalse\r\n\t>>>\r\n\r\n```\r\n\r\nWhen we call the built-in utility ```endswith()```, we are not concerned with how it is implemented. We only care about the fact that when called with ```World``` as a parameter on ```Hello World```, it returns ```True```. \r\n\r\nSame is the case with ```islower()```.Their implementations are abstracted away from you.\r\n\r\n### Abstraction In Microservices\r\n\r\nConsider the following enterprise application architecture:\r\n\r\n![image info](/images/Capture-012-02.png)\r\n\r\nIt is quite common in such architectures to have common components for security, logging and archetype. The reason we have them is that we want them to take care of a specific responsibility. \r\n\r\nLet's say you want to handle authorization and authentication. By using a specific Security component to handle this functionality, you are abstracting away this logic from the rest of the application. The higher level microservices shown only need to know how to integrate with the security component. It does not need to know the inner details of the security component.\r\n\r\nDo check out our video on this:\r\n\r\n[![image info](/images/Capture-012-03.png)](https://www.youtube.com/watch?v=OF55HZPE7lQ)\r\n\r\n### Summary\r\n\r\nIn this article, we had a look at what abstraction is, and understood that it is the basic pillar used to hide complexity. We also saw that abstraction takes up different forms at different levels. We looked at a number of examples to explore the same.\r\n\r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-04-17-Software-Design-016-Five-Tips-Simple-Design.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Software Design - How do you keep your design simple?\r\ndate:    2019-04-16 12:31:19\r\nsummary: With extreme programming and agile, the focus is being lean and keeping your design simple. In this context, how do you ensure that your design remains good and evolves along with the application requirements? Here are a five tips you can focus on.\r\ncategories: SwDesign\r\npermalink:  /software-design-keep-your-design-simple\r\nimage: /images/architecture.png\r\n---\r\n\r\nWith extreme programming and agile, the focus is being lean and keeping your design simple. In this context, how do you ensure that your design remains good and evolves along with the application requirements? Here are a five tips you can focus on.\r\n\r\n\r\n\r\n### Software Design\r\n\r\nThis is the first article in a series of articles on Software Design:\r\n\r\n- [1 - How do you keep your design simple?](/software-design-keep-your-design-simple){:target='_blank'}\r\n- [2 - Design Patterns For Beginners - with Java Examples](/design-patterns-for-beginners-with-java-examples){:target='_blank'}\r\n- [3 - What is Abstraction?](/software-design-what-is-abstraction){:target='_blank'}\r\n- [4 - Encapsulation - with examples](/software-design-encapsulation-with-examples){:target='_blank'}\r\n- [5 - Coupling - with examples](/software-design-coupling-with-examples){:target='_blank'}\r\n- [6 - Cohesion - with examples](/software-design-cohesion-with-examples){:target='_blank'}\r\n- [7 - Introduction to Evolutionary Design](/software-design-introduction-to-evolutionary-design){:target='_blank'}\r\n\r\n\r\n\r\n#### The Four Principle Of Simple Design\r\n\r\nThese are the foundation for keeping your design simple. When you try to learn the ropes using Extreme Programming, you really need to focus on these principles. \r\n\r\nA software application is said to have a simple design if it:\r\n* **Runs all tests**\r\n* **Contains no duplication**\r\n* **Expresses intent of programmers**\r\n* **Minimizes number of classes and methods**\r\n\r\nYou can read more about it [here](/four-principles-of-simple-design){:target='_blank'}\r\n\r\n#### SOLID Principles\r\n\r\nThis represents a good aim to have when designing Object Object Software. The term SOLID is an acronym for:\r\n\r\n* Single Responsibility Principle\r\n* Open-Closed Principle\r\n* Liskov Substitution Principle\r\n* Interface Segregation Principle\r\n* Dependency Inversion Principle\r\n\r\nYou can read more about it [here](/software-design-solid-principles){:target='_blank'}\r\n\r\n#### Appropriate Patterns\r\n\r\nBe choosy about the design pattern you use. Do not fill up your design with patterns, just because they are available. Understand the context of your application and the context of the design pattern. Make sure they make the right match before implementing design pattern.\r\n\r\n#### Simple Hand-drawn Diagrams\r\n\r\nSimple, hand-drawn diagrams are quite sufficient to communicate the initial design to the stakeholders and your peers. Trying to produce stunning, intricate diagrams only leads to a wastage of precious time. \r\n\r\nOnce the design is stabilized, you can work on more concrete diagrams.\r\n\r\n#### Great Unit Tests\r\n\r\nThis is a very important requirement for a simple design. Tests help to keep your design evolving, because they give you feed back on how correct your code is. If that is not the case, you won;t be confident of changing your design, and  the design would no longer evolve.\r\n\r\nDo check out our video on this:\r\n\r\n[![image info](/images/Capture-016-01.png)](https://www.youtube.com/watch?v=pjDphh9OBVk)   \r\n\r\n### Summary\r\n\r\nIn this article, we discussed a few tips on simple design.\r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-04-17-Software-Design-019-Encapsulation.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Software Design - Encapsulation - with examples\r\ndate:    2019-04-16 12:31:19\r\nsummary: Encapsulation is one of the important goals of Software Design. What is Encapsulation? Why is it important? Let's get started.\r\ncategories: SwDesign\r\npermalink:  /software-design-encapsulation-with-examples\r\nimage: /images/design-category.png\r\n---\r\n\r\nEncapsulation is one of the important goals of Software Design. What is Encapsulation? Why is it important? Let's get started.\r\n\r\n### You will learn\r\n- What does Encapsulation mean? \r\n- What are the advantages of building encapsulated software?\r\n- Is encapsulation restricted to Object Oriented Design? \r\n- How can encapsulation be followed in other programming approaches? \r\n\r\nWe initially start with encapsulation at a very basic level - that of a class. We then gradually shift focus to other levels, such as components and web services.\r\n\r\n\r\n\r\n### Software Design\r\n\r\nThis is the fourth article in a series of articles on Software Design:\r\n\r\n- [1 - How do you keep your design simple?](/software-design-keep-your-design-simple){:target='_blank'}\r\n- [2 - Design Patterns For Beginners - with Java Examples](/design-patterns-for-beginners-with-java-examples){:target='_blank'}\r\n- [3 - What is Abstraction?](/software-design-what-is-abstraction){:target='_blank'}\r\n- [4 - Encapsulation - with examples](/software-design-encapsulation-with-examples){:target='_blank'}\r\n- [5 - Coupling - with examples](/software-design-coupling-with-examples){:target='_blank'}\r\n- [6 - Cohesion - with examples](/software-design-cohesion-with-examples){:target='_blank'}\r\n- [7 - Introduction to Evolutionary Design](/software-design-introduction-to-evolutionary-design){:target='_blank'}\r\n\r\n\r\n\r\n### Encapsulation At The Basic Level (Level-1)\r\n\r\nLet's look at two implementations of a ```CricketScorer``` ```class```:\r\n\r\n```java\r\n\r\n\tpublic class CricketScorer {\r\n\t\tprivate int score;\r\n\r\n\t\tpublic int getScore() {\r\n\t\t\treturn score;\r\n\t\t}\r\n\t\t\r\n\t\tpublic void setScore(int score) {\r\n\t\t\tthis.score = score;\r\n\t\t}\r\n\t}\r\n\r\n```\r\n\r\nIf you're not familiar the sport of cricket, you could imagine a ```FootballScorer``` class instead. Here, ```CricketScorer``` provides its users with two methods, ```setScore()``` and ```getScore()```. These form the class interface. \r\n\r\nLet's next make use of this class:\r\n\r\n```java\r\n\r\n\tpublic static void main(String[] args) {\r\n\t\tCrickerScorer scorer = new CricketScorer();\r\n\t\tint score = scorer.getScore();\r\n\t\tscorer.setScore(score + 4);\r\n\t}\r\n\r\n```\r\n\r\nThe user here gets to call both ```getScore()``` and ```setScore()```. Let's say a boundary is scored in the cricket match, which should result in the score getting incremented by ```4```. The user is responsible for retrieving the current the current score, incrementing it by ```4```, and then setting it. \r\n\r\nThere are a few important things to note here:\r\n\r\n* The ```score``` is declared ```private```, which means users of ```CricketScorer``` cannot access it directly. We are hiding the implementation of ```score`` from the class users. This is what **encapsulation** is all about.\r\n* The various Java language keywords such as ```private``` and ```protected``` are the most basic level of implementing encapsulation.\r\n\r\n### Method-Level Encapsulation (Level-2)\r\n\r\nTo avoid putting the onus of getting and setting the score on the user, we could define a method such as:\r\n\r\n```java\r\n\r\n\tpublic void four() {\r\n\t\tscore += 4;\r\n\t}\r\n\r\n\tpublic static void main(String[] args) {\r\n\t\tCrickerScorer scorer = new CricketScorer();\r\n\t\tscorer.four();\r\n\t}\r\n\r\n```\r\nAll the user does is call this ```four()``` method, and no longer needs to explicitly manipulate the stored score. Here we have introduced a ```four()``` method to encapsulate the process of getting and setting the score. This is the next level of encapsulation, at the logical level. The user now no longer needs to know how to manipulate the score.\r\n\r\n### Abstraction And Encapsulation\r\n\r\nAbstraction is all about hiding complexity. How do you hide that complexity? By using Encapsulation. Apart from the two levels we saw just now, there are more ways to go with encapsulation. Let's look at them next.\r\n\r\n### Encapsulation At The Class Level\r\n\r\n#### The Factory Pattern\r\n\r\nHave a look at the following example of code.\r\n\r\n```java\r\n\r\n\tpublic class FactoryPattern {\r\n\r\n\t\tpublic static class PersonFactory {\r\n\t\t\tpublic static Person getPerson(Strinf name, String gender) {\r\n\t\t\t\tif(gender.equalsIgnoreCase(\"M\")) {\r\n\t\t\t\t\treturn new Male(name);\r\n\t\t\t\t} else if (gender.equalsIgnoreCase(\"F\")) {\r\n\t\t\t\t\treturn new Female(name);\r\n\t\t\t\t} else {\r\n\t\t\t\t\t//So on...\r\n\t\t\t\t}\r\n\t\t\t\treturn null;\r\n\t\t\t}\r\n\t\t}\r\n\t\r\n\t\tstatic abstract class Person {\r\n\t\t\tprivate String name;\r\n\t\t\t\r\n\t\t\tPerson(String name) {\r\n\t\t\t\tthis.name = name;\r\n\t\t\t}\r\n\t\t\r\n\t\t\tabstract String getSalutation();\r\n\t\r\n\t\t\tString getNameAndSalutation() {\r\n\t\t\t\treturn getSalutation() + \" \" + name;\r\n\t\t\t}\r\n\t\t}\r\n\t\r\n\t\tpublic static void main(String[] args) {\r\n\t\t\tPerson male = PersonFactory.getPerson(\"Robinhood\", \"M\");\r\n\t\t\tSystem.out.println(male.getNameAndSalutation());\r\n\t\r\n\t\t\tPerson female = PersonFactory.getPerson(\"Mary\", \"F\");\r\n\t\t\tSystem.out.println(female.getNameAndSalutation());\r\n\t\t}\r\n\t}\r\n\r\n``` \r\n\r\nSuppose we have a set of classes to represent and create different kinds of persons. Also, we would need a way to do the same in code as well. Also, we would not like the users of the class not to know, that there are underlying implementations of ```Person``` named ```Male``` and ```Female```. \r\n\r\nWe can abstract that detail away by using the **Factory Pattern**. As we see in the code above, the user creates a male person by passing in a name and a string \"M\" to the ```getPerson()``` method of ```PersonFactory```. He has no idea that there are classes called ```Male``` and ```Female``` hidden away from him.\r\n\r\n#### The Strategy Pattern\r\n\r\nThis is another good example of encapsulation. Consider the following piece of code:\r\n\r\n```java\r\n\r\n\tpublic class StrategyPattern {\r\n\t\tinterface Sortable {\r\n\t\t\tpublic int[] sort(int[] numbers);\r\n\t\t}\r\n\t\t\r\n\t\tstatic class BubbleSort implements Sortable {\r\n\t\t\t@Override\r\n\t\t\tpublic int[] sort(int[] numbers) {\r\n\t\t\t\t//Ideally, the bubble sort is implemented completely here\r\n\t\t\t\treturn numbers;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tstatic class ComplexClass {\r\n\t\t\tSortable sorter;\r\n\t\r\n\t\t\tComplexClass(Sortable sorter) {\r\n\t\t\t\tthis.sorter = sorter;\r\n\t\t\t}\r\n\r\n\t\t\tvoid doAComplexThing() {\r\n\t\t\t\tint[] values = null;\r\n\r\n\t\t\t\t//... logic...\r\n\t\t\t\tsorter.sort(values);\r\n\t\t\t\t//...logic...\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic static void main(String[] args) {\r\n\t\t\tComplexClass complexClassInstance = new ComplexClass(new BubbleSort());\r\n\t\t\t//This can also be a setter\r\n\t\t\tcomplexClassInstance.doAComplexThing();\r\n\t\t}\r\n\t}\r\n\r\n```\r\n\r\nIn this case, we created an ```interface``` called ```Sortable```. Any class that needs sorting behavior, such as:\r\n\r\nThe user of the interface, ```ComplexClass```, only directly calls the ```sort()``` method on the ```Sortable``` interface. It does not worry about what the underlying class that implements ```Sortbale```, actually is. It does not worry about whether that is a ```BubbleSort```:\r\n\r\n```\r\n\tstatic class BubbleSort implements Sortable {\r\n\t\t\t@Override\r\n\t\t\tpublic int[] sort(int[] numbers) {\r\n\t\t\t\t//Ideally, the bubble sort is implemented completely here\r\n\t\t\t\treturn numbers;\r\n\t\t\t}\r\n\t\t}\r\n\r\n```\r\n\r\nor a ```QuickSort```. Whoever uses the class ```ComplexClass```, needs to create an instance of it, provide an instance of the sorting algorithm, and out class can make use of ```sort()``` by accessing the interface. \r\n\r\n### An Interface Example\r\n\r\nWe are very much in the habit of playing games, especially those that involve using gaming consoles. How would a computer game allow you to play it? By allowing the console to use it like this:\r\n\r\n```java\r\n\r\n\tpublic class Interfaces {\r\n\r\n\t\tpublic interface GamingConsole {\r\n\t\t\tpublic void up();\r\n\t\t\tpublic void down();\r\n\t\t\tpublic void left();\r\n\t\t\tpublic void right();\r\n\t\t}\r\n\t\r\n\t\tpublic class MarioGame implements GamingConsole {\r\n\t\t\tpublic void up() {\r\n\t\t\t\tSystem.out.println(\"Jump\");\r\n\t\t\t}\r\n\t\r\n\t\t\tpublic void down() {\r\n\t\t\t\tSystem.out.println(\"Goes Into A Hole\");\r\n\t\t\t}\r\n\t\r\n\t\t\tpublic void left(){\r\n\t\r\n\t\t\t}\r\n\t\r\n\t\t\tpublic void right(){\r\n\t\t\t\tSystem.out.println(\"Go Forward\");\r\n\t\t\t} \r\n\t\t}\r\n\t\r\n\t\tpublic class ChessGame implements GamingConsole {\r\n\t\t\tpublic void up() {\r\n\t\t\t\tSystem.out.println(\"Move Piece Up\");\r\n\t\t\t}\r\n\t\r\n\t\t\tpublic void down() {\r\n\t\t\t\tSystem.out.println(\"Move Piece Down\");\r\n\t\t\t}\r\n\t\r\n\t\t\tpublic void left(){\r\n\t\t\t\tSystem.out.println(\"Move Piece Left\");\r\n\t\t\t}\r\n\t\r\n\t\t\tpublic void right(){\r\n\t\t\t\tSystem.out.println(\"Move Piece Right\");\r\n\t\t\t} \r\n\t\t}\r\n\t\r\n\t\tpublic static void main(String[] args) {\r\n\t\t\tGamingConsole games = { new MarioGame(),\r\n\t\t\t\t\t\t\t\t\tnew ChessGame() };\r\n\t\r\n\t\t\tfor(GamingConsole game: games) {\r\n\t\t\t\tgame.up();\r\n\t\t\t\tgame.down();\r\n\t\t\t\tgame.left();\r\n\t\t\t\tgame.right();\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n```\r\n\r\nThis shows use of one such console with four buttons: up, down, right and left. We are representing it by an interface, named ```GamingConsole```:\r\n\r\n\r\nWhoever uses a ```GamingConsole```, can play a game attached to it, irrespective of what the actual game is. It could be a ```MarioGame```, a ```ChessGame```, or whatever. The user knows he can call the ```up()```, ```down()```, ```left()``` and ```right()``` operations with ease. The actual game implementations are hidden away. How a ```MarioGame``` reacts to the console, is different from how a ```ChessGame``` responds.\r\n\r\nThe fact that we have created a ```GamingConsole``` interface, means the ```Game``` implementations can be hidden away. \r\n\r\n### An Abstract Class Example\r\n\r\nThe same high-level concept can be applied by using abstract classes as well. Consider the following abstract class definition:\r\n\r\n\r\n```java\r\n\r\n\tpublic abstract class AbstractRecipe {\r\n\t\tpublic void execute() {\r\n\t\t\tgetReady();\r\n\t\t\tdoTheDish();\r\n\t\t\tcleanup();\r\n\t\t}\r\n\r\n\t\tabstract void getReady();\r\n\t\tabstract void doTheDish();\r\n\t\tabstract void cleasnup();\r\n\t}\r\n\r\n\tpublic class Recipe1 extends AbstractRecipe() {\r\n\t\t@Override\r\n\t\tpublic void getReady() {\r\n\t\t\t//...\r\n\t\t}\r\n\r\n\t\t@Override\r\n\t\tpublic void doTheDish() {\r\n\t\t\t//...\r\n\t\t}\r\n\r\n\t\t@Override\r\n\t\tpublic void cleanup() {\r\n\t\t\t//...\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic class RecipeWithMicrowave extends AbstractRecipe() {\r\n\t\t@Override\r\n\t\tpublic void getReady() {\r\n\t\t\t//...\r\n\t\t}\r\n\r\n\t\t@Override\r\n\t\tpublic void doTheDish() {\r\n\t\t\t//...\r\n\t\t}\r\n\r\n\t\t@Override\r\n\t\tpublic void cleanup() {\r\n\t\t\t//...\r\n\t\t}\r\n\t}\r\n\r\n\tpublic static void main(String[] args) {\r\n\t\tRecipe1 recipe = new Recipe();\r\n\t\trecipe1.execute();\r\n\r\n\t\tRecipeWithMicrowave recipeWithMicrowave = new RecipeWithMicrowave();\r\n\t\trecipeWithMicrowave.execute();\r\n\t}\r\n\r\n```\r\n\r\nWe are implementing a **Template Method Pattern** in here. For every recipe that we end up creating, we want to make sure it has three steps: getting things ready, doing the dishes, and cleaning up. We are creating an abstract class ```AbstractRecipe```. Any user who ants to use a recipe, does not need to worry about the fact that an ```AbstractRecipe``` exists. They just create an instance of the particular recipe, and call ```execute()``` on it.\r\n\r\nUnderneath all that, is the recipe implementation:\r\n\r\n### Our Journey With Encapsulation Thus Far\r\n\r\nWe looked at a few examples of how encapsulation is implemented. We saw that:\r\n\r\n* At the very basic level, we achieve that by using built-in keywords such as ```private``` and ```protected``` around member variables\r\n*  The next level involves defining utility methods, to achieve encapsulation at a more logical level, to hide variable-level operations\r\n* The next level of abstraction involves creating the appropriate interfaces, or abstract classes\r\n* Another level involves the use of patterns such as Factory Pattern and Strategy Pattern \r\n\r\nThe thing is, encapsulation does not end at the code level. Let's look at a few more instances of the same.\r\n\r\n### Encapsulation In Layered Architecture\r\n\r\nWhen we build enterprise web applications, we normally like to structure them in layers:\r\n\r\n![image info](/images/Capture-019-16.png)\r\n\r\nThe idea behind doing so is that, for example, you do NOT want:\r\n\r\n* The Business layer to be too involved with storing and retrieving data\r\n* The Web layer to know this, and also how business logic deals with data\r\n* The Data layer to be bothered about how the application manages communication with other applications\r\n\r\nWe achieve this be creating an interface in each layer. For example, the Data layer exposes an interface which is used by the Business Layer. Similarly, other layers can also expose interfaces.\r\n\r\n#### A Specific Example: JPA And Hibernate\r\n\r\nAnother good example of layered encapsulation is that of JPA and Hibernate. JPA is the interface, and Hibernate is the implementation. An application can make use of the JPA  annotations, without worrying about the fact that underneath that interface, lies a Hibernate implementation. \r\n\r\n### Microservices: Common Components\r\n\r\nAnother example of encapsulation comes from the domain of microservices architecture. Have a look at the following architecture diagram:\r\n\r\n![image info](/images/Capture-019-17.png)\r\n\r\nSuch architectures make heavy use of common components. \r\n\r\n#### Security Example\r\n\r\nFor example, look at security. Implementation of authentication and authorization  is essentially the same across different microservices. By creating a common security component, you can abstract away how you store the security details of a user. It could be a database, or an LDAP server setup, or whatever. \r\n\r\nThe microservice will just end up using the interface that the Security component provides. The microservice will use the mechanism to ask whether a particular user is authorized to perform an action, but the implementation details are abstracted away. \r\n\r\n#### Web Services\r\n\r\nThis is another scenario where encapsulation is very much used. Suppose we implement one such service using REST. We expose a URL, as an access point for consumers of this service. We would also specify the formats of the messages to be exchanged with users. How the service is implemented underneath - what language and framework is made use of - does not matter to the consumer. All that matters is the interface. \r\n\r\nDo check out our video on this:\r\n\r\n[![image info](/images/Capture-019-01.png)](https://www.youtube.com/watch?v=UhzXNlsjHkA) \r\n\r\n### Summary\r\n\r\nIn this article, we tried to answer the main question of what Encapsulation is all about. We saw that it is all about hiding the implementation, and providing the right interface to the user. That user might be:\r\n\r\n* A class using your class\r\n* A component using your component\r\n* A layer using your layer\r\n* An end-user calling your service\r\n\r\nWe looked at encapsulation in great detail, at many different levels:\r\n\r\n* At a basic level with member variables\r\n* At a method level for better utility\r\n* At an interface or abstract class level\r\n* At a pattern level\r\n* At a application layer level\r\n* At a service component level\r\n\r\nIn particular, we saw how enterprise applications hide away things behind a component, and provide an interface to it.\r\n"
  },
  {
    "path": "_blog/articles/2019-04-17-Software-Design-109-Design-Patterns-For-Beginners.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Design Patterns For Beginners - with Java Examples\r\ndate:    2019-12-16 12:31:19\r\nsummary: In this guide, we give you an introduction to the world of design patterns.For each pattern, we understand 1) the pattern a2) the context in which it is applicable -  with a real-world example.\r\ncategories: SwDesign\r\npermalink:  /design-patterns-for-beginners-with-java-examples\r\nimage: /images/design-category.png\r\n---\r\n \r\nIn this guide, we give you an introduction to the world of design patterns.For each pattern, we understand 1) the pattern a2) the context in which it is applicable -  with a real-world example.\r\n\r\n## You will learn\r\n- What are Design Patterns?\r\n- Why do you use Design Patterns?\r\n- What are the different types of Design Patterns?\r\n- When do you use Design Patterns?\r\n- How do you implement different Design Patterns in Java?\r\n- What are the real world examples for Design Patterns?\r\n\r\n\r\n\r\n### Software Design\r\n\r\nThis is the second article in a series of articles on Software Design:\r\n\r\n- [1 - How do you keep your design simple?](/software-design-keep-your-design-simple){:target='_blank'}\r\n- [2 - Design Patterns For Beginners - with Java Examples](/design-patterns-for-beginners-with-java-examples){:target='_blank'}\r\n- [3 - What is Abstraction?](/software-design-what-is-abstraction){:target='_blank'}\r\n- [4 - Encapsulation - with examples](/software-design-encapsulation-with-examples){:target='_blank'}\r\n- [5 - Coupling - with examples](/software-design-coupling-with-examples){:target='_blank'}\r\n- [6 - Cohesion - with examples](/software-design-cohesion-with-examples){:target='_blank'}\r\n- [7 - Introduction to Evolutionary Design](/software-design-introduction-to-evolutionary-design){:target='_blank'}\r\n\r\n\r\n\r\n### What Are Design Patterns?\r\n\r\nWe have been building object-oriented software for over 40 years now, starting with Smalltalk, which was the first object-oriented language. \r\n\r\nThe programming world has encountered a large number of problems, and a variety of solution have been proposed to tackle them. \r\n\r\nAn attempt was made by a group of four people, famously called the \"Gang-Of-Four\" or GoF, to come up with a set of common problems and solutions for them, in the given context. \r\n\r\n> This catalog of common problems and their solutions is labeled as GOF (Gang of Four) Design Patterns. \r\n\r\n### Why Design Patterns?\r\n\r\nThe advantages of design patterns are:\r\n- To provide standard terminology that everybody understands\r\n- Not to repeat the same mistakes over and over again\r\n\r\n### What Are The Types Of Design Patterns?\r\n\r\nThe design patterns we talk about here, are from the perspective of an object-oriented world. There are mainly three different kinds of design patterns:\r\n- Creational Patterns\r\n- Structural Patterns\r\n- Behavioral Patterns\r\n\r\n#### Creational\r\n\r\nCreational patterns deal with the creation of objects.\r\n\r\n#### Structural\r\n\r\nStructural patterns deal with the composition of objects.\r\n\r\nIt deals with questions such as:\r\n* What does a class contain?\r\n* What are the relationships of a class with other classes? Is it inheritance or composition? \r\n\r\n#### Behavioral\r\n\r\nBehavioral patterns focus more on the behavior of objects, or more precisely, interactions between objects. \r\n\r\n> How does an object communicate with another object?\r\n\r\n![image info](images/Capture-109-02.png)\r\n\r\n### Exploring Creational Design Patterns\r\n\r\nWe explore the following creational design patterns:\r\n\r\n![image info](images/Capture-109-03.png)\r\n\r\n#### The Prototype Pattern\r\n\r\n![image info](images/Capture-109-04.png)\r\n\r\n> A Prototype represents a fully initialized instance, to be copied or cloned. \r\n\r\nLet's take an example:\r\n\r\nLet's consider the design of a Chess game. Every game of Chess has the same initial setup - The King, Queen, Rook, Bishop, Knight and the Pawns all have their specific places. Let's say we want to build software to model a Chess game. \r\n\r\nEvery time a new Chess game is played, we need to create the initial board layout.\r\n\r\nInstead of repeating the creation of chess board each time\r\n- We can create an object that contains the initial setup\r\n- Clone from it - each time a new Chess game is played. \r\n\r\nThe object with the initial setup of the chess board is the prototype. And, we are using the prototype pattern.\r\n\r\nIsn't it simple?\r\n\r\nIn the Prototype pattern, you have a fully initialized instance - here, the initial board layout - that is readily available. \r\n\r\nWhenever a new Chess game is started - for example, in any of the numerous online Chess portals - this initialized instance is merely copied, or cloned. \r\n\r\n#### The Builder Pattern\r\n\r\nThe Builder Pattern separates object construction from its representation. What does that mean?\r\n\r\n![image info](images/Capture-109-05.png)\r\n\r\nAssume that you go out for a multi-course dinner to a Restaurant. Such a dinner would have many options, such as Starters, Main course and Desserts. You would probably choose two or three out of the presented options. A particular client may want to have dinner with the first two options only, leaving out the Desserts option. Yet another would prefer the Main course and Desserts, skipping the Starters entirely. \r\n\r\nSimilar situations might arise in designing software. You may need to build an object using a subset of the options that are available - or, create the object in multiple ways. This is where the Builder pattern comes in handy. \r\n\r\nTo understand it further, let's look at a small piece of code.\r\n\r\n```java\r\n\r\npublic class BuilderPattern {\r\n    static class Coffee {\r\n        private Coffee(Builder builder) {\r\n            this.type = builder.type;\r\n            this.sugar = builder.sugar;\r\n            this.milk = builder.milk;\r\n            this.size = builder.size;\r\n        }\r\n\r\n        private String type;\r\n        private boolean sugar;\r\n        private boolean milk;\r\n        private String size;\r\n\r\n        public static class Builder {\r\n            private String type;\r\n            private boolean sugar;\r\n            private boolean milk;\r\n            private String size;\r\n\r\n            public Builder(String type) {\r\n                this.type = type;\r\n            }\r\n\r\n            public Builder sugar(boolean value) {\r\n                this.sugar = value;\r\n                return this;\r\n            }\r\n\r\n            public Builder milk(boolean value) {\r\n                this.milk = value;\r\n                return this;\r\n            }\r\n\r\n            public Builder size(String value) {\r\n                this.size = value;\r\n                return this;\r\n            }\r\n\r\n            public Coffee build() {\r\n                return new Coffee(this);\r\n            }\r\n        }\r\n\r\n        @Override\r\n        public String toString() {\r\n            return String.format(\"Coffee [type=%s, sugar=%s, milk=%s, size=%s]\", this.type, sugar, milk, size);\r\n        }\r\n\r\n    }\r\n\r\n    public static void main(String[] args) {\r\n        Coffee coffee = new BuilderPattern.Coffee.Builder(\"Mocha\").milk(true).sugar(false).size(\"Large\").build();\r\n        System.out.println(coffee);\r\n\r\n    }\r\n}\r\n``` \r\n\r\nLet's say you're writing software for a machine that prepares coffee. The main ingredients of coffee are coffee, milk and sugar. \r\n\r\nDepending from which part of the world you are from, you choose whether or not you have sugar and milk. \r\n\r\nThe Builder pattern steps in to provide these Coffee creation options for you. \r\n\r\nHave a look at the code inside ```main()```. \r\n\r\nWhat we have inside the ```Coffee``` is a ```Builder```, to which we pass the *mandatory* ```type``` of the coffee.  Chained to that call, we make other calls adding in our preferences of the other ingredients. \r\n\r\nSomeone else who wants a different coffee can easily build it. This leads to a huge amount of flexibility in building objects.\r\n\r\n> Other approaches to solving this problem, such as the use of setters, have many inherent problems. These solutions lead to code that is difficult to read, and also behave erratically in multithreaded programs. The Builder pattern solves all those problems. \r\n\r\nThe advantages of using the Builder pattern are:\r\n* It simplifies object creation\r\n* Leads to more readable code\r\n* Does not allow the values to be modified\r\n\r\n#### The Singleton Pattern\r\n\r\nThe Singleton pattern is the most famous among all the design patterns. What this pattern does is very clear from its name - allow only one instance of a class per JVM at any point in time. \r\n\r\nA good real-world comparison would probably be the President of a Nation. \r\n\r\n![image info](images/Capture-109-06.png)\r\n\r\nHowever, there is a disclaimer here - there can only be one instance of that class, **per JVM**. If you have a Java application that runs as part of a cluster of application servers, each server runs a separate JVM instance. Therefore, you are allowed to have one instance of the Singleton created on each application server, at any given point of time. \r\n\r\nThere are a few things to remember whenever you create a Singleton class. \r\n\r\n* The constructor needs to be ```private```, to prevent the possibility of other objects creating instances of your class. \r\n* In Java, build a Singleton using a ```Enum```. \r\n* JEE 7 has a built-in annotation named ```@Singleton```, along with other related annotations. \r\n* The main disadvantage of using the Singleton pattern is that the resulting code is difficult to unit test. Make a clear decision as to where you absolutely need to use a Singleton, and where you don't. \r\n* In frameworks such as Spring, the objects that are managed are called beans, and beans are Singletons by default. What Spring does well is to ensure all this is in the background. \r\n\r\n#### The Factory Method Pattern\r\n\r\n![image info](images/Capture-109-07.png)\r\n\r\nThe intent of the Factory Method pattern is to create a family of object types. Let's look at a code example.\r\n\r\n```java\r\n\r\n    public class FactoryPattern {\r\n        public static class PersonFactory {\r\n            public static Person getPerson(String name, String gender) {\r\n                if(gender.equalsIgnoreCase(\"M\")) {\r\n                    return new Male(name);\r\n                } else if(gender.equalsIgnoreCase(\"F\")) {\r\n                    return new Female(name);\r\n                } // So on\r\n                return null;\r\n            }\r\n        }\r\n    }\r\n\r\n    static abstract class Person {\r\n        Person(String name) {\r\n            this.name = name;\r\n        }\r\n\r\n        private String name;\r\n\r\n        abstract String getSalutation();\r\n\r\n        String getNameAndSalutation() {\r\n            \r\n        }\r\n    }\r\n\r\n    static class Male extends Person {\r\n        public Male(String name) {\r\n            super(name);\r\n        }\r\n\r\n        @Override\r\n        String getSalutation() {\r\n            return \"Mr\";\r\n        }\r\n    }\r\n\r\n    static class Female extends Person {\r\n        public Female(String name) {\r\n            super(name);\r\n        }\r\n\r\n        @Override\r\n        String getSalutation() {\r\n            return \"Miss/Mrs\";\r\n        }\r\n    }\r\n\r\n    public static void main(String[] args) {\r\n        Person male = PersonFactory.getPerson(\"Robinhood\", \"M\");\r\n        System.out.println(male.getNameAndSalutation);\r\n\r\n        Person female = PersonFactory.getPerson(\"Mary\", \"F\");\r\n        System.out.println(female.getNameAndSalutation);\r\n    }\r\n\r\n```\r\n\r\nThis code implements a ```PersonFactory```. This class has a static method named ```getPerson()``` that accepts a person's name and gender as parameters. Depending on the gender ```String``` passed in, it either returns a ```Male``` or a ```Female``` object. \r\n\r\nIf somebody wants to create a male person, they invoke the ```getPerson()``` method on the ```PersonFactory``` with a gender argument of ```\"M\"```. Similarly, you can create a female person by invoking the ```getPerson()``` method on the ```PersonFactory``` with a gender argument of ```\"F\"```. \r\n\r\nWe are passing in an  identifier of the type of object we need, at the time of creation, while still referring to the generic type, ```Person```. \r\n\r\nThe ```Male``` and ```Female``` classes are hidden behind the ```PersonFactory``` implementation. \r\n\r\nThe advantage of using the Abstract Method pattern is that you can add additional types to the factory, without much change in the other classes using this class. In our example, you can add more types of gender, without affecting the existing code that deals with other genders, which all use ```Person```.\r\n\r\nWhat about the complexity involved in creating an object? \r\n\r\nIt greatly simplifies the task of object creation. The ```PersonFactory``` makes the decision of what object to create, and delivers it to us.\r\n\r\nDo check out our video on the same topic:\r\n\r\n[![image info](images/Capture-109-01.png)](https://www.youtube.com/watch?v=f5Rzr5mVNbY)\r\n\r\n### Structural Design Patterns\r\n\r\nLet us now have a look at the structural design patterns we want to explore.\r\n\r\n#### The Proxy Pattern\r\n\r\n![image info](images/Capture-109-08.png)\r\n\r\n> A Proxy is an object that represents another object. \r\n\r\nLet's look at a real-world example.\r\n\r\nYour debit card is a proxy for your bank account.  Whenever you make a transaction using a debit card, the corresponding money is deducted from the bank account. \r\n\r\nThe debit card is a proxy for your bank account, which is the actual object.\r\n\r\nSimilar to that, in programming, you might have to program interactions with remote objects. In such situations, you create a proxy object that takes care of all external communications. You would communicate with the proxy as if it were residing on your local machine. \r\n\r\nGood examples are the EJB Home and Remote interfaces. \r\n\r\nA proxy hides the complexity involved in communicating with the real object.\r\n\r\n####  The Decorator Pattern\r\n\r\n> The Decorator pattern allows us to add responsibilities to objects, dynamically. \r\n\r\n![image info](images/Capture-109-09.png)\r\n\r\nIn object-oriented programming, we typically use a lot of inheritance. \r\n\r\n##### Example 1\r\n\r\nLet's say a particular Pizza outlet has ten types of pizza. Our implementation has ten classes for these Pizza types.\r\n\r\nNow there is a requirement to make these pizzas available with three types of toppings. If we would want to create individual classes for each pizza and topping combination, we have a total of 30 classes to manage.\r\n\r\nInstead of doing this, can we make the pizza-topping relationship dynamic? Can we add a topping on top of an existing pizza? \r\n\r\nWe need to use a topping as a decorator on top of any pizza.\r\n\r\n##### Example 2\r\n\r\nAnother example would be adding a discount on a pizza order. \r\n\r\nLet's say, you have an order, and based on some criteria, you want to offer a discount to the customer. There might be a variety of discounts which might be applicable at different times. If you add a different type of a discount to every kind of order, then in a static relationship, you need to maintain hundreds of classes. \r\n\r\nTreating a discount as a decorator on order makes the relationship dynamic.\r\n\r\n\r\n##### Example 3\r\n\r\nA perfect example where the Decorator pattern is implemented in Java is the Java I/O packages. This is reflected in the way we create an input stream in an I/O program:  \r\n\r\n```java\r\n\r\n    new LineNumberInputStream(new BufferedInputStream(new FileInputStream()));\r\n\r\n```\r\n\r\nYou have a ```FileInputStream```. If you want to make it buffered, then add a decorator to it in the form of a ```BufferedInputStream```. If you want the buffered ```FileInputStream``` to have line numbers also, then add a decorator for a ```LineNumberInputStream```.\r\n\r\n##### Summary\r\n\r\nDecorator Pattern enables you to add behavior to existing objects, at run time. This allows the user of the interface to decide, how he/she wants to create the objects. \r\n\r\nThe drawback of this approach is the complexity involved in creating objects. The user needs to understand a lot of classes and their relationships before being able to use the power of the Decorator.\r\n\r\n#### The Facade Pattern\r\n\r\n![image info](images/Capture-109-10.png)\r\n\r\n> A Facade is a single class that represents an entire subsystem. \r\n\r\nLet's take the example of an event manager. An event manager is a go-to person when you want to organize an event. He/She would handle several aspects of an event such as the decorations, the food, sending out invitations to guests, the music arrangements, and similar things.  The event manager acts as the facade of the event organization subsystem. \r\n\r\nConsider the case of a distributed system. You typically have the need for multiple calls, across layers. \r\n\r\nTake for instance, a system that offers the service for online book orders. Whenever an order comes in, several things need to be taken care of, such as checking for the stock, reserving the order, accepting the payment, updating the stock, and generating the invoice. \r\n\r\nWe can create a single facade, such as the order interface, which would manage all incoming orders and provide an interface to the customer. \r\n\r\nThe advantage of using the Facade pattern is that it reduces the number of network calls, as well as reduces coupling among classes. \r\n\r\nIt succeeds in establishing a transaction boundary between communicating objects. Facades, like services, are good hubs to implement transactions. \r\n\r\nAs long as the interface of the facade remains the same, the implementation details of the subsystem can change.\r\n\r\n#### The Adapter Pattern\r\n\r\n> An Adapter is used to match interfaces of different classes.\r\n\r\n![image info](images/Capture-109-11.png)\r\n\r\nLet's take the real world example of power adapters. \r\n\r\nProblem : If you buy a mobile phone in India, it comes with a charger that only works with power sockets used in India. If you take the same charger to the US for example, it will not work, as it will not fit into sockets there. \r\n\r\nSolution : The solution is to use a travel adapter, to use with your charger when you travel. You can plug in your charger into the travel adapter, and the travel adapter is used to connect to the socket in a particular country.\r\n\r\nSimilarly, when you try to talk to a system that uses a different message format or a language, you need an adapter to translate messages. \r\n\r\nAn interesting example is a communication between a Java program and a web service. Before sending out the data to the service, we need to convert the object into XML or JSON format. We are implementing the Adapter pattern!\r\n\r\n#### The Flyweight Pattern\r\n\r\nLet's consider a few scenarios\r\n- Creation of an object takes a lot of time and involves multiple instances\r\n- Each instance of an object occupies a lot of memory\r\n- Some objects might be used several times across the same application with the same values\r\n\r\nIn these scenarios, you might not want to create a new instance every time it is needed. \r\n\r\nHow about caching an instance and reusing it when needed?\r\n\r\n> A Flyweight represents creating a fine-grained instance, that is being used for efficient sharing.\r\n\r\n![image info](images/Capture-109-12.png)\r\n\r\n##### Example 1\r\n\r\nA really good real work example is the public switched telephone network (PSTN). \r\n\r\nIn the PSTN, there are always a limited number of lines, and for simplicity, let's assume this number is 10. However, there are thousands of customers that use these lines. Since all 1000 customers would not make calls at about the same time, it is possible to efficiently switch calls coming in, among the existing 10 lines.\r\n\r\n##### Example 2\r\n\r\nIn the software world, a good example of a Flyweight pattern is JDBC connections.\r\n\r\nA connection pool is a set of connections to the database. The application may be firing a lot of queries, but we don't create a new connection whenever a new query comes in. As soon as a query comes in, we match it to an available connection, and the query gets fired. Once query execution is done, the connection is released back into the pool. \r\n\r\nUsing such a pool allows us to avoid the cost involved in creating and closing a connection.\r\n\r\n### Behavioral Design Patterns\r\n\r\nLet us now have a look at the behavioral design patterns. \r\n\r\n#### The Chain Of Responsibility Pattern\r\n\r\n![image info](images/Capture-109-13.png)\r\n\r\n> The Chain Of Responsibility Pattern represents a way of passing a request between a chain of objects. \r\n\r\n##### Example 1\r\n\r\nThe best example of this pattern can be seen in the exception handling mechanism of most programming languages.\r\n\r\nSuppose you have a ```method1()``` calling ```method2()```, and ```method2()``` in turn calls ```method3()```. Assume that ```method3()``` throws an exception. \r\n\r\nIf ```method3()``` has no exception handling, then the exception is passed on to ```method2()``` to handle it. If again ```method2()``` has no exception handling inside it, then the exception is passed on to ```method1()```. If even ```method1()``` cannot handle it, it gets thrown out of ```method1()``` as well.\r\n\r\n##### Example 2\r\n\r\nConsider a real-world example of a loan approval process. \r\n\r\nA bank clerk has permissions to approve loans within a certain amount. If the amount goes above that, then it goes to the supervisor. The supervisor has a similar, albeit larger loan approval limit set for him. If the loan amount exceeds that limit, then it goes to his supervisor, and so on.\r\n\r\n##### Summary\r\n\r\nWith Chain Of Responsibility, we have a chain of objects already ready, that wait to process requests. When a new request enters the system, it goes to the first object in the chain to attempt processing. Depending on the processing condition, the request travels up the chain and gets fully processed at some level, or maybe not processed at all.\r\n\r\n#### The Iterator Pattern\r\n\r\n![image info](images/Capture-109-14.png)\r\n\r\nThe Iterator pattern is one of the most simple design patterns. You have a set of elements arranged in a collection, and you want to access those elements sequentially. A good example of an Iterator is a TV remote, which has the \"next\" and \"previous\" buttons to surf TV channels. Pressing the \"next\" button takes me one channel in the forward direction, and pressing the \"previous\" button takes me one channel in the backward direction.\r\n\r\nIn the programming works, examples of the ```Iterator``` class and the enhanced ```for``` loop in Java are examples of the Iterator pattern. \r\n\r\n#### The State Pattern\r\n\r\n> The State Pattern is used to alter an object's behavior when its state changes. \r\n\r\n![image info](images/Capture-109-15.png)\r\n\r\nTake a look at this Java example:\r\n\r\n```java\r\n\r\n    public class StatePattern {\r\n        static class FanWallControl {\r\n            private SpeedLevel current;\r\n    \r\n            public FanWallControl() {\r\n                current = new Off();\r\n            }\r\n\r\n            public void set_state(SpeedLevel state) {\r\n                current = state;\r\n            }\r\n    \r\n            public void rotate() {\r\n                current.rotate(this);\r\n            }\r\n\r\n            @Override\r\n            public String toString() {\r\n                return String.format(\"Fan Wall Control [current = %s]\", current);\r\n            }\r\n        }\r\n\r\n        interface speedLevel {\r\n            void rotate(FanWallControl fanWallControl);\r\n        }\r\n    \r\n        static class Off implements SpeedLevel {\r\n            public void rotate(FanWallControl fanWallControl) {\r\n                fanWallControl.set_state(new SpeedLevel1());\r\n            }\r\n        }\r\n    \r\n        static class SpeedLevel1 implements SpeedLevel {\r\n            public void rotate(FanWallControl fanWallControl) {\r\n                fanWallControl.set_state(new SpeedLevel2());\r\n            }\r\n        }\r\n    \r\n        static class SpeedLevel2 implements SpeedLevel {\r\n            public void rotate(FanWallControl fanWallControl) {\r\n                fanWallControl.set_state(new SpeedLevel3());\r\n            }\r\n        }\r\n    \r\n        static class SpeedLevel3 implements SpeedLevel {\r\n            public void rotate(FanWallControl fanWallControl) {\r\n                fanWallControl.set_state(new Off());\r\n            }\r\n        }\r\n    }\r\n\r\n```  \r\n\r\nLet's take the example of a fan wall control. The fan wall control controls the speed with a fan rotates. It has speed levels ranging from 0 to 5. When it is at level 0, the fan does not rotate, and it rotates the fastest at level 5.\r\n\r\nWhen you rotate the knob of the fan control, the level changes, and this causes the speed of the fan to change as well. This is a classic case of a change in state (level) causing a change in behavior (speed). \r\n\r\nA ```FanwallControl``` object is composed of a ```SpeedLevel``` object. ```SpeedLevel``` is an interface that has four different implementations. Initially, the level is at ```Off```, and when you click rotate at that time, the new speed is at ```SpeedLevel1```. The happens successively, and if you rotate at ```SpeedLevel3```, the level returns to ```Off```.\r\n\r\nIn case you need to define an additional speed level, just add in a new class that implements the ```SpeedLevel``` interface, and implement its rotate method. \r\n\r\nThis is an excellent example that highlights the advantages of an extensible class.\r\n\r\n#### The Strategy Pattern\r\n\r\n![image info](images/Capture-109-16.png)\r\n\r\nThe strategy has the task of encapsulating an algorithm inside a class. Let's look at a Java code example:\r\n\r\n```java\r\n\r\n    public class StrategyPattern {\r\n        interface Sortable {\r\n            public int[] sort(int[] numbers);\r\n        }\r\n\r\n        static class BubbleSort implements Sortable {\r\n            @Override\r\n            public int[] sort(int[] numbers) {\r\n                //sort using bubble sort algorithm\r\n\r\n                return numbers;\r\n            }\r\n        }\r\n\r\n        static class QuickSort implements Sortable {\r\n            @Override\r\n            public int[] sort(int[] numbers) {d \r\n                //sort using quicksort algorithm\r\n\r\n                return numbers;\r\n            }\r\n        }\r\n\r\n        static class ComplexClass {\r\n            private Sortable sorter;\r\n\r\n            ComplexClass(Sortable sorter) {\r\n                this.sorter = sorter;\r\n            }\r\n\r\n            void doAComplexThing() {\r\n                int[] values = null;\r\n\r\n                //logic...\r\n\r\n                sorter.sort(values);\r\n\r\n                //logic...\r\n            }\r\n        }\r\n\r\n        public static void main(String[] args) {\r\n            ComplexClass complexClassInstance = new ComplexClass(new BubbleSort());\r\n            complexClassInstance.doAComplexThing();\r\n        }\r\n    }\r\n\r\n```\r\n\r\nThe class ```ComplexClass``` intends to perform a lot of complex logic within it. One part of that logic is to sort a set of values. One direct way would be to implement the entire sorting logic within ```ComplexClass```. This would make it very inflexible, since if you wanted to change the sorting logic tomorrow, that entire code needs to change.\r\n\r\nWhen we use the Strategy pattern, we separate the algorithm of how the sorting is done, from ```ComplexClass```. \r\n\r\nWe define an interface named ```Sortable```, which has a method named ```sort()```. Any actual sort algorithm is an implementation of ```Sortable```, and needs to override ```sort()``` method. \r\n\r\nNow, ```ComplexClass``` is given a particular ```Sortable``` implementation as a constructor argument. ```ComplexAlgorithm``` does not care what exact sorting algorithm is being used; it is happy that that object implements the ```sort()``` method of ```Sortable```.\r\n\r\nA lot of flexibility results due to the use of the Strategy pattern. You can dynamically change the strategy, and pass in the right one according to the context.\r\n\r\n#### The Observer Pattern\r\n\r\n> The Observer pattern is a way of notifying a change, to a number of classes. \r\n\r\n![image info](images/Capture-109-17.png)\r\n\r\nIf you are a fan of cricket, you may want to know whenever Sachin Tendulkar scores a century, so that you can celebrate. \r\n\r\nAll such similar people would register themselves to the event of Sachin scoring a century. Each of these people is now an Observer for that event. Whenever Sachin does score a century, a centralized program will notify each observer. \r\n\r\nAnother example is that of online bidding. A group of bidders at an auction register themselves to receive notifications when a higher bid is placed. As soon as a bid higher than the current one is placed, all the registered bidders get to know about it. \r\n\r\nThere are two main parts to implementing the Observer design pattern. \r\n- Registration - where the interested objects register themselves with the centralized program to receive notifications\r\n- Notification - where the registered observers receive notifications from the centralized program\r\n\r\nHere is a simple implementation of the Observer pattern:\r\n\r\n```java\r\n\r\n    public class Observer Pattern {\r\n        static class SachinCenturyNotifier {\r\n            List<SachinFan> fans = new ArrayList<SachinFan>();\r\n            \r\n            void register(SachinFan fan) {\r\n                fans.add(fan);\r\n            } \r\n\r\n            void sachinScoredACentury() {\r\n                for(SachinFan fan: fans) {\r\n                    fan.announce();\r\n                }\r\n            }\r\n        }\r\n\r\n        static class SachinFan {\r\n            private String name;\r\n            \r\n            SachinFan(String name) {\r\n                this.name = name;\r\n            }\r\n\r\n            void announce() {\r\n                System.out.println(name + \" notified\");\r\n            }\r\n        }\r\n\r\n        public static void main(String[] args) {\r\n            SachinCenturyNotifier notifier = new SachinCenturyNotifier();\r\n            notifier.register(new SachinFan(\"Ranga\"));\r\n            notifier.register(new SachinFan(\"Ramya\"));\r\n            notifier.register(new SachinFan(\"Veena\"));\r\n\r\n            notifier.sachinScoredACentury();\r\n        }\r\n    }\r\n\r\n```\r\n\r\nWe have created an instance of ```SachinCenturyNotifier```, and registered three fans with it. \r\n\r\nWhenever Sachin scores a century, the call ```notifier.sachinScoredACentury()``` would be made, and all three fans would be notified. \r\n\r\n#### The Visitor Pattern\r\n\r\n> The Visitor pattern allows us to add a new operation to a class, without changing the class. \r\n\r\n![image info](images/Capture-109-18.png)\r\n\r\nThere are a lot of scenarios when designing frameworks, where we don't want other people to modify the code in the framework. We want others to extend the functionality without touching the framework code. They are allowed to add new operations, but not to change the existing operations. \r\n\r\nThe Visitor pattern allows you to do this.\r\n\r\nA good real-world example of the Visitor pattern is the operation of a taxi company. \r\n\r\nAs soon as a person calls a taxi company, and a cab is dispatched, the company accepts a visitor. Once the visitor, or customer enters the taxi, he is no longer in control of where he is going. The cab driver is now in control.  \r\n\r\nIf we look at it as object-oriented code, the driver class is in control of the customer class. The driver class can add new operations on top of the customer/visitor. \r\n\r\n#### The Template Method Pattern\r\n\r\n> The Template Method pattern is used to defer the exact steps of an algorithm, to a subclass. \r\n\r\n![image info](images/Capture-109-19.png)\r\n\r\nA good real-world example of this pattern is how we go about creating a house plan. Any good house plan consists of a floor plan, the foundation, plumbing, framing and wiring. Such a plan is almost identical for each house. \r\n\r\nIf you were to model this in software, you could create a template class with this standard behavior defined. A subclass could extend this and give actual implementations. Such details could include the wooden flooring type, the wall paint colors, and any added wings as required.\r\n\r\nA good example of the Template Method pattern is within the Spring framework, in the form of ```AbstractController```:\r\n\r\n```java\r\n\r\n    @Override\r\n    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) {\r\n        checkRequest(request);\r\n        prepareResponse(response);\r\n\r\n        if(this.synchronizeOnSession) {\r\n            HttpSession session = request.getSession(false);\r\n            if(session != null) {\r\n                ObjectMutex mutex = WebUtils.getSessionMutex(session);\r\n    \r\n                synchronized(mutex) {\r\n                    return handleRequestInternal(request, response);\r\n                }\r\n            }\r\n        }\r\n        return handleRequestInternal(request, response);\r\n    }\r\n\r\n```\r\n\r\n```handleRequest()``` merely takes care of the basic things. However, it leaves the lions to share for the implementation to the method ```handleRequestInternal()```. This method is defined by subclasses, where more specific logic can be implemented.\r\n\r\nThe Template Method pattern is all about doing the high-level steps, and leaving the low-level details to the subclasses. The subclasses can override the low steps and provide their own implementation.\r\n\r\n#### The Command Pattern\r\n\r\n> The Command pattern encapsulates a command request as an object. \r\n\r\n![image info](images/Capture-109-20.png)\r\n\r\nLet's take a real-world example.\r\n\r\nConsider the scenario when a customer goes to a restaurant and wants to place an order for a meal. The writer merely writes the order he gets on a piece of paper, and passes it on to the chef. The chef executes the order, and then prepares the meal. He passes the piece of paper to the manager.\r\n\r\nThe verbal order from the customer has now become a paper object. This piece of paper is the command object. The command object contains all the details needed to execute the request. \r\n\r\nSimilarly in object-oriented programming, we can encapsulate all the details of a request into an object, and pass that object to execute it. \r\n\r\nIn web applications, when a user types in the details on a form, these details are captured in a single request object, which is then passed across.\r\n\r\nThe interface ```java.lang.Runnable``` is also a good example of how this pattern is implemented. We create threads in Java by extending the ```Runnable``` interface, which has all the logic for execution in its ```start()``` method. When we want to create and start a thread, we pass this class to the ```start()``` method.\r\n\r\n#### The Memento Method\r\n\r\n> The Memento pattern captures and later restores an object's internal state. \r\n\r\n![image info](images/Capture-109-21.png)\r\n\r\nA lot of games that we play offer the option of performing an intermediate save. At a certain point in the game, you can save it and later come back to it. \r\n\r\nTo implement this, we need to save the internal states of the game objects, and restore them at a certain point in time.     \r\n\r\nThis save-revert functionality can be implemented by using serialization in a language such as Java. \r\n\r\nThe memento pattern is very useful for implementing undo/redo operations. \r\n\r\nFor example, if you are working on a text document in a word processor. If at a certain point, you decide to undo changes, you can see each undo until you reach a point where you are satisfied. You have now reverted to an earlier saved state of the document.\r\n\r\n#### The Mediator Pattern\r\n\r\nThe Mediator pattern is used to define simplified communication between classes. \r\n\r\n![image info](images/Capture-109-22.png)\r\n\r\nTake the example of an Air Traffic Controller (ATC). Let's say that at any point of time in India, we have about 500 flights in the air. We need to decide the routes that each of these flights needs to take. This also includes deciding the times at which each of these flights takes off and lands. It will be a highly complex situation if each of these 500 flights needs to talk with each other and arrive at an acceptable schedule of routes. \r\n\r\nThat's why we have the concept of an ATC. The flights communicate with the ATC, and having assimilated the information from all the flights, the ATC makes the decisions and communicates them back the flights. \r\n\r\nIn the software world, a good example of the Mediator pattern is the ESB (Enterprise Service Bus). In a distributed system, instead of letting the applications talk to each other, an application drops in a message to the ESB. The ESB routes the request to the application that needs to handle the request. It acts as the Mediator.\r\n\r\nDo check out our video on the same topic:\r\n\r\n[![image info](images/Capture-109-01.png)](https://www.youtube.com/watch?v=f5Rzr5mVNbY)\r\n\r\n### Summary\r\n\r\nIn this article, we had a quick look over a variety of design patterns.\r\n\r\nA design pattern is an approach to solve a problem in a given context. We focused on understanding the context in which a particular pattern may be applicable with real-world examples.\r\n"
  },
  {
    "path": "_blog/articles/2019-05-07-spring-boot-react-spring-security-basic-and-jwt-authentication.md",
    "content": "---\nlayout:     post\ntitle:      Integrating Spring Boot and React with Spring Security - Basic and JWT Authentication\ndate:       2019-05-06 12:31:19\nsummary:    This guide helps you create a full stack application secured with Basic and JWT Authentication using React as Frontend framework, Spring Boot as the backend REST API and Spring Security as the security framework.\ncategories:  SpringBootFullStack\npermalink:  /spring-boot-react-full-stack-with-spring-security-basic-and-jwt-authentication\nimage: /images/spring-boot-application.png\n---\n\n![Image](/images/full-stack-application-with-spring-boot-view-only-course-listing-page.png \"Spring Boot Full Stack Application\") \n\nThis guide helps you setup Spring Security with Basic and JWT authentication with a full stack application using React as Frontend framework and  Spring Boot as the backend REST API. We will be using JavaScript as the frontend language and Java as the backend language.\n\n![Image](/images/react_00_architecture.png \"Architecture of Spring Boot React Full Stack Application\")\n\n \n## You will learn\n- How do you use React as a Frontend Framework?\n- How do you use Spring to create Backend REST Service API?\n- How do you setup Basic Authentication with Spring Boot?\n- How do you use Spring Security with Spring Boot?\n- How do you use JWT Security with Spring Boot?\n- How do you verify Basic Authentication at user login calling a REST API with React?\n- How do you make secured REST API calls from React frontend?\n- How do you use sessionStorage to track tokens in the React frontend application?\n\n\n\n## Step 0: Get an overview of the Full Stack Application\n\n### Understanding Basic Features of the Application\n\nFollowing screenshot shows the application we would like to build: \n\nWe would request user for authentication credentials on the login page. \n\n![Image](/images/full-stack-application-with-spring-boot-login-page.png \"Spring Boot Full Stack Application\") \n\nOnce user is authenticated using Basic Authentication or JWT Authentication, we show the course details page.\n\n![Image](/images/full-stack-application-with-spring-boot-view-only-course-listing-page.png \"Spring Boot Full Stack Application\") \n\nUser would be able to logout by click the logout button.\n\n### Understanding Full Stack Architecture\n\nFollowing Screenshot shows the architecture of the application we would create:\n\n![Image](/images/react_00_architecture.png \"Architecture of Spring Boot React Full Stack Application\")\n\nImportant points to note:\n- REST API is exposed using Spring Boot\n- REST API is secured using Spring Security. We discuss two approaches - Basic Auth and JWT.\n- REST API is consumed from React Frontend to present the UI\n- The Database, in this example, is a hardcoded in-memory static list.\n\nYou can find more details about Full Stack Architecture here - [Full Stack Application Architecture - Spring Boot and React](https://youtu.be/TTWH_Q7uSlY){:target=\"_blank\"}\n\n[![Image](/images/Course-Go-Full-Stack-With-Spring-Boot-and-React.png \"Go Full Stack with Spring Boot and React\")](https://links.in28minutes.com/MISC-REACT){:target=\"_blank\"}\n\n\n### Getting an overview of Spring Boot and Spring Security REST API Resources\n\nIn this guide, we will create these services:\n\n- ```@GetMapping(\"/instructors/{username}/courses\")``` : Get Request Method exposing the list of courses taught by a specific instructor\n\n#### Services for Basic Authentication\n\n- ```@GetMapping(path = \"/basicauth\")``` : Get Request Method for Basic Authentication. You can send a request to this method to see if the user credentials entered on the login page are valid.\n\n#### Services for JWT Authentication\n\n- @RequestMapping(value = \"/authentication\", method = RequestMethod.POST) - Resource to get a JWT token providing user credentials.\n- @RequestMapping(value = \"/refresh\", method = RequestMethod.GET) - Resource to refresh a JWT Token before it expires.\n\n### Downloading the Complete Maven Project With Code Examples\n\nIn this example, the BACKEND Spring Boot projects are different for JWT Authentication and Basic Authentication\n- For Basic Authentication  - [Project](https://github.com/in28minutes/spring-boot-react-fullstack-examples/tree/master/spring-boot-react-basic-auth-login-logout/backend-spring-boot-react-basic-auth-login-logout){:target=\"_blank\"}\n- For JWT Authentication - [Project](https://github.com/in28minutes/spring-boot-react-fullstack-examples/tree/master/spring-boot-react-jwt-auth-login-logout/backend-spring-boot-react-jwt-auth-login-logout){:target=\"_blank\"}\n\nFRONTEND React projects are almost the same exception for a minor change. The Frontend project can be used from [Project](https://github.com/in28minutes/spring-boot-react-fullstack-examples/tree/master/spring-boot-react-basic-auth-login-logout/frontend-spring-boot-react-basic-auth-login-logout){:target=\"_blank\"}. For JWT, a minor change needs to be done which is explained at [Project](https://github.com/in28minutes/spring-boot-react-fullstack-examples/tree/master/spring-boot-react-jwt-auth-login-logout/frontend-spring-boot-react-jwt-auth-login-logout){:target=\"_blank\"}\n\nComplete Code Example shows all the code.\n\n> Our Github repository has all the code examples - [Github Repo](https://github.com/in28minutes/spring-boot-react-examples/){:target=\"_blank\"}\n\n\n### Understanding Spring Boot REST API Project Structure\n\nFollowing screenshot shows the structure of the Spring Boot project we create for Basic Authentication.\n\n![Image](/images/project-structure-spring-boot-fullstack-basic-auth.png \"Spring Boot Basic Auth - Project Structure\") \n\nFollowing screenshot shows the structure of the Spring Boot project we create for JWT Authentication.\n\n![Image](/images/project-structure-spring-boot-fullstack-jwt-auth.png \"Spring Boot JWT - Project Structure\") \n\n\nA few details:\n\nCommon Files\n\n- `CourseResource.java` - Rest Resource exposing all the service methods discussed above.\n- `Course.java, CoursesHardcodedService.java` - Business Logic for the application. CoursesHardcodedService exposes a few methods we would invoke from our Rest Resource.\n- `SpringBootFullStackBasicAuthLoginLogoutApplication.java` - Launcher for the Spring Boot Application. To run the application, launch this file as Java Application.\n- `pom.xml` - Contains all the dependencies needed to build this project. We use Spring Boot Starter Web and Spring Boot DevTools.\n\nBasic Authentication Files\n\n- `AuthenticationBean.java` - Simple bean which will be used to send a response for the basic authentication request.\n- `BasicAuthenticationController.java` - Provides the implementation for ```@GetMapping(path = \"/basicauth\")``` to check if the basic authentication credential are valid\n- `SpringSecurityConfigurationBasicAuth.java` - Contains Spring Configuration to enable Basic Authentication.\n\nJWT Authentication Files\n\n- `JwtAuthenticationRestController.java` - Exposes all the URLs related to JWT Authentication.\n- `JwtUserDetails.java` - Implementation of `UserDetails` interface providing user details.\n- `JwtInMemoryUserDetailsService.java` - Provides an in memory implementation of `UserDetailsService` storing the user credentials.\n- `JwtTokenAuthorizationOncePerRequestFilter.java` - \n- `JwtTokenRequest.java` - Represents the structure of request to get a JWT Token.  \n- `JwtTokenResponse.java` - Represnets to structure of response containing the JWT Token.\n- `JwtTokenUtil.java` - Provide JWT Utilities to encrypt and decrypt JWT tokens.\n- `JwtUnAuthorizedResponseAuthenticationEntryPoint.java` - Used when a valid token is not provided with a REST API call\n- `JWTWebSecurityConfig.java` - Customizes Spring Security for JWT Authentication Needs by extending `WebSecurityConfigurerAdapter`\n- `AuthenticationException.java` - Use to throw invalid credentials or token exception\n\n## Understanding React Frontend Project Structure\n\nFollowing screenshot shows the structure of the React project we create.\n\n![Image](/images/project-structure-react-fullstack-crud-maven.png \"React Frontend - Project Structure\") \n\n> Quick Tip: You can get a high-level overview of all files in the React Project Structure watching this video [React Project Structure](https://youtu.be/wI5G8FNFrto){:target=\"_blank\"}\n\nA few details:\n- `InstructorApp.jsx` : React Component representing the high-level structure of the application. Routing is defined in this file.\n- `ListCoursesComponent.jsx` - React Component for listing all the courses for an instructor.\n- `CourseDataService.js` - Service using axios framework to make the Backend REST API Calls.\n- `LoginComponent.jsx` - Login Component representing the login screen.\n- `LogoutComponent.jsx` - Logout Component handles the click of Logout button at the top right corner of the screen\n- `MenuComponent.jsx` - Handles display of the top menu.\n- `AuthenticationService.jsx` - Service handling all details related to JWT and Basic Authentication.\n- `AuthenticatedRoute.jsx` - We would want certain routes like /courses to be accessed only by authenticated users. `AuthenticationRoute` helps us implement this.\n\n\n### Understanding the tools you need to build this project\n\n- Maven 3.0+ for building Spring Boot API Project\n- npm, webpack for building frontend\n- Your favorite IDE. We use Eclipse for Java and Visual Studio Code for Frontend - JavaScript, TypeScript, Angular and React.\n- JDK 1.8+\n- Node v8+\n- Embedded Tomcat, built into Spring Boot Starter Web\n\n#### Installing Node Js (npm) & Visual Studio Code \n\n- [Click to see video Playlist](https://www.youtube.com/playlist?list=PLBBog2r6uMCQN4X3Aa_jM9qVjgMCHMWx6){:target=\"_blank\"}\n  - Step 01 - Installing NodeJs and NPM - Node Package Manager\n  - Step 02 - Quick Introduction to NPM\n  - Step 03 - Installing Visual Studio Code - Front End JavaScript Editor\n\n#### Installing Java, Eclipse & Embedded Maven\n\n- [Click to see video Playlist](https://www.youtube.com/playlist?list=PLBBog2r6uMCSmMVTW_QmDLyASBvovyAO3){:target=\"_blank\"}\n  - 0 - Overview - Installation Java, Eclipse and Maven\n  - 1 - Installing Java JDK\n  - 2 - Installing Eclipse IDE\n  - 3 - Using Embedded Maven in Eclipse\n  - 4 - Troubleshooting Java, Eclipse and Maven\n\n### Steps 1, 2 and 3 - Creating A Simple Full Stack application with React and Spring Boot - Step By Step Approach\n\nWe will use a step by step approach to creating the full stack application\n- Create a Spring Boot Application with Spring Boot Initializr\n- Create a React application using Create React App\n- Create the Retrieve Courses REST API and Enhance the React Front end to retrieve the courses using the axios framework\n\n> You can get an introduction to REST down here - [Introduction to REST API](http://www.springboottutorial.com/creating-rest-service-with-spring-boot){:target=\"_blank\"}\n\n\nAbove steps are similar to the full stack CRUD application guide here - [Creating Spring Boot and React CRUD Full Stack Application with Maven](https://www.springboottutorial.com/spring-boot-react-full-stack-crud-maven-application)\n\nYou can follow Step 1, 2 and 3 from the above guide.\n\nWhen you launch the React app in the browser, it will appear as shown below:\n\n![Image](/images/react-third-stage-getting-course-listing-from-rest-api.png \"Course Listing Component Retrieving from REST API\")\n\n## Step 4: Adding Basic Authentication to Backend\n\nAll that you need to do is to add Spring Boot Starter Security to your pom.xml\n\n<dependency>\n  <groupId>org.springframework.boot</groupId>\n  <artifactId>spring-boot-starter-security</artifactId>\n</dependency>\n\nYou would see that the Basic Authentication is now enabled. \n\nIf you restart the backend application, you would see the basic authentication password is printed into the console\n\n```\n\nUsing generated security password: 5434c56e-05bc-4b33-b54d-cf3a7c358f5b\n\n\n```\n\n\nIf you try to launch the url `http://localhost:8080/instructors/in28minutes/courses`, you will be asked for credentials. The  user id as `user` and password is shown above.\n\nInstead of using Random Password, we can configure our own user credentials in `application.properties`.\n\n```\nspring.security.user.name=in28minutes\nspring.security.user.password=dummy\n```\n\nWhen you launch the url `http://localhost:8080/instructors/in28minutes/courses` in a new browser, you can use the username and password specified above.\n\nIf you go the frontend and refresh the page, you would see that the page does not load as expected.\n\n## Step 5: Updating Frontend React Application to use hardcoded Basic Authentication\n\nLet's now update the react front end to use basic authentication credentials to call the course listing api.\n\nYou can see the complete listing of CourseDataService below:\n\n```\nimport axios from 'axios'\n\nconst INSTRUCTOR = 'in28minutes'\nconst PASSWORD = 'dummy'\nconst COURSE_API_URL = 'http://localhost:8080'\nconst INSTRUCTOR_API_URL = `${COURSE_API_URL}/instructors/${INSTRUCTOR}`\n\nclass CourseDataService {\n\n    retrieveAllCourses(name) {\n        console.log('executed service')\n        return axios.get(`${INSTRUCTOR_API_URL}/courses`,\n            { headers: { authorization: 'Basic ' + window.btoa(INSTRUCTOR + \":\" + PASSWORD) } }\n        );\n    }\n}\n\nexport default new CourseDataService()\n```\n\nIf you refresh the course listing page, you should see another error.\n\n```\nAccess to XMLHttpRequest at 'http://localhost:8080/basicauth' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.\n```\n\n[![Image](/images/Course-Go-Full-Stack-With-Spring-Boot-and-React.png \"Go Full Stack with Spring Boot and React\")](https://links.in28minutes.com/MISC-REACT){:target=\"_blank\"}\n\n\n## Step 5: Updating Spring Security to allow Preflight OPTION Requests\n\n> Preflight request failed - what does that mean?\n\nWhen you are using authentication, before executing the actual request , browser sends something called an OPTION request.\n\nIf you go to the network tab, you would see the request and responses with following headers\n```\nRequest URL: http://localhost:8080/instructors/in28minutes/courses\nRequest Method: OPTIONS\nStatus Code: 401 \nRemote Address: [::1]:8080\nReferrer Policy: no-referrer-when-downgrade\n```\n\nWe can configure Spring Security to enable all OPTIONS requests. Following snippets show the spring security configuration needed.\n\n```\n@Configuration\n@EnableWebSecurity\npublic class SpringSecurityConfigurationBasicAuth extends WebSecurityConfigurerAdapter{\n    \n    @Override\n    protected void configure(HttpSecurity http) throws Exception {\n        http\n        .csrf().disable()   \n        .authorizeRequests()\n        .antMatchers(HttpMethod.OPTIONS,\"/**\").permitAll()\n                .anyRequest().authenticated()\n                .and()\n            //.formLogin().and()\n            .httpBasic();\n    }\n}\n```\n\nWhen you launch the React app in the browser, it will appear as shown below:\n\n![Image](/images/react-third-stage-getting-course-listing-from-rest-api.png \"Course Listing Component Retrieving from REST API\")\n\nIf you look at the request to http://localhost:8080/instructors/in28minutes/courses in the browser, you would see the following headers:\n\n```\nAccept: application/json, text/plain, */*\nauthorization: Basic aW4yOG1pbnV0ZXM6ZHVtbXk=\n```\n\nYou would also see a successful response.\n\n> Congratulations on your first authenticated API call!\n\nIs this the end of story? Nope. Ideally, we should have a Login Page to get the credentials from the user, authenticate the credentials and use those details for subsequent REST API calls. \n\nLet's focus on this in the next steps.\n\n## Step 06: Create an API for basic authentication\n\nWhen we create a login page, we need to call an authentication url to validate the user credentials. You don't want to use some random url. Let's create a REST API.\n\nWe create a simple url \"/basicauth\" returning an `AuthenticationBean` of successful.\n\n```\n@CrossOrigin(origins={ \"http://localhost:3000\", \"http://localhost:4200\" })\n@RestController\npublic class BasicAuthenticationController {\n\n    @GetMapping(path = \"/basicauth\")\n    public AuthenticationBean authenticate() {\n        //throw new RuntimeException(\"Some Error has Happened! Contact Support at ***-***\");\n        return new AuthenticationBean(\"You are authenticated\");\n    }   \n}\n```\n\n```\npublic class AuthenticationBean {\n\n    private String message;\n\n    //constructors, getters\n\n}\n```\n\n> There is no authentication logic in `authenticate()` method. Why? Because, we already configured spring security, it auto protects all URLs with basic authentication. An user would be able to get to `/basicauth` only if they provide the right credentials.\n\n\n## Step 07: Create a Login Component with hardcoded authentication\n\nWe will create a Login Component with hardcoded authentication.\n\n```\nimport React, { Component } from 'react'\nimport AuthenticationService from '../service/AuthenticationService';\n\nclass LoginComponent extends Component {\n\n    constructor(props) {\n        super(props)\n\n        this.state = {\n            username: 'in28minutes',\n            password: '',\n            hasLoginFailed: false,\n            showSuccessMessage: false\n        }\n\n        this.handleChange = this.handleChange.bind(this)\n        this.loginClicked = this.loginClicked.bind(this)\n    }\n\n    handleChange(event) {\n        this.setState(\n            {\n                [event.target.name]\n                    : event.target.value\n            }\n        )\n    }\n\n    loginClicked() {\n        if(this.state.username==='in28minutes' && this.state.password==='dummy'){\n            AuthenticationService.registerSuccessfulLogin(this.state.username,this.state.password)\n            this.setState({showSuccessMessage:true})\n            this.setState({hasLoginFailed:false})\n        }\n        else {\n             this.setState({showSuccessMessage:false})\n             this.setState({hasLoginFailed:true})\n        }\n    }\n\n    render() {\n        return (\n            <div>\n                <h1>Login</h1>\n                <div className=\"container\">\n                    {this.state.hasLoginFailed && <div className=\"alert alert-warning\">Invalid Credentials</div>}\n                    {this.state.showSuccessMessage && <div>Login Sucessful</div>}\n                    User Name: <input type=\"text\" name=\"username\" value={this.state.username} onChange={this.handleChange} />\n                    Password: <input type=\"password\" name=\"password\" value={this.state.password} onChange={this.handleChange} />\n                    <button className=\"btn btn-success\" onClick={this.loginClicked}>Login</button>\n                </div>\n            </div>\n        )\n    }\n}\n\nexport default LoginComponent\n```\n\nLet's look at above component in depth:\n\n\n\nWe are using `state` to represent user credentials entered by user and also to contain messages for showing success and failed authentication messages.\n\n```\n        this.state = {\n            username: 'in28minutes',\n            password: '',\n            hasLoginFailed: false,\n            showSuccessMessage: false\n        }\n```\n\nWe are creating a simple form with username and password which is tied to the `state`:\n\n```\n  User Name: <input type=\"text\" name=\"username\" value={this.state.username} onChange={this.handleChange} />\n  Password: <input type=\"password\" name=\"password\" value={this.state.password} onChange={this.handleChange} />\n  <button className=\"btn btn-success\" onClick={this.loginClicked}>Login</button>\n```\n\nWe are using events to update state as soon as values in the text fields change.\n\n```\nhandleChange(event) {\n    this.setState(\n        {\n            [event.target.name]\n                : event.target.value\n        }\n    )\n}\n```\n\n`loginClicked` is called when user clicks Login button. We add a bit of hardcoded validation for now.\n\n```\nloginClicked() {\n    if(this.state.username==='in28minutes' && this.state.password==='dummy'){\n        this.setState({showSuccessMessage:true})\n        this.setState({hasLoginFailed:false})\n    }\n    else {\n         this.setState({showSuccessMessage:false})\n         this.setState({hasLoginFailed:true})\n    }\n}\n```\n\nIf you update the `InstructorApp` to show the `LoginComponent`, you can play with the login component.\n\n```\nclass InstructorApp extends Component {\n    render() {\n        return (<>\n              <h1>Instructor Application</h1>\n              <LoginComponent/>\n            </>\n        )\n    }\n}\n\nexport default InstructorApp\n```\n\n## Step 08 - Adding Routing to React Application\n\nWhen user click login and user is successfully authenticated, we would want to see the course listing page. We would want to route from `LoginComponent` to `ListCoursesComponent`. We would need to implement routing. \n\nIn Step 03, we added a framework to support routing - react-router-dom\n\nWhen the user clicks the update course button on the course listing page, we would want to route to the course page. How do we do it? That’s where Routing comes into the picture.\n\nLet's update `InstructorApp` to define the routes.\n\n/src/component/InstructorApp.jsx\n\n```\nclass InstructorApp extends Component {\n\n\n    render() {\n        return (\n            <>\n                <Router>\n                    <>\n                        <MenuComponent />\n                        <Switch>\n                            <Route path=\"/\" exact component={LoginComponent} />\n                            <Route path=\"/login\" exact component={LoginComponent} />\n                            <AuthenticatedRoute path=\"/courses\" exact component={ListCoursesComponent} />\n                        </Switch>\n                    </>\n                </Router>\n            </>\n        )\n    }\n}\n```\n\nWe are defining a Router around all the components and configuring paths to each of them.\n\n- http://localhost:3000/ and http://localhost:3000/login takes you to login page\n- http://localhost:3000/courses takes you to course listing page\n\nNow that we have the routes defined, we can route from `LoginComponent` to `ListCoursesComponent` on successful login.\n\n\n```\nloginClicked() {\n    if(this.state.username==='in28minutes' && this.state.password==='dummy'){\n        this.props.history.push(`/courses`)\n        //this.setState({showSuccessMessage:true})\n        //this.setState({hasLoginFailed:false})\n    }\n    else {\n         this.setState({showSuccessMessage:false})\n         this.setState({hasLoginFailed:true})\n    }\n}\n```\n\nYou would see that we are now able to route from login to course listing page if we enter the right credentials.\n\n## Step 09 - Remove Authentication hardcoding and call the REST API for Basic Authentication\n\nDo you like hardcoded authentication? Let's fix it.\n\n```\nif(this.state.username==='in28minutes' && this.state.password==='dummy'){\n```\n\nLet's create `AuthenticationService` to call the basic authentication url.\n\n```\nclass AuthenticationService {\n\n    executeBasicAuthenticationService(username, password) {\n        return axios.get(`${API_URL}/basicauth`,\n            { headers: { authorization: this.createBasicAuthToken(username, password) } })\n    }\n\n    createBasicAuthToken(username, password) {\n        return 'Basic ' + window.btoa(username + \":\" + password)\n    }\n}\n```\n\nLet's update the `LoginComponent` to use the service.\n\n```\n    loginClicked() {\n        //in28minutes,dummy\n        // if(this.state.username==='in28minutes' && this.state.password==='dummy'){\n        //     AuthenticationService.registerSuccessfulLogin(this.state.username,this.state.password)\n        //     this.props.history.push(`/courses`)\n        //     //this.setState({showSuccessMessage:true})\n        //     //this.setState({hasLoginFailed:false})\n        // }\n        // else {\n        //     this.setState({showSuccessMessage:false})\n        //     this.setState({hasLoginFailed:true})\n        // }\n\n        AuthenticationService\n            .executeBasicAuthenticationService(this.state.username, this.state.password)\n            .then(() => {\n                this.props.history.push(`/courses`)\n            }).catch(() => {\n                this.setState({ showSuccessMessage: false })\n                this.setState({ hasLoginFailed: true })\n            })\n      }\n```\n\nWhen we call REST API we need to use promises to define success (`then`) and failure scenarios (`catch`).\n\n\n## Step 10 - Remove Hardcoded Header from Course Listing REST API call\n\nEarlier we hardcoded the basic authentication header in the REST API call. This is not ideal.\n```\n        return axios.get(`${INSTRUCTOR_API_URL}/courses`,\n            { headers: { authorization: 'Basic ' + window.btoa(INSTRUCTOR + \":\" + PASSWORD) } }\n```\n\n\nWhen we make any REST API call, we would want to automatically add the authorization header that we added for the authentication api call.\n\nHow do we do that?\n\nWhen user login is successful, we can setup an axios header to added a authorization header on every subsequent API call. Does that sound like a plan?\n\nAuthenticationService.registerSuccessfulLogin(this.state.username, this.state.password)\n\nLet's add these methods to `AuthenticationService`:\n\n```\n    registerSuccessfulLogin(username, password) {\n        //let basicAuthHeader = 'Basic ' +  window.btoa(username + \":\" + password)\n        //console.log('registerSuccessfulLogin')\n        sessionStorage.setItem(USER_NAME_SESSION_ATTRIBUTE_NAME, username)\n        this.setupAxiosInterceptors(this.createBasicAuthToken(username, password))\n    }\n\n    setupAxiosInterceptors(token) {\n        axios.interceptors.request.use(\n            (config) => {\n                if (this.isUserLoggedIn()) {\n                    config.headers.authorization = token\n                }\n                return config\n            }\n        )\n    }\n\n```\n\n`setupAxiosInterceptors` sets up the axios interceptor to add the authorization token on every subsequent REST API call. `config.headers.authorization = token`\n\nLet's call it on successful login in `loginClicked` in `LoginComponent`:\n\n```\nAuthenticationService\n    .executeBasicAuthenticationService(this.state.username, this.state.password)\n    .then(() => {\n        AuthenticationService.registerSuccessfulLogin(this.state.username, this.state.password)\n        this.props.history.push(`/courses`)\n    }).catch(() => {\n        this.setState({ showSuccessMessage: false })\n        this.setState({ hasLoginFailed: true })\n    })\n\n```\n\nLet's also remove the hardcode authorization from `CourseDataService`\n\n```\nclass CourseDataService {\n\n    retrieveAllCourses(name) {\n        //console.log('executed service')\n        return axios.get(`${INSTRUCTOR_API_URL}/courses`,\n            //{ headers: { authorization: 'Basic ' + window.btoa(INSTRUCTOR + \":\" + PASSWORD) } }\n        );\n    }\n}\n\n```\n\nCool! If you run the app now, you should be fine. \n\n> Congratulations on implementing Basic Authentication\n\nYou can look up the `MenuComponent`, `LogoutComponent` to add features like Menu and Logout.\n\n[![Image](/images/Course-Go-Full-Stack-With-Spring-Boot-and-React.png \"Go Full Stack with Spring Boot and React\")](https://links.in28minutes.com/MISC-REACT){:target=\"_blank\"}\n\n\n## Step 11 - Implementing JWT Authentication for Backend\n\nJWT stands for JavaScript Web Token.\n\nYou can refer https://jwt.io/ for a quick introduction to JWT.\n\nBasic Authentication Header does not have an expiry time and therefore a hacker get his hand on a basic authentication header, he can use it until the password is changed. \n\nInstead of passing userid and password, in JWT, we pass a token with every request.\n\nWhen a user logs in, we use his credential to get a JWT token. In all subsequent rest api requests, we use the token. Since the token has an expiration time, it offers better security than Basic Authentication.\n\nImplementing JWT Authentication for Spring Boot is complex. Following are some of the important components involved. \n\n### JWT Authentication Files\n\n- `JwtAuthenticationRestController.java` - Exposes all the URLs related to JWT Authentication.\n- `JwtUserDetails.java` - Implementation of `UserDetails` interface providing user details.\n- `JwtInMemoryUserDetailsService.java` - Provides an in memory implementation of `UserDetailsService` storing the user credentials.\n- `JwtTokenAuthorizationOncePerRequestFilter.java` - \n- `JwtTokenRequest.java` - Represents the structure of request to get a JWT Token.  \n- `JwtTokenResponse.java` - Represnets to structure of response containing the JWT Token.\n- `JwtTokenUtil.java` - Provide JWT Utilities to encrypt and decrypt JWT tokens.\n- `JwtUnAuthorizedResponseAuthenticationEntryPoint.java` - Used when a valid token is not provided with a REST API call\n- `JWTWebSecurityConfig.java` - Customizes Spring Security for JWT Authentication Needs by extending `WebSecurityConfigurerAdapter`\n- `AuthenticationException.java` - Use to throw invalid credentials or token exception\n\nI would recommend to check out the code for these components in the `Complete Code Example` at the end of this article.\n\n> For setting up the JWT Backend Spring Boot API , I would recommend to download the project at this URL - [Github Repo](https://github.com/in28minutes/spring-boot-react-fullstack-examples/tree/master/spring-boot-react-jwt-auth-login-logout/backend-spring-boot-react-jwt-auth-login-logout){:target=\"_blank\"}. Once you import the project, you can launch `SpringBootFullStackJwtAuthLoginLogoutApplication` as a Java Application.\n\n### JWT Authentication URLs\n\nYou can send a POST request to `http://localhost:8080/authenticate` with the request body containing the credentials.\n```\n{\n  \"username\":\"in28minutes\",\n  \"password\":\"dummy\"\n}\n```\n\nThe Response contains the JWT token\n```\n{\n\"token\": \"eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJyYW5nYSIsImV4cCI6MTU0MjQ3MjA3NCwiaWF0IjoxNTQxODY3Mjc0fQ.kD6UJQyxjSPMzAhoTJRr-Z5UL-FfgsyxbdseWQvk0fLi7eVXAKhBkWfj06SwH43sY_ZWBEeLuxaE09szTboefw\"\n}\n```\n\nWe can use this token for subsequent API calls.\n\nTo refresh the token, we can send a GET request to `http://localhost:8080/authenticate` with the token in the header. You would get a new token in the response\n\n## Step 12 - Updating Front End Code to Use JWT\n\nUpdating front end code to use JWT is very simple.\n\nWe will create a method to call the JWT authenticate url with POST method in `AuthenticationService`. \n\n```\n  executeJwtAuthenticationService(username, password) {\n      console.log(username);\n      return axios.post(`${API_URL}/authenticate`, {\n          username,\n          password\n      })\n  }\n```\n\nWe will create another method in `AuthenticationService` to register successful login for JWT. This will setup the token in sessionStorage and also setup the axios interceptors for subsequent api calls.\n\n```\nregisterSuccessfulLoginForJwt(username, token) {\n    sessionStorage.setItem(USER_NAME_SESSION_ATTRIBUTE_NAME, username)\n    this.setupAxiosInterceptors(this.createJWTToken(token))\n}\n\ncreateJWTToken(token) {\n    return 'Bearer ' + token\n}\n\n```\n\nWe can now comment out the Basic Authentication call and call JWT authentication service in `LoginComponent`.\n\n```\nAuthenticationService\n    .executeJwtAuthenticationService(this.state.username, this.state.password)\n    .then((response) => {\n        AuthenticationService.registerSuccessfulLoginForJwt(this.state.username, response.data.token)\n        this.props.history.push(`/courses`)\n    }).catch(() => {\n        this.setState({ showSuccessMessage: false })\n        this.setState({ hasLoginFailed: true })\n    })\n```\n\nWhen you login, you should the REST API request to `/authenticate` returning with a response containing JWT token. This JWT token is used in all subsequent REST API calls.\n\n\n### Downloading the Complete Maven Project With Code Examples\n\nIn this example, the BACKEND Spring Boot projects are different for JWT Authentication and Basic Authentication\n- For Basic Authentication  - [Project](https://github.com/in28minutes/spring-boot-react-fullstack-examples/tree/master/spring-boot-react-basic-auth-login-logout/backend-spring-boot-react-basic-auth-login-logout){:target=\"_blank\"}\n- For JWT Authentication - [Project](https://github.com/in28minutes/spring-boot-react-fullstack-examples/tree/master/spring-boot-react-jwt-auth-login-logout/backend-spring-boot-react-jwt-auth-login-logout){:target=\"_blank\"}\n\nFRONTEND React projects are almost the same exception for a minor change. The Frontend project can be used from [Project](https://github.com/in28minutes/spring-boot-react-fullstack-examples/tree/master/spring-boot-react-basic-auth-login-logout/frontend-spring-boot-react-basic-auth-login-logout){:target=\"_blank\"}. For JWT, a minor change needs to be done which is explained at [Project](https://github.com/in28minutes/spring-boot-react-fullstack-examples/tree/master/spring-boot-react-jwt-auth-login-logout/frontend-spring-boot-react-jwt-auth-login-logout){:target=\"_blank\"}\n\nComplete Code Example shows all the code.\n\n> Our Github repository has all the code examples - [Github Repo](https://github.com/in28minutes/spring-boot-react-examples/){:target=\"_blank\"}\n"
  },
  {
    "path": "_blog/articles/2019-05-08-Microservice-Basics-056-The-Cloud.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Microservices Architectures - Quick introduction to Cloud - Why, What and How?\r\ndate:    2019-05-08 12:31:19\r\nsummary:  In this article, we focus our attention on the cloud. Why do we need the cloud?\r\ncategories:  SpringBootMicroservices\r\npermalink:  /introduction-to-cloud\r\nimage: /images/spring-boot-application.png\r\n---\r\n\r\nIn this article, we focus our attention on the cloud. Why do we need the cloud?\r\n\r\n## You will learn\r\n- What is Cloud?\r\n- Why do we need the Cloud?\r\n- How does cloud provide auto scaling?\r\n- What are the advantages of Cloud?\r\n- What are the challenges with Cloud?\r\n\r\n\r\n### Introduction to Cloud, Microservice - Challenges and Advantages\r\n\r\nThis is the first article in a series of five articles on cloud and microservices:\r\n- [1 - Microservices Architecutres - Quick introduction to Cloud - Why, What and How?](/introduction-to-cloud){:target='_blank'}\r\n- [2 - Microservice Architectures - Introduction to Spring Cloud](/introduction-to-spring-cloud){:target='_blank'}\r\n- [3 - Microservices Architectures - Advantages Of Microservices](/microservice-architectures-advantages-of-microservices){:target='_blank'}\r\n- [4 - Microservice Architectures - Challenges with building Microservices](/microservice-architectures-challenges-with-microservices){:target='_blank'}\r\n- [5 - Microservices Architectures - Microservices vs SOA](/microservice-architectures-soa-vs-microservices){:target='_blank'}\r\n\r\n\r\n### The Need For The Cloud\r\n\r\nLoads on applications is not consistent throughout the year:\r\n- Consider a startup company, which could have a potential to grow very fast.\r\n- Imagine an online shopping portal, whose customer load varies throughout the year. \r\n- Other online business portals, such the insurance sector, which have peak load at a particular time of the year, and very little load during other times.\r\n\r\n> If you provision your infrastructure to be able to handle the peak system lead, what would that infrastructure be doing the rest of the time? \r\n\r\nMost of it would just be sitting idle, watching the fun. \r\n\r\nThat is exactly the problem cloud wants to solve.\r\n\r\nCloud intends to make it easy to provision infrastructure when you need, and just as easy to release it when you don't. This feature of the cloud has created a lot of buzz around it, over the last decade or so.  \r\n\r\n### Building Applications For The Cloud\r\n\r\nThe thing is, you cannot take any application and just put it on the cloud. \r\n\r\n> A lot of things need to be right, in order to make an application cloud-enabled. They are known as **cloud-native applications**. \r\n\r\nThere are best practices in place to develop such cloud-native applications, also known as the twelve-factor apps. We discuss those in a seperate article.\r\n\r\n#### Advantages Of The Cloud\r\n\r\n##### Auto Scaling and Agility\r\n\r\nThere is no longer a need to statically provision infrastructure to ensure availability for peak loads. You can do that on-demand.\r\n\r\n##### Cost Reduction\r\n\r\nThere are significant cost reductions with using infrastructure from the cloud, because you only use what you need for the duration you need them.\r\n\r\n##### Scalability And Elasticity\r\n\r\nWhen applications are built well, they can auto scale based on the load.\r\n\r\n##### Reliability \r\n\r\nSince your applications are cloud-enabled, they are designed to withstand certain kinds of outages. For example, applications with microservices architecture have fault-tolerance built into them. \r\n\r\n### Migrating Applications To The Cloud\r\n\r\nIt is not very straightforward to migrate your application to be cloud-enabled. \r\n\r\nThe first step is to make them cloud-native. The next decision to make is choosing a platform to migrate the application to. You generally have choice of platforms to migrate to, such as Microsoft Azure, AWS and Google Cloud, among others.\r\n\r\n### Best Practices\r\n\r\nThe best practices listed for making applications cloud-native are often termed as **12 factor apps**. These capture the experiences of Heroku, with developing cloud enabled applications. \r\n\r\n### Challenges With Developing Cloud Applications\r\n\r\n#### Security\r\n\r\nSecurity is a major concern, as the infrastructure is not what you own, and it can be dynamically acquired and released. \r\n\r\n#### Application Compatibility\r\n\r\nMost applications are not compatible with the cloud. Applications have to enhanced to make them cloud native.\r\n\r\n### Manifestations Of Cloud\r\n\r\n#### IaaS\r\n\r\nInfrastructure as a service is the first level of cloud. Cloud provider only provides the hardware needed to run applications.\r\n\r\n#### PaaS \r\n\r\nPlatform of service is the next level of cloud, where the cloud provider provides you a platform - an operating system or managed software (databases, programming languages, web application platforms) - on top of the hardware. \r\n\r\n#### SaaS\r\n\r\nSoftware as a Service is the third level of cloud, where the cloud provider offers a software product on the cloud - like Google Docs.\r\n\r\nDo check out our video on this:\r\n\r\n[![image info](/images/Capture-056-01.png)](https://www.youtube.com/watch?v=rxTNUw0wp-U)\r\n\r\n### Summary\r\n\r\nIn this article, we had a good look at the cloud. We saw that a cloud helps ease the infrastructure management of online businesses by making provisioning dynamic. A cloud could be public, or private. Using a cloud has many advantages to offer, such as agility, cost reduction and reliability.\r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-05-09-Microservice-Basics-063-Introduction-To-Spring-Cloud.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Microservice Architectures - Introduction to Spring Cloud\r\ndate:    2019-05-09 12:31:19\r\nsummary:  In this article, we focus on Spring Cloud. We talk about the various components under its umbrella. \r\ncategories:  SpringBootMicroservices\r\npermalink:  /introduction-to-spring-cloud\r\nimage: /images/spring-boot-application.png\r\n---\r\n\r\nIn this article, we focus on Spring Cloud. We talk about the various components under its umbrella. \r\n \r\n## You will learn\r\n- What is Spring Cloud?\r\n- What are the typical challenges in microservices architectures?\r\n- What are the challenges that Spring Cloud solves?\r\n- What are the important projects under Spring Cloud umbrella?\r\n- How does Spring Cloud help you build your microservices architecture?\r\n\r\n\r\n### Introduction to Cloud, Microservice - Challenges and Advantages\r\n\r\nThis is the second article in a series of five articles on cloud and microservices:\r\n- [1 - Microservices Architecutres - Quick introduction to Cloud - Why, What and How?](/introduction-to-cloud){:target='_blank'}\r\n- [2 - Microservice Architectures - Introduction to Spring Cloud](/introduction-to-spring-cloud){:target='_blank'}\r\n- [3 - Microservices Architectures - Advantages Of Microservices](/microservice-architectures-advantages-of-microservices){:target='_blank'}\r\n- [4 - Microservice Architectures - Challenges with building Microservices](/microservice-architectures-challenges-with-microservices){:target='_blank'}\r\n- [5 - Microservices Architectures - Microservices vs SOA](/microservice-architectures-soa-vs-microservices){:target='_blank'}\r\n\r\n\r\n## Introducing Spring Cloud\r\n\r\nIf you go to the homepage of Spring Cloud:\r\n\r\n![image info](/images/Capture-063-02.png)\r\n\r\n> Spring Cloud provides tools for developers to quickly build some of the common patterns in distributed systems (e.g. configuration management, service discovery, circuit breakers, intelligent routing, micro-proxy, control bus, one-time tokens, global locks, leadership election, distributed sessions, cluster state)\r\n\r\nSpring Cloud is not a single project, rather a cluster of them.\r\n\r\nShown below is just a small sample of the projects present under this umbrella. \r\n\r\n![image info](/images/Capture-063-03.png)\r\n\r\nLet's get a quick introduction to some of the important projects under Spring Cloud umbrella \r\n\r\n### Spring Cloud Netflix\r\n\r\nNetflix was one of the first organizations to play around with microservices architecture. Under this project, a large number of projects have been open sourced for public use. Eureka, Hystrix and Zuul are popular ones among them. \r\n\r\n#### Spring Cloud Config\r\n\r\nThis project provides a framework for centralized configuration management, making use of a Git or a SVN repository.\r\n\r\n#### Spring Cloud Bus\r\n\r\nThis enables the microservices and infrastructure components to communicate with each other, in a distributed setup. \r\n\r\n### Challenges in Microservices Architectures\r\n\r\nLet's now have a look at the challenges we face while developing microservices applications, and the solutions offered by Spring Cloud for them.\r\n\r\n### Configuration Management\r\n\r\nIn a system with a microservices architecture, there are a large number of small-sized microservices that communicate with each other: \r\n\r\n![image info](/images/Capture-063-04.png)\r\n\r\nEach of these microservices needs to execute across multiple environments. In a given environment, there could be multiple instances of that microservice running. This means the operations team needs to manage a lot of configuration information for each microservice. \r\n\r\n> The Spring Cloud Config Server provides a solution to such configuration management\r\n\r\n![image info](/images/Capture-063-05.png)\r\n\r\nIt provides an approach, where all the configurations across environments for all the microservices, is stored in a Git repository. The Spring Cloud Config Server then exposes this information to all the microservices. \r\n\r\nStoring the configurations in such a centralized location makes it easier for the operations team to manage it.\r\n\r\n### Dynamic Scale Up And Down\r\n\r\nConsider the following example: \r\n\r\nThe CurrencyCalculationService microservice talks to another microservice, the CurrencyExchangeService. Currently, three instances of CurrencyExchangeService are running. it is possible that at any point in time, more instances can be added in, or existing instances can be removed. \r\n\r\n![image info](/images/Capture-063-06.png)\r\n\r\nWe need the CurrencyCalculationService to be able to distribute the load across the instances available at that point in time. \r\n\r\nThe need is to dynamically find out the number of instances of the CurrencyExchangeService at that time, and distribute the load across them.\r\n\r\nSolution involves multiple components.\r\n\r\n#### Service Registration\r\n\r\nAll microservices register with a naming server. One of the options Spring Boot provides is Eureka.\r\n\r\n#### Service Discovery\r\n\r\nWhen any microservice wants to talk to another microservice, it asks the naming server In the example above, the CurrencyCalculationService can ask the Eureka naming server, about the instances of the CurrencyExchangeService that are running. The naming service would, in turn, provide the URLs of those instances back to the CurrencyConversionService. \r\n\r\nThis helps establish a dynamic relationship between instances of the communicating microservices. \r\n\r\n#### Load Balancing\r\n\r\nWhen there are multiple instances of same microservice, you want to distribute load between them. One of the options Spring Cloud provides is a client side load balancing framework, Ribbon. \r\n\r\nThe CurrencyCalculationService uses Ribbon and distributes requests across instances of the CurrencyExchangeService. \r\n\r\nThe Feign framework helps us to write simpler RESTful clients. \r\n\r\n### Visibility And Monitoring\r\n\r\nIn Microservices Architectures, You would need to have complete visibility into what's happening in your microservices.\r\n\r\nIn order to trace a request, you need to assign it a unique identifier. Spring Cloud Sleuth helps in assigning an identifier to every request. You can use a distributed tracing solution like Zipkin to trace the request across multiple components. \r\n\r\n### API Gateway\r\n\r\nAll micorservices have a few common features -  security, logging, analytics, and so on. What is best place to implement these common features?\r\n\r\nAn API Gateway provides a great solution to this kind of a challenge. \r\n\r\nThe Netflix Zuul API gateway is a great solution to implement an API Gateway.\r\n\r\n### Fault Tolerance\r\n\r\nWhat if a microservice is down? How do other microservices respond to it?\r\n\r\nHystrix helps in improving fault tolerance of your microservices.\r\n\r\nDo check out our video on this:\r\n\r\n[![image info](/images/Capture-063-01.png)](https://www.youtube.com/watch?v=Lr96QgqylIU)\r\n\r\n### Summary\r\n\r\nIn this article, we had a look at the Spring Cloud project, and saw that it is an umbrella for a wide variety of projects. Each of these solves a particular problem associated with microservices. Important problems include service registration, service discovery, load distribution, event tracing, service monitoring and fault tolerance.\r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-05-10-Microservice-Basics-065-Microservices-SOA-Differences.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Microservices Architectures - Microservices vs SOA\r\ndate:    2019-05-10 12:31:19\r\nsummary: Microservices architectures are very popular today. In this article, we take a look at how microservices architectures are different from Service Oriented Architectures (SOA).\r\ncategories:  SpringBootMicroservices\r\npermalink:  /microservice-architectures-soa-vs-microservices\r\nimage: /images/microservices-category.png\r\n---\r\n\r\nMicroservices architectures are very popular today. In this article, we take a look at how microservices architectures are different from Service Oriented Architectures (SOA).\r\n\r\n\r\n\r\n\r\n### Introduction to Cloud, Microservice - Challenges and Advantages\r\n\r\nThis is the last article in a series of five articles on cloud and microservices:\r\n- [1 - Microservices Architecutres - Quick introduction to Cloud - Why, What and How?](/introduction-to-cloud){:target='_blank'}\r\n- [2 - Microservice Architectures - Introduction to Spring Cloud](/introduction-to-spring-cloud){:target='_blank'}\r\n- [3 - Microservices Architectures - Advantages Of Microservices](/microservice-architectures-advantages-of-microservices){:target='_blank'}\r\n- [4 - Microservice Architectures - Challenges with building Microservices](/microservice-architectures-challenges-with-microservices){:target='_blank'}\r\n- [5 - Microservices Architectures - Microservices vs SOA](/microservice-architectures-soa-vs-microservices){:target='_blank'}\r\n\r\n\r\n### Deployability\r\n\r\nBoth Microservices and Service Oriented Architectures primarily talk about creating small services. \r\n\r\nWhenever we talk of microservices, we refer to small sized services that are also independently deployable.\r\n\r\n![image info](images/Capture-065-02.png)\r\n\r\nFor example, we should be able to release Microservice1 without affecting the behavior of any of the other microservices. We would be able to take such a microservice to production very quickly. \r\n\r\nThe focus of SOA might be on creating independent services, but not exactly independently deployable ones. In SOA, while we focused on API, the deployable units were generally large.\r\n\r\n### Thin Pipes v Enterprise System Bus\r\n\r\nWith the evolution of its architectures, SOA ended up having large Enterprise Service Buses (ESBs). ESBs were introduced to enable loose coupling between SOA components. \r\n\r\n![image info](images/Capture-065-03.png)\r\n\r\nIn order to implement a new feature in an application, changes are needed both on the application logic, as well as in the enterprise bus. \r\n\r\nThe enterprise system bus become a central spoke where a lot of business logic also made its way. Over a period of time, these sucked in a lot of business logic, making the application difficult to maintain. \r\n\r\nMicroservices architectures keep minimum logic in the communication infrastructure - thin pipes.\r\n\r\n### Tied To XML\r\n\r\nSOA was tied to the XML technologies, inheriting its formalities and complexities.\r\n\r\n### Governance\r\n\r\nWith SOA, there is always an centralize architecture team that decides what logic goes into an ESB, and what cannot, among other things.\r\n\r\nOn the other hand, microservices architectures focuses on having decentralized governance.\r\n\r\n### Let's take an example\r\n\r\nConsider a banking application. Along with a savings account, a customer gets a debit card for free. An Insurance Savings Account and a Debit Card are different banking products, managed by different product systems.\r\n\r\n![image info](images/Capture-065-03.png)\r\n\r\n#### SOA\r\n\r\nIn the SOA architecture, the ESB takes the order from the selling application, and handles the communication with the systems that create the appropriate products. \r\n\r\nThe ESB ends up having a lot of business logic, making it top-heavy.\r\n\r\n#### Microservices\r\n\r\nTypical microservices architecture makes use of an event driven architecture. It makes extensive use of a message queue to ensure reliable communication between different microservices, each having it own responsibility. \r\n\r\nThe sales app would create an order event, and put it in the queue. Each of the other services would look at the event, and process it if relevant to them.\r\n\r\nDo check out our video on the same topic:\r\n\r\n[![image info](images/Capture-065-01.png)](https://www.youtube.com/watch?v=Ng79aeXukDE)\r\n\r\n### Summary\r\n\r\nIn this article, we had a look at the differences between microservices architecture and SOA. We  looked at independent deployability, de-centralized governance, and the event based nature of microservices architectures.\r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-05-11-Microservice-Basics-066-Challenges-With-Microservices.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Microservice Architectures - Challenges with building Microservices\r\ndate:    2019-05-11 12:31:19\r\nsummary: Microservices architectures are very popular today. In this article, we discuss the important challenges in developing a microservices architecture.\r\ncategories:  SpringBootMicroservices\r\npermalink:  /microservice-architectures-challenges-with-microservices\r\nimage: /images/microservices-category.png\r\n---\r\n\r\nMicroservices architectures are very popular today. In this article, we discuss the important challenges in developing a microservices architecture.\r\n- Identifying Microservice Boundaries - Implementing Bounded Context\r\n- Having Proper Configuration Management\r\n- Implementing Technology for Dynamic Scale Up And Scale Down\r\n- Ensuring High Visibility\r\n- Ensuring High Fault Tolerance\r\n\r\n\r\n\r\n### Introduction to Cloud, Microservice - Challenges and Advantages\r\n\r\nThis is the fourth article in a series of five articles on cloud and microservices:\r\n- [1 - Microservices Architecutres - Quick introduction to Cloud - Why, What and How?](/introduction-to-cloud){:target='_blank'}\r\n- [2 - Microservice Architectures - Introduction to Spring Cloud](/introduction-to-spring-cloud){:target='_blank'}\r\n- [3 - Microservices Architectures - Advantages Of Microservices](/microservice-architectures-advantages-of-microservices){:target='_blank'}\r\n- [4 - Microservice Architectures - Challenges with building Microservices](/microservice-architectures-challenges-with-microservices){:target='_blank'}\r\n- [5 - Microservices Architectures - Microservices vs SOA](/microservice-architectures-soa-vs-microservices){:target='_blank'}\r\n\r\n\r\n### Identifying Microservice Boundaries - Implementing Bounded Context\r\n\r\nWe are aware that in a microservices architecture, instead of single big monolith application, we build a number of independent microservices talking with each other:\r\n\r\n![image info](images/Capture-066-02.png)\r\n\r\n> An important question one faces while designing such a system is, how do we define the boundaries of individual microservices? \r\n\r\nHow do you decide what one service does, and what it should not do? \r\n\r\nThis is particularly difficult for a new application, as there may not be enough business knowledge to establish the right boundaries. \r\n\r\nThe task of deciding the boundaries of microservices is an evolving process. It is not something you necessarily get right the first time. \r\n\r\nIt often involves using domain driven design while playing around the functionality of the microservices. As you gain design knowledge, you need to put that knowledge back into the microservices architecture.\r\n\r\nThe best practices include following domain driven design.\r\n\r\n### Having Proper Configuration Management\r\n\r\nConfiguration management poses quite a stiff challenge in implementing microservices. \r\n\r\nSuppose that in our system, we have a few microservices, each of which has multiple instances in each environment:\r\n![image info](images/Capture-066-03.png)\r\n\r\nIn a slightly larger system, there could be 10 microservices with 5 environments, and 50 instances at the least. We are talking about tons of configuration  here! \r\n\r\nThis will involve a lot of work for the operations team, just to maintain all these configuration. \r\n\r\nTypically, centralized configuration helps you manage configuration.\r\n\r\n### Implementing Technology for Dynamic Scale Up And Scale Down\r\n\r\nFor a microservices architecture, establishing the technology to do dynamic scaling of infrastructure, is a mountain to scale in itself. \r\n\r\nThe loads on different microservices could be different, at different instances of time:\r\n![image info](images/Capture-066-03.png)\r\n\r\nAt a particular point of time, you may need 2 instances of Microservice2. However at a later point in time, that need may go up to 4. Again, it could shoot up to 10 later. In essence, we need to bring up new instances of a microservices when they are in demand, and bring them down when no longer needed.\r\n\r\nAll this scaling needs to be done with dynamic load balancing. At the point of time shown in the diagram, the load from Microservice1 needs to be distributed among the 4 instances of Microservice2. Later, when there are 10 instances of Microservice2, there needs to be another load redistribution among those 10 instances. \r\n\r\nBuilding an architecture for this involves a number of technical components - Naming Server, Load Balancers, Monitoring tools to identify whether to scale in or scale out.\r\n\r\n### Ensuring High Visibility \r\n\r\nEnsuring visibility is one of the most important challenges that needs to be addressed. \r\n\r\n![image info](images/Capture-066-02.png)\r\n\r\nIf we say that the functionality of the above system needs to be distributed among 10 microservices, but there is a bug, how do you identify where the bug is? There is clearly a need for a centralized log, where we need to find out what happened with a specific request.\r\n\r\nWe also need to have effective monitoring across the microservices.\r\n\r\n### Ensuring High Fault Tolerance\r\n\r\nIf not well designed, a microservices architecture can behave like a pack of cards. A microservice at the end of such a chain would be fundamental to the system behaving well.\r\n\r\nTherefore, it is very important for you to have sufficient fault tolerance in place, in your system. \r\n\r\nDo check out our video on the same topic:\r\n\r\n[![image info](images/Capture-066-01.png)](https://www.youtube.com/watch?v=KGYpmVlIkIw)\r\n\r\n### Summary\r\n\r\nIn this article, we looked at the various challenges that need to be addressed, while designing a microservices architecture. We covered areas such as bounded context, configuration management, dynamic scale up and scale down, visibility and fault tolerance.\r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-05-12-Microservice-Basics-067-Advantages-Of-Microservices.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Microservices Architectures - Advantages Of Microservices\r\ndate:    2019-05-12 12:31:19\r\nsummary: Microservices architectures are very popular today. In this article, we discuss the three main advantages of having a microservices architecture.\r\ncategories:  SpringBootMicroservices\r\npermalink:  /microservice-architectures-advantages-of-microservices\r\nimage: /images/microservices-category.png\r\n---\r\n\r\nMicroservices architectures are very popular today. In this article, we discuss the three main advantages of having a microservices architecture.\r\n- New Technology And Process Adoption\r\n- Dynamic Scaling Up And Down\r\n- Faster Release Cycles\r\n\r\n\r\n\r\n### Introduction to Cloud, Microservice - Challenges and Advantages\r\n\r\nThis is the third article in a series of five articles on cloud and microservices:\r\n- [1 - Microservices Architecutres - Quick introduction to Cloud - Why, What and How?](/introduction-to-cloud){:target='_blank'}\r\n- [2 - Microservice Architectures - Introduction to Spring Cloud](/introduction-to-spring-cloud){:target='_blank'}\r\n- [3 - Microservices Architectures - Advantages Of Microservices](/microservice-architectures-advantages-of-microservices){:target='_blank'}\r\n- [4 - Microservice Architectures - Challenges with building Microservices](/microservice-architectures-challenges-with-microservices){:target='_blank'}\r\n- [5 - Microservices Architectures - Microservices vs SOA](/microservice-architectures-soa-vs-microservices){:target='_blank'}\r\n\r\n\r\n### Increased Technology Innovation due to New Technology And Process Adoption\r\n\r\nA microservices architecture enables you to adopt new technology, and technical processes into your system.\r\n\r\n![image info](images/Capture-067-02.png)\r\n\r\nMicroservices usually communicate with each other using simple messages. Each of these can then be built using different technologies. \r\n\r\nFor instance, it is possible to have Microservice1 written in Java, Microservice2 in NodeJS and Microservice3 in Kotlin.\r\n\r\nTomorrow, there may be a new language XYZ that is well suited for your application, and it could be used to write a new microservice for you.  \r\n\r\nIn a typical monolith application, we would have no such flexibility.  \r\n\r\n> In addition to this, we can bring in new processes - for development, testing and deployment - for the new microservices that we create. \r\n\r\n### Reduced Costs due to Dynamic Scaling Up And Down\r\n\r\nConsider a large online shopping application, such as Amazon. They do not have the same number of users or amount of load, throughout the year. Usually, there is a lot of activity with the application during the holiday season, and not much at other times of the year. If your microservices are cloud enabled, they can scale dynamically. \r\n\r\nThis means there is no need to statically provision infrastructure to a fixed quantity for the entire year. \r\n\r\n> Infrastructure can be provisioned based on the load.\r\n\r\n### Increased Business Innovation due to Faster Release Cycles\r\n\r\nSince you are developing your application in smaller components, its much easier to release microservices as compared to monolith applications. This means you can bring new features, faster to market. That's a big advantage to have in the modern competitive business world.   \r\n\r\n### Summary\r\n\r\nIn this article, we had a discussion about the advantages of microservices. We had a look at plus areas such as technology and process adoption, dynamic scaling and faster release cycles.  \r\n\r\nDo check out our video on the same topic:\r\n\r\n[![image info](images/Capture-067-01.png)](https://www.youtube.com/watch?v=nfLll9Ep9DI)\r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-05-19-Microservice-Terminology-051-Why-Service-Discovery-With-Eureka.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Microservices Architectures - What is Service Discovery?\r\ndate:    2019-05-19 12:31:19\r\nsummary:  In this article, we talk about Service Discovery. Why is Service Discovery important in microservices architecture, and how to set it up for your application.\r\ncategories:  SpringBoot\r\npermalink:  /service-discovery-in-microservices\r\nimage: /images/microservices-category.png\r\n---\r\n\r\nIn this article, we talk about Service Discovery. Why is it important in microservices architecture, and how to set it up for your application?\r\n\r\n### What you will learn\r\n- What is Service Discovery?\r\n- Why is Service Discovery important in microservices architecture?\r\n- How do you implement Service Discovery?\r\n- What is Eureka?\r\n\r\n\r\n### Cloud and Microservices Terminology\r\n\r\nThis is the first article in a series of six articles on terminology used with cloud and microservices:\r\n- [1 - Microservices Architectures - What is Service Discovery?](/service-discovery-in-microservices){:target='_blank'}\r\n- [2 - Microservices Architectures - Centralized Configuration and Config Server](/introduction-to-centralized-configuration-with-spring-cloud-config-server){:target='_blank'}\r\n- [3 - Microservices Architectures - API Gateways](/introduction-to-api-gateways-with-microservices){:target='_blank'}\r\n- [4 - Microservices Architectures - Importance of Centralized Logging](/introduction-to-centralized-logging-with-microservices){:target='_blank'}\r\n- [5 - Microservices Architectures - Introduction to Auto Scaling](/introduction-to-auto-scaling-or-dynamic-scaling-in-cloud){:target='_blank'}\r\n- [6 - Microservices Architectures - What is Fault Tolerance?](/fault-tolerance-in-microservices){:target='_blank'}\r\n\r\n\r\n### What Is Service Discovery?\r\n\r\nWhen we talk about a microservices architecture, we refer to a system with a large number of small services, working with each other:\r\n\r\n![image info](/images/Capture-051-02.png)\r\n\r\nAn important feature of such architectures is **auto-scaling**. The number of instances of a microservice varies based on the system load. Initially, you could have 5 instances of Microservice5, which go up later to 20, 100 or 1000!  \r\n\r\nTwo important questions arise\r\n- How does Microservice4 know how many instances of Microservice5 are present, at a given time? \r\n- In addition, how does it distribute the load among all of them?\r\n\r\n#### Hardcoding URLs is not an Option\r\n\r\nOne way to do this is to hard-code the URLs of Microservice5 instances, within Microservice4. That means every time the number of Microservice5 instances changes (with addition of new, or deletion of existing), the configuration within Microservice4 needs to change. This is a big headache.\r\n\r\n#### Using Service Discovery\r\n\r\nIdeally, you want to change the number of instances of Microservice5 based on the load, and make Microservice4 dynamically aware of the instances. \r\n\r\nThat's where the concept of **Service Discovery** comes into the picture. \r\n\r\nThe component that provides this service is generally called a **naming server**. \r\n\r\nAll instances of all the microservices, register themselves with the naming server. Whenever a microservice wants to talk to another microservices, it asks the naming server about the available instances.\r\n\r\nIn the example above, whenever a new instance of Microservice5 is launched, it registers with the naming server. When Microservice4 wants to talk to Microservice5, it asks the naming server - what are the available instances of Microservice5?\r\n\r\n\r\n### Another example of Service Discovery\r\n\r\nUsing Service Discovery to identify microservice instances, helps keep things dynamic. \r\n\r\nLet's say there is a service for currency conversion:\r\n\r\n![image info](/images/Capture-051-03.png)\r\n\r\nThe CurrencyConversionService (CCS) talks to the ForexService. At a certain point of time, these services have two instances each: \r\n\r\n![image info](/images/Capture-051-04.png)   \r\n\r\nHowever, there could be a time where there are 5 instances of the ForexService (FS): \r\n\r\n![image info](/images/Capture-051-05.png)\r\n\r\nIn that case, CurrencyConversionService needs to make sure that the load is evenly distributed across all the ForexService instances. It needs to answer two important questions:\r\n\r\n* How does the CurrencyConversionService know how many instances of ForexService are active?\r\n* How does the CurrencyConversionService distribute the load among those active instances?\r\n\r\n![image info](/images/Capture-051-06.png)\r\n\r\nWhen a CCS microservice instance is brought up, it registers with Eureka. The same thing happens with all instances of FS as well. \r\n\r\nWhen a CCS instance needs to talk to a FS instance, it requests information from Eureka. Eureka would then return the URLS of the two FS instances active at that time. Here, the application makes use of a client-side load distribution framework called Ribbon. Ribbon ensures proper load distribution over the two FS instances, for events coming in from the CCS.\r\n\r\nDo check out our video on this:\r\n\r\n[![image info](/images/Capture-051-01.png)](https://www.youtube.com/watch?v=T36Usw_QbP0)\r\n\r\n### Summary\r\n\r\nIn this video, we talked about microservice Service Discovery. We saw that microservices need to be able to communicate with each other. The number of instances of a microservice changes over time, depending on the load. Service Discovery enables us to dynamically adapt to new instances and distribute load among microservices.\r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-05-19-Microservice-Terminology-058-Centralized-Configuration.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Microservices Architectures - Centralized Configuration and Config Server\r\ndate:    2019-05-19 12:31:19\r\nsummary:  In this article, we explore the concept of centralized configuration, in the context of microservices. \r\ncategories:  SpringBootMicroservices\r\npermalink:  /introduction-to-centralized-configuration-with-spring-cloud-config-server\r\nimage: /images/microservices-category.png\r\n---\r\n\r\nIn this article, we explore the concept of centralized configuration, in the context of microservices. \r\n\r\n### You will learn\r\n- What is a Cloud config server?\r\n- What is centralized configuration?\r\n- Why do we need centralized configuration in microservices architectures?\r\n- What are the important features of Spring Cloud Config Server?\r\n\r\n\r\n\r\n### Cloud and Microservices Terminology\r\n\r\nThis is the second article in a series of six articles on terminology used with cloud and microservices:\r\n- [1 - Microservices Architectures - What is Service Discovery?](/service-discovery-in-microservices){:target='_blank'}\r\n- [2 - Microservices Architectures - Centralized Configuration and Config Server](/introduction-to-centralized-configuration-with-spring-cloud-config-server){:target='_blank'}\r\n- [3 - Microservices Architectures - API Gateways](/introduction-to-api-gateways-with-microservices){:target='_blank'}\r\n- [4 - Microservices Architectures - Importance of Centralized Logging](/introduction-to-centralized-logging-with-microservices){:target='_blank'}\r\n- [5 - Microservices Architectures - Introduction to Auto Scaling](/introduction-to-auto-scaling-or-dynamic-scaling-in-cloud){:target='_blank'}\r\n- [6 - Microservices Architectures - What is Fault Tolerance?](/fault-tolerance-in-microservices){:target='_blank'}\r\n\r\n\r\n### Why Centralized Configuration?\r\n\r\nWhen we talk about microservices architecture, we visualize a large number of small microservices talking to each other. The number of microservices depends on the size of the enterprise. \r\n\r\n[![image info](/images/Capture-058-03.png)\r\n\r\nThe  interesting part is that each of these microservices can have its own configuration. \r\n\r\nSuch configuration includes details such as:\r\n* Application configuration\r\n* Database configuration\r\n* Communication Channel Configuration - queues and other infrastructure\r\n* URLs of other microservices to talk to\r\n\r\nIn addition, each microservice would have a separate configuration for different environments, such as development, qa and production. \r\n\r\n> If maintaining a single configuration for a large application is difficult, imagine maintaining configurations for hundreds of microservice in different environments\r\n\r\n### Centralized Config Server To The Rescue\r\n\r\nThat's where a centralized configuration server steps in. \r\n\r\nConfiguration for all microservices (for all environments) is stored at one place - a centralized configuration store. \r\n\r\nWhen a microservice needs its configuration, it provides an id at launch - a combination of microservice name and the environment. \r\n\r\nThe centralize config server looks up the configuration and provides the configuration to the microservice.\r\n\r\n> Ensure that the configuration in centralized config server is secured and has role based access.\r\n\r\n### Introducing Spring Cloud Config Server\r\n\r\nSpring Cloud Config Server is one of the popular implementations of a cloud config server.\r\n\r\nSpring Cloud Config Server enables you to store all the configuration for multiple microservices for different environments in a Git or a SVN Repository. A set of folder structures and conventions need to be followed for the setup to work.\r\n\r\n![image info](/images/Capture-058-02.png)\r\n\r\nA microservice can connect to the config server and identify itself, and also specify the instance it represents. This enables it to get the required configuration. \r\n\r\nThe setup ensures that the operations team does not need to take time out to configure the individual microservices on a case-by-case basis. All that they need to worry about is to configure the centralized config server, and start putting relevant configuration into the Git repository.\r\n\r\n#### Automatically picking up configuration changes\r\n\r\nAn interesting feature present with the Spring Cloud Config Server, is auto refresh. \r\n\r\nWhenever a change is committed to the Git repository, configuration in the application is auto-refreshed.\r\n\r\nDo check out our video on this:\r\n\r\n[![image info](/images/Capture-058-01.png)](https://www.youtube.com/watch?v=IsAzbA-IM98)\r\n\r\n### Summary\r\n\r\nIn this article, we looked at why we need centralized configuration in microservices based applications. We looked at how the Spring Cloud Config Server manages centralized configuration.\r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-05-20-Microservice-Terminology-059-API-Gateway.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Microservices Architectures - Introduction to API Gateway\r\ndate:    2019-05-20 12:31:19\r\nsummary:  In this article, we look at what an API Gateway is, in the context of microservices.\r\ncategories:  SpringBootMicroservices\r\npermalink:  /introduction-to-api-gateways-with-microservices\r\nimage: /images/microservices-category.png\r\n---\r\n\r\nIn this article, we look at what an API Gateway is, in the context of microservices.\r\n\r\n## You will learn\r\n- What is an API Gateway?\r\n- Why do we need API Gateways?\r\n- How does an API Gateway Work?\r\n\r\n\r\n\r\n### Cloud and Microservices Terminology\r\n\r\nThis is the third article in a series of six articles on terminology used with cloud and microservices:\r\n- [1 - Microservices Architectures - What is Service Discovery?](/service-discovery-in-microservices){:target='_blank'}\r\n- [2 - Microservices Architectures - Centralized Configuration and Config Server](/introduction-to-centralized-configuration-with-spring-cloud-config-server){:target='_blank'}\r\n- [3 - Microservices Architectures - API Gateways](/introduction-to-api-gateways-with-microservices){:target='_blank'}\r\n- [4 - Microservices Architectures - Importance of Centralized Logging](/introduction-to-centralized-logging-with-microservices){:target='_blank'}\r\n- [5 - Microservices Architectures - Introduction to Auto Scaling](/introduction-to-auto-scaling-or-dynamic-scaling-in-cloud){:target='_blank'}\r\n- [6 - Microservices Architectures - What is Fault Tolerance?](/fault-tolerance-in-microservices){:target='_blank'}\r\n\r\n\r\n### Handling Cross Cutting Concerns\r\n\r\nWhenever we design and develop a large software application, we make use of  a **layered architecture**. For instance, in a web application, it is quite common to see an architecture similar to the following:\r\n\r\n![image info](/images/Capture-02-01.png)\r\n\r\nHere, we see that the application is organized into a Web layer, a Business layer, and a Data layer. \r\n\r\nIn a layered architecture, there are specific parts that are common to all these different layers. Such parts include:\r\n* Logging\r\n* Security\r\n* Performance\r\n* Auditing\r\n\r\nAll these features are applicable across layers, hence it makes sense to implement them in a common way. \r\n\r\nAspect Oriented programming is a well established way of handling these concerns. Use of constructs such as filters and interceptors is common while implementing them.\r\n\r\n### The Need For API Gateway\r\n\r\nWhen we talk about a microservices architecture, we deal with multiple microservices talking to each other:\r\n![image info](/images/Capture-059-02.png)\r\n\r\nWhere do you implement all the features that are common across microservices?\r\n- authentication\r\n- logging\r\n- auditing\r\n- rate limiting\r\n\r\nThat's where the API Gateway comes into the picture.\r\n\r\n### How does an API Gateway Work?\r\n\r\nIn microservices, we route all requests - both internal and external - through API Gateways. We can implement all the common features like authentication, logging, auditing, and rate limiting in the API Gateway. \r\n\r\nFor example, you may not want Microservice3 to be called more than 10 times by a particular client. You could do that as part of rate limiting in the API gateway.\r\n\r\nYou can implement the common features across microservices in the API gateway. A popular API Gateway implementation is Zuul API Gateway.\r\n\r\nDo check out our video on this:\r\n\r\n[![image info](/images/Capture-059-01.png)](https://www.youtube.com/watch?v=rg7Xkdur-vc)\r\n\r\n### Summary\r\n\r\nJust like AOP handles cross cutting concerns in standalone applications, the API gateway manages common features for microservices in an enterprise. \r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-05-21-Microservice-Terminology-057-Centralized-Logging-In-Microservices.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Microservices Architectures - Importance of Centralized Logging\r\ndate:   2019-05-21 12:31:19\r\nsummary: In this article, we explore the concept of centralized logging, in the context of microservices. \r\ncategories:  SpringBootMicroservices\r\npermalink: /introduction-to-centralized-logging-with-microservices\r\nimage: /images/microservices-category.png\r\n---\r\n\r\nIn this article, we explore the concept of centralized logging, with respect to microservices.\r\n\r\n### You will learn\r\n- What is centralized logging?\r\n- Why do we need centralized logging?\r\n- Why are microservices difficult to debug?\r\n\r\n\r\n\r\n### Cloud and Microservices Terminology\r\n\r\nThis is the fourth article in a series of six articles on terminology used with cloud and microservices:\r\n- [1 - Microservices Architectures - What is Service Discovery?](/service-discovery-in-microservices){:target='_blank'}\r\n- [2 - Microservices Architectures - Centralized Configuration and Config Server](/introduction-to-centralized-configuration-with-spring-cloud-config-server){:target='_blank'}\r\n- [3 - Microservices Architectures - API Gateways](/introduction-to-api-gateways-with-microservices){:target='_blank'}\r\n- [4 - Microservices Architectures - Importance of Centralized Logging](/introduction-to-centralized-logging-with-microservices){:target='_blank'}\r\n- [5 - Microservices Architectures - Introduction to Auto Scaling](/introduction-to-auto-scaling-or-dynamic-scaling-in-cloud){:target='_blank'}\r\n- [6 - Microservices Architectures - What is Fault Tolerance?](/fault-tolerance-in-microservices){:target='_blank'}\r\n\r\n\r\n### The Need For Visibility\r\n\r\nIn a microservices architecture, there are a number of small microservices talking to each other:\r\n\r\n![image info](/images/Capture-057-02.png)\r\n\r\nIn the above example, let's assume there is a problem with Microservice5, due to which Microservice1 throws an error. \r\n\r\nHow does a developer debug the problem?\r\n\r\nHe would like to know the details of what's happening in every microservice from Microservice1 through Microservice5. From such a trace, it should be possible to identify that something went wrong at Microservice5.\r\n\r\nThe more you break things down into smaller microservices, the more visibility you need into what's going on in the background. Otherwise, a lot of time and effort needs to be spent in debugging problems. \r\n\r\nOne of the popular ways to improve visibility is by using **centralized logging**. \r\n\r\n### Centralized Logging Using Log Streams\r\n\r\nUsing Log Streams is one way to implement centralized logging. The common way to implement it is to stream microservice logs to a common queue. Distributed logging server listens to the queue and acts as log store. It provides search capabilities to search the trace.\r\n\r\n### Popular Implementations\r\n\r\nSome of the popular implementations include \r\n- the ELK stack (Elastic Search, Logstash and Kibana) for Centralized Logging\r\n- Zipkin, Open Tracing API And Zaeger for Distributed Tracing\r\n\r\nDo check out our video on this:\r\n\r\n[![image info](/images/Capture-057-01.png)](https://www.youtube.com/watch?v=rxTNUw0wp-U)\r\n\r\n### Summary\r\n\r\nIn this article, we had a look at centralized logging. We saw that there is a need for high visibility in microservices architecture. Centralized logging provides visibility for better debugging of problems. Using log streams is one way of implementing centralized logging.\r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-05-22-Microservice-Terminology-055-Dynamic-Scaling.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Microservices Architectures - Introduction to Auto Scaling\r\ndate:    2019-05-22 12:31:19\r\nsummary:  In this article, we focus our attention on the Dynamic Scaling or Auto Scaling. Why do we need applications that can auto scale?\r\ncategories:  SpringBootMicroservices\r\npermalink:  /introduction-to-auto-scaling-or-dynamic-scaling-in-cloud\r\nimage: /images/microservices-category.png\r\n---\r\n\r\nIn this article, we focus our attention on the Dynamic Scaling or Auto Scaling. Why do we need applications that can auto scale?\r\n\r\n## You will learn\r\n- What is Auto or Dynamic Scaling?\r\n- Why is Dynamic Scaling important in a microservices context?\r\n- How can you implement Dynamic Scaling in Cloud?\r\n\r\n\r\n\r\n### Cloud and Microservices Terminology\r\n\r\nThis is the fifth article in a series of six articles on terminology used with cloud and microservices:\r\n- [1 - Microservices Architectures - What is Service Discovery?](/service-discovery-in-microservices){:target='_blank'}\r\n- [2 - Microservices Architectures - Centralized Configuration and Config Server](/introduction-to-centralized-configuration-with-spring-cloud-config-server){:target='_blank'}\r\n- [3 - Microservices Architectures - API Gateways](/introduction-to-api-gateways-with-microservices){:target='_blank'}\r\n- [4 - Microservices Architectures - Importance of Centralized Logging](/introduction-to-centralized-logging-with-microservices){:target='_blank'}\r\n- [5 - Microservices Architectures - Introduction to Auto Scaling](/introduction-to-auto-scaling-or-dynamic-scaling-in-cloud){:target='_blank'}\r\n- [6 - Microservices Architectures - What is Fault Tolerance?](/fault-tolerance-in-microservices){:target='_blank'}\r\n\r\n\r\n\r\n### Load On Applications Varies\r\n\r\nLoad on your applications vary depending on time of the day, the day of the month or the month of the year. \r\n\r\nTake for instance, amazon.com. It has very high loads during Thanks Giving Period, up to 20 times the normal load. However, during the major sports events such as Superbowl or a Football World Cup, the traffic could be considerably lesser - because every body is busy watching the event.\r\n\r\n> How can you setup infrastructure for applications to manage varying loads? \r\n\r\nIt is quite possible that the infrastructure needed to handle 10x the load, is ten times that needed to handle 1x the load. \r\n\r\nIf you have on premise infrastructure, you need a large infrastructure in place to handle peak load. \r\n\r\nDuring periods with lesser load, a lot of infrastructure would be sitting idle.\r\n\r\n### Cloud To The Rescue\r\n\r\nThat's where cloud comes into picture.  With cloud, you can request more resources when the load is high and give them back to the cloud when you have less load.\r\n\r\n> This is called Scale Out (create more instances as load increases) and Scale In (reduces instances as load goes down)\r\n\r\nHow do you build applications that are cloud enabled - applications that work well in the cloud?\r\n\r\nThat's where a microservices architecture comes into picture.\r\n\r\n### Introducing Auto Scaling Example\r\n\r\nBuilding your application using microservices enables you to increase the number of microservice instances during high load, and reduce them during less load. \r\n\r\nConsider the following example of a CurrencyConversionService:\r\n\r\n![image info](/images/Capture-055-02.png)\r\n\r\n![image info](/images/Capture-055-03.png)\r\n\r\nThe CurrencyConversionService talks to the ForexService. The ForexService is concerned with calculating how many INR can result from 1 USD, or how many INR can result from 1 EUR. \r\n\r\nThe CurrencyConversionService takes a bag of currencies and amounts, and produce the total amount in a currency of your choice. For example, it will tell the total worth in INR of 10 EUR and 25 USD. \r\n\r\nThe ForexService might also be consumed from a number of other microservices.\r\n\r\n#### Scaling Infrastructure To Match Load\r\n\r\nThe load on ForexService might be different from the load on CurrencyConversionService. You might need to have different number of instances of CurrencyConversionService and ForexService. For example, there may be two instances of the CurrencyConversionService, and five instances of the ForexService:  \r\n\r\n![image info](/images/Capture-055-04.png)\r\n\r\n![image info](/images/Capture-055-05.png)\r\n\r\nAt a later point in time, the load on CurrencyConversionService could be low, needing just two instances. On the other hand, a much higher load on ForexService could need 50 instances. The requests coming in from the 2 instances of CurrencyConversionService are distributed across the 50 instances of the ForexService. \r\n\r\nThat in essence, is the requirement for auto scaling - dynamically changing number of microservice instances, and evenly distributing the load across them.\r\n\r\n### Implementing Auto Scaling\r\n\r\nThere are a few important concepts involved in implementing auto scaling. The following sections discuss them in some detail.\r\n\r\n#### Naming Server\r\n\r\nNaming servers enables something called **location transparency**. Every microservice registers with the naming service. Any microservice that needs to talk to another microservice, will ask the naming server for its location. \r\n\r\nWhenever a new instance of CurrencyConversionService or ForexService comes up, it registers with the naming server. \r\n![image info](/images/Capture-055-06.png)\r\n\r\nWhen CurrencyConversionService wants to talk to ForexService, it asks the naming server for available instances.\r\n\r\n\r\n### Implementing Location Transparency\r\n\r\nCurrencyConversionService knows that there are five instances of the ForexService.\r\n\r\n> How does it distribute the load among all these instances?\r\n\r\nThat's where a load balancer comes into the picture. \r\n\r\nA popular client side load balancing framework is Ribbon.\r\n![image info](/images/Capture-055-07.png)\r\n\r\nLet's look at a diagram to understand whats happening:\r\n\r\n![image info](/images/Capture-055-08.png)\r\n\r\nAs soon as any instance of CurrencyConversionService or ForexService comes up, it registers itself with the naming server. If the CCSInstance2 wants to know the URL of ForexService instances, it again talks to the naming server. The naming server responds with a list of all instances of the ForexService - FSInstance1 and FSinstance2, and their corresponding URLs. \r\n\r\nThe Ribbon load balancer does a round-robin among the ForexService instances to balance out the load among the instances. \r\n\r\n> Ribbon offers wide variety of load balancing algorithms to choose from.\r\n\r\n### When to increase and decrease instances?\r\n\r\nThere is one question we did not really talk about.\r\n\r\nHow do we know when to increase or decrease the number of instances of a microservices?\r\n\r\nThat is where application monitoring and container (Docker) management (using Kubernetes) comes into the picture.\r\n\r\n![image info](/images/Capture-055-09.png)\r\n\r\nAn application needs to be monitored to find out how much load it has. For this, the application has to expose metrics for us to track the load. \r\n\r\nYou can containerize each microservice using Docker and create an image. \r\n\r\nKubernetes has the capability to manage containers. Kubernetes can configured to auto scale based on the load. Kubernetes can identify the application instances, monitor their loads, and automatically scale up and down.\r\n\r\nDo check out our video on this:\r\n\r\n[![image info](/images/Capture-055-01.png)](https://www.youtube.com/watch?v=rxTNUw0wp-U)\r\n\r\n### Summary\r\n\r\nIn this article, we talked about auto scaling. We look at important parts of implementing auto scaling - naming server, load balancer, containers (Docker) and container orchestration (Kubernetes).\r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-05-23-Microservice-Terminology-053-Fault-Tolerance.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Microservices Architectures - What is Fault Tolerance?\r\ndate:    2019-05-23 12:31:19\r\nsummary:  In this article, we discuss an important property of microservices, called fault tolerance\r\ncategories:  SpringBootMicroservices\r\npermalink:  /fault-tolerance-in-microservices\r\nimage: /images/microservices-category.png\r\n---\r\n\r\nIn this article, we discuss an important property of microservices, called fault tolerance.\r\n\r\n## You will learn\r\n\r\n- What is Fault Tolerance?\r\n- Why is fault tolerance important in microservices architecture?\r\n- How do you achieve fault tolerance?\r\n\r\n\r\n\r\n### Cloud and Microservices Terminology\r\n\r\nThis is the last article in a series of six articles on terminology used with cloud and microservices:\r\n- [1 - Microservices Architectures - What is Service Discovery?](/service-discovery-in-microservices){:target='_blank'}\r\n- [2 - Microservices Architectures - Centralized Configuration and Config Server](/introduction-to-centralized-configuration-with-spring-cloud-config-server){:target='_blank'}\r\n- [3 - Microservices Architectures - API Gateways](/introduction-to-api-gateways-with-microservices){:target='_blank'}\r\n- [4 - Microservices Architectures - Importance of Centralized Logging](/introduction-to-centralized-logging-with-microservices){:target='_blank'}\r\n- [5 - Microservices Architectures - Introduction to Auto Scaling](/introduction-to-auto-scaling-or-dynamic-scaling-in-cloud){:target='_blank'}\r\n- [6 - Microservices Architectures - What is Fault Tolerance?](/fault-tolerance-in-microservices){:target='_blank'}\r\n\r\n\r\n### What Is Fault Tolerance?\r\n\r\nMicroservices need to be extremely reliable. \r\n\r\nWhen we build a microservices architecture, there are a large number of small microservices, and they all need to communicate with one another. \r\n\r\nLets consider the following example:\r\n\r\n![image info](/images/Capture-053-02.png)\r\n\r\nLet's say Microservice5 is down at some point of time. \r\n\r\nAll the other microservices are directly or indirectly dependent on it, so they all go down as well.\r\n\r\nThe solution to this problem is to have a fallback in case of failure of a microservice. This aspect of a microservice is called **fault tolerance**.\r\n\r\n### Implementing Fault Tolerance with Hystrix\r\n\r\nA popular framework used to implement fault tolerance is Hystrix, a Netflix open source framework. Here is a code example of the same:\r\n\r\n```java\r\n\r\n\t@GetMapping(\"/fault-tolerance-example\")\r\n\t@HystrixCommand(fallbackMethod=\"fallbackRetrieveConfguration\")\r\n\tpublic LimitConfiguration retrieveConfiguration() {\r\n\t\tthrow new RuntimeException(\"Not Available\");\r\n\t}\r\n\r\n\tpublic LimitConfiguration fallbackRetrieveConfiguration() {\r\n\t\treturn new LimitConfiguration(999, 9);\r\n\t} \r\n\r\n```\r\n\r\nHystrix enables you to specify the fallback method for each of your service methods. If the method throws an exception, what should be returned to the service consumer? \r\n\r\nHere, if ```retrieveConfiguration()``` fails, then ```fallbackRetrieveConfiguration``` is called, which returns a hardcoded ```LimitConfiguration``` instance:\r\n\r\n![image info](/images/Capture-053-03.png)\r\n\r\n\r\n#### Hystrix And Alerts\r\n\r\nWith Hystrix, you can also configure alerts at the back-end. If a service starts failing continuously, you can send alerts to the maintainance team.\r\n\r\n### Hystrix is not a silver bullet\r\n\r\nUsing Hystrix and fallback methods is appropriate for services that handle non critical information. \r\n\r\nHowever, it is not a silver bullet.\r\n\r\nConsider for instance, a service that returns the balance of a bank  account. You cannot provide a default hardcoded value back. \r\n\r\n### Using sufficient redundancy\r\n\r\nIt is important to design critical services in a fail safe manner. It is important to build enough redundancy into the system to ensure that the services do not fail.\r\n\r\n### Have sufficient testing\r\n\r\nIt is important to test for failure. Bring a microservice down. See how your system reacts. \r\n\r\nChaos Monkey is a good example from Netflix.\r\n\r\nDo check out our video on this:\r\n\r\n[![image info](/images/Capture-053-01.png)](https://www.youtube.com/watch?v=7qlQlvnQsuU)\r\n\r\n### Summary\r\n\r\nIn this article, we discussed about fault tolerance. We saw how fault tolerance is essential in microservices architecture. We then saw how it can be implemented at the code level using frameworks such as Hystrix.\r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-06-12-Microservice-Best-Practices-037-Vertical-Slice.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Microservice Best Practice - Why do you build a Vertical Slice?\r\ndate:    2019-06-09 12:31:19\r\nsummary:  In this article, we look at what is a vertical slice, and why we build it. We also discuss the best practices involved in building vertical slices.\r\ncategories:  SpringBootMicroservices\r\npermalink:  /software-best-practices-building-a-vertical-slice\r\nimage: /images/microservices-category.png\r\n---\r\nIn this article, we look at what is a vertical slice, and why we build it. We also discuss the best practices involved in building vertical slices.\r\n\r\n### What you will learn\r\n- What is an vertical slice?\r\n- When do you build a vertical slice?\r\n- What are the advantages in building a vertical slice?\r\n- What are the best practices in building a vertical slice?\r\n\r\n\r\n\r\n### Best Practices with Cloud and Microservices\r\n\r\nThis is the third article in a series of six articles on best practices with cloud and microservices:\r\n- [1 - The 12 Factor App - Best Practices In Cloud Native Applications and Microservices](/12-factor-app-cloud-native-microservices-best-practices){:target='_blank'}\r\n- [2 - Microservices Architectures - Event Driven Approach](/introduction-to-event-driven-architectures-with-microservices){:target='_blank'}\r\n- [3 - Microservice Best Practice - Why do you build a Vertical Slice?](/software-best-practices-building-a-vertical-slice){:target='_blank'}\r\n- [4 - Microservice Architecture Best Practices - Messaging Queues](/messaging-queues-and-asynchronous-communication-in-microservices){:target='_blank'}\r\n- [5 - Microservice Best Practice - Build an Archetype](/creating-archetypes-in-microservices-architectures-best-practices){:target='_blank'}\r\n- [6 - Asynchronous communication with queues and microservices - A perfect combination?](/asynchronous-communication-with-queues-in-microservices){:target='_blank'}\r\n\r\n\r\n### Need For A Vertical Slice\r\n\r\nLet's say you want to start off writing a new microservice, or developing any new application. There are several technical risks that need to be addressed , such as deciding what framework to use, identifying the layers of the architecture, figuring out communication with other systems, and so on. \r\n\r\nYou want to make sure you have great unit tests in place, and also have a good continuous integration and deployment system to process the builds.\r\n\r\nHow do we address these challenges?\r\n\r\n### What Is A Vertical Slice?\r\n\r\nA vertical slice involves selecting one or more of the complex or risky use cases of the systems, and implementing them first. \r\n\r\nTypically, this involves addressing all the risks listed above - selecting the right framework, organizing into layers, handling communication properly, having great tests in place, and following a CI/CD process. \r\n\r\nYou will also deploy and test it to make sure all requirements are met.\r\n\r\n### Benefits Of A Vertical Slice\r\n\r\nA vertical slice will help you identify and solve technology risk faster. Once a vertical slice is built well, adhering to coding and other standards, it could also act as a reference point for other developers in your team.\r\n\r\n### Best Practices\r\n\r\nLets quickly look at a few best practices around building vertical slices:\r\n\r\n#### Ensure Static Analysis\r\n\r\nMake sure that a tool to perform static analysis of your code is in place during the development of the vertical slice. Also make sure development adheres to all relevant best practices.\r\n\r\n#### Ensure Continuous Integration\r\n\r\nIt is very important you have a continuous integration process in place, to take the vertical slice build through development, QA, staging and deployment.\r\n\r\n#### Address Technical Training Issues\r\n\r\nIf the vertical slice is well implemented, it acts as a good reference point. This means that the development team can be trained using the vertical slice as a case study. \r\n\r\n### Challenges\r\n\r\nIt is very important that care be shown in selecting the use case for your vertical slice. Make sure that you choose a sufficiently complex use case, because you need to explore how the various technical risks will be addressed.\r\n\r\nDo check out our video on this:\r\n\r\n[![image info](/images/Capture-037-01.png)](https://www.youtube.com/watch?v=fk4itQzBsEE)\r\n\r\n### Summary\r\n\r\nIn this article, we had a look at what are the technical risks involved in starting application development. We then saw how creating a vertical slice, using a complex use case, helps in exploring solutions to these risks, and acts as a reference point for the development team. We explored the best practices for creating a vertical slice, and looked at the challenges involved. \r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-06-12-Microservice-Best-Practices-046-Why-Asynchronous-Communication.md",
    "content": "---\r\nlayout:  post\r\ntitle: Asynchronous communication with queues and microservices - A perfect combination?\r\ndate:    2019-06-12 12:31:19\r\nsummary:  In this article, we throw some light on what asynchronous messaging is all about and discuss why you should consider it for your microservices architectures.\r\ncategories:  SpringBootMicroservices\r\npermalink:  /asynchronous-communication-with-queues-in-microservices\r\nimage: /images/microservices-category.png\r\n---\r\n\r\nIn this article, we throw some light on what asynchronous messaging is all about and discuss why you should consider it for your microservices architectures.\r\n\r\n### What you will learn\r\n- What is Asynchronous Communication?\r\n- Why Do We Need Asynchronous Communication?\r\n- How is Asynchronous Communication implemented?\r\n- Why should you consider using Asynchronous Communication for your microservices?\r\n\r\n\r\n\r\n### Best Practices with Cloud and Microservices\r\n\r\nThis is the last article in a series of six articles on best practices with cloud and microservices:\r\n- [1 - The 12 Factor App - Best Practices In Cloud Native Applications and Microservices](/12-factor-app-cloud-native-microservices-best-practices){:target='_blank'}\r\n- [2 - Microservices Architectures - Event Driven Approach](/introduction-to-event-driven-architectures-with-microservices){:target='_blank'}\r\n- [3 - Microservice Best Practice - Why do you build a Vertical Slice?](/software-best-practices-building-a-vertical-slice){:target='_blank'}\r\n- [4 - Microservice Architecture Best Practices - Messaging Queues](/messaging-queues-and-asynchronous-communication-in-microservices){:target='_blank'}\r\n- [5 - Microservice Best Practice - Build an Archetype](/creating-archetypes-in-microservices-architectures-best-practices){:target='_blank'}\r\n- [6 - Asynchronous communication with queues and microservices - A perfect combination?](/asynchronous-communication-with-queues-in-microservices){:target='_blank'}\r\n\r\n\r\n### What Is Synchronous Communication?\r\n\r\nConsider the following example of a microservices architecture:\r\n\r\n![image info](/images/Capture-046-02.png)\r\n\r\nYou have Microservice1 calling Microservice2, which in turn invokes Microservice3. Suppose that Microservice3 offers a simple web service functionality. So Microservice1 can send it a request for data over HTTP, and get back a response containing the requested data. \r\n\r\nThe communication that exists between these two microservices is called **synchronous communication**. Microservice1 sends the request, waits for the data to be returned, and then proceeds. \r\n\r\n#### Drawbacks Of Synchronous Communication\r\n\r\nThis mode of communication works well when the response arrives almost immediately. However, it puts restrictions on the microservices that are involved. In order that Microservice1 be available, Microservice2 also needs to be available. \r\n\r\nIn certain scenarios, synchronous communication might not even be user friendly.\r\n\r\nLet's say Microservice2 is down. In that case, the user who submitted the request needs to be intimated about it. You don't always want to do that. In such situations, **asynchronous communication** provides a better alternative. \r\n\r\n### Asynchronous Communication\r\n\r\nHave a look at the following application architecture:\r\n\r\n![image info](/images/Capture-046-03.png)\r\n\r\nIn the picture above, we make use of a ZipkinDistributedTracingServer. Different Microservices send logs that are finally consolidated in the Zipkin Tracing Service. Each microservice puts its tracing information into the RabbitMQ message queue. The server processes messages as and when they come into the queue. \r\n\r\nIn this architecture, applications communicate through RabbitMQ. CurrencyCalculationService puts its own tracing information into RabbitMQ, and then forgets about it. It does not worry about the responses coming back to it.\r\n\r\nNow, what would happen if the ZipkinDistributedTracingServer were to go down? \r\n\r\nThe services communicating with it would not worry one bit. They would continue sending messages to the queue. When the server comes back up, it resumes processing the messages present in the queue, and saves them to the database. \r\n\r\n#### Advantages Of Asynchronous Communication\r\n\r\nLet's look at a few advantages of asynchronous communication:\r\n* In a system that involves asynchronous messaging, the server does not need to be up and running, all the time. Messages that are put into the message queue can be processed in batches, at a later time.\r\n* Instead of a single instance of the tracing server processing the message queue, you could spawn multiple instances to lighten the load. \r\n* If you use a modern version of a messaging queue, there is a good chance you get to use a replay feature. This helps in re-processing a message that initially threw an error. \r\n* Asynchronous communication is great for systems that require **eventual consistency**. \r\n\r\n> Great thing is as long as we fix the errors and reprocess the message, the users of services that initiated the requests with errors do not even need to know about them. \r\n\r\n#### Limitations Of Asynchronous Communication\r\n\r\nAsynchronous communication cannot be used \r\n- If the processing needs to be real-time - if there is a hard constraint on the response time of a certain request. \r\nDo check out our video on this:\r\n\r\n[![image info](/images/Capture-046-01.png)](https://www.youtube.com/watch?v=wCugdNicf-0)\r\n\r\n### Summary\r\n\r\nIn this article, we had a look at what asynchronous communication is all about, We started with a peek at synchronous communication, and saw that it puts constraints on applications and their availability. Asynchronous communication solves the problem by causing services to enqueue requests into a message queue. A server then processes them independently, often in batches.\r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-06-12-Microservice-Best-Practices-048-Why-Build-An-Archetype.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Microservice Best Practice - Build an Archetype\r\ndate:    2019-06-11 12:31:19\r\nsummary:  In this article, we focus on learning why creating proper archetypes is important for successful microservices architecture. \r\ncategories:  SpringBootMicroservices\r\npermalink:  /creating-archetypes-in-microservices-architectures-best-practices\r\nimage: /images/microservices-category.png\r\n---\r\n\r\nIn this article, we focus on learning why creating proper archetypes is important for successful microservices architecture. \r\n\r\n# What you will learn\r\n- What is an archetype?\r\n- Why do you want to build microservices quickly?\r\n- How does an archetype help?\r\n- How can you use an archetype?\r\n- How can you build an archetype of your own?\r\n\r\n\r\n\r\n### Best Practices with Cloud and Microservices\r\n\r\nThis is the fifth article in a series of six articles on best practices with cloud and microservices:\r\n- [1 - The 12 Factor App - Best Practices In Cloud Native Applications and Microservices](/12-factor-app-cloud-native-microservices-best-practices){:target='_blank'}\r\n- [2 - Microservices Architectures - Event Driven Approach](/introduction-to-event-driven-architectures-with-microservices){:target='_blank'}\r\n- [3 - Microservice Best Practice - Why do you build a Vertical Slice?](/software-best-practices-building-a-vertical-slice){:target='_blank'}\r\n- [4 - Microservice Architecture Best Practices - Messaging Queues](/messaging-queues-and-asynchronous-communication-in-microservices){:target='_blank'}\r\n- [5 - Microservice Best Practice - Build an Archetype](/creating-archetypes-in-microservices-architectures-best-practices){:target='_blank'}\r\n- [6 - Asynchronous communication with queues and microservices - A perfect combination?](/asynchronous-communication-with-queues-in-microservices){:target='_blank'}\r\n\r\n\r\n### Why Do We Need Archetypes?\r\n\r\nIn microservices architectures, we have a number of microservices interacting with each other. And, we keep adding microservices as we evolve.\r\n\r\n![image info](/images/Capture-048-01.png)\r\n\r\nA few questions arise:\r\n- How do you ensure that the microservices are consistent i.e. similarly built and deployed? This will ensure that a developer moving from one microservice to another will not have a great deal of learning to do!\r\n- How do you ensure that you are able to setup a new microservice quickly?\r\n- How do you ensure that the new microservice is consistent with older microservices?\r\n\r\n With microservices architectures, while the functionality of each microservice is different, you want a bit of consistency in how they are built and deployed\r\n - Programming Language used\r\n - Frameworks used\r\n - The way unit tests are written\r\n - Deployment and Monitoring processes\r\n - QA & Automation Testing Approaches\r\n - Integration with Infrastructure components like Naming Server, API Gateways etc\r\n\r\nThis is where the reference architecture for your microservices comes into the picture. Having a good reference architecture ensures that your microservices are uniform. \r\n\r\nHow do you ensure that the reference architecture is properly implemented? \r\n\r\n### Enter Archetypes\r\n\r\nCreating an **archetype** standardizes the reference architecture. An archetype is a piece of component code that can create the initial setup of microservice, adhering to the reference architecture. \r\n\r\nWhat would the output of an archetype look like? \r\n\r\nIt would consist of an example microservice with\r\n* Framework Integration\r\n* Configuration of common external components\r\n* Multiple layer Setup\r\n* Initial Security Configuration - For Authentication and Authorization\r\n* Sample Automation Tests for Unit Testing and Integration Testing\r\n* Infrastructure setup for communication with other microservices\r\n\r\nOnce you generate a component using the archetype, you can focus on adding business features to your microservice.\r\n\r\n### Reference Archetype Example\r\n\r\nWe have created a reference archetype for a Spring Boot Microservice. Github repo for the project is https://github.com/in28minutes/microservice-reference-archetype.\r\n\r\n#### Using the archetype to create a new project\r\n\r\nSteps are detailed below:\r\n\r\n##### Download or Clone the github repository \r\n\r\n You can start with cloning the repository - https://github.com/in28minutes/microservice-reference-archetype. Other option is to download the repository as a zip file using this link - https://github.com/in28minutes/microservice-reference-archetype/archive/master.zip\r\n\r\n##### Install the archetype\r\n\r\n- cd to the root of the project and run \r\n\r\n```\r\nmvn clean install\r\n```\r\n\r\n- This will install the archetype to your local repository\r\n\r\n```\r\n[INFO] Installing /in28Minutes/git/microservice-archetype/microservice-archetype/target/project-name-archetype-0.0.2-SNAPSHOT.jar to /Users/rangaraokaranam/.m2/repository/com/organization/project/project-name-archetype/0.0.2-SNAPSHOT/project-name-archetype-0.0.2-SNAPSHOT.jar\r\n```\r\n\r\n##### Create a new project using the archetype\r\n\r\n- Create a new folder on your hard drive. Let's call it first-project\r\n\r\n- Execute the following commands\r\n\r\n```\r\ncd first-project\r\nmvn archetype:generate -DarchetypeCatalog=local\r\n```\r\n\r\n- archetype plugin asks for a groupId and artifactId as shown below\r\n\r\n```\r\nChoose a number or apply filter (format: [groupId:]artifactId, case sensitive contains): : 1\r\nDefine value for property 'groupId': com.first\r\nDefine value for property 'artifactId': first-project\r\nDefine value for property 'version' 1.0-SNAPSHOT: : \r\nDefine value for property 'package' com.first: : \r\nConfirm properties configuration:\r\ngroupId: com.first\r\nartifactId: first-project\r\nversion: 1.0-SNAPSHOT\r\npackage: com.first\r\n Y: : Y\r\n```\r\n- When the archetype plugin executes successfully, you should see the message shown below:\r\n\r\n```\r\n[INFO] Project created from Archetype in dir: /in28Minutes/git/microservice-archetype/first-project\r\n```\r\n\r\n##### Verify the new project\r\n\r\nYou can do a ```mvn clean install``` on the new project in first-project to check it everything is good.\r\n\r\nThis is a Spring Boot Project with a couple of controllers and unit/integration tests. \r\n\r\n### Creating Your Own Reference Archetype\r\n\r\nYou can also create a reference archetype of your own. The first thing you need to do is to create a reference project - which would serve as the base for creating your archetype. \r\n\r\n#### Setting up Reference Project\r\n\r\n- We have our reference microservice in the folder microservice-reference. This is a Spring Boot Project with a couple of controllers and unit/integration tests. We use this as the reference project to reverse engineer an archetype. \r\n- When we create a new project using a maven archetype, the two important inputs are groupId and artifactId. In the reference project we would need to make sure that everything that needs to customized based on these inputs should be using similar values. In the microservice-reference, we use the following as the standard:\r\n     - groupId - com.organization.project \r\n     - artifactId - project-name\r\n- You would need to customize the reference-project to meet your needs or you can create a new reference-project.\r\n- Ensure that you configure the latest version of maven-archetype-plugin in your microservice-reference \r\n\r\n```xml\r\n\t<build>\r\n\t\t<pluginManagement>\r\n\t\t\t<plugins>\r\n\t\t\t\t<plugin>\r\n\t\t\t\t\t<artifactId>maven-archetype-plugin</artifactId>\r\n\t\t\t\t\t<version>3.0.1</version>\r\n\t\t\t\t</plugin>\r\n\t\t\t</plugins>\r\n\t\t</pluginManagement>\r\n\t</build>\r\n```\r\n\r\n#### Reverse Engineering an Archetype from microservice-reference\r\n- In the command prompt cd to the folder containing this project\r\n\r\n```\r\ncd microservice-reference\r\nmvn archetype:create-from-project\r\n```\r\n\r\n- You will see the following statements in the log\r\n\r\n```\r\n[INFO] Setting default groupId: com.organization.project\r\n[INFO] Setting default artifactId: project-name\r\n[INFO] Setting default version: 0.0.2-SNAPSHOT\r\n[INFO] Setting default package: com.organization.project\r\n```\r\n\r\nArchetype project is created in microservice-reference/target/generated-sources/archetype\r\n\r\n#### Copy the created archetype to the microservice-archetype project\r\n\r\n- Copy the archetype project created in earlier step to the folder microservice-archetype\r\n\r\nDo check out our video on this:\r\n\r\n[![image info](/images/Capture-048-01.png)](https://www.youtube.com/watch?v=KPAe72TqLIw)\r\n\r\n### Summary\r\n\r\nIn this article, we talked about the need for an archetype in microservices architecture. Archetype serves a starting point for creating new projects and ensure uniformity across microservices. We looked at an example archetype and got an overview of how to create an archetype. \r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-06-12-Microservice-Best-Practices-050-Why-Message-Queues-Asynchronous-Communication.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Microservice Architecture Best Practices - Messaging Queues\r\ndate:    2019-06-10 12:31:19\r\nsummary:  In this article, we discuss why Messaging queues are needed, and how they form the cornerstone of communication in microservices architectures.\r\ncategories:  SpringBootMicroservices\r\npermalink:  /messaging-queues-and-asynchronous-communication-in-microservices\r\nimage: /images/microservices-category.png\r\n---\r\n\r\nIn this article, we discuss why queues are needed, and how they form the cornerstone of asynchronous communication in microservices architectures.\r\n\r\n# What you will learn\r\n- What is a Queue?\r\n- What is asynchronous communication or asynchronous messaging?\r\n- What are the advantages of using Queues in microservices architectures?\r\n\r\n\r\n\r\n### Best Practices with Cloud and Microservices\r\n\r\nThis is the fourth article in a series of six articles on best practices with cloud and microservices:\r\n- [1 - The 12 Factor App - Best Practices In Cloud Native Applications and Microservices](/12-factor-app-cloud-native-microservices-best-practices){:target='_blank'}\r\n- [2 - Microservices Architectures - Event Driven Approach](/introduction-to-event-driven-architectures-with-microservices){:target='_blank'}\r\n- [3 - Microservice Best Practice - Why do you build a Vertical Slice?](/software-best-practices-building-a-vertical-slice){:target='_blank'}\r\n- [4 - Microservice Architecture Best Practices - Messaging Queues](/messaging-queues-and-asynchronous-communication-in-microservices){:target='_blank'}\r\n- [5 - Microservice Best Practice - Build an Archetype](/creating-archetypes-in-microservices-architectures-best-practices){:target='_blank'}\r\n- [6 - Asynchronous communication with queues and microservices - A perfect combination?](/asynchronous-communication-with-queues-in-microservices){:target='_blank'}\r\n\r\n\r\n### Why Asynchronous Messaging?\r\n\r\nWhy is asynchronous messaging important? \r\n\r\nConsider the simple example of an ordering service:\r\n\r\n![image info](/images/Capture-050-02.png)\r\n\r\nA customer places an order through the OrderService. Let's say following steps are involved:\r\n- It needs to send a request to the StockService \r\n- Send communication to the user through the EmailService and SMSService \r\n- Call the PackageService to start delivery\r\n\r\n### Option 1 : Single Component for all processing\r\n\r\nOne way to design this application would be to have a single component that accomplishes all this functionality. For example, write a Java class which accepts the order, and does the entire processing itself. \r\n\r\n### Option 2 : Introducing Asynchronous Messaging using Queues\r\n\r\nThe other option is to have a queue in-between the receiving OrderService component, and the rest of the components. When the OrderService receives an order, it places the request on the Queue. The rest of the components are independent services, listening on the Queue. \r\n\r\nAs soon as an order is placed on the queue:\r\n* The StockService processes the order and updates the database\r\n* The EmailService sends out an email to the customer\r\n* The SMSService sends out an SMS to the user\r\n* The PackageService does the required package processing on the item\r\n\r\n### Single Component v Queue\r\n\r\nIf your business goal is to support a few hundreds or thousands of users, then a simple architecture would be a good choice. The first architecture might be all you need. \r\n\r\nHowever, when we talk of a large scale e-commerce web application such as Amazon.com, that receives millions of orders in a short time, you need a lot of flexibility. That's when you go for the second approach, of bringing a queue in.\r\n\r\n### Advantages of Using A Messaging Queue\r\n\r\nLet's look at the advantages of using asynchronous communication based on a messaging queue.\r\n\r\n#### A Queue Improves Reliability\r\n\r\nLet's say the SMSService is down for a short time. \r\n\r\nIn Option 1, since the OrderService directly invokes the SMSService on receiving an order, an SMS cannot be sent out. That might mean canceling the order, as all steps are part of a single transaction. Failure of one of the components would lead to cancellation of the customer request, with a need for him to re-initiate the order - at a later point in time. \r\n\r\nHowever in the second approach, called **asynchronous** communication, the order request is placed on the queue. When the SMSService comes back up, it will find the order event and process it. It can then send out the SMS messages for all its pending requests.\r\n\r\n#### A Queue Provides Scalability\r\n\r\nSuppose on a given day, there is a need to send out 100,000 SMS messages. An option with having asynchronous communication is that you can increase the number of instances of the SMSService. This flexibility in number of instances of the components, improves system scalability. \r\n\r\n#### A Queue Improves Testability\r\n\r\nEach of the components/services are loosely tied, and have independent requirements. It is thus much easier to test each one of them, preferably in isolation. \r\n\r\n#### A Queue Improves Maintainability\r\n\r\nA queue also improves system maintainability, as the application is divided into smaller services.\r\n\r\n#### A Queue Improves Flexibility\r\n\r\nNot only increase instances of existing services, a queue makes the system flexible to add more services in future. All that you need to do is add a new service listen to events on the queue and consuming them. The new service could be plugged in, with a minimum of down time. \r\n\r\n#### Popular Message Queues\r\n\r\nAn extremely popular message queue framework is RabbitMQ. \r\n\r\nDifferent frameworks use different communication protocols, but the concept underlying all of them is the same. At the core, a queue separates the component that generates the event, from the services that consume the event. \r\n\r\nIn general, if you need a system that addresses a very large user base, whose users submit a large number of requests to be processed,  go for queue-based systems. \r\n\r\nDo check out our video on this:\r\n\r\n[![image info](/images/Capture-050-01.png)](https://www.youtube.com/watch?v=cyXToKjXXQY)\r\n\r\n### Summary\r\n\r\nIn this article, we looked at the fact that there are two types of architectures - synchronous and asynchronous. Synchronous systems have the disadvantage that one component being down, causes loss of service to the entire system. Asynchronous systems solve this problem by introducing an intermediary queue to hold events. An architecture based on asynchronous communication using a queue improves testability, scalability, maintainability and flexibility. \r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-06-12-Microservice-Best-Practices-060-Event-Driven-Architectures.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Microservices Architectures - Event Driven Approach\r\ndate:    2019-06-08 12:31:19\r\nsummary:  In this article, we talk about event driven approach, in the context of microservices architectures. We also discuss what are the advantages of using an event driven approach.\r\ncategories:  SpringBootMicroservices\r\npermalink:  /introduction-to-event-driven-architectures-with-microservices\r\nimage: /images/microservices-category.png\r\n---\r\n\r\nIn this article, we talk about event driven architectures, in the context of microservices architectures. We also discuss what are the advantages of using an event driven approach.\r\n \r\n## You will learn\r\n- What is Event Driven Architecture?\r\n- Why do we need Event Driven Architectures?\r\n- What is the relationship between event driven architectures and microservices?\r\n- What are the advantages of Event Driven Architectures?\r\n\r\n\r\n\r\n### Best Practices with Cloud and Microservices\r\n\r\nThis is the second article in a series of six articles on best practices with cloud and microservices:\r\n- [1 - The 12 Factor App - Best Practices In Cloud Native Applications and Microservices](/12-factor-app-cloud-native-microservices-best-practices){:target='_blank'}\r\n- [2 - Microservices Architectures - Event Driven Approach](/introduction-to-event-driven-architectures-with-microservices){:target='_blank'}\r\n- [3 - Microservice Best Practice - Why do you build a Vertical Slice?](/software-best-practices-building-a-vertical-slice){:target='_blank'}\r\n- [4 - Microservice Architecture Best Practices - Messaging Queues](/messaging-queues-and-asynchronous-communication-in-microservices){:target='_blank'}\r\n- [5 - Microservice Best Practice - Build an Archetype](/creating-archetypes-in-microservices-architectures-best-practices){:target='_blank'}\r\n- [6 - Asynchronous communication with queues and microservices - A perfect combination?](/asynchronous-communication-with-queues-in-microservices){:target='_blank'}\r\n\r\n\r\n### The Need For Event Driven Architecture\r\n\r\nMicroservices architectures have multiple small-sized microservices talking to each other. Here is one such architecture:\r\n![image info](/images/Capture-060-02.png)\r\n\r\nThere are a set of common components - technical as well as infrastructure. Examples of technical components are Security and Logging components. Examples of infrastructure components include Naming Server, API Gateway and Centralized Logging. \r\n\r\nWhen implementing microservices, you would want to make them as event driven as possible. Why? Let's take an example\r\n\r\n### Take A Use Case\r\n\r\nConsider the use case of an online shopping application. Whenever there is an order, it is received by the order service. There are several actions that need to be carried out in order service:\r\n- Update the stock\r\n- Send out email and SMS\r\n- Notify the packaging team.\r\n\r\n#### Monolithic Approach\r\n\r\nAn initial approach could be to have a single monolith application to take care of all the functionality. \r\n\r\n#### Microservices Approach\r\n\r\nAlternatively, these are fairly independent activities, and the entire application can be structured to have microservices for them, in a straightforward manner.\r\n\r\n![image info](/images/Capture-060-03.png)\r\n\r\nIn this approach, you create an order event for the request coming in, and place it in the Queue. The rest of the individual services listen in to the queue for order events, and do the processing subsequently. \r\n\r\n#### How to choose?\r\n\r\n> How do we make the decision which of the two application architectures to choose? \r\n\r\nThe nature of your application decides this. \r\n\r\nIf your system does not have a very high load at any given time, and also does not have any pressing scalability requirements, then you might want go with a monolith approach.\r\n\r\nHowever, when your system is a large , handling millions of requests every day, and also has very stringent scalability requirements, you might be better off with the microservices approach. \r\n\r\n> An event driven architecture would be the one best suited to your needs. \r\n\r\n### Advantages Of Event Driven Architectures\r\n\r\n#### Improved Flexibility And Maintainability\r\n\r\nOne of the most important needs of an application is maintainability. Ease of maintainability comes with proper **separation of concerns**. \r\n\r\nIn our example above, the OrderService is only responsible for collecting the order and placing it in the queue. It does not worry about how it is going to be processed, who is going to process it, and so on. \r\n\r\nSimilarly,  the StockService is only responsible for updating the stock, and the same with the other microservices. \r\n\r\nIf there is a need for an additional processing step on an order, you write a new microservice to listen on the queue, and easily integrate it into the system. \r\n\r\nSuch an architecture is clearly extensible, and also easily maintainable, due to separation of concerns. \r\n\r\n#### High Scalability\r\n\r\nLet's consider an example : One fine day, a large volume of emails need to be sent out. \r\n\r\nIn that case, you have the freedom to create a large number of instances of the EmailService, to handle additional load. \r\n\r\nA similar thing can be spoken about the other microservices in the mix, depending on the need of the hour. \r\n\r\nThis is a clear advantage of this architecture, over using a single component to handle all the functionality. \r\n\r\n#### Improved Availability\r\n\r\nLet's say one of the services listening for order events from the queue, such as the PackageService, goes down. \r\n\r\nIn the first architecture approach of using a monolithic approach, any one functionality going down would mean the application cannot process orders any more.\r\n\r\nIn case of an event driven architecture, the PackageService going down would not prevent the OrderService from putting the order event into the Queue. The OrderService can notify the user of successful request receipt. \r\n\r\nA notification request would then be sent to the troubleshooting team about the PackageServer going down, and while it is being restored, the order event remains in the Queue. It can be processed by all the other services during this time, and when PAckageService comes back up, it can process the event as if nothing untoward has happened.\r\n\r\n#### Good Reliability\r\n\r\nEvent driven architectures ensure a good standard of reliability for the system as a whole. However, the individual microservices can function with different levels of reliability. For example the StockService normally needs to ensure a high level of reliability, the EmailService and SMSService a medium level of reliability, and the PackageService - between low and medium levels of reliability.\r\n\r\n#### Good Performance and Responsiveness\r\n\r\nNote that in our example event driven architecture, all that the OrderService does is receive the order and place it on the queue, before acknowledging the user. The user does not need to wait till all the steps are performed on an order. This has high high responsiveness, and is seen by the user as high performance. \r\n\r\nDo check out our video on this:\r\n\r\n[![image info](/images/Capture-060-01.png)](https://www.youtube.com/watch?v=uJ4JFMMbSO8)\r\n\r\n### Summary\r\n\r\nIn this article, we had a look at event driven architectures. We saw that event driven architecture is ideal for implementing applications with high load, and strict scalability needs. \r\n\r\nWe saw an example of an online shopping application that employs such an architecture. The advantages of using such an architecture include improved flexibility and maintainability, high scalability, imrpoved availability, good reliability and good performance. \r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-06-12-Microservice-Best-Practices-068-The-12-Factor-App-CLoud-Native-Best-Practices.md",
    "content": "---\r\nlayout:  post\r\ntitle: The 12 Factor App - Best Practices In Cloud Native Applications and Microservices\r\ndate:    2019-06-07 12:31:19\r\nsummary: In order that an application be deployed in the cloud and enjoy features such as auto scaling, it first needs to be cloud native. In this article, we have a close look at the best practices for cloud native applications, popularly known as The 12 Factor App. \r\ncategories:  SpringBootMicroservices\r\npermalink:  /12-factor-app-cloud-native-microservices-best-practices\r\nimage: /images/microservices-category.png\r\n---\r\n\r\nIn order that an application be deployed in the cloud and enjoy features such as auto scaling, it first needs to be cloud native. In this article, we have a close look at the best practices for cloud native applications, popularly known as The 12 Factor App. \r\n\r\n### Best Practices with Cloud and Microservices\r\n\r\nThis is the first article in a series of six articles on best practices with cloud and microservices:\r\n- [1 - The 12 Factor App - Best Practices In Cloud Native Applications and Microservices](/12-factor-app-cloud-native-microservices-best-practices){:target='_blank'}\r\n- [2 - Microservices Architectures - Event Driven Approach](/introduction-to-event-driven-architectures-with-microservices){:target='_blank'}\r\n- [3 - Why do you build a Vertical Slice?](/software-best-practices-building-a-vertical-slice){:target='_blank'}\r\n- [4 - Microservice Architecture Best Practices - Messaging Queues](/messaging-queues-and-asynchronous-communication-in-microservices){:target='_blank'}\r\n- [5 - Build an Archetype](/creating-archetypes-in-microservices-architectures-best-practices){:target='_blank'}\r\n- [6 - Asynchronous communication with queues and microservices - A perfect combination?](/asynchronous-communication-with-queues-in-microservices){:target='_blank'}\r\n\r\n\r\n\r\n\r\n## The 12 Factor App\r\n\r\n12 Factor App is a set of best practices that guide you to build a great cloud native application. These were framed by Heroku, based on their experiences with building cloud native applications. \r\n\r\n### Codebase - One codebase tracked in revision control, many deploys\r\n\r\nYou have the codebase in a version control system, and you extract and build it, then deploy it many times.\r\n\r\n### Dependencies - Explicitly declare and isolate dependencies\r\n\r\nWhenever you build a software application, say in Java, you need a number of dependencies such as frameworks. You may need to manage the versions of the libraries you need to use. Explicitly declare and isolate such dependencies.\r\n\r\n### Config - Store config in the environment\r\n\r\nThere are a variety of environments where an application could execute, such as development, QA, staging and production. Applications have different configuration in each of the environments. It is recommended to seperate the configuration and store it within the environment itself.\r\n\r\nAnother option is to store the configuration information in a centralized repository. \r\n\r\nAn good example is Spring Cloud Config Server. The configuration is stored in the config server, which can then be mapped to the environment.\r\n\r\n###  Backing services - Treat backing services as attached resources\r\n\r\nBacking services refers to the other systems that an application needs to talk to, and this also includes the databases. All such services need to be considered as attached resources. \r\n\r\nAll of these need to be configurable, and it should be easy to switch from one backing service to another. This switch should be possible with just a switch in configuration.  \r\n\r\n### Build, release, run - Strictly separate build and run stages\r\n\r\nThe build, release and run stages need to be strictly separated. \r\n\r\nYou need to be able to build a deployable component, such as a JAR, WAR or an EAR, that is independent of the environment. There should not be any change in this component as the deployment environment changes. \r\n\r\nA release is a phase where we take this reusable component, and combine it with a specific configuration for a target environment. \r\n\r\nThe next phase is to take the released entity, create a container out of it, and run it in the environment.\r\n\r\n### Processes - Execute the app as one or more stateless processes\r\n\r\nIdeally an application should be stateless.\r\n\r\nBut, in case you have state - where you store the state of an application determines how flexible it is. \r\n\r\nIf you store state in a central data store such as redis, it makes the application very flexible. \r\n\r\nYou no longer need sticky sessions. You can have any instance of an app, answer any request. \r\n\r\n### Port binding - Export services via port binding\r\n\r\nYou should be able to deploy applications as services, by tying them with ports.\r\n\r\n### Concurrency - Scale out via the process model\r\n\r\nThere are two kinds of scaling that can be applied to an application - horizontal and vertical. Vertical scaling refers to increasing the hardware infrastructure, such as increasing the CPU processing power, or increasing the amount of physical memory available to the application. Clearly, there are limits to such an approach.\r\n\r\nHorizontal scaling refers to the possibility of dynamically increasing or decreasing the number of instances of an application, depending on the system needs. \r\n\r\nYour applications should be built to be able to dynamically adapt to changing number of instances of various services. \r\n\r\n### Disposability - Maximize robustness with fast startup and graceful shutdown\r\n\r\nIf one of the instances of the application is causing errors, or is slow in responding to requests, or is not responding at all, it should be possible to gracefully shut the instance down. \r\n\r\nIn addition, the other applications in the system should not be affected by this change in the environment. \r\n\r\nYou should be able to bring in new instances as they are needed, and take down instances when required. This property is known as disposability, and is a measure of the system's robustness.\r\n\r\n### Development / Production Parity\r\n\r\nThere is a strong need to keep the development, QA, staging and production stages of a deployment pipeline, as similar as possible. The similarities should apply to the processes you follow, the technologies you make use of, and the infrastructure you employ. \r\n\r\nIf you have this parity among these stages, then most of the problems that could arise with the application, would appear in the earlier stages. Not many surprises would be in store for you at production. \r\n\r\n### Logs - Treat logs as event streams\r\n\r\nVisibility is one of the most important requirements of a microservices architecture.\r\n\r\nBy treating each log message entered into a centralized logging system as an event, you get a sequence of actions that are performed on a request when it enters the system, right up to when it is completed or abandoned. \r\n\r\nAll one needs to do in order to debug a problem, is to go to the central dashboard and search for it.\r\n\r\n### Admin processes - Run admin/management tasks as one-off processes\r\n\r\nThere are a number of one-off process that you need to run - batch programs, database migrations, scripts.\r\n\r\nTreat one-off processes the same way as long running processes.\r\n\r\nHave the same standards - have code base in version control, follow standard deployment processes and use the same environments\r\n\r\nDo check out our video on the same topic:\r\n\r\n[![image info](images/Capture-068-01.png)](https://www.youtube.com/watch?v=wjqBxJX35fU)\r\n\r\n### Summary\r\n\r\nIn this article, we looked at the best practices for cloud native applications, called the 12 Factor App.\r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-06-20-Programming-Basics-002-AspectOrientedProgramming.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Introduction To Aspect Oriented Programming and Cross Cutting Concerns\r\ndate:    2019-06-21 12:31:19\r\nsummary: Software applications are built in layers. There is common functionality that is sometimes needed across layers - logging, performance tracing etc. How do you implement these common features? \r\ncategories:  SwProgramming\r\npermalink:  /introduction-to-aspect-oriented-programming-and-cross-cutting-concerns\r\nimage: /images/programming-category.png\r\n---\r\n\r\nSoftware applications are built in layers. There is common functionality that is sometimes needed across layers - logging, performance tracing etc. \r\n\r\nHow do you implement these common features?\r\n\r\n### You will learn?\r\n* What Is Aspect Oriented Programming?\r\n* What are the important concepts behind Aspect-Oriented Programming? \r\n* What are the situations where AOP is used?\r\n* Why is AOP needed?\r\n* What are the best Java frameworks to implement AOP?\r\n\r\n\r\n\r\n\r\n### What Is Aspect Oriented Programming?\r\n\r\nIn order to understand what **Aspect Oriented Programming (AOP)** is all about, let's first talk about **layered architecture**, and  something called **cross-cutting concerns**. \r\n\r\n#### What is a Layered Architecture\r\n\r\nWhenever we design and develop a large software application, we make use of  a **layered architecture**. For instance, in a web application, it is quite common to see an architecture similar to the following:\r\n\r\n![image info](/images/Capture-02-01.png)\r\n\r\nHere, we see that the application is organized into a Web layer, a Business layer, and a Data layer. \r\n\r\n#### Understanding Cross Cutting Concerns\r\n\r\nIn a layered architecture, there are specific parts that are common to all these different layers. Such parts include:\r\n\r\n* Logging\r\n* Security\r\n* Performance\r\n* Auditing\r\n\r\nAll these features are applicable across layers, hence it makes sense to implement them in a common way. \r\n\r\nLet's say you want to implement logic to find out how much time each method takes to execute, in each of the three layers (Web, Business and Data) above. \r\n\r\nThat's where AOP steps in.\r\n\r\n#### An Example Of AOP\r\n\r\nLet's now look at a simple example where we apply AOP.\r\n\r\n```java\r\n\r\n\t@Component\r\n\tclass HiByeService {\r\n\t  public void sayHi(String name) {\r\n\t    System.out.println(\"Hi \" + name);\r\n\t  }\r\n\t\r\n\t  public void sayBye() {\r\n\t    System.out.println(\"Bye\");\r\n\t  }\r\n\t\r\n\t  public String returnSomething() {\r\n\t    return \"Hi Bye\";\r\n\t  }\r\n\t}\r\n```\r\n\r\nThe ```class``` ```HiByeService``` has a few methods such as ```sayHi()```, ```sayBye()``` and ```returnSomething()``` defined within it. \r\n\r\nWe want to do a few computations by taking up each of these methods, by turn at the following stages:\r\n* Do something before the method begins execution\r\n* Do something after the method completes execution\r\n* Track how much time the method takes during its execution\r\n\r\nHere we take ```HiByeService``` as a specific example to work with. The same could be done across several classes that make up such an application. \r\n\r\nLet's take each of these computations and look at them in some detail.\r\n\r\n#### Doing Stuff Before Execution\r\n\r\nHave a look at the following AOP code:\r\n\r\n```java\r\n\r\n\t@Aspect\r\n\t@Component\r\n\tclass MyAspect {\r\n\t  @Before(\"execution(* HiByeService.*(..))\")\r\n\t  public void before(JoinPoint joinPoint) {\r\n\t    System.out.print(\"Before \");\r\n\t    System.out.print(joinPoint.getSignature().getName());\r\n\t    System.out.println(Arrays.toString(joinPoint.getArgs()));\r\n\t  }\r\n```\r\n\r\nWe first define an **aspect** with the annotation ```@Aspect``` for the ```class``` ```MyAspect```. Within it is another annotation, ```@Before``` that describes the method ```before()```. The idea of this aspect is that whatever logic lies in the ```before()``` body, is executed before any method of ```HiByeService``` is run. Note that in the ```@Before``` annotation, a package name could also be mentioned instead of a class name. This aspect would then be executed before any method in the entire package. \r\n\r\n#### Doing Stuff After Execution\r\n\r\nSimilar to this, it is also possible to define an aspect to execute after every method within ```HiByeService``` is run:\r\n\r\n```java\r\n\r\n\t@AfterReturning(pointcut = \"execution(* HiByeService.*(..))\"\r\n\t                    , returning = \"result\")\r\n\t  public void after(JoinPoint joinPoint, Object result) {\r\n\t    System.out.print(\"After \");\r\n\t    System.out.print(joinPoint.getSignature().getName());\r\n\t    System.out.println(\" result is \" + result);\r\n\t  }\r\n\t}\r\n\r\n```\r\n\r\nFor this, you need to define a method with an ```@AfterReturning``` annotation, defined above for the ```after()``` method. This method here takes an extra argument to store the result of execution of the method of ```HiByeService```. \r\n\r\n#### Doing Stuff Around Execution\r\n\r\nAn additional thing you can do is define an aspect around the execution of a method:\r\n\r\n```java\r\n\r\n\t@Around(value = \"execution(* HiByeService.*(..))\")\r\n\tpublic void around(ProceedingJoinPoint joinPoint) \r\n\t                                      throws Throwable {\r\n\t  long startTime = new Date().getTime();\r\n\t  Object result = joinPoint.proceed();\r\n\t  long endTime = new Date().getTime();\r\n\t  System.out.print(\"Execution Time - \" \r\n\t                  + (endTime - startTime));\r\n\t}\r\n\r\n```\r\n\r\nOver here, we have made use of an annotation called ```@Around``` to decorate the ```around()``` method. \r\n\r\nIn this method body, we intercept the call to the method in ```HiByeService``` in the following manner:\r\n\r\n* We make note of the start time of execution\r\n* Allow the method to run its course\r\n* Finally, we make note of the end time of execution\r\n\r\nWe then output the computed execution time of that method. \r\n\r\n#### How To Make Use Of AOP\r\n\r\nAt a high level, AOP allows you to intercept calls to methods, and perform logic around these calls. We have used annotations to decorate our computations within the aspect. \r\n\r\nIn our examples above, we have restricted ourselves to a single class. However, we could easily extend it to more classes or packages by *varying* the **regular expression** we use in the annotations. \r\n\r\nFor example, we could choose to intercept classes pertaining to the web layer, or classes across all three layers of the example web application.\r\n\r\n#### Terms We Use In AOP\r\n\r\nLet's now look at some important terms we use when talking about AOP.\r\n\r\n* **Point Cut** : It refers to the regular expression that defines what methods need to be intercepted by this aspect. It essentially says where the logic within an aspect method is applicable. \r\n* **Advice** : This is nothing but the logic within the aspect method. It describes what we do when the Point Cut expression is matched. \r\n* **Aspect**: The combination of the Point Cut and the Advice\r\n* **Join Point**: This refers to the situation where a method's execution has been intercepted, and the aspect is in execution\r\n* **Weaving**: The entire process of taking a method, intercepting its execution and applying an aspect to its execution. This is the functionality provided by the AOP framework. Examples of AOP frameworks are **SpringAOP** and **AspectJ**.\r\n\r\n#### AOP In Summary\r\n\r\nIn this article, we looked at Aspect Oriented Programming (AOP). We talked about cross-cutting concerns, and described the situations where AOP can be used. In particular, we saw examples of how we can define a point cut, and define the logic of an aspect. We focused on how we can specify aspects to run before, after or around the execution of a method. We then examined the important terms that describe AOP concepts.\r\n\r\nDo check out our video on this:\r\n\r\n[![image info](/images/Capture-02-08.png)](https://www.youtube.com/watch?v=3UE_QTaohOg)\r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-06-20-Programming-Basics-080-5-Things-Think-About-Programming.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Programming Basics - Five Things To Think About While Programming\r\ndate:    2019-06-19 12:31:19\r\nsummary: You would obviously want to write code that meets your core requirements and provide good performance - choosing right data structures and algorithms to use is the fundamental part of programming.  What are the other things that you need to worry about? Here are five things that we think are essential.\r\ncategories:  SwProgramming\r\npermalink:  /programming-basics-five-things-to-think-about-while-programming\r\nimage: /images/programming-category.png\r\n\r\n---\r\n\r\nYou would obviously want to write code that meets your core requirements and provide good performance - choosing right data structures and algorithms to use is the fundamental part of programming.  \r\n\r\nWhat are the other things that you need to worry about? Here are five things that we think are essential.\r\n\r\n\r\n\r\n### Readability of Code\r\n\r\nThis is an indicator of how easy it is for another programmer, to read your code. \r\n\r\n> Would another programmer be able to easily understand what your classes and methods do? \r\n\r\nThe critical aspect to be addressed here is how well your variables, methods and classes are named. \r\n\r\n### Reusability of Components\r\n\r\nBefore you implement a new functionality, check whether there is already a common component that can do the work for you. \r\n\r\nIs any part of your feature reusable across the enterprise? Is there is a need to create a component out of this feature?\r\n\r\n### Unit Testing\r\n\r\nThe best way to systematically ensure unit tests are written, is to follow Test Driven Development (TDD). With TDD, you write the tests before you actually write the code.  \r\n\r\nWriting unit tests and running them regularly, is the only way to continuously improve the design of your code. If you fail to do so, your design becomes stagnant.\r\n\r\n### Non Functional Requirements\r\n\r\nNon functional requirements are typically those requirements which are missing in your requirement documents or user stories. \r\n\r\nExamples of non functional requirements are:\r\n\r\n* Security\r\n* Scalability\r\n* Performance\r\n* Maintainability\r\n\r\nand other kinds of fun stuff! Doing well on these parameters should always be on the back of your mind.\r\n\r\n### What's For Dinner?\r\n\r\nAlways have fun when you code. Programming is an intense mental activity, and keep taking fun breaks during the course of a day. It could mean pulling your teammate's leg. \r\n\r\nDo check out our video on the same topic:\r\n\r\n[![image info](images/Capture-080-01.png)](https://www.youtube.com/watch?v=svJ_htqB12E)\r\n\r\n### Summary\r\n\r\nIn this article, we took a quick look at 5 things programmers should focus on while writing code. \r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-06-20-Programming-Basics-088-Introduction-To-Object-Oriented-Programming.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Programming Basics - Introduction To Object Oriented Programming\r\ndate:    2019-06-20 12:31:19\r\nsummary: Object oriented programming (OOP) is all about thinking in terms of objects. Let's dig deeper.\r\ncategories:  SwProgramming\r\npermalink:  /programming-basics-introduction-to-object-oriented-programming\r\nimage: /images/programming-category.png\r\n\r\n---\r\n\r\nObject oriented programming (OOP) is all about thinking in terms of objects. Let's dig deeper.\r\n \r\n## You will learn\r\n- What Is Structured Programming?\r\n- What Is Object Oriented Programming?\r\n- How is Object Oriented Programming different from Structured Programming?\r\n- How can you think in terms of objects - state and responsibility?\r\n- We look at a few examples of designing object oriented programs.\r\n\r\n\r\n\r\n\r\nBefore we discuss OOP, let us first look at structured programming.\r\n\r\n### What Is Structured Programming?\r\n\r\nIf you have ever done any programming in languages such as C and Pascal, then you have done what is called **procedural**, or **structured programming**. Such programming involves thinking in terms of procedures (or methods/functions). If you have a problem to solve, you split the logic of the solution into a sequence of multiple procedures, as the steps. You would start thinking about what functions need to be written.  \r\n\r\n#### Example: Flight Problem\r\n\r\nSuppose the problem at hand is flying from one city to another. The different steps involved in that would take the form of a sequence of procedures as shown below:\r\n\r\n```\r\n\r\n\t// Global Data\r\n\r\n\tfly() {\r\n\t\ttravelToairport();\r\n\t\tfindCheckInCounter();\r\n\t\tcheckIn();\r\n\t\tpassSecurityCheck();\r\n\t\twaitForBoardingCall();\r\n\t\tboardTheFlight();\r\n\t\twishTheAirHostess();\r\n\t\ttakeOff();\r\n\t\thaveFun();\r\n\t\tlanding();\r\n\t}\r\n\r\n```\r\n\r\nWe are looking to combine the functions that we write, to solve the stated problem. \r\n\r\n### What Is Object Oriented Programming?\r\n\r\nObject Oriented Programming (OOP) brings a new thought process to the table. OOP focuses instead on the actors in the system called objects. It focuses on:\r\n* The data that these objects contain\r\n* The actions that can be performed on them\r\n\r\nIf this sounds complex to you, then you are not alone! \r\n\r\nEvery new programmer who is introduced to OOP feels pretty much the same way. \r\n\r\nHow would OOP approach the problem of taking a flight from one city to another? \r\n\r\n### Example: Flight Problem Revisited\r\n\r\nLets take a step by step approach:\r\n\r\n#### Step-1 : Identify Objects\r\n\r\nWe first think about the different objects involved in the solution.\r\n- Aeroplane\r\n- Airhostess\r\n- Passenger\r\n\r\nIn addition to these, we could have more objects such as:\r\n* Cab\r\n* Airport\r\n* Co-passengers\r\n* Pilot\r\n\r\nand many more. \r\n\r\n\r\n#### Step-2\r\n\r\nOnce you have identified the objects of the system, you next determine the data an object would contains and actions that can be performed on it. \r\n\r\nAeroplane\r\n\r\n- Data : airline, make, type, position\r\n- Actions : takeOff(), land(), cruise()\r\n\r\nAirhostess\r\n- Data : name, address\r\n- Actions : wish(), serve()\r\n\r\nPassenger\r\n- Data : name, address\r\n- Actions : takeCab(), checkIn(), walk(), smile()\r\n\r\nOf course, there could be a lot more data and actions in each of the objects that we have elaborated on, above. \r\n\r\nIn summary, structured programming is only concerned about identifying procedures, and combining them to form a solution. In contrast, OOP focuses on the objects involves, and deals with their individual data and actions.\r\n\r\n### Understanding OOP Terminology\r\n\r\nLet's now deal with a few standard terms that are used, when dealing with OOP. \r\n\r\n#### Class\r\n\r\nA class is nothing but a template used to create objects within a program. A class allows you to define the data that can be stored inside the object, as well as what actions can be performed on them. What you see below is the definition of a simple class, named Planet: \r\n\r\n```\r\n\r\n\tclass Planet {\r\n\t\tname, location, distanceFromSun //state\r\n\t\trevolve(), rotate() // behavior\r\n\t}\r\n\r\n```\r\n\r\n#### Object\r\n\r\nAn object is defined as an instance of a class. For example, earth and venus are instances of the Planet class. Here is how you go about creating Planet instances: \r\n\r\n```\r\n\tPlanet earth = new Planet();\r\n\tPlanet venus = new Planet();\r\n\r\n```\r\n\r\nYou can have other instances as well. If Planet defined the attributes of a planet, then earth and venus are live instances of planets.\r\n\r\n#### State\r\n\r\nThe data that an object might contain is also referred to as its **state**. These are represented by the member variables inside the class. \r\n\r\nThe state of an object can change over a period of time. \r\n\r\nThe position of an Aeroplane at this point of time, would be different from what it will be after say, an hour's time. Similarly, the distance of the earth from the Sun changes with the passage of time. \r\n\r\n#### Behavior\r\n\r\nThe actions that can be performed on an object are referred to as its **behavior**. This translates to the methods that can be defined inside a class. \r\n\r\n### Let's Try Some Exercises\r\n\r\nLet's now apply what we have learned so far, by applying OOPs to a couple of exercises.\r\n\r\n#### Exercise 1 : Online Shopping System\r\n\r\nThink about the different things that are involved in creating an online shopping system. Make sure to focus on their data, and enumerate what actions can be performed on them.\r\n\r\n#### Exercise 2 : Person\r\n\r\nThink about the different things that are related to a Person. Make sure to focus on the data that such a class stores, and enumerate what actions can be performed on a Person.\r\n\r\n### Solutions To Exercises\r\n\r\n#### Exercise 1 : Online Shopping System\r\nCustomer\r\n- Data : name, address\r\n- Actions : login(), logout(), selectProduct(product)\r\n\r\nShopping Cart\r\n- Data : items\r\n- Actions : addItem(item), removeItem(item)\r\n\r\nProduct\r\n\r\n- Data : name, price, quantityAvailable\r\n- Actions : order(), changePrice()\r\n\r\n#### Exercise 2 : Person\r\n\r\n- Data - name, address, hobbies, work\r\n- Actions - walk(), run(), sleep(), eat(), drink()\r\n\r\nThe idea behind these exercises was to get you thinking about applying concepts in OOP.\r\n\r\nDo check out our video on the same topic:\r\n\r\n[![image info](images/Capture-088-01.png)](https://www.youtube.com/watch?v=5dObhVYrgsA)\r\n\r\n### Summary\r\nIn this article, we had a introductory look at object oriented programming, or OOP. We first saw the approach taken by structured programming, that focuses on procedures. OOP brings a different approach by focusing on objects involved, and their data and actions. We introduced some OOP terminology, such as class, object, state and behavior. Finally, we explored a couple of exercises to try and apply the simple concepts of OOP that we saw here.\r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-08-28-Automation-Testing-024-Mocking.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Programming Basics - Unit Testing - What Is Mocking?\r\ndate:    2019-08-28 12:30:19\r\nsummary: Mocking is an important concept that is made use of, when writing unit tests. In this article, we explore what mocking is all about, and explore some of the popular Java mocking frameworks in use.\r\ncategories:  SpringBootUnitTesting\r\npermalink:  /programming-basics-introduction-to-mocking-in-unit-tests\r\nimage: /images/unit-test-category.png\r\n---\r\n\r\nMocking is an important concept that is made use of, when writing unit tests. In this article, we explore what mocking is all about, and explore some of the popular Java mocking frameworks in use.\r\n\r\n### You will learn\r\n- What is mocking?\r\n- Why is mocking important?\r\n- How can you use Mockito framework to mock classes in Java?\r\n- What are things Mockito framework good at?\r\n- What are features of PowerMock framework?\r\n\r\nThis is third article in a series of 4 articles on Automation Testing in Microservices\r\n- [1 - Automation Testing in Microservices - Five Types Of Automation tests](/microservice-and-automation-testing){:target='_blank'}\r\n- [2 - Best Java Unit Testing Frameworks - With Examples of JUnit, Mockito and More...](/java-unit-testing-frameworks-with-examples-junit-mockito){:target='_blank'}\r\n- [3 - Programming Basics - Unit Testing - What Is Mocking?](/programming-basics-introduction-to-mocking-in-unit-tests){:target='_blank'}\r\n- [4 - Unit Testing Best Practices - with Java and Junit Examples](/unit-testing-best-practices-with-java-and-junit-examples){:target='_blank'}\r\n\r\n\r\n\r\n\r\n### Why Do We Need Mocking?\r\n\r\nHave a look at the following Java code:\r\n\r\n```java\r\n\r\n\tpublic class SomeBusinessImpl {\r\n  \tprivate DataService dataService;\r\n\t  //Constructor - public SomeBusinessImpl(DataService dataService)\r\n\t  int findTheGreatestFromAllData() {\r\n\t    int[] data = dataService.retrieveAllData();\r\n\t    int greatest = Integer.MIN_VALUE;\r\n\t\r\n\t    for (int value : data) {\r\n\t      if (value > greatest) {\r\n\t        greatest = value;\r\n\t      }\r\n\t    }\r\n\t    return greatest;\r\n\t  }\r\n\t}\r\n\r\n```\r\n\r\n```SomeBusinessImpl``` gets the data it needs, through a ```DataService```, which is an external interface. ```findTheGreatestFromAllTheData()``` represents a certain business logic applied to this data. \r\n\r\nLet's say we want to write a unit test for ```SomeBusinessImpl```. The basic approach is to let the code run as is, connect to the database and write test based on the data in the database. \r\n\r\nLet's say the data in the database has been modified by another developer. The unit test would start failing even though the code is still right. \r\n\r\nThe unit test for ```SomeBusinessImpl``` might because it has an **external dependency**, which is never stable. How do we write a test for ```SomeBusinessImpl``` which does not have such an external dependency? \r\n\r\n### Enter Mocking\r\n\r\nOne way out is to create a **mock** for ```DataService```:\r\n\r\n\r\n```java\r\n\r\n\t@RunWith(MockitoJUnitRunner.class)\r\n\tpublic class SomeBusinessMockAnnotationsTest {\r\n\t\r\n\t  @Mock\r\n\t  DataService dataServiceMock;\r\n\t\r\n\t  @InjectMocks\r\n\t  SomeBusinessImpl businessImpl;\r\n\t\r\n\t  @Test\r\n\t  public void testFindTheGreatestFromAllData() {\r\n\t    when(dataServiceMock.retrieveAllData())\r\n\t            .thenReturn(new int[] { 24, 15, 3 });    \r\n\t    assertEquals(24, businessImpl.findTheGreatestFromAllData());\r\n\t  }\r\n\r\n```\r\n\r\nYou create a mock with the ```DataService``` class, and then do what you need to with that mock. \r\n\r\nOur mock here says: \"When ```retrieveAllData()``` is called, then return the specific data ```new int[] { 24, 15, 3 }```\". We know that if the input data is ```{24, 15, 3}```, the value expected to be returned is ```24```. We write the test using this.\r\n\r\nThis makes sure that the data which is provided to ```SomeBusinessImpl``` is within the boundary of the unit test.\r\n\r\nThe code that we see above uses a popular mocking framework called Mockito. You would see that the code written is very readable, almost like plain English. Using mocks, you can mock away entire classes. Mocking also leads to stable unit tests.\r\n\r\n### Exploring Mocking Frameworks\r\n\r\n#### Using Mockito With Good Design\r\n\r\nWhen you have well defined classes and interfaces, unit testing with Mockito is a breeze. Mockito also provides useful annotations such as ```@Mock``` and ```@InjectMocks```.\r\n\r\n```java\r\n\r\n\t@RunWith(MockitoJUnitRunner.class)\r\n\tpublic class SomeBusinessMockAnnotationsTest {\r\n\t\r\n\t  @Mock\r\n\t  DataService dataServiceMock;\r\n\t\r\n\t  @InjectMocks\r\n\t  SomeBusinessImpl businessImpl;\r\n\t\r\n\t  @Test\r\n\t  public void testFindTheGreatestFromAllData() {\r\n\t    when(dataServiceMock.retrieveAllData())\r\n\t            .thenReturn(new int[] { 24, 15, 3 });    \r\n\t    assertEquals(24, businessImpl.findTheGreatestFromAllData());\r\n\t  }\r\n\r\n```\r\n\r\n#### Using PowerMock With Poor Design\r\n\r\nSometimes however, your code might be designed very poorly. You could be making heavy use of ```static``` methods, and could also be using ```private``` methods. In addition, you might need to mock a constructor. In such cases, you need to use PowerMock along with Mockito.\r\n\r\nDo check out our video on this:\r\n\r\n[![image info](/images/Capture-024-01.png)](https://www.youtube.com/watch?v=xJreuzP2C0M)\r\n\r\n### Summary\r\n\r\nMocking is a technique of unit testing a class, where we mock an external dependency in order to test our classes and methods. When unit tests are written well with mocks, they would not have any external dependencies and will not fail when external stuff changes. We looked at the Mockito framework. We also looked at the option of PowerMock for testing badly designed code. \r\n\r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-08-28-Automation-Testing-026-Five-Types-Of-Automation-Tests.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Automation Testing in Microservices - Five Types Of Automation tests\r\ndate:    2019-08-26 12:31:19\r\nsummary: Automation tests are a very important requirement to have highly successful microservice architectures. In order to take things live on a frequent basis, it is imperative to have great automation tests. In this article, we talk of the five kinds of automation tests that you can write, for your microservices.\r\ncategories:  SpringBootUnitTesting\r\npermalink:  /microservice-and-automation-testing\r\nimage: /images/unit-test-category.png\r\n---\r\n\r\nAutomation tests are a very important requirement to have highly successful microservice architectures. In order to take things live on a frequent basis, it is imperative to have great automation tests. In this article, we talk of the five kinds of automation tests that you can write, for your microservices.\r\n\r\nThis is first article in a series of 4 articles on Automation Testing in Microservices\r\n- [1 - Automation Testing in Microservices - Five Types Of Automation tests](/microservice-and-automation-testing){:target='_blank'}\r\n- [2 - Best Java Unit Testing Frameworks - With Examples of JUnit, Mockito and More...](/java-unit-testing-frameworks-with-examples-junit-mockito){:target='_blank'}\r\n- [3 - Programming Basics - Unit Testing - What Is Mocking?](/programming-basics-introduction-to-mocking-in-unit-tests){:target='_blank'}\r\n- [4 - Unit Testing Best Practices - with Java and Junit Examples](/unit-testing-best-practices-with-java-and-junit-examples){:target='_blank'}\r\n\r\n\r\n\r\n\r\n#### Unit Tests\r\n\r\nWhen you develop an application, it could contain a large number of classes, each of which probably has several methods. You normally write a test case for a particular **unit** of code. A unit could be a method, a group of methods, or  the entire code of a class. Typically, you want to keep the individual unit tests as independent as possible. \r\n\r\nA common approach to unit testing is to mock external dependencies, for effectively testing the business logic. For example, a unit test could be run independent of a database. This ensures that tests do not have external dependencies and do not fail when something external to the test changes. \r\n\r\n#### Layer Integration Tests\r\n\r\nWhen we develop enterprise applications, we generally structure them into layers. For instance, a web applications could have  web, business and data layers. You would want these separate layers to work well together. Therefore, you write layer integration tests to ensure their proper integration. \r\n\r\nFor example, when you make a call to the web layer, is it being propagated correctly to the business layer, and from there to the data layer? Finally, are you getting a proper response to the request? \r\n\r\n#### API Tests\r\n\r\nWhen we create a microservice, we end up offering APIs for the consumers to access and consume resources. Examples are REST and SOAP APIs. You can test an API by writing an automation test for it. Even for such API tests, the need of the hour is an in-memory database, as it is good to avoid external dependencies.  \r\n\r\n#### System Tests\r\n\r\nHere is where all the systems external to our application come into the picture, during testing. You would start accounting for databases, external interfaces and other dependencies needed by your application. This is where you actually deploy your application in a real-world environment.  \r\n\r\n#### User Acceptance Tests\r\n\r\nThis is the final level of automation testing, where you test every aspect of the end-user usage scenarios. The focus here is on creating real-time usage scenarios, such as accessing a production-mode database for testing the logic. This step is necessary before you take the application live.\r\n\r\nDo check out our video on this:\r\n\r\n[![image info](/images/Capture-026-02.png)](https://www.youtube.com/watch?v=kwqH1C76siE)\r\n\r\n### Summary\r\n\r\nIn this article, we explored the five different kinds of automation testing that is generally performed on applications. These are unit testing, layer integration testing, API testing, system testing and user acceptance testing. \r\n\r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-08-28-Automation-Testing-099-Top-Six-Java-Unit-Testing-Frameworks.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Best Java Unit Testing Frameworks - With Examples of JUnit, Mockito and More...\r\ndate:    2019-06-27 12:31:19\r\nsummary: Unit Testing is an important skill for programmers. What are the frameworks you can use to write great unit tests in the Java World?\r\ncategories:  SpringBootUnitTesting\r\npermalink:  /java-unit-testing-frameworks-with-examples-junit-mockito\r\nimage: /images/unit-test-category.png\r\n---\r\n\r\nUnit Testing is an important skill for programmers. What are the frameworks you can use to write great unit tests in the Java World?\r\n\r\nThis is second article in a series of 4 articles on Automation Testing in Microservices\r\n- [1 - Automation Testing in Microservices - Five Types Of Automation tests](/microservice-and-automation-testing){:target='_blank'}\r\n- [2 - Best Java Unit Testing Frameworks - With Examples of JUnit, Mockito and More...](/java-unit-testing-frameworks-with-examples-junit-mockito){:target='_blank'}\r\n- [3 - Programming Basics - Unit Testing - What Is Mocking?](/programming-basics-introduction-to-mocking-in-unit-tests){:target='_blank'}\r\n- [4 - Unit Testing Best Practices - with Java and Junit Examples](/unit-testing-best-practices-with-java-and-junit-examples){:target='_blank'}\r\n \r\n\r\n## You will learn\r\n- What are best java unit testing frameworks?\r\n- What is JUnit? How do you use JUnit for unit testing?\r\n- What is Mockito? \r\n- What is Mocking?\r\n- How do you write unit tests with Junit, Mockito, AssertJ and other frameworks? \r\n- What are the best java unit testing frameworks for writing great asserts?\r\n\r\n\r\n\r\n### The Base Unit Testing Framework - JUnit / TestNG\r\n\r\nWhenever you write a unit test, you execute some code, and then check its output. You need a basic framework in place to run a large number of tests in a similar manner. \r\n\r\n#### JUnit\r\n\r\nThe JUnit framework provides the basic framework that allows you to specify the test that you want to run, along with its inputs, and the result that comes out of it. \r\n\r\nHave a look at the following test:\r\n\r\n```java\r\n\r\n\t@Test\r\n\tpublic truncateAInFirst2Positions_AinFirstPosition() {\r\n\t\tassertEquals(\"CD\", helper.truncateAInFirstPosition(\"ACD\"));\r\n\t}\r\n\r\n```\r\n\r\nNotice the annotation ```@Test``` used the decorate the test. The name of the test is descriptive, and demonstrates the intent of the test. JUnit provides different kinds of assertion methods to check the result of the code executed within a test. These include ```assertEquals()```, ```assertTrue()``` and ```assertFalse()```. \r\n\r\nNow have a look at this one, that tests a negative scenario:\r\n\r\n```java\r\n\r\n\t@Test\r\n\tpublic testAreFirstAndLastTwoCharactersTheSame_BasicNegativeScenario() {\r\n\t\tassertFalse(helper.areFirstAndLastTwoCharactersTheSame(\"ABCD\"));\r\n\t}\r\n\r\n```\r\n\r\nJUnit also supports something called parameterized tests. \r\n\r\n#### TestNG\r\n\r\nTestNG is a good alternative to JUnit to write unit tests, that makes it easy to write customized tests. Suppose you have the test data needed to execute your suites in a spreadsheet or an XML document. TestNG makes it easy to get the data for tests to be written around them. \r\n\r\nAt a high level, JUnit and TestNG are frameworks that enable you to write tests and check results. If a test succeeds, you see a green bar. Else, a red bar. \r\n\r\n### Mocking Frameworks - Mockito and EasyMock\r\n\r\nWhen writing unit tests, it is often required to mock or stub dependencies. \r\n\r\nMocking is preferred to stubbing. There are couple of great options for mocking in the java world - Mockito and EasyMock. \r\n\r\n#### Mockito\r\n\r\nHave a look at the following example:\r\n\r\n```java\r\n\r\n\tpublic class SomeBusinessImpl {\r\n\t\tprivate DataService dataService;\r\n\t\t//Constructor - public SomeBusinessImpl(DataService dataService) { //... }\r\n\r\n\t\tint findTheGreatestFromAllData() {\r\n\t\t\tint[] data = dataService.retrieveAllData();\r\n\t\t\tint greatest = Integer.MIN_VALUE;\r\n\t\t\r\n\t\t\tfor (int value : data) {\r\n\t\t\t\tif(value > greatest)\r\n\t\t\t\t\tgreatest = value;\r\n\t\t\t}\r\n\t\t\treturn greatest;\r\n\t\t}\r\n\t}\r\n\r\n``` \r\n\r\nThe value returned by the ```findTheGreatestFromAllData()``` depends on the data that comes back from the data service. \r\n\r\nTo be able to write a good unit test for this method, you need to mock this dependency out. \r\n\r\nHave a look at the following test for the class:\r\n\r\n```java\r\n\r\n\t@Test\r\n\tpublic void testFindTheGreatestFromAllData() {\r\n\t\tDataService dataServiceMock = mock(DataService.class);\r\n\t\twhen(dataServiceMock.retrieveAllData())\r\n\t\t\t.thenReturn(new int[] {24, 15, 3});\r\n\r\n\t\tSomeBusinessImpl businessImpl = new SomeBusinessImpl(dataServiceMock);\r\n\t\tint result = businessImpl.returnTheGreatestFromAllData();\r\n\t\t\r\n\t\tassertEquals(24, result);\r\n\t}\r\n\r\n```\r\n\r\nMockito make it easy to mock the DataService. Here, we use its ```mock()``` method to mock the ```DataService```, and inject the mock into the ```SomeBusinessImpl``` class. \r\n\r\nMockito also provides great annotations to inject mocks automatically.\r\n\r\n```java\r\n\r\n\t@RunWith(MockitoJUNitRunner.class)\r\n\tpublic class SomeBusinessMockAnnotationsTest {\r\n\t\t@Mock\r\n\t\tDataService dataServiceMock;\r\n\r\n\t\t@InjectMocks\r\n\t\tSomeBusinessImpl businessImpl;\r\n\r\n\t\t@Test\r\n\t\tpublic void testFindTheGreatesFromAllData() {\r\n\t\t\twhen(dataServiceMock.retrieveAllData())\r\n\t\t\t\t.thenReturn(new int[] {24, 15, 3});\r\n\t\t\tassertEquals(24, businessImpl.findTheGreatestFromAllData());\r\n\t\t}\r\n\t}\r\n\r\n```\r\n\r\nAnnotations such as ```@Mock``` and ```@InjectMocks``` take care of what their names suggest, thereby making the test code smaller, and more readable.\r\n\r\n#### EasyMock\r\n\r\nEasyMock is also a mocking framework that can be effectively used in unit tests. It is a popular alternative to Mockito.\r\n\r\n### Mocking complex scenarios - Use PowerMock\r\n\r\nFramworks such as Mockito allow you to insert mocks only when the code design is good. When the design is not so good, PowerMock comes to your rescue. \r\n\r\nPowermock is useful when you want to mock static methods, constructors and private methods.   \r\n\r\nHave a look at the following code:\r\n\r\n```java\r\n\r\n\tinterface Dependency {\r\n\t\tList<Integer> retrieveAllStats();\r\n\t}\r\n\r\n\tpublic class SystemUnderTest {\r\n\t\tprivate Dependency dependency;\r\n\r\n\t\tpublic int methodUsingAnArrayListConstructor() {\r\n\t\t\tArrayList list = new ArrayList();\r\n\t\t\treturn list.size();\r\n\t\t}\r\n\r\n\t\tpublic int methodCallingAStaticMethod() {\r\n\t\t\t//private methodUnderTest calls static method SomeClass.staticMethod\r\n\r\n\t\t\tList<Integer> stats = dependency.retrieveAllStats();\r\n\t\t\t\r\n\t\t\tlong sum = 0;\r\n\t\t\tfor(int stat : stats) {\r\n\t\t\t\tsum += stat;\r\n\t\t\t}\r\n\t\t\treturn UtilityClass.staticMethod(sum);\r\n\t\t}\r\n\r\n\t\tprivate long privateMethodUnderTest() {\r\n\t\t\tList<Integer> stats = dependency.retrieveAllStats();\r\n\t\t\t\r\n\t\t\tlong sum = 0;\r\n\t\t\tfor(int stat : stats) {\r\n\t\t\t\tsum += stat;\r\n\t\t\t}\r\n\r\n\t\t\treturn sum;\r\n\t\t}\r\n\t}\r\n\r\n```\r\n\r\nHere, ```SomeClass.staticMethod``` is a static method that is defined. Therefore, we have a need to mock it out. We need to test the method ```methodCallingAStaticMethod()``` after this mock. Have a look at the following test code:\r\n\r\n```java\r\n\r\n\t@RunWith(PowerMockRunner.class)\r\n\t@PrepareForTest({UtilityClass.class})\r\n\t\r\n\tpublic class PowerMockitoMockingStaticMethodTest {\r\n\t\t@Mock\r\n\t\tDependency dependencyMock;\r\n\t\t\r\n\t\t@InjectMocks\r\n\t\tSystemUnderTest systemUnderTest;\r\n\r\n\t\t@Test\r\n\t\tpublic void powerMockito_MockingAStaticMethodCall() {\r\n\t\t\twhen(dependencyMock.retrieveAllStats()).thenReturn(Arrays.asList({1, 2, 3}));\r\n\t\t\t\r\n\t\t\tPowerMockito.mockStatic(UtilityClass.class);\r\n\t\t\twhen(UtilityClass.staticMethod(anyLong())).thenReturn(150);\r\n\r\n\t\t\tassertEquals(150, systemUnderTest.methodCallingAStaticMethod);\r\n\r\n\t\t\t//Verify the specific method call\r\n\r\n\t\t\t//First, call PowerMockito.verifyStatic()\r\n\t\t\t//Second, call the method to be verified\r\n\r\n\t\t\tPowerMockito.verifyStatic(); \r\n\t\t\tUtilityClass.staticMethod(1 + 2 + 3);\r\n\r\n\t\t\t//verify exact number of calls\r\n\r\n\t\t\t//PowerMockito.verifyStatic(Mockito.times(1));\r\n\t\t}\r\n\t}\r\n\r\n```  \r\n\r\nHere we have written code that allows us to mock out a static method. \r\n\r\nIt is also possible to mock a constructor:\r\n\r\n```java\r\n\r\n\t@RunWith(PowerMockRunner.class)\r\n\t@PrepareForTest({UtilityClass.class})\r\n\tpublic class PowerMockitoMockingConstructorTest {\r\n\t\tprivate static final int SOME_DUMMY_SIZE = 100;\r\n\r\n\t\t@Mock\r\n\t\tDependency dependencyMock;\r\n\t\t\r\n\t\t@InjectMocks\r\n\t\tSystemUnderTest systemUnderTest;\r\n\r\n\t\t@Test\r\n\t\tpublic void powerMockito_MockingAConstructor throws Exception {\r\n\t\t\tArrayList<String> mockList = mock(ArrayList.class);\r\n\t\t\tstub(mockList.size()).toReturn(SOME_DUMMY_SIZE);\r\n\r\n\t\t\tPowerMockito.whenNew(ArrayLst.class).withAnyArguments().thenReturn(mockList);\r\n\r\n\t\t\tint size = systemUnderTest.methodUsingAnArrayListConstructor();\r\n\t\t\tassertEquals(SOME_DUMMY_SIZE, size);\r\n\t\t}\r\n\t}\r\n\r\n``` \r\n\r\nWhen the constructor is called, the ```mockList``` is returned instead. \r\n\r\nPowerMock can also be used to mock private methods:\r\n\r\n```java\r\n\r\n\t@RunWith(PowerMockRunner.class)\r\n\t@PrepareForTest({UtilityClass.class})\r\n\tpublic class PowerMockitoMockingPrivateMethodTest {\r\n\r\n\t\t@Mock\r\n\t\tDependency dependencyMock;\r\n\t\t\r\n\t\t@InjectMocks\r\n\t\tSystemUnderTest systemUnderTest;\r\n\r\n\t\t@Test\r\n\t\tpublic void powerMockito_CallingAPrivateMethod throws Exception {\r\n\t\t\twhen(dependencyMock.retrieveAllStats()).thenReturn(Arrays.asList({1, 2, 3}));\r\n\r\n\t\t\tlong value = (Long) WhiteBox.invokeMethod(systemUnderTest,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"PrivateMethodUnderTest\");\r\n\t\t\tassertEquals(6, value);\r\n\t\t}\r\n\r\n```\r\n\r\nNote that you cannot directly invoke a private method from test code. We are using the functionality of a class named ```WhiteBox```, to which we pass the string name of the private method. \r\n\r\n### Writing great asserts using AssertJ / Hamcrest\r\n\r\nWhenever you write tests, you want to have great assertions.\r\n\r\n#### AssertJ\r\n\r\nHave a look at the folowing code:\r\n\r\n```java\r\n\r\n\tpublic class AssertJTest {\r\n\t\t@Test\r\n\t\tpublic void learning() {\r\n\t\t\tList<Integers> numbers = Arrays.asList({12, 15, 45});\r\n\r\n\t\t\tassertThat(numbers).hasSize(3)\r\n\t\t\t\t\t\t\t\t\t.contains(12, 15)\r\n\t\t\t\t\t\t\t\t\t.allMatch(x -> x > 10)\r\n\t\t\t\t\t\t\t\t\t.allMatch(x -> x < 100)\r\n\t\t\t\t\t\t\t\t\t.noneMatch(x -> x < 0);\r\n\t\t\tassertThat(\"\").isEmpty;\r\n\t\t\tassertThat(\"ABCDE\").contains(\"BCD\")\r\n\t\t\t\t\t\t\t\t\t.startsWith(\"ABC\")\r\n\t\t\t\t\t\t\t\t\t.endsWith(\"\"CDE);\r\n\t\t}\r\n\t}\r\n\r\n```\r\n\r\n```numbers``` is a list of integers that contains 3 values as shown. AssertJ provides the method ```assertThat()```, which allows you to chain together multiple assertions. \r\n\r\nInterestingly, you can see that the method ```allMatch()``` accepts a lambda expression to test the truth value of a predicate.  The call ```allMatch(x -> x > 10)``` checks whether all the integers within ```numbers``` match the predicate of being greater than ```10```. \r\n\r\n```assertThat()``` also works with strings, and works well especially with alphabetical text. The code is there for you to see.\r\n\r\n#### Hamcrest\r\n \r\nHamcrest provides an alternative to AssertJ to write great asserts. \r\n\r\n```java\r\n\r\n\tpublic class HamcrestMatchersTest {\r\n\t\tpublic void learning() {\r\n\t\t\tList<Integer> numbers = Arrays.asList({12, 15, 45});\r\n\r\n\t\t\tassertThat(numbers, hasSize(3));\r\n\t\t\tassertThat(numbers, hasItems(12, 15));\r\n\t\t\tassertThat(numbers, everyItem(greaterThan(10)));\r\n\t\t\tassertThat(numbers, everyItem(lessThan(100)));\r\n\r\n\t\t\tassertThat(\"\", isEmptyString());\r\n\t\t\tassertThat(\"ABCDE\", containsString(\"BCD\"));\r\n\t\t\tassertThat(\"ABCDE\", startsWith(\"ABC\"));\r\n\t\t\tassertThat(\"ABCDE\", endsWith(\"CDE\"));\r\n\t\t}\r\n\t}\r\n\r\n```\r\n\r\n### Using Spring Unit\r\n\r\nTypical applications have multiple layers and you want to write unit tests for different layers - web, business and data. \r\n\r\nHere are some of the recommended options:\r\n- Web layer - Spring MockMVC\r\n- Data layer - DataJpaTest\r\n- Business layer - Mockito based test preferably without launching a Spring Context\r\n\r\n#### Unit Tests For The Web Layer  \r\n\r\nHave a look at the following code:\r\n\r\n```java\r\n\r\n\t@RunWith(SpringRunner.class)\r\n\t@WebMvcTest(ItemController.class)\r\n\tpublic class ItemControllerTest {\r\n\t\t@Autowired\r\n\t\tprivate MockMvc mockMvc;\r\n\r\n\t\t@MockBean\r\n\t\tprivate ItemBusinessService businessService;\r\n\r\n\t\t@test\r\n\t\tpublic void dummyItem_basic throws Exception {\r\n\t\t\tRequestBuilder request = MockMvcRequestBuilders\r\n\t\t\t\t\t\t\t\t\t\t.get(\"/dummy-item\")\r\n\t\t\t\t\t\t\t\t\t\t.accept(MediaType.APPLICATION_JSON);\r\n\r\n\t\t\tMvcResult result = mockMvc.perform(request)\r\n\t\t\t\t\t\t\t\t.andExpect(status().isOk())\r\n\t\t\t\t\t\t\t\t.andExpect(content()\r\n\t\t\t\t\t\t\t\t\t\t\t.json(\"{\\\"id\\\":1, \\\"name\\\":\\\"Ball\\\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t, \\\"price\\\":10, \\\"quantity\\\":5}\"))\r\n\t\t\t\t\t\t\t\t.andReturn();\r\n\r\n\t\t//JSONAssert.assertEquals(expected, result.getResponse.getContentAsString(), flase);\r\n\t\t}\r\n\t}\r\n\r\n```\r\n\r\nThis unit test uses the Spring Unit framework, and the Spring MockMVC framework. \r\n\r\nWe are launching a Spring context and wiring  ```ItemController``` to use a mock for ```ItemBusinessService```. \r\n\r\nSpring MockMVC framework makes it easy to perform REST API requests. In the code above we are using it to execute a REST API, and then setting certain expectations of the result: \r\n* The URL is ```/dummy-item```\r\n* The accepted content type is ```application+json```\r\n* After the request has been sent, check that the response status is \"OK\", and the content is a JSON object with certain data\r\n\r\nIt is also possible for us to mock the business service:\r\n\r\n```java\r\n\r\n\t@Test\r\n\tpublic void retrieveAllItems_basic() throws Exception {\r\n\t\twhen(businessService.retrieveAllItems()).thenReturn(\r\n\t\t\t\t\tArrays.asList(new Item(2, \"Item2\", 10, 10)\r\n\t\t\t\t\t\t\t\t\t, new Item(3, \"Item3\", 20, 20)));\r\n\r\n\t\tRequestBuilder request = MockMvcRequestBuilders\r\n\t\t\t\t\t\t\t\t\t\t.get(\"/all-items-from-database\")\r\n\t\t\t\t\t\t\t\t\t\t.accept(MediaType.APPLICATION_JSON);\r\n\r\n\t\tMvcResult result = mockMvc.perform(request)\r\n\t\t\t\t\t\t\t\t.andExpect(status().isOk())\r\n\t\t\t\t\t\t\t\t.andExpect(content()\r\n\t\t\t\t\t\t\t\t\t\t\t.json(\"[{\\\"id\\\":3, \\\"name\\\":\\\"Item3\\\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t, \\\"price\\\":20}]\"))\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t,{\\\"id\\\":2, \\\"name\\\":\\\"Item2\\\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t, \\\"price\\\":10}]\")\r\n\t\t\t\t\t\t\t\t.andReturn();\r\n\t}\r\n\r\n```\r\n\r\nWhen ```retrieveAllItems()``` is called on ```businessService```, it is made to return the fixed list of items shown. Once again, we execute a request to a different URL, and when the response comes in, the content is verified to be the proper JSON type, with the expected data.\r\n\r\n#### Unit Tests For The Data Layer  \r\n\r\nDataJpaTest can be used during unit testing of the data layer in an Spring Based enterprise application.  DataJpaTest uses an in-memory database for the unit test, by default.\r\n\r\n```java\r\n\r\n\t@RunWith(SpringRunner.class)\r\n\t@DataJpaTest\r\n\tpublic class ItemRepositoryTest {\r\n\t\t@Autowired\r\n\t\tprivate ItemRepository repository;\r\n\t\t\r\n\t\t@Test\r\n\t\tpublic void testFindAll() {\r\n\t\t\tList<Item> items = repository.findAll();\r\n\t\t\tassertEquals(3, items.size());\r\n\t\t}\r\n\t\t\r\n\t\t@Test\r\n\t\tpublic void testFindOne() {\r\n\t\t\tItem item = repository.findById(10001).get();\r\n\t\t\tassertEquals(\"Item1\", item.getName());\r\n\t\t}\r\n\t}\r\n\r\n```\r\n\r\n### Asserting JSON Responses - JSONAssert / JSONPath\r\n\r\nAlmost all REST API use JSON. How do you assert JSON Content?\r\n\r\n#### Using JSONAssert\r\n\r\nHave a look at the following test code:\r\n\r\n![image info](images/Capture-099-02.png)\r\n\r\n```actualResponse``` is the content that is returned by a service. \r\n\r\nJSONAssert allows us to check specific parts of the request that we are interested in. \r\n* Within the test ```jsonAssert_StrictFalse()```, we are only concerned with the ```id```, ```name``` and ```price```, ignoring the ```quantity```.\r\n* You can also write a test to check without escape characters, as we have done with ```jsonAssert_WithoutEscapeCharacters()```. This is much easier on the eye, and can be used to compare with an actual response that contains escape characters. This mode of comparing responses is called Strict False. \r\n\r\nYou can also do assertions in Strict mode, where you compare all the fields, and in the actual format they are in. That is what we have done with ```jsonAssert_StrictFalse_ExactMatchExceptForSpaces()```.\r\n\r\n#### Using JSONPath\r\n\r\nAlternative approach in asserting JSONs is the JSONPath framework. You might want to check for specific aspects of the response, such as three items in the response. \r\n\r\n![image info](images/Capture-099-03.png)\r\n\r\nJust as XPath is used to query XML, JSONPath is used to query JSON. \r\n* The expression ```$.length()``` returns the number of elements. An assertion can then be used on that returned value.\r\n* You can check for all the ```id``` fields with ```$..id``` and compare them with a list of pre-fixed values. \r\n* You can extract slices of the element list that is in the resonse, such as the first element (```$.[1]```), or the first 2 elements (```$.[0:2]```). \r\n* You can query the reponse to check if a particular field is present : ```$.[?(@.name == 'Eraser')]``` or ```$.[?(@.quantity == 5)]```.\r\n\r\nDo check out our video on the same topic:\r\n\r\n[![image info](images/Capture-099-01.png)](https://www.youtube.com/watch?v=VG7ohV4weYw)\r\n\r\n### Summary\r\n\r\nIn this article, we looked at a wide variety of unit testing fraemworks present in the Java world. We started with the basic unit testing framework JUnit, and its alternative, TestNG. We looked at how we can do mocking with Mockito and its alternative, EasyMock. We then had a look at Powermock, which is useful when mocking static methods, private methods and constructors.\r\n\r\nWe then had a feel of powerful assertion frameworks such as AsserJ and Hamcrest. Spring Unit framework provides MockMVC as the mocking framework for the web layer and DataJPATest for the data layer. Finally, we explored JSONAssert and JSONPath, used to assert JSON responses in a unit test.   \r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-08-28-Automation-Testing107-JUnit-Unit-Testing-Best-Practices.md",
    "content": "---\r\nlayout: post\r\ntitle: Unit Testing Best Practices - with Java and Junit Examples\r\ndate:    2019-08-28 12:31:19\r\nsummary: Unit Testing is often underrated. As far as I am concerned, having good unit tests seperates good projects from bad. In this article, let's look at unit testing best practices in depth. We use examples from Java and JUnit to illustrate the concepts. However, the best practices are applicable irrespective of the programming language used.\r\ncategories:  SwProgramming\r\npermalink:  /unit-testing-best-practices-with-java-and-junit-examples\r\nimage: /images/unit-test-category.png\r\n---\r\n\r\nUnit Testing is often underrated. As far as I am concerned, having good unit tests seperates good projects from bad. In this article, let's look at unit testing best practices in depth. We use examples from Java and JUnit to illustrate the concepts. However, the best practices are applicable irrespective of the programming language used.\r\n \r\n## You will learn\r\n- What are the benefits of Unit Testing?\r\n- What is a good unit test?\r\n- What are examples of Unit Testing Best Practices?\r\n- How do you write great unit tests?\r\n- What are the important principles for Unit Testing?\r\n\r\nThis is fourth article in a series of 4 articles on Automation Testing in Microservices\r\n- [1 - Automation Testing in Microservices - Five Types Of Automation tests](/microservice-and-automation-testing){:target='_blank'}\r\n- [2 - Best Java Unit Testing Frameworks - With Examples of JUnit, Mockito and More...](/java-unit-testing-frameworks-with-examples-junit-mockito){:target='_blank'}\r\n- [3 - Programming Basics - Unit Testing - What Is Mocking?](/programming-basics-introduction-to-mocking-in-unit-tests){:target='_blank'}\r\n- [4 - Unit Testing Best Practices - with Java and Junit Examples](/unit-testing-best-practices-with-java-and-junit-examples){:target='_blank'}\r\n\r\n\r\n\r\n### What Is Unit Testing?\r\n\r\nBy unit testing, we are referring to the xUnit testing (JUnit, NUnit, etc) done on individual code units, such as methods and classes.\r\n\r\n### Your Attitude Toward Unit Testing\r\n\r\nThe most important aspect of unit testing is your attitude towards it. \r\n\r\n##### Unit Testing Is More Important Than Code\r\n\r\nUnit testing is more important than coding, because it gives you the confidence to carry out continuous refactoring of code. As a result, the overall quality of the low level design improves continuously.\r\n\r\n##### Unit Tests Are Best Written Before Code\r\n\r\nThe practice of writing unit tests even before you write code is called test driven development (TDD). TDD gives you an outside-in perspective, because you look at code functionality from the perspective of the test. Following TDD improves low level design along with providing with great unit tests. \r\n\r\n### The Unit Testing Principles\r\n\r\nWe start with look at generic principles that are applicable to any code, including unit test code. After that we look at principles specific to Unit Tests.\r\n\r\n#### The Four Principles Of Simple Design\r\n\r\nAny code, including unit test code, should adhere to Four Principles of Simple Design.\r\n\r\nA software application is said to have a simple design if it:\r\n* **Runs all tests**\r\n* **Contains no duplication**\r\n* **Expresses intent of programmers**\r\n* **Minimizes number of classes and methods**\r\n\r\n#### Unit Test Specific Principles\r\n\r\nHere are some of the important principles which are specific to Unit Tests.\r\n\r\n##### Unit Tests Fail Only when there is a problem with In Production Code\r\n\r\nLet's consider an example where you write a unit test depending on some data in the database. A new developer accidentally changed the data. What would happen? Unit test would fail.\r\n\r\nLet's say it happens again. \r\n\r\nThe development team would lose confidence in unit tests. \r\n\r\n> Over a period of time, they would start ignoring tests which are failing.\r\n\r\nUnit tests should fail only when there is something wrong with the code. How do we ensure this?\r\n\r\n###### No dependencies between test conditions\r\n\r\nDon't assume the order in which the tests would be run. \r\n\r\nJUnit does not guarantee that tests would run in the same order that they are written in.\r\n\r\n###### Avoid External Dependencies\r\n\r\nAvoid writing tests that depends on an external database, external interface, a container or a network connection. \r\n\r\nIf you need to test code functionality that otherwise depends on these, make use of stubs or mock servers.\r\n\r\n###### Avoid Depending On System Date etc\r\n\r\nSince the system on which the code will is deployed will be different the development machine, don't depend on any setup on a machine. Also, avoid hard-coding of system paths within the test code. This will make the test code tied to one machine. \r\n\r\n\r\n##### Unit Tests Find All Problems With Production Code\r\n\r\nThis is the very reason why we test.  \r\n* Test everything that could possibly break. Test exceptions well, and closely test boundary conditions.\r\n* Try to use strong assertions to detect failures. Do not write tests just for coverage.\r\n\r\nQuoting a common JUnit maxim: \"Test until fear turns to boredom.\" \r\n\r\n```\r\n\r\n\tbecomeTimidAndTestEverything\r\n\twhileWritingTheSameThingOverAndOverAgain\r\n\t\tbecomeMoreAggressive\r\n\t\twriteFewerTests\r\n\t\twriteTestsForMoreInterestingCases\r\n\t\tifGetBurnedByStupidDefect\r\n\t\t\tfeelStupid\r\n\t\t\tbecomeTimidAndTestEverything\r\n\t\tend\r\n\tEnd\r\n\r\n```\r\n\r\nRemember, this is an infinite loop!\r\n\r\n#### Unit Tests Run Quickly\r\n\r\nTo maximize benefits, tests should be run as frequently as possible. \r\n\r\nIf unit tests are slow, they would be run less often. \r\n\r\nAvoid reading from the file system, or from the network. \r\n\r\nA common solution to test duration is to collect all long-running tests into a single test suite, and run that suite less often.\r\n\r\n#### Unit Tests should be easy to read\r\n\r\nTypical tests should not take more than 15 seconds to read. \r\n\r\nHere are a couple of examples we use, in explaining Unit Testing standards more effectively:\r\n\r\n* ```Amount getClientProductsSum(List<Products>)```:\r\n\t*  For a list of Products, calculate the sum of Product amounts and return the total.\r\n\t*  Throw a ```DifferentCurrenciesException``` if products have different currencies.\r\n\r\n##### Example-1: Unit Testing Principle - Easy To Understand\r\n\r\n```java\r\n\r\n\t@Test\r\n\tpublic void testClientProductsSum() {\r\n\t\tList<Product> products = new ArrayList<Products>();\r\n\r\n\t\tproducts.add(new ProductImpl(100, \"Product 15\", ProductType.BANK_GUARANTEE, \r\n\t\t\t\t\t new AmountImpl(new BigDecimal(\"5.0\"), Currency.EURO)));\r\n\t\t\r\n\t\tproducts.add(new ProductImpl(120, \"Product 20\", ProductType.BANK_GUARANTEE, \r\n\t\t\t\t\t new AmountImpl(new BigDecimal(\"6.0\"), Currency.EURO)));\r\n\r\n\t\tAmount temp = null;\r\n\r\n\t\ttry {\r\n\t\t\ttemp. clientBO.getClientProductsSum(products);\r\n\t\t} catch(DirrerentCurrenciesException e) {\r\n\t\t\tfail();\r\n\t\t}\r\n\r\n\t\tassertEquals(Currency.EURO, temp.getCurrency());\r\n\t}\r\n\r\n```\r\n\r\nThis test code is not very readable, isn't it! The following is another way to write the same test:\r\n\r\n```java\r\n\r\n\tpublic void testClientProductsSum_AllProductsSameCurrency() throws DifferentCurrenciesException{\r\n\t\tAmount[] amounts = {\r\n\t\t\tnew AmountImpl(new BigDecimal(\"5.0\"), Currency.EURO),\r\n\t\t\tnew AmountImpl(new BigDecimal(\"6.0\"), Currency.EURO)\r\n\t\t};\r\n\r\n\t\tList<Product> products = createProductsWithAmounts(amounts);\r\n\t\tAmount actual = clientBO.getClientProductsSum(products);\r\n\t\tAmount expected = new AmountImpl(new BigDecimal(\"11.0\"), Currency.EURO);\r\n\t\t\r\n\t\tassertAmount(actual, expected);\r\n\t}\r\n\r\n```\r\n\r\nThe second version is very easy to understand. The inputs and expectations are clearly states, and this makes it very readable. Teh differences between the two can be summed up in the following points:\r\n\r\n###### Name Of The Test\r\n\r\nThe name of the test should include the condition being tested and if necessary, the result.  hence, ```testClientProductsSum_AllProductsSameCurrency()``` is preferrable to ```testClientProductsSum()```. Also, variations such as ```testClientProductsSum_DifferentCurrenciews_ThrowException()``` takes on a different condition, and also includes the result. This is preferrable to something mundane such as ```testClientProductsSum()```. \r\n\r\n###### The keyword \"test\" Is Now Superfluous\r\n\r\nIn later versions of JUnit, after annotations were supported, you don't need to prefix \"test\" before every test name. Something like ```clientProductsSum_DifferentCurrenciews_ThrowException()``` will do.  \r\n\r\n###### Highlight Values Important To A Test\r\n\r\nCompare how test setup is being done in the two versions.\r\n\r\n```java\r\n\r\n\tList<Product> products = new ArrayList<Products>();\r\n\r\n\t\tproducts.add(new ProductImpl(100, \"Product 15\", ProductType.BANK_GUARANTEE, \r\n\t\t\t\t\t new AmountImpl(new BigDecimal(\"5.0\"), Currency.EURO)));\r\n\t\t\r\n\t\tproducts.add(new ProductImpl(120, \"Product 20\", ProductType.BANK_GUARANTEE, \r\n\t\t\t\t\t new AmountImpl(new BigDecimal(\"6.0\"), Currency.EURO)));\r\n\r\n```\r\n\r\nOver here, there are a lot of values in the setup code that are not relevant to the test at all, such as ```120```, ```\"Product 15\"```, ```ProductType.BANK_GUARANTEE``` and the like. Compare this to the following in the second example:\r\n\r\n```java\r\n\r\n\tAmount[] amounts = {\r\n\t\t\tnew AmountImpl(new BigDecimal(\"5.0\"), Currency.EURO),\r\n\t\t\tnew AmountImpl(new BigDecimal(\"6.0\"), Currency.EURO)\r\n\t\t};\r\n\r\n\t\tList<Product> products = createProductsWithAmounts(amounts);\r\n\r\n```\r\n\r\nOne the data relevant to the condition being tested are included in the test.\r\n\r\n###### One Condition Per Test\r\n\r\nThis standard states that:\r\n\r\n* The test results should be presented in simple code without using conditionals, loops, etc.  \r\n* If the test fails, you need to know the exact condition that is failing.\r\n* Create useful assertion methods to test the specific condition.\r\n\r\n```java\r\n\r\n\tprivate void assertAmount(Amount expected, Amount actual) {\r\n\t\tassertEquals(expected.getCurrency(), actual.getCurrency());\r\n\t\tassertEquals(expected.getValue(), actual.getValue());\r\n\t}\r\n\r\n```\r\n\r\n###### No Exception Handling Within A Test\r\n\r\nHave the test method itself throw an exception instead. Prefer the following code:\r\n\r\n```java\r\n\r\n\tpublic void testClientProductsSum_AllProductsSameCurrency() throws DifferentCurrenciesException{\r\n\t\t//...\r\n\t}\r\n\r\n```\r\n\r\nInstead of the following:\r\n\r\n```java\r\n\r\n\t//BAD PRACTICE\r\n\ttry {\r\n\t\t\ttemp. clientBO.getClientProductsSum(products);\r\n\t\t} catch(DirrerentCurrenciesException e) {\r\n\t\t\tfail();\r\n\t\t}\r\n\r\n```\r\n\r\nThis keeps the code very readable. If an exception is thrown, the test would fail any way.\r\n\r\n###### Use Annotated Exception Handling To Test For Exceptions\r\n\r\nUse code that uses annotated exceptions, such as the following:\r\n\r\n```java\r\n\r\n\t@Test(exception=DifferentCurrenciesException.class)\r\n\tpublic void testClientProductsSum_DifferentCurrencies_ThrowsException() throws DifferentCurrenciesException{\r\n\t\t//... Code That Throws Exception\r\n\t}\r\n\r\n```\r\n\r\nAvoid code that does things like:\r\n\r\n```java\r\n\r\n\t//BAD CODE WARNING\r\n\t@Test\r\n\tpublic void testClientProductsSum1() {\r\n\t\t//...\r\n\r\n\t\ttry {\r\n\t\t\t//... Code That Throws Exception\r\n\t\t} catch(DirrerentCurrenciesException e) {\r\n\t\t\tfail(\"DifferentCurrenciesException expected\");\r\n\t\t}\r\n\r\n\t\t//...\r\n\t}\r\n\r\n```\r\n\r\nIf the particular exception is thrown, the annotation detects it, and the test would pass. Otherwise, the test would fail.\r\n\r\n###### Use The New Features\r\n\r\nMaking use of new features makes code easy to read. Here are a few examples:\r\n\r\n* Comparing arrays: Use ```assertArrayEquals(expectedArray, actualArray)```\r\n* Testing exceptions: Use ```<Annotation>(exception=Exception.class)```\r\n* Testing performance: use an annotation like this: ```<Annotation>(timeout=2)```. This sets a timeout of 2 milliseconds. The moment the test takes longer to run, it will fail.\r\n\r\n#### Other Unit Testing Best Practices\r\n\r\n##### Unit Tests Should be Separated From Production Code\r\n\r\nUnit tests should be organized in separate folders and should not be part of your production deployable unit.\r\n\r\n##### Unit Tests should be included in CI Builds\r\n\r\nAll unit tests should be run in a CI Build as soon as the code is commited. This leads to early detection of bugs.\r\n\r\nYou can check out our video on the same topic:\r\n\r\n[![image info](images/Capture-107-01.png)](https://www.youtube.com/watch?v=BukAouJgEjo)\r\n\r\n### Summary\r\n\r\nIn this article, we focused on the principles behind writing good unit tests. \r\n\r\nIf you follows these principles of unit testing, the result is that your tests can be used a documentation. For example, have  a look at the tests that we explored a little earlier:\r\n\r\n* ```testClientProductsSum_AllProductsSameCurrency```\r\n* ```testClientProductsSum_DifferentCurrencies_ThrowsException```\r\n* ```testClientProductsSum_NoProducts```\r\n\r\nThese are very readable tests, and they can be used in your business discussions as well!\r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-09-07-spring-boot-videos.md",
    "content": "---\nlayout:     post\ntitle:      Index - 500+ Videos \ndate:       2020-01-02 12:31:19\nsummary:    At in28Minutes, we are creating a number of tutorials with videos, articles &amp; courses on Spring Boot for Beginners and Experienced Developers. Here's a list of video tutorials and courses for you\ncategories:  SpringBoot\npermalink:  /spring-boot-video-tutorials-for-beginners\nimage: /images/generic-category.png\n---\n\nHere's the **index of 500+ FREE Videos** on Spring Boot, JPA, Hibernate, REST API, Microservices and Cloud. Have a wonderful time watching these amazing videos. \n\n\n### Learn in 10 Steps - Free Video Courses\n\n- [FREE 5 DAY CHALLENGE - Learn Spring and Spring Boot](https://links.in28minutes.com/SBT-Page-Top-LearningChallenge-SpringBoot){:target=\"_blank\"}\n- [Learn Spring Boot in 10 Steps](https://links.in28minutes.com/in28minutes-10steps-springboot){:target=\"_blank\"}\n- [Learn Docker in 10 Steps](https://links.in28minutes.com/in28minutes-10steps-docker){:target=\"_blank\"}\n- [Learn Kubernetes in 10 Steps](https://links.in28minutes.com/in28minutes-10steps-k8s){:target=\"_blank\"}\n- [Learn AWS in 10 Steps](https://links.in28minutes.com/in28minutes-10steps-aws-beanstalk){:target=\"_blank\"}\n- [Learn Spring in 10 Steps](https://courses.in28minutes.com/p/spring-framework-for-beginners){:target=\"_blank\"}\n- [Learn Spring MVC in 10 Steps](https://www.youtube.com/watch?v=BjNhGaZDr0Y){:target=\"_blank\"}\n- [Learn JPA and Hibernate in 10 Steps](https://courses.in28minutes.com/p/jpa-and-hibernate-tutorial-for-beginners-with-spring-boot){:target=\"_blank\"}\n- [Learn Full Stack with Spring Boot and React](https://www.youtube.com/watch?v=SWXuXhZkNQc){:target=\"_blank\"}\n- [Learn Full Stack with Spring Boot and Angular](https://www.youtube.com/watch?v=8ueiZf988qY){:target=\"_blank\"}\n\n\n\n### Spring\n- [Spring Tip : Why Is Spring Popular?](https://www.youtube.com/watch?v=T8rJ_jU9W8k)\n- [Spring Framework - What is Inversion of Control (IOC)?](https://www.youtube.com/watch?v=oLxsTnH_peI)\n- [Spring Framework - What is Dependency Injection?](https://www.youtube.com/watch?v=4sD_3BzxJOo)\n- [Spring Framework - What is Component Scan?](https://www.youtube.com/watch?v=L1Y5pwy09Vw)\n- [Spring Framework - What is a Dependency?](https://www.youtube.com/watch?v=4VajgnSHwOw)\n- [Spring Framework - What are Spring Projects?](https://www.youtube.com/watch?v=gsqYVsVh7iM)\n- [Spring Framework - What are Spring Modules?](https://www.youtube.com/watch?v=Lbz7yGXe_EM)\n\n### Spring Boot\n- [Spring Boot Vs Spring - A Comparison](https://www.youtube.com/watch?v=bNFoN956P2A)\n- [Spring Boot Vs Spring MVC - A Comparison](https://www.youtube.com/watch?v=ILRmPKEL4U0)\n- [Spring Boot Interview Questions](https://www.youtube.com/watch?v=OBFjJKT0DIw)\n- [Spring Boot Auto Configuration - Understand The Magic](https://www.youtube.com/watch?v=J_kTukE7hr8)\n- [Spring Boot - What is Spring Boot Starter Parent?](https://www.youtube.com/watch?v=vPvHRZwY8l0)\n- [Spring Boot - What is Spring Boot Data Rest?](https://www.youtube.com/watch?v=8_bEl0zME0k)\n- [Spring Boot - What is Auto Configuration?](https://www.youtube.com/watch?v=-jwd-9PKr5Y)\n- [Spring Boot - What are Spring Boot Starter Projects - Web and JPA?](https://www.youtube.com/watch?v=itMb3Hf8F_w)\n- [Spring Boot - What are Profiles?](https://www.youtube.com/watch?v=XXCNe4HiLYI)\n- [Spring Framework Tutorial For Beginners](https://www.youtube.com/watch?v=edgZo2g-LTM)\n- [Spring Boot Tutorial For Beginners](https://www.youtube.com/watch?v=pcdpk3Yd1EA)\n- [Spring Boot Starter Projects And Spring Boot Starter Web](https://www.youtube.com/watch?v=y1uHFZ4PKwU)\n- [Spring Boot Starter Security - Secure Your Rest Services And Web Applications](https://www.youtube.com/watch?v=4x-HgnJ31cg)\n- [Spring Boot Integration Testing - For Rest Web Services](https://www.youtube.com/watch?v=Psei7F7KsDw)\n- [Spring Boot Unit Testing - For Rest Web Services](https://www.youtube.com/watch?v=RbZvXCAtMus)\n- [Spring Boot Profiles & Configuration Management - Application Properties](https://www.youtube.com/watch?v=vHnOwhSUTAo)\n- [Exception Handling With Spring Boot](https://www.youtube.com/watch?v=2o7LJLTIgdE)\n- [Rest Web Services With Spring Boot](https://www.youtube.com/watch?v=YEEUn5JZ9t0)\n- [Spring Boot Tutorial For Beginners](https://www.youtube.com/watch?v=PSP1-2cN7vM)\n\n---\n\nLearn Every Day With Our Amazing [85,000+ YouTube Subscribers](https://links.in28minutes.com/in28minute-YT-Subscribe)\n\n---\n\n### Interview Preparation\n- [Servlets Interview Questions and Answers](https://www.youtube.com/watch?v=ov2zrhUxDxQ)\n- [JSP Interview Questions and Answers](https://www.youtube.com/watch?v=ouml01jXi8M)\n- [JDBC Interview Questions and Answers](https://www.youtube.com/watch?v=uYc6RKwLb0o)\n- [OOPS Interview Questions and Answers](https://www.youtube.com/watch?v=ot9kXA3PK4w)\n- [J2EE (Java EE) Interview Questions and Answers](https://www.youtube.com/watch?v=kxpGuw02TJU)\n- [Eclipse Interview Questions and Answers](https://www.youtube.com/watch?v=IuUuKwwXtK8)\n- [Design Patterns Interview Questions and Answers](https://www.youtube.com/watch?v=W9gz3NGeojU)\n- [Maven Interview Questions and Answers](https://www.youtube.com/watch?v=6cWWrTVn0mg)\n- [Java Collections Interview Questions and Answers -  New Version](https://www.youtube.com/watch?v=3hgYHXDVh-o)\n- [Java Interview Questions and Answers - New Version](https://www.youtube.com/watch?v=5aHZABb1Iwk)\n- [Java Multithreading Interview Questions](https://www.youtube.com/watch?v=AfVbJDr-8ic)\n- [Java Instructors Interview - Ankush Gorav from Gontu Series](https://www.youtube.com/watch?v=GO4_3AP0yfg)\n- [Java Exception Handling Interview Questions and Answers](https://www.youtube.com/watch?v=wj3UmzeyrvE)\n- [Spring Interview Questions and Answers](https://www.youtube.com/watch?v=2prdt2byiTs)\n- [Hibernate Interview Questions](https://www.youtube.com/watch?v=nb4kKVDc4cE)\n- [Core Java Interview Questions](https://www.youtube.com/watch?v=r2BAVRRB-1I)\n- [Design Patterns - An introduction](https://www.youtube.com/watch?v=0jjNjXcYmAU)\n- [Structural Design Patterns - in Java](https://www.youtube.com/watch?v=ACrzAB4ncfo)\n- [Facade Design Pattern](https://www.youtube.com/watch?v=K80P1NlQ4Gc)\n- [Factory Method Design Pattern](https://www.youtube.com/watch?v=rUisbJExtFM)\n- [Creational Design Patterns](https://www.youtube.com/watch?v=uCkZemGbsJ4)\n- [Builder Design Pattern](https://www.youtube.com/watch?v=UEPFYWfQe5Y)\n- [Java interview questions for Freshers  - Part 2](https://www.youtube.com/watch?v=xyXuo0y-xoU)\n- [Introduction To Transaction Management](https://www.youtube.com/watch?v=HcjHJLEbtRs)\n- [Java Interview Questions and Answers : A guide for experienced](https://www.youtube.com/watch?v=0xcgzUdTO5M)\n- [Java Interview Questions and Answers : A Freshers Guide - Part 1](https://www.youtube.com/watch?v=njZ48YVkei0)\n\n### 5 Minute Introductions - Tools and Terminology\n- [Introduction to Web Services in 5 minutes](https://www.youtube.com/watch?v=vim2_LSqcvE)\n- [Introduction to Spring Initializr in 5 Minutes](https://www.youtube.com/watch?v=pLn0WLCdNx0)\n- [Introduction to Spring Framework in 10 Minutes](https://www.youtube.com/watch?v=6xB-uXqbOqo)\n- [Introduction to Spring Data Rest in 5 Minutes](https://www.youtube.com/watch?v=prtat_cKUVA)\n- [Introduction to Spring Data in 5 Minutes](https://www.youtube.com/watch?v=bg0_9FsOI64)\n- [Introduction to Spring Cloud in 10 Minutes](https://www.youtube.com/watch?v=hgp6dlJJaCI)\n- [Introduction to Spring Boot in 10 Minutes](https://www.youtube.com/watch?v=sKdD3wYP9SM)\n- [Introduction to Spring Batch in 5 Minutes](https://www.youtube.com/watch?v=eohUc-kRUPw)\n- [Introduction to Maven in 7 Minutes](https://www.youtube.com/watch?v=EjymtpicGtg)\n- [Eclipse Quick Start](https://www.youtube.com/watch?v=0s2l_t70x50)\n- [JUnit Quick Start](https://www.youtube.com/watch?v=bdc5WbKKbK4)\n\n\n### Microservices\n- [Introduction To Microservice Architectures for Beginners](https://www.youtube.com/watch?v=DGid-3LhBG4)\n- [Microservices - First Steps from Monolith to Microservices](https://www.youtube.com/watch?v=d_wVZ6sgVbs)\n- [Microservices - Differences between Microservices and SOA](https://www.youtube.com/watch?v=Ng79aeXukDE)\n- [Microservices - Challenges with Microservices](https://www.youtube.com/watch?v=KGYpmVlIkIw)\n- [Microservices - Advantages of Microservices](https://www.youtube.com/watch?v=nfLll9Ep9DI)\n- [Introduction To Microservices](https://www.youtube.com/watch?v=LLA2ozKh4vA)\n- [Introduction To Microservices - 2 Important Things](https://www.youtube.com/watch?v=8VUbMuAezrc)\n- [Microservices - What is a Microservice?](https://www.youtube.com/watch?v=SeOpfBUAA1o)\n- [Microservices - Introduction to Spring Cloud](https://www.youtube.com/watch?v=Lr96QgqylIU)\n- [Microservices - 12 Factors App - Best Practices in Cloud Native Applications](https://www.youtube.com/watch?v=wjqBxJX35fU)\n- [Microservices -  Best Practices](https://www.youtube.com/watch?v=O91rjFs3S6I)\n- [Introduction To Microservice Architectures for Beginners](https://www.youtube.com/watch?v=DGid-3LhBG4)\n- [Microservices -  Best Practices](https://www.youtube.com/watch?v=O91rjFs3S6I)\n- [Microservices Architecture - Why should you build an Archetype?](https://www.youtube.com/watch?v=KPAe72TqLIw)\n- [Microservices Architecture - Why should we build Redundancy?](https://www.youtube.com/watch?v=uO6LWYAyCMc)\n- [Microservices Architecture - Why do we use Queues and Asynchronous Messaging?](https://www.youtube.com/watch?v=cyXToKjXXQY)\n- [Microservices Architecture - What is Service Discovery with Eureka?](https://www.youtube.com/watch?v=T36Usw_QbP0)\n- [Microservices Architecture - What is Monitoring?](https://www.youtube.com/watch?v=ZrEXW4y4WEA)\n- [Microservices Architecture - What is Fault Tolerance?](https://www.youtube.com/watch?v=7qlQlvnQsuU)\n- [Microservices Architecture - What is Eventual Consistency?](https://www.youtube.com/watch?v=-7JK2dyACNk)\n- [Microservices Architecture - What is Dynamic Scaling?](https://www.youtube.com/watch?v=rxTNUw0wp-U)\n- [Microservices Architecture - What is Cloud?](https://www.youtube.com/watch?v=MvRvKJuRs8c)\n- [Microservices Architecture - What is Centralized Logging?](https://www.youtube.com/watch?v=Va-KMSKO190)\n- [Microservices Architecture - What is Centralized Configuration?](https://www.youtube.com/watch?v=IsAzbA-IM98)\n- [Microservices Architecture - What is API Gateway?](https://www.youtube.com/watch?v=rg7Xkdur-vc)\n- [Microservices Architecture - What are event driven architectures?](https://www.youtube.com/watch?v=uJ4JFMMbSO8)\n- [Microservices Architecture - Importance of Automation Testing](https://www.youtube.com/watch?v=0A8KocCZ_n8)\n- [Microservices and Cloud Native Applications](https://www.youtube.com/watch?v=u_MG_fY1JuA)\n\n\n### Software Design\n- [Should I be an expert at all Design Patterns?](https://www.youtube.com/watch?v=8lEfj1cmBJ4)\n- [Design Patterns for Beginners - New Version](https://www.youtube.com/watch?v=f5Rzr5mVNbY)\n- [Introduction to Design Patterns in 25 Minutes](https://www.youtube.com/watch?v=Vp7q_pE7Fzg)\n- [Software Design Principles For Beginners](https://www.youtube.com/watch?v=60EqoRcanpo)\n- [Software Design - 5 Things to Look For in Your Design Reviews](https://www.youtube.com/watch?v=idgO7_Dvdm0)\n- [Software Design - Aspect Orient Programming](https://www.youtube.com/watch?v=3UE_QTaohOg)\n- [What is Continuous Integration?](https://www.youtube.com/watch?v=0uJvjygC0Co)\n- [What is Continuous Delivery?](https://www.youtube.com/watch?v=cI5ELFlLDPY)\n- [Agile Myths](https://www.youtube.com/watch?v=KQ7Qw_ACFgI)\n- [Software Design - REST API - What is Code First?](https://www.youtube.com/watch?v=9yXtlEegx90)\n- [Software Design - Cross Cutting Concerns](https://www.youtube.com/watch?v=DAbljE_Dj0U)\n- [Software Design - What is Single Responsibility Principle?](https://www.youtube.com/watch?v=eympIQPQLx4)\n- [Software Design - What is Coupling?](https://www.youtube.com/watch?v=f32UZn8fQiw)\n- [Software Design - REST API - What is HATEOAS?](https://www.youtube.com/watch?v=gCNAudrbWCo)\n- [Software Design - What is Cohesion?](https://www.youtube.com/watch?v=Gx2N-kkO4FU)\n- [Software Design - Introduction to 4 Principles of Simple Design in 5 Minutes](https://www.youtube.com/watch?v=jQIJkzCmUvo)\n- [Software Design - DRY Principle](https://www.youtube.com/watch?v=kQj-uOeqwQI)\n- [Software Fundamentals - What is an API?](https://www.youtube.com/watch?v=Npn1dgiEiS0)\n- [Software Design - What is Abstraction?](https://www.youtube.com/watch?v=OF55HZPE7lQ)\n- [REST API - What is REST?](https://www.youtube.com/watch?v=ONelFjri_j0)\n- [REST API - SOAP VS REST](https://www.youtube.com/watch?v=PbIT0yppvW8)\n- [Software Design - What is Dependency Inversion Principle?](https://www.youtube.com/watch?v=PdQ4xAUGitk)\n- [Software Design - 5 Tips to Keep Design Simple](https://www.youtube.com/watch?v=pjDphh9OBVk)\n- [Software Design - What is Open Closed Principle?](https://www.youtube.com/watch?v=P-OttkIo-_4)\n- [Software Design - REST API - What is Contract First?](https://www.youtube.com/watch?v=SKEuvFyBYdE)\n- [Software Design - What is Encapsulation?](https://www.youtube.com/watch?v=UhzXNlsjHkA)\n- [Sofware Fundamentals - What is Deployment?](https://www.youtube.com/watch?v=Y_qU7Llx_DE)\n- [Software Design - REST API - What is Code First?](https://www.youtube.com/watch?v=yDAujtMk2oQ)\n- [Software Design - Introduction to SOLID Principles in 8 Minutes](https://www.youtube.com/watch?v=yxf2spbpTSw)\n\n### Software Architecture\n- [Introduction to Software Architecture In 3 Minutes](https://www.youtube.com/watch?v=RxNNPU7pz_s)\n- [Programmer To Software Architect - What is the Goal of an Architect?](https://www.youtube.com/watch?v=kpGG-GxM2DA)\n- [Software Architects - Top 5 Responsibilities](https://www.youtube.com/watch?v=QAUa41CXsrk)\n- [Software Architects - Top 5 Qualities of Successful Software Architects](https://www.youtube.com/watch?v=M4A532ksLow)\n- [Programmer To Software Architect  - Why do we need Architecture?](https://www.youtube.com/watch?v=RALT8z8Ya0w)\n- [Programmer To Software Architect - Course Introduction](https://www.youtube.com/watch?v=kQfH9QTAdD4)\n- [Introduction To Non Functional Requirements](https://www.youtube.com/watch?v=lcJQe6tu0tw)\n- [Introduction To Microservices](https://www.youtube.com/watch?v=LLA2ozKh4vA)\n- [Software Architecture - What is Security?](https://www.youtube.com/watch?v=4cQE9DU_A9U)\n- [Software Architecture - What is an In Memory Database?](https://www.youtube.com/watch?v=7mdZT_yDgCU)\n- [Software Architecture - What is an embedded server?](https://www.youtube.com/watch?v=BUP8-YJ-smI)\n- [Software Architecture - Why do you build a Vertical Slice?](https://www.youtube.com/watch?v=fk4itQzBsEE)\n- [Software Architecture - What should build applications in multiple layers?](https://www.youtube.com/watch?v=fS2JnypQKWs)\n- [Software Architecture - Seperation of Concerns](https://www.youtube.com/watch?v=GRTQ896UWaI)\n- [Software Architecture - What are non functional requirements?](https://www.youtube.com/watch?v=InXlzJjwgYw)\n- [Software Architecture - What is an embedded server?](https://www.youtube.com/watch?v=BUP8-YJ-smI)\n- [Software Architecture - What are non functional requirements?](https://www.youtube.com/watch?v=InXlzJjwgYw)\n- [Software Architecture - Why should you build a Prototype?](https://www.youtube.com/watch?v=P62Dhw4Z2uQ)\n- [Software Architecture - Seperation of Concerns](https://www.youtube.com/watch?v=GRTQ896UWaI)\n- [Software Architecture - Why do you build a Vertical Slice?](https://www.youtube.com/watch?v=fk4itQzBsEE)\n- [Software Architecture - Why do we need Asynchronous Communication?](https://www.youtube.com/watch?v=wCugdNicf-0)\n- [Software Architecture - What should build applications in multiple layers?](https://www.youtube.com/watch?v=fS2JnypQKWs)\n- [Software Architecture - What is Security?](https://www.youtube.com/watch?v=4cQE9DU_A9U)\n- [Software Architecture - What is Modularity?](https://www.youtube.com/watch?v=v-0ClsJ5UcI)\n- [Software Architecture - What is an In Memory Database?](https://www.youtube.com/watch?v=7mdZT_yDgCU)\n- [Microservices Architectures - Non Functional Requirements - Testability](https://www.youtube.com/watch?v=fmvVSieVw2U)\n- [Microservices Architectures - Non Functional Requirements - Scalability](https://www.youtube.com/watch?v=-aO7GNzvol4)\n- [Microservices Architectures - Non Functional Requirements - Reusability](https://www.youtube.com/watch?v=xfHgYXENDkk)\n- [Microservices Architectures - Non Functional Requirements - Reliability](https://www.youtube.com/watch?v=mF-c2xK8Lqk)\n- [Microservices Architectures - Non Functional Requirements - Portability](https://www.youtube.com/watch?v=2HWEde56mYM)\n- [Microservices Architectures - Non Functional Requirements - Performance](https://www.youtube.com/watch?v=zjZ7-pmfezE)\n- [Microservices Architectures - Non Functional Requirements - Maintainability](https://www.youtube.com/watch?v=q89zx2VOOvY)\n- [Microservices Architectures - Non Functional Requirements - Reliability](https://www.youtube.com/watch?v=WBGx6NO9Qeo)\n- [Software Architecture - Why should you build a Prototype?](https://www.youtube.com/watch?v=P62Dhw4Z2uQ)\n- [Software Architecture - What is Modularity?](https://www.youtube.com/watch?v=v-0ClsJ5UcI)\n- [Software Architecture - Why do we need Asynchronous Communication?](https://www.youtube.com/watch?v=wCugdNicf-0)\n- [Microservices Architectures - Non Functional Requirements - Avaliability](https://www.youtube.com/watch?v=R3j0Z1c-0qY)\n\n### Code Quality\n- [Introduction to Coding Standards](https://www.youtube.com/watch?v=XRKDpQ3b27M)\n- [Introduction to Code Quality](https://www.youtube.com/watch?v=M4Ip6joERv4)\n- [Code Review Best Practices](https://www.youtube.com/watch?v=hVJGu0xdXII)\n- [Agile and Evolutionary Design](https://www.youtube.com/watch?v=gt6js9zl1Rs)\n- [How to become a good programmer?](https://www.youtube.com/watch?v=iJe1Ru4bJQo)\n- [10 Maven Tips for Beginners](https://www.youtube.com/watch?v=exNl7USPfsg)\n- [Introduction to Modern Development Practices](https://www.youtube.com/watch?v=0Kqzfyp-w4s)\n- [Introduction to Non Functional Requirements](https://www.youtube.com/watch?v=JTYxAcZC8Io)\n- [Introduction to DevOps](https://www.youtube.com/watch?v=I-JkJZruWyU)\n- [Unit Testing (JUnit) Best Practices](https://www.youtube.com/watch?v=BukAouJgEjo)\n- [Static Code Analysis - Best Practices](https://www.youtube.com/watch?v=rB_BaftN3nE)\n- [10 Eclipse Tips for Beginners](https://www.youtube.com/watch?v=dN9GYsG1v_c)\n- [Code Quality - What is Technical Debt?](https://www.youtube.com/watch?v=BUQuYy0upPE)\n- [Code Quality - What is Refactoring?](https://www.youtube.com/watch?v=2kxgoBZw9Xc)\n- [Code Quality - What is Readability of Code?](https://www.youtube.com/watch?v=DoX3UiYn85A)\n- [Code Quality - What is Legacy Code?](https://www.youtube.com/watch?v=5odeVADF2Og)\n- [Code Quality - What is Code Duplication?](https://www.youtube.com/watch?v=uauZjxAu3p8)\n- [Code Quality - What is Code Coverage?](https://www.youtube.com/watch?v=Ra42js3AXIQ)\n- [Code Quality - What is Code Complexity?](https://www.youtube.com/watch?v=cE44izR3A5E)\n- [Code Quality - What are Coding Standards?](https://www.youtube.com/watch?v=7Ef_2_bQBKU)\n- [Code Quality - What are Code Smells?](https://www.youtube.com/watch?v=r0CyMrZBYa4)\n- [Code Quality - Top 5 Coding Standards](https://www.youtube.com/watch?v=xOPTwJyFnMM)\n- [Code Quality - An Overview](https://www.youtube.com/watch?v=aGQda_tlfdw)\n- [Code Quality - 5 Things to think about while Programming](https://www.youtube.com/watch?v=svJ_htqB12E)\n\n\n### Best Practices and Tips\n- [REST API Web Service Best Practices](https://www.youtube.com/watch?v=NzgFdEGI8sI)\n- [JPA And Hibernate Tutorial For Beginners](https://www.youtube.com/watch?v=MaI0_XdpdP8)\n- [Top 6 Java Unit Testing Frameworks](https://www.youtube.com/watch?v=VG7ohV4weYw)\n- [Top 5 Tools to Learn](https://www.youtube.com/watch?v=jA-I7JYxly0)\n- [Top 5 Languages to Learn](https://www.youtube.com/watch?v=gSME35wOO1E)\n- [Top 5 Frameworks to Learn](https://www.youtube.com/watch?v=kF1FleBnb1w)\n- [How to Introduce Yourselves in a Technical Interview?](https://www.youtube.com/watch?v=UuTKEUM6B-k)\n- [Microservices Course - Role of Docker and Kubernetes in Dynamic Scaling](https://www.youtube.com/watch?v=WaZTtpa8SaA)\n- [JSP Servlets Course - Debugging Problems in First Step](https://www.youtube.com/watch?v=fRBBCMZkTHY)\n- [in28Minutes Roadmap - Java, Spring Boot, REST, Microservices Learning Path](https://www.youtube.com/watch?v=jf6doctfxWQ)\n\n### Web Service Best Practices\n- [Restful Web Service Tip 1 -  Consumer First](https://www.youtube.com/watch?v=dEL6762fj8M)\n- [Restful Web Service Tip 3 -  What is Code First Approach?](https://www.youtube.com/watch?v=6rYbmInAeDM)\n- [Restful Web Service Tip 2 -  Use Contract First Approach](https://www.youtube.com/watch?v=puV7GPAa-jQ)\n- [Restful Web Service Tip 4 -  Code First vs Contract First](https://www.youtube.com/watch?v=KbL_80jujJ8)\n- [Restful Web Service Tip 5 -  Defining Organizational Standards](https://www.youtube.com/watch?v=DDfvxibpges)\n- [Restful Web Service Tip 6 -  Build a Standard Organizational Framework](https://www.youtube.com/watch?v=A0ZjD6h1r3k)\n- [Restful Web Service Tip 7 -  Have Great Documentation](https://www.youtube.com/watch?v=CLuO_s4uErM)\n- [Restful Web Service Tip 9 -  Richardson Maturity Model](https://www.youtube.com/watch?v=IL1lPStSTCw)\n- [Restful Web Service Tip 10 -  Use Nouns for Resources when possible](https://www.youtube.com/watch?v=anZ2DuXE7E8)\n- [Restful Web Service Tip 11 -  Representation](https://www.youtube.com/watch?v=m-9d1gYQZXs)\n- [Restful Web Service Tip 12 -  Versioning](https://www.youtube.com/watch?v=kefiGlVOgpA)\n- [Restful Web Service Tip 13 -  Error Handling](https://www.youtube.com/watch?v=ow8oxoQdhj8)\n- [Restful Web Service Tip 14 -  Swagger for Documentation](https://www.youtube.com/watch?v=eRGIPVQ6hV0)\n- [Restful Web Service Tip 15 -  Make Great Use of HTTP](https://www.youtube.com/watch?v=rvX0Gdz2hPM)\n- [Restful Web Service Tip 16 -  Use Plurals](https://www.youtube.com/watch?v=eGnPHcmwzKA)\n- [Restful Web Service Tip 17 -  Use Spring Boot](https://www.youtube.com/watch?v=PpTf0TcWbUM)\n- [Restful Web Service Tip 8 -  Governance Of Apis](https://www.youtube.com/watch?v=tNTIYbGhofQ)\n\n\n### Java\n- [Java Advanced Object Oriented Programming Tutorial](https://www.youtube.com/watch?v=0flBHkyET_E)\n- [Java Object Oriented Programming For Beginners - 02](https://www.youtube.com/watch?v=i6EztA-F8UI)\n- [Java Object Oriented Programming For Beginners - 01](https://www.youtube.com/watch?v=NOD802rMMCw)\n- [Java Abstract Class Tutorial](https://www.youtube.com/watch?v=wJ6D0i0AHvU)\n- [Java Generics Tutorial](https://www.youtube.com/watch?v=v4o0wyFPwEs)\n- [Java Exception Handling Tutorial 1](https://www.youtube.com/watch?v=34ttwuxHtAE)\n- [Java Functional Programming Tutorial - 01](https://www.youtube.com/watch?v=aFCNPHfvqEU)\n- [Java Functional Programming Tutorial - 02](https://www.youtube.com/watch?v=5Xw1_IREXQs)\n\n### Web Application Security\n- [Web Application Security and OWASP - Top 10 Security Flaws](https://www.youtube.com/watch?v=j5PuYFCS0Iw)\n- [Web Application Security - What is SQL Injection?](https://www.youtube.com/watch?v=3K7bE10-eiY)\n- [Web Application Security - What is Cross Site Scripting (XSS)?](https://www.youtube.com/watch?v=oWTV-OwTeiM)\n- [Web Application Security - What is Cross Site Request Forgery (CSRF)?](https://www.youtube.com/watch?v=TUaijWRw4YI)\n- [Web Application Security and OWASP - Top 10 Security Flaws](https://www.youtube.com/watch?v=j5PuYFCS0Iw)\n- [Web Application Security - What is SQL Injection?](https://www.youtube.com/watch?v=3K7bE10-eiY)\n- [Web Application Security - What is Cross Site Scripting (XSS)?](https://www.youtube.com/watch?v=oWTV-OwTeiM)\n- [Web Application Security - What is Cross Site Request Forgery (CSRF)?](https://www.youtube.com/watch?v=TUaijWRw4YI)\n\n### Modern Development Practices\n- [Modern Development Practices - Unit Testing - What is Mocking?](https://www.youtube.com/watch?v=xJreuzP2C0M)\n- [Modern Development Practices - Continuous Integration - 5 Tips to get better at CI](https://www.youtube.com/watch?v=i8WNumrDMcA)\n- [Modern Development Practices - Automation Testing - 5 Types of Automation Tests](https://www.youtube.com/watch?v=kwqH1C76siE)\n"
  },
  {
    "path": "_blog/articles/2019-09-08-Java-Programmer-035-In-Memory-Database.md",
    "content": "---\r\nlayout:  post\r\ntitle:  What is an In Memory Database?\r\ndate:    2019-09-06 12:31:19\r\nsummary: In this article, we understand what the term \"In-Memory Database\" actually means. We see what scenarios they can be used, and why they are important.\r\ncategories: SwJavaProgrammers\r\npermalink:  /java-programmer-essentials-what-is-an-in-memory-database\r\nimage: /images/spring-data-category.png\r\n---\r\n\r\nIn this article, we understand what the term \"In-Memory Database\" actually means. We see what scenarios they can be used, and why they are important.\r\n\r\n### You will Learn\r\n- What Is An In-Memory Database?\r\n- Why should you use an In-Memory Database?\r\n- When should you use An In-Memory Database?\r\n- How do in-memory databases help with unit testing?\r\n\r\n\r\n\r\n### Java Programmer Essentials\r\n\r\nAs we go towards microservices architectures, what should a Java Programmer learn? \r\n\r\nThis is the last article in series of six articles on Java Programmer Essentials :\r\n- [1 - Five Languages To Learn as a Java Programmer](/five-great-languages-to-learn-as-a-java-programmer){:target='_blank'}\r\n- [2 - Five Great Frameworks To Try for Java Programmers](/five-frameworks-for-java-programmers){:target='_blank'}\r\n- [3 - Five Tools To Learn as a Java Developer](/five-tools-to-learn-for-java-programmers){:target='_blank'}\r\n- [4 - Java Tools and Frameworks : Introduction To Maven](/java-tools-and-frameworks-introduction-to-maven){:target='_blank'}\r\n- [5 - What is an Embedded Server?](/java-programmer-essentials-what-is-an-embedded-server){:target='_blank'}\r\n- [6 - What is an In Memory Database?](/java-programmer-essentials-what-is-an-in-memory-database){:target='_blank'}\r\n\r\n\r\n\r\n### What Is An In-Memory Database?\r\n\r\nImagine a real world database such as MySQL Server or Oracle. The first step in using one is to install it. The second step would be to create the schemas, and the third involves creating the tables and other definitions. \r\n\r\nWith an in-memory database: \r\n* The step of installing a separate database is done away with. \r\n* The database now sits inside the running application's memory. \r\n* The database schema can be automatically created at application startup using a simple script or based on entities configured in case of Spring Data JPA.\r\n\r\nIn memory databases allow you to focus on building a great prototype and validate business ideas.\r\n\r\nOnce you have a prototype ready, you can make a switch to a real world database.\r\n\r\n### When to use An In-Memory Database?\r\n\r\nAn in-memory database is of great value when a developer tries to learn a new language or framework. You would prefer to learn the features of the language or a framework, rather than be caught up with configuring a database, or learning how to create a schema.\r\n\r\nSwitching over to a real database is relatively easy, with a few simple configuration changes. \r\n\r\nAnother major advantage of an in-memory database is in unit testing or system testing. You don't want to depend on external resources such as a database, because the information stored in them can change any time. This can lead to tests failing, even with code remaining the same! \r\n\r\nIt is much better to launch a database in memory, populate the data, run the tests and verify the results.\r\n\r\nAn in memory database also provides a great option when you are building prototypes or initial designs.\r\n\r\n### Features of in memory databases\r\n\r\nAn in-memory database typically supports a subset of the SQL language standard. Make sure that it supports all features you want to use. Such a database also offers a browser-based console, such as the following for H2:\r\n\r\n![image info](/images/Capture-035-02.png)\r\n\r\nWhen you launch your application, you could also visit the in memory DB console and connect to the application. That would enable you to view the data stored there:\r\n\r\n![image info](/images/Capture-035-03.png)\r\n\r\nYou can see data from various tables.\r\n\r\n### Examples Of In-Memory Databases\r\n\r\nPopular examples of in-memory databases are \r\n\r\n* H2 : This is the more popular one among others\r\n* HSQL\r\n\r\n### Using An In-Memory Database with Spring Boot\r\n\r\nIf you are developing an application using the Spring Boot framework, then the Spring Initializr web utility makes this very easy for you. You just need to add your in-memory database as a dependency to your configuration:\r\n\r\n![image info](/images/Capture-035-05.png)\r\n\r\nNotice how we added H2 and JPA as dependencies in our list.\r\n\r\nDo check out our video on this:\r\n\r\n[![image info](/images/Capture-035-01.png)](https://www.youtube.com/watch?v=7mdZT_yDgCU)\r\n\r\n### Summary\r\n\r\nIn this article, we talked about the need for an in memory database, and how it is good for quick prototyping and learning. We focused on what such a database is, and how it is different from a real world database. We then took the example of H2 and described how to use an in-memory database.Finally, we showed you how easy it is to use an in-memory database, such as H2.\r\n"
  },
  {
    "path": "_blog/articles/2019-09-09-Java-Programmer-036-EmbeddedServers.md",
    "content": "---\r\nlayout:  post\r\ntitle:  What is an Embedded Server? (Spring Boot)\r\ndate:    2019-09-05 12:31:19\r\nsummary: In this article, we focus in exploring what an embedded server is, and how they help make application deployment simpler.\r\ncategories: SwJavaProgrammers\r\npermalink:  /java-programmer-essentials-what-is-an-embedded-server\r\nimage: /images/spring-boot-feature.png\r\n---\r\n\r\nIn this article, we focus in exploring what an embedded server is, and how they help make application deployment simpler.\r\n\r\n### You will Learn\r\n- What Is An Embedded Server?\r\n- Why should you use an Embedded Server?\r\n- How do Embedded Server help with simplifying deployment?\r\n\r\n\r\n\r\n### Java Programmer Essentials\r\n\r\nAs we go towards microservices architectures, what should a Java Programmer learn? \r\n\r\nThis is the fifth article in series of six articles on Java Programmer Essentials :\r\n- [1 - Five Languages To Learn as a Java Programmer](/five-great-languages-to-learn-as-a-java-programmer){:target='_blank'}\r\n- [2 - Five Great Frameworks To Try for Java Programmers](/five-frameworks-for-java-programmers){:target='_blank'}\r\n- [3 - Five Tools To Learn as a Java Developer](/five-tools-to-learn-for-java-programmers){:target='_blank'}\r\n- [4 - Java Tools and Frameworks : Introduction To Maven](/java-tools-and-frameworks-introduction-to-maven){:target='_blank'}\r\n- [5 - What is an Embedded Server?](/java-programmer-essentials-what-is-an-embedded-server){:target='_blank'}\r\n- [6 - What is an In Memory Database?](/java-programmer-essentials-what-is-an-in-memory-database){:target='_blank'}\r\n\r\n\r\n\r\n### Why We Need An Embedded Server?\r\n\r\nIn a typical microservice architecture, there could be hundreds of microservice instances deployed at a given point in time. \r\n\r\nWe would like to automate development and deployment of microservices to the maximum extent possible. \r\n\r\nA good approach would be to take the application, wrap it in a container image, and manage it as needed using something like Kubernetes.\r\n\r\nFor this, the deployment process needs to be very simple.\r\n\r\nIf you are using a custom version of Tomcat, or WebLogic to deploy your application, then you would need to \r\n- Install Java \r\n- Install Web Server\r\n- Deploy application artififact to web server\r\n\r\n#### How can we make it simpler? \r\n\r\nAn interesting approach would be to make the server a part of your application. In that case, there are just two steps: install the right version of Java, and run the application. \r\n\r\nThis is where the concept of an embedded server comes in.\r\n\r\n### What Is An Embedded Server?\r\n\r\nAn embedded server is embedded as part of the deployable application. \r\n\r\nIf we talk about Java applications, that would be a JAR. \r\n\r\nThe advantage with this is you don't need the server pre-installed in the deployment environment. \r\n\r\nWith SpringBoot, the default embedded server is Tomcat. Other options available are Jetty and UnderTow. \r\n\r\nA lot of developers used to working with WAR and EAR files tend to assume that using an embedded server in a JAR is not stable. \r\n\r\nEmbedded servers are quite scalable, and can host applications that support millions of users. These are no less scalable than the conventional fat servers.\r\n\r\n### Switching To Jetty\r\n\r\nBy default, the Spring Boot framework uses Tomcat as the embedded server of choice. However, you could override this default setting by specifying certain configuration settings. For instance, if you want to use a Jetty dependency instead, then use an ```<exclusion>``` element in the XML configuration file, and specify a ```<dependency>``` element as well: \r\n\r\n![image info](/images/Capture-036-02.png)\r\n\r\nA similar dependency also exists for Undertow.\r\n\r\n### Embedded Servers Have High Utility\r\n\r\nAs a concept, embedded servers might take some time to get used to. These can be used with applications for deployment in high-workload environments, without sacrificing any reliability or stability.\r\n\r\nEmbedded servers are also quite lightweight. If you look at a conventional WebSphere or Weblogic installation, or even a default Tomcat setup, their install sizes are huge! \r\n\r\nEmbedded server images don't generally result in huge archive sizes and helps in building smaller containers.\r\n\r\nDo check out our video on this:\r\n\r\n[![image info](/images/Capture-036-01.png)](https://www.youtube.com/watch?v=BUP8-YJ-smI)\r\n\r\n### Summary\r\n\r\nIn this article, we talked about the need for embedded servers as a concept. We discussed how an embedded server works, and how it sits inside an application image. We also saw an example with the Spring Boot framework, which uses Tomcat by default, as the embedded server. \r\n"
  },
  {
    "path": "_blog/articles/2019-09-10-Java-Programmer-089-Introduction-To-Maven.md",
    "content": "---\r\ntitle:  Java Tools and Frameworks - Introduction To Maven\r\ndate:    2019-09-04 12:31:19\r\nsummary: In this article, we experience a brief introduction to Maven, and will see how it helps in managing your project dependencies.\r\ncategories: SwJavaProgrammers\r\npermalink:  /java-tools-and-frameworks-introduction-to-maven\r\nimage: /images/java-category.png\r\n---\r\n\r\nIn this article, we get a brief introduction to Maven, and see how it helps in managing project dependencies.\r\n\r\n## You will learn\r\n- What is Maven?\r\n- Why do we need Maven in the Java World?\r\n- How does Maven do dependency management?\r\n- How does Maven help you to build and deploy projects?\r\n\r\n\r\n\r\n### Java Programmer Essentials\r\n\r\nAs we go towards microservices architectures, what should a Java Programmer learn? \r\n\r\nThis is the fourth article in series of six articles on Java Programmer Essentials :\r\n- [1 - Five Languages To Learn as a Java Programmer](/five-great-languages-to-learn-as-a-java-programmer){:target='_blank'}\r\n- [2 - Five Great Frameworks To Try for Java Programmers](/five-frameworks-for-java-programmers){:target='_blank'}\r\n- [3 - Five Tools To Learn as a Java Developer](/five-tools-to-learn-for-java-programmers){:target='_blank'}\r\n- [4 - Java Tools and Frameworks : Introduction To Maven](/java-tools-and-frameworks-introduction-to-maven){:target='_blank'}\r\n- [5 - What is an Embedded Server?](/java-programmer-essentials-what-is-an-embedded-server){:target='_blank'}\r\n- [6 - What is an In Memory Database?](/java-programmer-essentials-what-is-an-in-memory-database){:target='_blank'}\r\n\r\n\r\n\r\n### What Is Maven?\r\n\r\nWhen we develop a Java software project, such as a microservice, the major dependencies we need are: \r\n\r\n* Spring MVC framework.\r\n* Spring framework\r\n* Hibernate\r\n\r\nIn addition to these 3 direct dependencies, we need to include their individual dependencies as well. So we need the dependencies of Spring MVC, Spring and Hibernate.  \r\n\r\nLet's consider an example: REST API typically returns JSON responses. Spring MVC needs to convert Java Bean to JSON. It makes use of the Jackson framework to do the conversion. Jackson framework is a dependency of Spring MVC. \r\n\r\n### What if I manually download all the jars?\r\n\r\nIt is quite a task at project start-up, because you need to download a large number of JARs in the proper way, and set them up in the project folder. \r\n\r\nThe flip side of doing this manually is that each time there is a change in version of a dependency, you need to manually download the new version of dependency and its dependencies again.\r\n\r\n### Enter Maven\r\n\r\nMaven provides **dependency management**. Any Maven project contains a file called pom.xml. In this file, we specify the dependencies that we need. This is done within the <dependency> tag. \r\n\r\n###### Example pom.xml\r\n\r\nWithin each <dependency> tag, we specify the dependency we need for an application to work. Maven reads this pom.xml file, downloads the dependencies and transitive dependencies (dependencies of dependencies) , and makes them available for your project. \r\n\r\n![image info](images/Capture-089-02.png)\r\n\r\n### Dependency Management With Maven \r\n\r\n#### Identifying Artifacts\r\n\r\nIn order to describe each of the artifacts stored here, Maven uses two tags - <groupId> and <artifactId>. In addition to that, there is also a version that is maintained for each artifact. using these 3 identifiers, Maven can retrieve the correct version of the required dependency.\r\n\r\n#### Managing Transitive Dependencies\r\n\r\nWhen Maven downloads a particular artifact, it also downloads those dependencies of this artifact that are needed in the project. These are known as **transitive dependencies**. This reduces the amount of effort that is spent on enumerating all the artifacts. \r\n\r\n### Maven Does A Lot More!\r\n\r\nThe truth is in the Java world, Maven does a lot more than just dependency management. \r\n\r\n#### Building Deployable unit - Jars and Wars\r\n\r\nSuppose we want to deploy an application to a different environment. We do not want to take the source code and build it again! \r\n\r\nWe can create an application deployable unit JAR/WAR/EAR and use it in other environments. Maven enables us to create application deployable unit in a simple way. \r\n\r\nThis entire sequence is called a **build** process, thereby making Maven a **build tool** as well. \r\n\r\n### Summary\r\n\r\nIn this article, we had an introduction on Maven. Maven is primarily used as a dependency management tool. In a large Java project, managing application dependencies manually is a daunting task. Maven steps up by automating the dependency identification and download process. Maven is also used in the Java world as an efficient build tool.\r\n\r\nDo check out our video on the same topic:\r\n\r\n[![image info](images/Capture-089-01.png)](https://www.youtube.com/watch?v=EjymtpicGtg)\r\n"
  },
  {
    "path": "_blog/articles/2019-09-11-Java-Programmer-100-Five-Great-Tools-To-Learn.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Five Tools To Learn as a Java Developer\r\ndate:    2019-09-03 12:31:19\r\nsummary: In this article, we introduce you to five great tools that we recommend every Java Developer to learn.\r\ncategories: SwJavaProgrammers\r\npermalink:  /five-tools-to-learn-for-java-programmers\r\nimage: /images/java-category.png\r\n---\r\n\r\nIn this article, we introduce you to five great tools that we recommend every Java Developer to learn.\r\n\r\n\r\n### Java Programmer Essentials\r\n\r\nAs we go towards microservices architectures, what should a Java Programmer learn? \r\n\r\nThis is the second article in series of six articles on Java Programmer Essentials :\r\n- [1 - Five Languages To Learn as a Java Programmer](/five-great-languages-to-learn-as-a-java-programmer){:target='_blank'}\r\n- [2 - Five Great Frameworks To Try for Java Programmers](/five-frameworks-for-java-programmers){:target='_blank'}\r\n- [3 - Five Tools To Learn as a Java Developer](/five-tools-to-learn-for-java-programmers){:target='_blank'}\r\n- [4 - Java Tools and Frameworks : Introduction To Maven](/java-tools-and-frameworks-introduction-to-maven){:target='_blank'}\r\n- [5 - What is an Embedded Server?](/java-programmer-essentials-what-is-an-embedded-server){:target='_blank'}\r\n- [6 - What is an In Memory Database?](/java-programmer-essentials-what-is-an-in-memory-database){:target='_blank'}\r\n\r\n\r\n\r\n### Learn Jenkins\r\n\r\nJenkins is not a new tool, and has been around for over a decade. \r\n\r\nJenkins allows you to run builds in continuous integration. As soon as a developer checks in code into the source repository, you can run the builds and check if everything's fine. You can also configure periodic builds.\r\n\r\nJenkins enables continuous integration, continuous deployment and continuous verification. \r\n\r\nJenkins allows you to create pipelines to automate deployment.\r\n\r\nIn the world of microservices, Jenkins is a must have in your arsenal.\r\n\r\n### Make Use Of Docker\r\n\r\nToday, we are in a containerized world. Docker has changed how the world looks at deployment. \r\n\r\nToday, every cloud provider and deployment environments supports containers. Kubernetes provides an awesome solution for container archestration.\r\n\r\nDocker should be on your list of things to learn.\r\n\r\n### Check Out Kubernetes\r\n\r\nA very important feature that all microservices need to have is auto scaling. When a microservice is deployed, it needs to be immediately responsive to changes in load, causing it to increase or decrease the number of instances as required. \r\n\r\nKubernetes provides all the necessary features that you need to monitor the applications, so that the deployed containers can be effectively managed (this is called container orchestration).\r\n\r\n### Use SonarQube\r\n\r\nSonarQube is an awesome tool the check the code quality of your application. It not only checks how good the design is, but also gives feedback on the quality of the code written.\r\n\r\nIt is a good idea to include SonarQube as part of your continuous integration builds, ensuring good quality of the code base.\r\n\r\n### Do Consider Using Headless Chrome\r\n\r\nAutomation testing of a web application becomes much easier, if you use a headless browser. Headless Chrome is a great addition to this space. \r\n\r\nDo check out our video on the same topic:\r\n\r\n[![image info](images/Capture-100-01.png)](https://www.youtube.com/watch?v=jA-I7JYxly0)\r\n\r\n### Summary\r\n\r\nIn this article, we introduced you to five programming related tools that we believe will make you more productive, and the application you develop, a better one.\r\n\r\nDo you have any tools that you recommend? Leave a comment."
  },
  {
    "path": "_blog/articles/2019-09-12-Java-Programmer-101-Five-Great-Languages-To-Learn.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Five Languages To Learn as a Java Programmer\r\ndate:    2019-09-02 12:31:19\r\nsummary: As a programmer, you want to explore new things. Learning a new language gives you a different perspective when solving problems. What are the 5 languages that a Java developer should explore? \r\ncategories: SwJavaProgrammers\r\npermalink:  /five-great-languages-to-learn-as-a-java-programmer\r\nimage: /images/java-category.png\r\n---\r\n\r\nAs a programmer, you want to explore new things. Learning a new language gives you a different perspective when solving problems. \r\n\r\nWhat are the 5 languages that a Java developer should explore? \r\n\r\n\r\n\r\n### Java Programmer Essentials\r\n\r\nAs we go towards microservices architectures, what should a Java Programmer learn? \r\n\r\nThis is the first article in series of six articles on Java Programmer Essentials :\r\n- [1 - Five Languages To Learn as a Java Programmer](/five-great-languages-to-learn-as-a-java-programmer){:target='_blank'}\r\n- [2 - Five Great Frameworks To Try for Java Programmers](/five-frameworks-for-java-programmers){:target='_blank'}\r\n- [3 - Five Tools To Learn as a Java Developer](/five-tools-to-learn-for-java-programmers){:target='_blank'}\r\n- [4 - Java Tools and Frameworks : Introduction To Maven](/java-tools-and-frameworks-introduction-to-maven){:target='_blank'}\r\n- [5 - What is an Embedded Server?](/java-programmer-essentials-what-is-an-embedded-server){:target='_blank'}\r\n- [6 - What is an In Memory Database?](/java-programmer-essentials-what-is-an-in-memory-database){:target='_blank'}\r\n\r\n\r\n### Learn Functional Programming and Modularity with Java 8+/Java 9+\r\n\r\nJava is still one of the most popular programming languages around in the world today. \r\n\r\nJava is an object oriented programming language. \r\n\r\nWhether you want to build a web application, or an android app, or a microservices based application, Java provides you great options.\r\n\r\nWith the evolution of Android and Spring Boot, the development of mobile and web applications using Java has become a lot easier. \r\n\r\nWith Java 8, a number of functional programming features are introduced which were further enhanced in Java 9.\r\n\r\nModularity is introduced into Java with Java 9.\r\n\r\nAs a Java developer, we recommend you to start with focusing on getting familiar with functional programming constructs and building modular applications with Java.\r\n\r\n### Master Python\r\n\r\n> Do you know? The first version of Python was actually released two years prior to Java! \r\n\r\nPython is by no means a new language, it's been around since the 2 decades. Python allows you to do structured, object oriented and functional programming. Python makes it easy to write readable code. \r\n\r\nPython contains several powerful data structures, and the Python style guidelines are very interesting indeed! \r\n\r\nPython has several powerful features, that makes it the language of choice in fields such as Data Science, Machine Learning, Data Analytics and Big Data Analytics. \r\n\r\nPython is definitely our pick among these programming languages.\r\n\r\n### Get Fluent In JavaScript\r\n\r\nEven a few years back, no serious programmer would have identified JavaScript as a language to learn! \r\n\r\nThe evolution of JavaScript in the past decade has been mind-boggling. You can even build server side REST APIs with JavaScript using NodeJS.\r\n\r\nJavaScript has evolved as the language of the browser. Earlier JavaScript frameworks were restricted to making DOM manipulation easy. Today, there are excellent client-side JavaScript frameworks such as AngularJS and React providing great options to develop Single Page Applications - without directly manipulating anything in the DOM.\r\n\r\nYou can easily build large maintainable applications with JavaScript.  You can write object oriented code in JavaScript programs, and organize this code efficiently into modules. \r\n\r\nThere are several large scale applications deployed that are written solely in JavaScript (both the front-end and back-end), known as full-stack applications.  \r\n\r\nIf you are not familiar with Modern JavaScript, get started now!\r\n\r\n### Check Out Kotlin\r\n\r\nKotlin is a JVM based language. \r\n\r\nKotlin provides very simple programming constructs, which makes coding simple.\r\n\r\nKotlin is now a supported language to develop applications using Android framework, and the Spring/Spring Boot Frameworks. \r\n\r\nIf you are a Java programmer looking to learn a new language, Kotlin might be a good option.\r\n\r\n### Pick Up Scala\r\n\r\nScala is a functional programming language, that is also JVM based. If you want to learn to start learning pure functional style code, Scala is the way to go. \r\n\r\nDo check out our video on the same topic:\r\n\r\n[![image info](images/Capture-101-01.png)](https://www.youtube.com/watch?v=gSME35wOO1E)\r\n\r\n### Summary\r\n\r\nIn this video, we looked at five languages that we also recommend you to pick up, if interested in a learning a new programming language. These languages are Java Functional Programming, Python, JavaScript, Kotlin and Scala.\r\n"
  },
  {
    "path": "_blog/articles/2019-09-13-Java-Programmer-102-Five-Great-Frameworks-To-Learn.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Five Great Frameworks To Try for Java Programmers\r\ndate:   2019-09-01 12:31:19\r\nsummary: As a programmer you want to explore new languages and frameworks. What would be the best frameworks to explore in 2019 for Java Programmers?\r\ncategories: SwJavaProgrammers\r\npermalink:  /five-frameworks-for-java-programmers\r\nimage: /images/spring-boot-category.png\r\n---\r\n\r\nAs a programmer you want to explore new languages and frameworks. What would be the best frameworks to explore in 2019 for Java Programmers?\r\n\r\n\r\n### Java Programmer Essentials\r\n\r\nAs we go towards microservices architectures, what should a Java Programmer learn? \r\n\r\nThis is the second article in series of six articles on Java Programmer Essentials :\r\n- [1 - Five Languages To Learn as a Java Programmer](/five-great-languages-to-learn-as-a-java-programmer){:target='_blank'}\r\n- [2 - Five Great Frameworks To Try for Java Programmers](/five-frameworks-for-java-programmers){:target='_blank'}\r\n- [3 - Five Tools To Learn as a Java Developer](/five-tools-to-learn-for-java-programmers){:target='_blank'}\r\n- [4 - Java Tools and Frameworks : Introduction To Maven](/java-tools-and-frameworks-introduction-to-maven){:target='_blank'}\r\n- [5 - What is an Embedded Server?](/java-programmer-essentials-what-is-an-embedded-server){:target='_blank'}\r\n- [6 - What is an In Memory Database?](/java-programmer-essentials-what-is-an-in-memory-database){:target='_blank'}\r\n\r\n\r\n### Learn Spring Boot\r\n\r\nIf you're a Java developer, Spring Boot is the first framework you should learn. Spring Boot makes it easy to develop microservices in Java, and for this, you need to have an understanding of the Spring Framework.\r\n\r\nSpring Boot make it easy to build great REST APIs with all the features that microservices need, such as monitoring, exception handling etc. In combination with Spring Cloud, Spring Boot provides great options to build microservices.\r\n\r\n### Pick Up The Play Framework\r\n\r\nPlay framework is another Java framework to develop REST APIs.\r\n\r\n### Become a Full Stack Developer with Angular And React\r\n\r\nJavaScript language and the eco system is quickly evolving, especially the last 5 years.\r\n\r\nToday, there are wonderful opportunities for Java developers to learn Modern JavaScript and become full stack developers.\r\n\r\nThe recommended frameworks to start with are \r\n- Angular\r\n- React and \r\n- VueJS\r\n\r\n### Check Out Django\r\n\r\nDjango belongs to the Python world. It is used to build web applications and REST API. \r\n\r\nDo check out our video on the same topic:\r\n\r\n[![image info](images/Capture-102-01.png)](https://www.youtube.com/watch?v=kF1FleBnb1w)\r\n\r\n### Summary\r\n\r\nAs a programmer you want to explore new languages and frameworks. Learning new things gives you a different perspective in solving problems. Keep exporing and keep learning.\r\n"
  },
  {
    "path": "_blog/articles/2019-10-07-spring-boot-vue-crud-full-stack-with-maven.md",
    "content": "---\nlayout: post\ntitle: Creating Spring Boot and Vue JS CRUD Java Full Stack Application with Maven\ndate: 2022-08-07 12:31:19\nsummary: This guide helps you create a Java full stack application with all the CRUD (Create, Read, Update and Delete) features using Vue JS as Frontend framework and  Spring Boot as the backend REST API. We use Maven as the build tool.\ncategories: SpringBootFullStack\npermalink: /spring-boot-vue-full-stack-crud-maven-application\nimage: /images/spring-boot-application.png\n---\n\n![Image](/images/full-stack-application-with-spring-boot-screenshot.png \"Spring Boot Full Stack Application\")\n\nThis guide helps you create a Java full stack application with all the CRUD (Create, Read, Update and Delete) features using Vue as Front end framework and Spring Boot as the backend REST API. We will be using JavaScript as the front end language and Java as the backend language.\n\n![Image](/images/vue_00_architecture.png \"Architecture of Spring Boot Vue Full Stack Application\")\n\n## You will learn\n\n- What is a full stack application?\n- Why do we create full stack applications?\n- How do you use Vue as a Frontend Framework?\n- How do you use Spring to create Backend REST Service API?\n- How do you call Spring Boot REST API from Vue using the axios framework?\n- How and When to use different REST API Request Methods - GET, POST, PUT and DELETE?\n- How do you perform CRUD (Create, Read, Update and Delete) operations using Vue as Frontend framework and Spring Boot as the backend REST API?\n- How do you create a form in Vue?\n\n\n## Step 0: Get an overview of the Full Stack Application\n\n### Understanding Basic Features of the Application\n\nFollowing screen shot shows the application we would like to build:\n\nIt is a primary instructor portal allowing instructors to maintain their courses.\n\n![Image](/images/full-stack-application-with-spring-boot-screenshot.png \"Spring Boot Full Stack Application\")\n\n![Image](/images/full-stack-application-with-spring-boot-screenshot-2.png \"Spring Boot Full Stack Application\")\n\n### Understanding Full Stack Architecture\n\nFollowing Screen shot shows the architecture of the application we would create:\n![Image](/images/vue_00_architecture.png \"Architecture of Spring Boot Vue Full Stack Application\")\n\nImportant points to note:\n\n- REST API is exposed using Spring Boot\n- REST API is consumed from Vue Frontend to present the UI\n- The Database, in this example, is a hardcoded in-memory static list.\n\n### Getting an overview of Spring Boot REST API Resources\n\nIn this guide, we will create these services using proper URIs and HTTP methods:\n\n- `@GetMapping(\"/instructors/{username}/courses\")` : Get Request Method exposing the list of courses taught by a specific instructor\n- `@GetMapping(\"/instructors/{username}/courses/{id}\")` : Get Request Method exposing the details of a specific course taught by a specific instructor\n- `@DeleteMapping(\"/instructors/{username}/courses/{id}\")` : Delete Request Method to delete a course belonging to a specific instructor\n- `@PutMapping(\"/instructors/{username}/courses/{id}\")` : Put Request Method to update the course details of a specific course taught by a specific instructor\n- `@PostMapping(\"/instructors/{username}/courses\")` : Post Request Method to create a new course for a specific instructor\n\n> The REST API can be enhanced to interact with other microservices infrastructure components and act as microservices.\n\n### Downloading the Complete Maven Project With Code Examples\n\nFollowing GitHub repository hosts the complete frontend and backend projects - https://github.com/in28minutes/spring-boot-vuejs-fullstack-examples/tree/master/spring-boot-crud-full-stack\n\n> Our Github repository has all the code examples - https://github.com/in28minutes/spring-boot-vuejs-fullstack-examples\n\n### Understanding Spring Boot REST API Project Structure\n\nFollowing screenshot shows the structure of the Spring Boot project we create.\n\n![Image](/images/project-structure-spring-boot-fullstack-crud-maven.png \"Spring Boot Rest Service - Project Structure\")\n\nA few details:\n\n- `CourseResource.java` - Rest Resource exposing all the service methods discussed above.\n- `Course.java, CoursesHardcodedService.java` - Business Logic for the application. CoursesHardcodedService exposes a few methods we would invoke from our Rest Resource.\n- `SpringBootFullStackCrudFullStackWithMavenApplication.java` - Launcher for the Spring Boot Application. To run the application, launch this file as Java Application.\n- `pom.xml` - Contains all the dependencies needed to build this project. We use Spring Boot Starter Web and Spring Boot DevTools.\n\n## Understanding Vue Frontend Project Structure\n\nFollowing screenshot shows the structure of the Vue JS project we create.\n\n![Image](/images/project-structure-vue-fullstack-crud.png \"Vue Frontend - Project Structure\")\n\nA few details:\n\n- `App.vue` : Vue Component representing the high-level structure of the application.\n- `routes.js` : Route Component for the application\n- `Courses.vue` - Vue Component for listing all the courses for an instructor.\n- `Courses.vue` - Vue Component for editing Course Details and creating a new course\n- `CourseDataService.js` - Service using axios framework to make the Backend REST API Calls.\n- `AuthenticationService.js` - Service using axios framework to make the Backend REST API Calls.\n\n### Understanding the tools you need to build this project\n\n- Maven 3.0+ for building Spring Boot API Project\n- npm, webpack for building frontend\n- Your favorite IDE. We use Eclipse for Java and Visual Studio Code for Frontend - JavaScript, TypeScript, Angular, Vue JS and React.\n- JDK 1.8+\n- Node v8+\n- Embedded Tomcat, built into Spring Boot Starter Web\n\n[![Image](/images/Course-Go-Full-Stack-With-Spring-Boot-and-React.png \"Go Full Stack with Spring Boot and React\")](https://links.in28minutes.com/MISC-REACT){:target=\"_blank\"}\n\n[![Image](/images/Course-Go-Full-Stack-With-SpringBoot-And-Angular.png \"Go Full Stack with Spring Boot and Angular\")](https://links.in28minutes.com/MISC-ANGULAR){:target=\"_blank\"}\n\n#### Installing Node Js (npm) & Visual Studio Code\n\n- [Click to see video Playlist](https://www.youtube.com/playlist?list=PLBBog2r6uMCQN4X3Aa_jM9qVjgMCHMWx6){:target=\"_blank\"}\n  - Step 01 - Installing NodeJs and NPM - Node Package Manager\n  - Step 02 - Quick Introduction to NPM\n  - Step 03 - Installing Visual Studio Code - Front End JavaScript Editor\n\n#### Installing Java, Eclipse & Embedded Maven\n\n- [Click to see video Playlist](https://www.youtube.com/playlist?list=PLBBog2r6uMCSmMVTW_QmDLyASBvovyAO3){:target=\"_blank\"}\n  - 0 - Overview - Installation Java, Eclipse and Maven\n  - 1 - Installing Java JDK\n  - 2 - Installing Eclipse IDE\n  - 3 - Using Embedded Maven in Eclipse\n  - 4 - Troubleshooting Java, Eclipse and Maven\n\n### Creating Full Stack CRUD application with Vue and Spring Boot - Step By Step Approach\n\nWe will use a step by step approach to creating the full stack application\n\n- Create a Spring Boot Application with Spring Boot Initializr\n- Create a Vue application using Vue CLI\n- Create the Retrieve Courses REST API and Enhance the Vue Front end to retrieve the courses using the axios framework\n- Add feature to delete a course in Vue front end and Spring Boot REST API\n- Add functionality to update course details in Vue front end and Spring Boot REST API\n- Add feature to create a course in Vue front end and Spring Boot REST API\n\n> You can get an introduction to REST down here - [Introduction to REST API](http://www.springboottutorial.com/creating-rest-service-with-spring-boot){:target=\"_blank\"}\n\n## Step 1: Bootstrapping Spring Boot REST API with Spring Initializr\n\nCreating a REST service with Spring Initializr is a cake walk. We will use Spring Web MVC as our web framework.\n\nSpring Initializr [http://start.spring.io/](http://start.spring.io/){:target=\"_blank\"} is great tool to bootstrap your Spring Boot projects.\n\n![Image](/images/spring-boot-full-stack-with-web-and-dev-tools.png \"Spring Boot Project with Web and Developer Tools\")\n\nAs shown in the image above, the following steps have to be done\n\n- Launch Spring Initializr and choose the following\n  - Choose `com.in28minutes.fullstack.springboot.maven.crud` as Group\n  - Choose `spring-boot-fullstack-crud-full-stack-with-maven` as Artifact\n  - Choose following dependencies\n    - Web\n    - DevTools\n- Click Generate Project.\n- Import the project into Eclipse. File -> Import -> Existing Maven Project. For more details about creating Spring Boot Projects, you can read - [Creating Spring Boot Projects](http://www.springboottutorial.com/creating-spring-boot-project-with-eclipse-and-maven){:target=\"_blank\"}\n\n> If you are new to Spring Boot, we recommend watching this video - [Spring Boot in 10 Steps](https://www.youtube.com/watch?v=PSP1-2cN7vM){:target=\"_blank\"}\n\n## Step 2 - Bootstrapping Vue JS Frontend with Vue CLI\n\n[Vue CLI](https://github.com/vuejs/vue-cli){:target=\"_blank\"} is an amazing tool to bootstrap your Vue applications.\n\nCreating Vue Frontend Applications with Vue CLI is very simple.\n\nLaunch up your terminal/command prompt. Make sure that you have node installed.\n\n```\nnpm install -g @vue/cli\n# OR\nyarn global add @vue/cli\n\nvue create frontend-spring-boot-vue-crud-full-stack\n```\n\nThis command will ask you for the structure and features for the project you need. Just select `default` for now.\n\n### Launching up Vue Frontend\n\nYou would need to cd to the project we created and execute `npm start`\n\n```\ncd frontend-spring-boot-vue-crud-full-stack\nnpm run serve\n```\n\nYou would see the screen below:\n\n![Image](/images/npm-start-new-vue-app.png \"Starting a Vue JS Project\")\n\nWhen you launch up the application in the browser at `http://localhost:8080/`, you would see the following welcome screen.\n\n![Image](/images/vue-on-load-screenshot.png \"New Vue Project on the Browser\")\n\nNote: Vue application runs on default port 8080, to change it go to `package.json`, under `scripts` change `serve` command to `vue-cli-service serve --port 8081`. Here onwards your Vue application will start at port 8081.\n\n> Cool! You are all set to rock and roll with Vue.\n\n## Step 3 - Creating REST API for Retrieve All Courses and Connecting Vue Frontend\n\nWe would want to start building the screen shown below:\n\n![Image](/images/full-stack-application-with-spring-boot-screenshot.png \"Spring Boot Full Stack Application\")\n\nLet's start with building the course listing screen.\n\nTo be able to do that, we need to\n\n- Create REST API for retrieving a list of courses.\n- Connect the Vue JS Frontend to the backend REST API\n\n### Create REST API for retrieving a list of courses\n\nWeb Services, REST and Designing REST API, are pretty deep concepts. We would recommend to check this out for more - [Designing Great REST API](https://www.youtube.com/watch?v=NzgFdEGI8sI){:target=\"_blank\"}\n\nWe will create\n\n- A model object `Course.java`\n- A Hardcoded Business Service `CoursesHardcodedService.java`\n- A Resource to expose the REST API `CourseResource.java`\n\nWe will start with creating a model object `Course.java`. The snippet below shows the content of the model class. For the complete listing, refer `course/Course.java` in the complete code example at the end of this article.\n\n```\npublic class Course {\n  private Long id;\n  private String username;\n  private String description;\n  //no arg constructor\n  //constructor with 3 args\n  //getters and setters\n  //hashcode and equals\n```\n\nNext, let's create a Business Service. In this article, we will use hardcoded data.\n\n```\n@Service\npublic class CoursesHardcodedService {\n\n  private static List<Course> courses = new ArrayList<>();\n  private static long idCounter = 0;\n\n  static {\n    courses.add(new Course(++idCounter, \"in28minutes\", \"Learn Full stack with Spring Boot and Angular\"));\n    courses.add(new Course(++idCounter, \"in28minutes\", \"Learn Full stack with Spring Boot and React\"));\n    courses.add(new Course(++idCounter, \"in28minutes\", \"Master Microservices with Spring Boot and Spring Cloud\"));\n    courses.add(new Course(++idCounter, \"in28minutes\",\n        \"Deploy Spring Boot Microservices to Cloud with Docker and Kubernetes\"));\n  }\n\n  public List<Course> findAll() {\n    return courses;\n  }\n}\n```\n\nFew things to note\n\n- Data is hardcoded\n- findAll returns the complete list of courses\n- You can see that the API of the Service is modelled around the Spring Data Repository interfaces. If you are familiar with JPA and Spring Data, you can easily replace this with a Service talking to a database.\n\nNext, let create the REST Resource to retrieve the list of courses for an instructor.\n\n```\n@RestController\npublic class CourseResource {\n\n  @Autowired\n  private CoursesHardcodedService courseManagementService;\n\n  @GetMapping(\"/instructors/{username}/courses\")\n  public List<Course> getAllCourses(@PathVariable String username) {\n    return courseManagementService.findAll();\n  }\n}\n```\n\nFew things to note:\n\n- `@RestController : Combination of @Controller and @ResponseBody` - Beans returned are converted to/from JSON/XML.\n- `@Autowired private CoursesHardcodedService courseManagementService` - Autowire the CoursesHardcodedService so that we can retrieve details from business service.\n\nIf you launch up the Spring boot application and go to `http://localhost:8080/instructors/in28minutes/courses` in the browser, you would see the response from the API.\n\n```\n[\n   {\n      \"id\": 1,\n      \"username\": \"in28minutes\",\n      \"description\": \"Learn Full stack with Spring Boot and Angular\"\n   },\n   {\n      \"id\": 2,\n      \"username\": \"in28minutes\",\n      \"description\": \"Learn Full stack with Spring Boot and React\"\n   },\n   {\n      \"id\": 3,\n      \"username\": \"in28minutes\",\n      \"description\": \"Master Microservices with Spring Boot and Spring Cloud\"\n   },\n   {\n      \"id\": 4,\n      \"username\": \"in28minutes\",\n      \"description\": \"Deploy Spring Boot Microservices to Cloud with Docker and Kubernetes\"\n   }\n]\n```\n\nWe have the REST API up and running. Its time to focus on the Frontend.\n\n### Enhancing Vue App to consume the REST API\n\nTo be able to enhance the Vue Application to consume the REST API, we would need to\n\n- Create an Application Component - to represent the structure of the complete application and include it in `App.vue` - `InstructorApp.vue`\n- Add the frameworks need to call the REST API - axios and support routing - vue-router\n- Create a view component for showing a list of course details and include it in the Application Component - `Courses.vue`\n- Invoking Retrieve Courses REST API from Vue Component - To enable this we will create a service to call the REST API using the axios framework - `CourseDataService.js`. `Courses.vue` will make use of `CourseDataService.js`\n\nLet's start with creating an Application Component - `InstructorApp.vue`\n\n/src/components/InstructorApp.vue\n\n```vue\n<template>\n    <div>\n        This is instructors test!\n    </div>\n</template>\n\n<script>\nexport default {\n    name: \"InstructorApp\"\n}\n</script>\n\n<style scoped>\n\n</style>\n```\n\nFew things to note:\n\n- One of the first things you would need to understand about Vue is the concept of the component. Vue component is consist of `template`, `script` and `style`.\n- `template` is nothing but the HTML template with Vue directives\n- `script` is javascript code to write for the Vue module\n- `style` is CSS for the Vue module\n\nLet's update the `App.vue` to display the InstructorApp component.\n\nsrc/App.vue\n\n```js\n<template>\n  <div class=\"container\">\n    <InstructorApp />\n  </div>\n</template>\n\n<script>\nimport InstructorApp from './components/InstructorApp.vue'\n\nexport default {\n  name: 'In28Minutes',\n  components: {\n    InstructorApp\n  }\n}\n</script>\n\n<style>\n@import url(https://unpkg.com/bootstrap@4.1.0/dist/css/bootstrap.min.css)\n</style>\n```\n\nFew things to note:\n\n- `import InstructorApp from './components/InstructorApp'` - Importing the InstructorApp component\n- `<InstructorApp />` - Display the Instructor App component.\n- `@import url(https://unpkg.com/bootstrap@4.1.0/dist/css/bootstrap.min.css)` - Add styling to application\n\nWhen you launch the Vue app in the browser, it will appear as shown below:\n\n![Image](/images/vue-initial-instructor-component.png \"Initial View of Instructor Component\")\n\n#### Adding Frameworks to Vue Application\n\nIn this project, we will make use of axios to execute REST APIs, vue-router to do the Routing between pages. Let's stop the front end app running in the command prompt and execute these commands.\n\n```\nnpm add axios\n```\n\n```\nnpm add vue-router\n```\n\nWhen commands execute successfully, you would see new entries in `package.json`\n\n```\n    \"axios\": \"^0.19.0\",\n    \"vue-router\": \"^3.1.3\"\n```\n\nYou can run 'npm start' to relaunch the front end app loading up all the new frameworks.\n\n#### Creating a List Courses Component\n\nLet's create a new component for showing the List of courses - `ListCoursesComponent.vue`. For now, let's hardcode a course into the course list.\n\n/src/components/ListCoursesComponent.vue\n\n```js\n<template>\n  <div class=\"container\">\n    <h3>All Courses</h3>\n    <div class=\"container\">\n      <table class=\"table\">\n        <thead>\n          <tr>\n            <th>Id</th>\n            <th>Description</th>\n          </tr>\n        </thead>\n        <tbody>\n          <tr>\n            <td>1</td>\n            <td>Learn Full stack with Spring Boot and Vue</td>\n          </tr>\n        </tbody>\n      </table>\n    </div>\n  </div>\n</template>\n\n<script>\nexport default {\n  name: \"CoursesList\"\n};\n</script>\n\n<style>\n</style>\n```\n\nThings to Note:\n\n- It's a simple component. Returning a hardcoded table displaying a list of courses.\n\nLet's update the InstructorApp component to display the ListCoursesComponent.\n\n/src/components/InstructorApp.vue\n\n```js\n<template>\n  <div>\n    <h1>Instructor Application</h1>\n    <ListCoursesComponent></ListCoursesComponent>\n  </div>\n</template>\n\n<script>\nimport ListCoursesComponent from \"./ListCoursesComponent\";\nexport default {\n  name: \"InstructorApp\",\n  components: {\n    ListCoursesComponent\n  }\n};\n</script>\n\n<style scoped>\n</style>\n```\n\nWe are importing the ListCoursesComponent and displaying it in the InstructorApp.\n\nWhen you launch the Vue JS app in the browser, it will appear as shown below:\n\n![Image](/images/vue-second-stage-hardcoded-instructor-component.png \"Hardcoded Instructor Component\")\n\n#### Invoking Retrieve Courses REST API from Vue JS Component\n\nWe had created the REST API for retrieving the list of courses earlier. To call the REST API we would need to use a framework called axios.\n\n> Axios is a Promise based HTTP client for the browser and node.js\n\nAxios is a frontend framework that helps you make\n\n- REST API calls with different request methods including GET, POST, PUT, DELETE etc\n- Intercept Front end REST API calls and add headers and request content\n\nLet's create a data service method to call the REST API.\n\n/src/service/CourseDataService.js\n\n```js\nimport axios from \"axios\";\n\nconst INSTRUCTOR = \"in28minutes\";\nconst COURSE_API_URL = \"http://localhost:8080\";\nconst INSTRUCTOR_API_URL = `${COURSE_API_URL}/instructors/${INSTRUCTOR}`;\n\nclass CourseDataService {\n  retrieveAllCourses() {\n    return axios.get(`${INSTRUCTOR_API_URL}/courses`);\n  }\n}\n\nexport default new CourseDataService();\n```\n\nImportant points to note:\n\n- `` const INSTRUCTOR_API_URL = `${COURSE_API_URL}/instructors/${INSTRUCTOR}` `` - We are forming the URL to call in a reusable way.\n- `` axios.get(`${INSTRUCTOR_API_URL}/courses`) `` - Call the REST API with the GET method.\n- `export default new CourseDataService()` - We are creating an instance of CourseDataService and making it available for other components.\n\nTo make the REST API call, we would need to call the CourseDataService - retrieveAllCourses method from the ListCoursesComponent\n\nImportant snippets are shown below:\n\n```js\n<script>\nimport CourseDataService from '../service/CourseDataService';\nexport default {\n  name: \"CoursesList\",\n  data() {\n    return {\n      INSTRUCTOR: \"in28minutes\"\n    };\n  },\n  methods: {\n    refreshCourses() {\n      CourseDataService.retrieveAllCourses(this.INSTRUCTOR) //HARDCODED\n        .then(response => {\n          console.log(response.data);\n        });\n    }\n  },\n  created() {\n    this.refreshCourses();\n  }\n};\n</script>\n\n```\n\nThings to note:\n\n- `created()` - Vue defines a component lifecycle. created will be called as soon as the component is mounted. We are calling refreshCourses as soon as a component is mounted.\n- `methods: { refreshCourses() {}}` - Any method in a vue component should be under methods. -`CourseDataService.retrieveAllCourses(INSTRUCTOR).then` - This would make the call to the REST API. You can define how to process the response in the then method.\n\nWhen you run the vue app in the browser right now, you would see the following errors in the console\n\n```bash\n[Error] Access to XMLHttpRequest at 'http://localhost:8080/instructors/in28minutes/courses' from origin 'http://localhost:8081' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.\n[Error] Uncaught (in promise) Error: Network Error\n    at createError (createError.js?2d83:16)\n    at XMLHttpRequest.handleError (xhr.js?b50d:81)\n```\n\nThe Backend Spring Boot REST API is running on http://localhost:8080, and it is not allowing requests from other servers - http://localhost:8081, in this example.\n\nLet's configure Rest Resource to allow access from specific servers.\n\n```java\n@CrossOrigin(origins = { \"http://localhost:3000\", \"http://localhost:4200\", \"http://localhost:8081\" })\n@RestController\npublic class CourseResource {\n\n```\n\nAn important thing to note\n\n- @CrossOrigin(origins = { \"http://localhost:3000\", \"http://localhost:4200\", \"http://localhost:8081\" }) - Allow requests from specific origins\n- We will use 3000 to run React, and 8081 to run Vue JS apps, and we use 4200 to run Angular apps. Hence we are allowing requests from all ports.\n\nIf you refresh the page again, you would see the response from server printed in the console.\n\nWe would need to use the data from the response and show it on the component.\n\n> In Vue, we use the state to do that.\n\nFollowing snippet highlights the significant changes\n\n```js\n\n<script>\nimport CourseDataService from '../service/CourseDataService';\nexport default {\n  name: \"CoursesList\",\n  data() {\n    return {\n      courses: [],\n      message: null,\n      INSTRUCTOR: \"in28minutes\"\n    };\n  },\n  methods: {\n    refreshCourses() {\n      CourseDataService.retrieveAllCourses(this.INSTRUCTOR) //HARDCODED\n        .then(response => {\n          this.courses = response.data;\n        });\n    }\n  },\n  created() {\n    this.refreshCourses();\n  }\n};\n</script>\n\n```\n\nImportant things to note:\n\n- `courses: [], message: null,` - To display courses, we need to make them available to the component. We add courses to the state of the component and initialize it in the constructor.\n- `response => {this.courses = response.data;}` - When the response comes back with data, we update the state.\n\nWe have data in the state. How do we display it?\n\nWe need to update the template.\n\n```javascript\n<template>\n  <div class=\"container\">\n    <h3>All Courses</h3>\n    <div class=\"container\">\n      <table class=\"table\">\n        <thead>\n          <tr>\n            <th>Id</th>\n            <th>Description</th>\n          </tr>\n        </thead>\n        <tbody>\n          <tr v-for=\"course in courses\" v-bind:key=\"course.id\">\n            <td>{% raw %}{{course.id}{% endraw %}}</td>\n            <td>{% raw %}{{course.description}}{% endraw %}</td>\n          </tr>\n        </tbody>\n      </table>\n    </div>\n  </div>\n</template>\n```\n\nImportant things to note\n\n- `v-for=\"course in courses\"` - Allow you to loop around a list of items and define how each item should be displayed.\n- `v-bind:key=\"course.id\"` - A key is used to uniquely identify a row.\n- `{% raw %}<td>{{course.id}}</td>{% endraw %}` - Decide how column is displayed\n- `{% raw %}<td>{{course.description}}</td>{% endraw %}` - Decide how column is displayed\n\nWhen you launch the Vue app in the browser, it will appear as shown below:\n\n![Image](/images/vue-third-stage-getting-course-listing-from-rest-api.png \"Course Listing Component Retrieving from REST API\")\n\n> Congratulations! You have successfully integrated Vue with a REST API. Time to celebrate!\n\n## Step 4: Adding Delete Feature to List Courses Page\n\nTo be able to do this\n\n- We need a REST API in Spring Boot Backend for deleting a course\n- We would need to update Vue frontend to use the API\n\n### Adding Delete Method in the Backend REST API\n\nIt should be easy.\n\nSnippets below show how we create a simple deleteById method in CoursesHardcodedService and expose it from CourseResource.\n\n```java\n@Service\npublic class CoursesHardcodedService {\n\n  public Course deleteById(long id) {\n    Course course = findById(id);\n\n    if (course == null)\n      return null;\n\n    if (courses.remove(course)) {\n      return course;\n    }\n\n    return null;\n  }\n\n```\n\n```java\npublic class CourseResource {\n\n  @DeleteMapping(\"/instructors/{username}/courses/{id}\")\n  public ResponseEntity<Void> deleteCourse(@PathVariable String username, @PathVariable long id) {\n\n    Course course = courseManagementService.deleteById(id);\n\n    if (course != null) {\n      return ResponseEntity.noContent().build();\n    }\n\n    return ResponseEntity.notFound().build();\n  }\n```\n\nImportant things to note:\n\n- `@DeleteMapping(\"/instructors/{username}/courses/{id}\")` - We are mapping the Delete Request Method with two path variables\n- `@PathVariable String username, @PathVariable long id` - Defining the variables for Path Variables\n- `ResponseEntity.noContent().build()` - If Request is successful, return no content back\n- `ResponseEntity.notFound().build()` - If delete failed, return error - resource not found.\n\n### Enhancing Vue app with Delete Course Feature\n\nLet's add `deleteCourse` method to `CourseDataService`. As you can see it execute the delete request to specific course api url.\n\n```javascript\ndeleteCourse(name, id) {\n    return axios.delete(`${INSTRUCTOR_API_URL}/courses/${id}`);\n}\n```\n\nWe can add a delete button corresponding to each of the courses:\n\n```html\n<td>\n  <button class=\"btn btn-warning\" v-on:click=\"deleteCourseClicked(course.id)\">\n    Delete\n  </button>\n</td>\n```\n\nOn click of the button we are calling the `deleteCourseClicked` method passing the course `id`. The implementation for `deleteCourseClicked` is shown below:\n\nWhen we get a successful response for delete API call, we set a `message` into state and refresh the courses list.\n\n```javascript\nmethods: {\n  ...\n  deleteCourseClicked(id) {\n    CourseDataService.deleteCourse(this.INSTRUCTOR, id).then(response => {\n      this.message = `Delete of course ${id} Successful`;\n      this.refreshCourses();\n    });\n  }\n}\n```\n\nWe display the message just below the header\n\n```html\n<h3>All Courses</h3>\n<div v-if=\"message\" class=\"alert alert-success\">\n  {% raw %}{{message}}{% endraw %}\n</div>\n```\n\nComplete `ListCoursesComponent`, at this stage, is shown below:\n\n```html\n<template>\n  <div class=\"container\">\n    <h3>All Courses</h3>\n    <div v-if=\"message\" class=\"alert alert-success\">\n      {% raw %}{{message}}{% endraw %}\n    </div>\n    <div class=\"container\">\n      <table class=\"table\">\n        <thead>\n          <tr>\n            <th>Id</th>\n            <th>Description</th>\n          </tr>\n        </thead>\n        <tbody>\n          <tr v-for=\"course in courses\" v-bind:key=\"course.id\">\n            <td>{% raw %}{{course.id}}{% endraw %}</td>\n            <td>{% raw %}{{course.description}}{% endraw %}</td>\n            <td>\n              <button\n                class=\"btn btn-warning\"\n                v-on:click=\"deleteCourseClicked(course.id)\"\n              >\n                Delete\n              </button>\n            </td>\n          </tr>\n        </tbody>\n      </table>\n    </div>\n  </div>\n</template>\n\n<script>\n  import CourseDataService from \"../service/CourseDataService\";\n  export default {\n    name: \"CoursesList\",\n    data() {\n      return {\n        courses: [],\n        message: null,\n        INSTRUCTOR: \"in28minutes\"\n      };\n    },\n    methods: {\n      refreshCourses() {\n        CourseDataService.retrieveAllCourses(this.INSTRUCTOR) //HARDCODED\n          .then(response => {\n            this.courses = response.data;\n          });\n      },\n      deleteCourseClicked(id) {\n        CourseDataService.deleteCourse(this.INSTRUCTOR, id).then(response => {\n          this.message = `Delete of course ${id} Successful`;\n          this.refreshCourses();\n        });\n      }\n    },\n    created() {\n      this.refreshCourses();\n    }\n  };\n</script>\n\n<style></style>\n```\n\nWhen you launch the Vue app in the browser, it will appear as shown below:\n\n![Image](/images/vue-course-listing-with-delete.png \"Course Listing Component Retrieving from REST API and Delete Button\")\n\nWhen you click the delete button, the course will be deleted.\n\n### Updating Course Details\n\nTo be able to update the course details, we would need to create a new component to represent the todo form.\n\nLet's start with creating a simple component.\n\n/src/components/CourseComponent.vue\n\n```javascript\n<template>\n  <div>\n    <h1>Course Details</h1>\n  </div>\n</template>\n\n<script>\nexport default {\n  name: \"courseDetails\",\n};\n</script>\n\n<style>\n</style>\n```\n\n#### Implementing Routing\n\nWhen the user clicks the update course button on the course listing page, we would want to route to the course page. How do we do it? That's where Routing comes into the picture.\n\n/src/routes.js\n\n```javascript\nimport Vue from \"vue\";\nimport Router from \"vue-router\";\n\nVue.use(Router);\n\nconst router = new Router({\n  mode: \"history\", // Use browser history\n  routes: [\n    {\n      path: \"/\",\n      name: \"Home\",\n      component: () => import(\"./components/Courses\")\n    },\n    {\n      path: \"/courses\",\n      name: \"Courses\",\n      component: () => import(\"./components/Courses\")\n    },\n    {\n      path: \"/courses/:id\",\n      name: \"Course Details\",\n      component: () => import(\"./components/Course\")\n    }\n  ]\n});\n\nexport default router;\n```\n\n/src/App.vue\n\n```javascript\n<template>\n  <div class=\"container\">\n    <router-view/>\n  </div>\n</template>\n\n<script>\nexport default {\n  name: \"app\"\n};\n</script>\n\n<style>\n@import url(https://unpkg.com/bootstrap@4.1.0/dist/css/bootstrap.min.css);\n</style>\n```\n\n/src/main.js\n\n```javascript\nimport Vue from \"vue\";\nimport App from \"./App.vue\";\nimport router from \"./routes\";\n\nVue.config.productionTip = false;\n\nnew Vue({\n  router,\n  render: h => h(App)\n}).$mount(\"#app\");\n```\n\nWe are defining a Router around all the components and configuring paths to each of them.\n\n- `http://localhost:8081/` takes you to home page\n- `http://localhost:8081/courses` takes you to course listing page\n- `http://localhost:8081/courses/2` takes you to course page\n\nWhen you launch the Vue app in the browser using this URL `http://localhost:8081/courses/2`, it will appear as shown below:\n\n![Image](/images/vue-1-course-details.png \"Course Component First Version\")\n\n#### Adding Update Button to Course Listing Page\n\nLet's add update button to the course listing page.\n\n/src/components/ListCoursesComponent.vue\n\n```javascript\n<template>\n  <table class=\"table\">\n    <thead>\n      <tr>\n        ...\n        <th>Update</th>\n        <th>Delete</th>\n      </tr>\n    </thead>\n    <tbody>\n      <tr v-for=\"course in courses\" v-bind:key=\"course.id\">\n        ...\n        <td><button class=\"btn btn-success\" v-on:click=\"updateCourseClicked(course.id)\">Update</button></td>\n        <td><button class=\"btn btn-warning\" v-on:click=\"deleteCourseClicked(course.id)\">Delete</button></td>\n      </tr>\n    </tbody>\n  </table>\n  ....\n</template>\n```\n\nWe can create the add `updateCourseClicked` method to redirect to Course Component and add the binding in the constructor method.\n\n```javascript\nmethods: {\n  ...\n  updateCourseClicked(id) {\n    this.$router.push(`/courses/${id}`);\n  },\n}\n```\n\n#### Adding Add button to Course Listing Page\n\nLet's add an Add button at the bottom of Course Listing Page.\n\n/src/components/ListCoursesComponent.vue\n\n```html\n<!-- At the end of table -->\n<div class=\"row\">\n    <button class=\"btn btn-success\" v-on:click=\"addCourseClicked()\">Add</button>\n</div>\n```\n\nLet's add the appropriate method to handle click of Add button.\n\n```javascript\nmethods: {\n  ...\n  addCourseClicked() {\n    this.$router.push(`/course/-1`);\n  },\n}\n```\n\nWhen you launch the Vue app in the browser using this URL `http://localhost:8081`, it will appear as shown below:\n\n![Image](/images/vue-full-stack-application-with-spring-boot-screenshot.png \"Course listing page final version\")\n\nClicking any of the Update or Add buttons would take you to the Course Component.\n\n#### Create API to Retrieve Specific Course Details\n\nNow that we have the course component beinging rendered on the click of update button, let's start focusing on getting the course details from the REST API.\n\nLet's add `findById` method to `CoursesHardcodedService`. It retrieves the details of a specific course based on it.\n\n```\npublic Course findById(long id) {\n  for (Course course: courses) {\n    if (course.getId() == id) {\n      return course;\n    }\n  }\n  return null;\n}\n```\n\nLet's add `getCourse` method to `CourseResource` class. It exposes the GET method to get the details of a specific course based on id.\n\n```\n@GetMapping(\"/instructors/{username}/courses/{id}\")\npublic Course getCourse(@PathVariable String username, @PathVariable long id) {\n  return courseManagementService.findById(id);\n}\n\n```\n\n#### Invoking the API from Course Component\n\n> How do we invoke the retrieve course details from the Vue frontend?\n\nLet's add `retrieveCourse` method to `CourseDataService`\n\n```javascript\nretrieveCourse(name, id) {\n    return axios.get(`${INSTRUCTOR_API_URL}/courses/${id}`);\n}\n```\n\nWe would want to call the retrieveCourse method in CourseDataService on the load of CourseComponent.\n\n> How do we do it?\n\n> Yes. `created` is the right solution.\n\nBefore we get to it we would need to be able to get the course id from the URL. In the course details page, we are redirecting to the url `/courses/${id}`. From the path parameter, we would want to capture the id. We can use `this.$route.params.id` to get the id from path parameters.\n\nThe code listing below shows the updated CourseComponent.\n\n```javascript\n<template>\n  <div>\n      <h3>Course</h3>\n      <div>{% raw %}{{id}}{% endraw %}</div>\n      <div>{% raw %}{{description}}{% endraw %}</div>\n  </div>\n</template>\n\n<script>\nimport CourseDataService from '../service/CourseDataService';\nexport default {\n  name: \"courseDetails\",\n  data() {\n    return {\n      description: \"\",\n      INSTRUCTOR: \"in28minutes\",\n      errors: []\n    };\n  },\n  computed: {\n    id() {\n      return this.$route.params.id;\n    }\n  },\n  methods: {\n    refreshCourseDetails() {\n        CourseDataService.retrieveCourse(this.INSTRUCTOR, this.id).then(res => {\n          this.description = res.data.description;\n        });\n    },\n  },\n  created() {\n    this.refreshCourseDetails();\n  }\n};\n</script>\n\n<style>\n</style>\n```\n\nWe are setting the details of the course into data.\n\nNote the data can be computed at runtime using `computed` function. Here `id` is taken from url params\n\n```javascript\ncomputed: {\n  id() {\n    return this.$route.params.id;\n  }\n},\n```\n\nIn `created` - `refreshCourseDetails`, we are calling the `CourseDataService.retrieveCourse` to get the details for a course. Once we have the details, we are updating the state.\n\n```javascript\nCourseDataService.retrieveCourse(this.INSTRUCTOR, this.id).then(res => {\n  this.description = res.data.description;\n});\n```\n\nWe are updating the `template` to show the course details from component.\n\n```html\n<div>\n    <h3>Course</h3>\n    <div>{% raw %}{{id}}{% endraw %}</div>\n    <div>{% raw %}{{description}}{% endraw %}</div>\n</div>\n```\n\nWhen you try to update a course, you would see the screen below.\n\n![Image](/images/vue-2-course-details-update.png \"Course Component Second Version\")\n\nWhen you try to create a course, you would see the screen below.\n\n![Image](/images/vue-3-course-details-create.png \"Course Component Second Version\")\n\n\n#### Create a Form\n\nNow that we have loaded up the details of a specific course, let's shift out our attention to editing them and saving them back to the database.\n\n\nLet's now create a simple form.\n\n```javascript\n<template>\n  <div>\n    <h3>Course</h3>\n    <div class=\"container\">\n      <form>\n        <fieldset class=\"form-group\">\n          <label>Id</label>\n          <input type=\"text\" class=\"form-control\" v-model=\"id\" disabled>\n        </fieldset>\n        <fieldset class=\"form-group\">\n          <label>Description</label>\n          <input type=\"text\" class=\"form-control\" v-model=\"description\">\n        </fieldset>\n        <button class=\"btn btn-success\" type=\"submit\">Save</button>\n      </form>\n    </div>\n  </div>\n</template>\n```\n\nFollowing are some of the important details:\n- Form creation in Vue is similar as creating form in HTML\n- `v-model` is binding input to the data, same is with description, it will automaticall display initial values.\n- `<input type=\"text\" class=\"form-control\" v-model=\"id\" disabled>` - Creating a disabled text element for id. v-model value should match data.\n- `<input type=\"text\" class=\"form-control\" v-model=\"description\">` - Creating a text element for description.\n- `<button class=\"btn btn-success\" type=\"submit\">Save</button>` - Adding a submit button.\n\nWhen you try to update a course, you would see the screen below.\n\n![Image](/images/vue-4-course-details-form.png \"Course Component Fourth Version\")\n\n#### Adding Handling of Submit Event\n\nLet's try to handle the Submit event now.\n\nLet's create an onSubmit method to log the values\n\n```javascript\nmethods: {\n  ...\n  validateAndSubmit(e) {\n    console.log({\n      id: this.id,\n      description: this.description\n    })  \n  }\n}\n```\n\nIt's time to tie up the form with the submit method. The key snippet is `@submit=\"validateAndSubmit\"`.\n\n```html\n<form @submit=\"validateAndSubmit\">\n```\n\nWhen you click Submit, the form details are now printed to the console.\n\n```javascript\n{id: \"1\", description: \"Learn Full stack with Spring Boot and Vue\"}\n```\n\n#### Adding Validation using Formik\n\nWhat's a form without validation?\n\nLet's add validations.\n\n```javascript\nvalidate(values) {\n    e.preventDefault();\n    this.errors = [];\n    if(!this.description) {\n        this.errors.push(\"Enter valid values\");\n    } else if(this.description.length < 5) {\n        this.errors.push(\"Enter atleast 5 characters in Description\");\n    }\n}\n```\n\nWe are adding two validations:\n\n- check for empty description\n- check for a minimum length of 5\n\nYou can add other validations as you need.\n\nIf you run the page right now and submit invalid description, you would see that validations prevent the form from getting submitted.\n\n> How do we see validation messages on the screen?\n\nLet's add error message to the field:\n\n```html\n<form @submit=\"validateAndSubmit\">\n  <div v-if=\"errors.length\">\n    <div class=\"alert alert-warning\" v-bind:key=\"index\" v-for=\"(error, index) in errors\">{{error}}</div>\n  </div>\n  ...\n</form>\n```\n\nWhen you try to update a course, you would see the screen below.\n\n![Image](/images/vue-5-course-details-validation-error.png \"Course Component Fifth Version\")\n\n### Updating Course Details on click of submit\n\nNow that the form is ready, we would want to call the backend API to save the course details.\n\nLet's quickly create the API to Update and Create Courses.\n\n#### Create API to Update Course\n\nLet's add a `save` method to `CoursesHardcodedService` to handle creation and updation of course.\n\n```java\npublic Course save(Course course) {\n  if (course.getId() == -1 || course.getId() == 0) {\n    course.setId(++idCounter);\n    courses.add(course);\n  } else {\n    deleteById(course.getId());\n    courses.add(course);\n  }\n  return course;\n}\n```\n\nLet's add a method to the Resource class to update the course. We are using PUT method to update the course. On course updation, we are returning 200 status with updaated course details in the body.\n\n```java\n  @PutMapping(\"/instructors/{username}/courses/{id}\")\n  public ResponseEntity<Course> updateCourse(@PathVariable String username, @PathVariable long id,\n      @RequestBody Course course) {\n\n    Course courseUpdated = courseManagementService.save(course);\n\n    return new ResponseEntity<Course>(courseUpdated, HttpStatus.OK);\n  }\n```\n\n#### Adding API to Create Course\n\nLet's add a method to the Resource class to create the course. We are using POST method to create the course. On course updation, we are returning a status of CREATED.\n\n```java\n  @PostMapping(\"/instructors/{username}/courses\")\n  public ResponseEntity<Void> createCourse(@PathVariable String username, @RequestBody Course course) {\n\n    Course createdCourse = courseManagementService.save(course);\n\n    // Location\n    // Get current resource url\n    /// {id}\n    URI uri = ServletUriComponentsBuilder.fromCurrentRequest().path(\"/{id}\").buildAndExpand(createdCourse.getId())\n        .toUri();\n\n    return ResponseEntity.created(uri).build();\n  }\n```\n\n#### Invoking Update and Create APIs from Course Screen\n\nNow that the REST API is ready, let's create the frontend methods to call them.\n\nLet's create respective methods in the `CourseDataService`. `updateCourse` uses a `put` and `createCourse` uses `post`.\n\n```java\nclass CourseDataService {\n  updateCourse(name, id, course) {\n      return axios.put(`${INSTRUCTOR_API_URL}/courses/${id}`, course);\n  }\n\n  createCourse(name, course) {\n      return axios.post(`${INSTRUCTOR_API_URL}/courses/`, course);\n  }\n```\n\nLet's update the `CourseComponent` to invoke the right service on the click of the submit button.\n\n```javascript\n    validateAndSubmit(e) {\n        e.preventDefault();\n        this.errors = [];\n        if(!this.description) {\n            this.errors.push(\"Enter valid values\");\n        } else if(this.description.length < 5) {\n            this.errors.push(\"Enter atleast 5 characters in Description\");\n        }\n\n        if(this.errors.length === 0) {\n            if (this.id === -1) {\n                CourseDataService.createCourse(this.INSTRUCTOR, {\n                    description: this.description\n                })\n                .then(() => {\n                    this.$router.push('/courses');\n                });\n            } else {\n                CourseDataService.updateCourse(this.INSTRUCTOR, this.id, {\n                    id: this.id,\n                    description: this.description\n                })\n                .then(() => {\n                    this.$router.push('/courses');\n                });\n            }\n        }\n    }\n\n```\n\nWe are creating a course object with the updated details and calling the appropriate method on the `CourseDataService`. Once the request is successful, we are redirecting the user to the course listing page using `this.$router.push('/courses')`.\n\n> Congratulations! You are reading an article from a series of 50+ articles on Spring Boot and Vue. We also have 20+ projects on our Github repository. For the complete set of 50+ articles and code examples, [click here](http://www.springboottutorial.com/spring-boot-tutorials-for-beginners).\n\n\n\n### Downloading the Complete Maven Project With Code Examples\n\nFollowing GitHub repository hosts the complete frontend and backend projects - https://github.com/in28minutes/spring-boot-vuejs-fullstack-examples/tree/master/spring-boot-crud-full-stack\n\n> Our Github repository has all the code examples - https://github.com/in28minutes/spring-boot-vuejs-fullstack-examples\n\n## Next Steps\n\nYou can pursue our amazing courses on Full Stack Development and Microservices. \n[![Image](/images/Course-Go-Full-Stack-With-Spring-Boot-and-React.png \"Go Full Stack with Spring Boot and React\")](https://links.in28minutes.com/MISC-REACT){:target=\"_blank\"}\n[![Image](/images/Course-Go-Full-Stack-With-SpringBoot-And-Angular.png \"Go Full Stack with Spring Boot and Angular\")](https://links.in28minutes.com/MISC-ANGULAR){:target=\"_blank\"}\n[![Image](/images/Course-Master-Microservices-with-Spring-Boot-and-Spring-Cloud.png \"Master Microservices with Spring Boot and Spring Cloud\")](https://links.in28minutes.com/MISC-MICROSERVICES){:target=\"_blank\"}\n"
  },
  {
    "path": "_blog/articles/2019-11-03-udemy-courses-discount-codes.md",
    "content": "---\nlayout:     post\ntitle:      25 in28Minutes Courses with 3000,000+ Learners\ndate:       2017-11-19 12:31:19\nsummary:    Get Amazing Offers on all in28Minutes Udemy Courses.\ncategories: zzCourses\npermalink:  /p/in28minutes-udemy-courses-discount-codes.html\nimage: /images/generic-category.png\n---\n\nEach of these courses come with\n- ✔ Amazing Hands-on Step By Step Learning Experiences\n- ✔ Real Project Experiences using the Best Tools and Frameworks\n- ✔ Awesome Troubleshooting Guides with 200+ FAQs Answered\n- ✔ Friendly Support in the Q&A section\n- ✔ Free Udemy Certificate of Completion on Completion of Course\n\n\n# Recommended Learning Paths\n\n> Skills, Learning Path, Videos and Course Recommendations\n\n - [Learning Path 01 - Spring and Spring Boot Web Applications and API Developer](https://links.in28minutes.com/in28minutes-LP-01)\n - [Learning Path 02 - Full Stack Java Developer with Spring Boot, React and Angular](https://links.in28minutes.com/in28minutes-LP-02)\n - [Learning Path 03 - Java Cloud Microservices Developer with Spring Boot, Docker and Kubernetes](https://links.in28minutes.com/in28minutes-LP-03)\n - [Learning Path 04 - Java Cloud Web Developer with Spring Boot, AWS, Azure and PCF](https://links.in28minutes.com/in28minutes-LP-04)\n - [Learning Path 05 - Java AWS Expert with Microservices, Docker and Kubernetes](https://links.in28minutes.com/in28minutes-LP-05)\n"
  },
  {
    "path": "_blog/articles/2019-11-15-Code-Quality-025-Five-Things-About-CI.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Continuous Integration - 5 Important Questions or Tips\r\ndate:    2019-11-14 12:31:19\r\nsummary: Almost everybody does Continuous Integration today. But the question is - How effective is your Continuous Integration? In this short article, let's explore five important questions we need to ask about Continuous Integration (CI).\r\ncategories: SwBestPractices\r\npermalink:  /five-tips-on-continuous-integration-best-practices\r\nimage: /images/architecture.png\r\n---\r\n\r\nAlmost everybody does Continuous Integration today. But the question is : How effective is your Continuous Integration? In this short article, let's explore five important questions we need to ask about **Continuous Integration** (**CI**).\r\n\r\n\r\n\r\n### Article Series\r\n\r\nThis is the last article in a series of eight articles on Code Quality\r\n- [1 - Introduction To Code Quality](/introduction-to-code-quality){:target='_blank'}\r\n- [2 - Introduction To Coding Standards - Java examples](/coding-standards-with-java-examples){:target='_blank'}\r\n- [3 - Five Important Coding Standards](/code-quality-five-important-coding-standards){:target='_blank'}\r\n- [4 - Best Practices in Static Code Analysis with SonarQube](/static-code-analysis-and-code-quality-best-practices-sonarqube){:target='_blank'}\r\n- [5 - Code Review Best Practices](/code-review-best-practices){:target='_blank'}\r\n- [6 - What Are Code Smells?](/code-quality-code-smells){:target='_blank'}\r\n- [7 - What Is Refactoring?](/code-quality-basics-introduction-to-refactoring){:target='_blank'}\r\n- [8 - Continuous Integration - 5 Important Questions or Tips](/five-tips-on-continuous-integration-best-practices){:target='_blank'}\r\n\r\n\r\n### Questions To Ask About Continuous Integration\r\n\r\nLet's look at them one by one:\r\n\r\n#### Frequency Of Commits\r\n\r\n> How frequently is code being committed to the version control system? \r\n\r\nIt is awesome to have great CI infrastructure in place with frequent builds, wonderful unit tests and integration tests. However, if code is not committed frequently enough to the repository, all this infrastructure is sitting idle. \r\n\r\nWhenever you think your code is in a good working state, commit it to get immediate feedback. Do this five, ten, or a hundred times a day!\r\n\r\n#### Frequency Of Builds\r\n\r\n> How often are your CI builds running? \r\n\r\nAre they running every time a commit is done, every minute, every hour, or once a day? With CI, it is important to get immediate feedback. If you are running your builds less frequently, you might be enjoying all the possible benefits of CI.\r\n\r\nIdeally, CI should run for every commit.\r\n\r\n#### What's in the Build?\r\n\r\n> What are the various steps that are run in your CI build?\r\n \r\n Are all of these are run in CI?\r\n - Code compilation\r\n - Unit tests\r\n - Integration tests\r\n - User acceptance tests\r\n - Deployment\r\n\r\n It is desirable to have as many steps as possible as part of the CI build.\r\n\r\n#### Build Performance\r\n\r\nHow fast is your CI build? \r\n\r\nAny CI build should not take more than 10-15 minutes of time, as a benchmark. Of course, the steps involved in the build affects build performance. \r\n\r\nAs the number of steps in the build increase, the longer it takes. You need to find the right balance between the two, such as testing everything versus testing quickly. \r\n\r\nOne strategy would be to have two kinds of CI builds - one smaller frequent build, and one larger slower build that only runs from time to time.\r\n\r\n#### Handling Broken Builds\r\n\r\nThis is one of the more fun events for the team. Having the member who breaks the build, buy lunch for the entire team is incentive enough for careful programming and commits! Not the least, it helps foster team building and team spirit. \r\n\r\n\r\nDo check out our video on this:\r\n\r\n[![image info](/images/Capture-025-01.png)](https://www.youtube.com/watch?v=i8WNumrDMcA)\r\n\r\n### Summary\r\n\r\nIn this article, we explored the five important questions that a team using a CI infrastructure, to ask about its development process.\r\n"
  },
  {
    "path": "_blog/articles/2019-11-15-Code-Quality-070-Refactoring.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Code Quality Basics - What Is Refactoring?\r\ndate:    2019-11-14 12:31:19\r\nsummary: As you make enhancements to your source code, how do you ensure that you are adhering to all the standards? What is Refactoring? How can you refactor your code?\r\ncategories: SwCodeQuality\r\npermalink:  /code-quality-basics-introduction-to-refactoring\r\nimage: /images/design-category.png\r\n---\r\n\r\nAs you make enhancements to your source code, how do you ensure that you are adhering to all the standards? What is Refactoring? How can you refactor your code?\r\n\r\n## You will learn\r\n- What is code refactoring?\r\n- What are the challenges with having bad code?\r\n- Why should you refactor code?\r\n- What are the best practices in refactoring code?\r\n\r\n\r\n\r\n## Article Series\r\n\r\nThis is the seventh article in a series of eight articles on Code Quality\r\n- [1 - Introduction To Code Quality](/introduction-to-code-quality){:target='_blank'}\r\n- [2 - Introduction To Coding Standards - Java examples](/coding-standards-with-java-examples){:target='_blank'}\r\n- [3 - Five Important Coding Standards](/code-quality-five-important-coding-standards){:target='_blank'}\r\n- [4 - Best Practices in Static Code Analysis with SonarQube](/static-code-analysis-and-code-quality-best-practices-sonarqube){:target='_blank'}\r\n- [5 - Code Review Best Practices](/code-review-best-practices){:target='_blank'}\r\n- [6 - What Are Code Smells?](/code-quality-code-smells){:target='_blank'}\r\n- [7 - What Is Refactoring?](/code-quality-basics-introduction-to-refactoring){:target='_blank'}\r\n- [8 - Continuous Integration - 5 Important Questions or Tips](/five-tips-on-continuous-integration-best-practices){:target='_blank'}\r\n\r\n\r\n### Why Refactoring?\r\n\r\nSuppose you end up working in  a project which has code that looks like this:\r\n\r\n```java\r\n\r\n\tpublic Lock isLockAvailableForFile(long clientID, String status, boolean firstScreen, User user, List list) {\r\n\t\tDate sysTime = new Date();\r\n\t\tLock lock = new Lock();\r\n\t\tif(list.size() > 0 && list.get(0) != null) {\r\n\t\t\tObject[] o1 = (Object[]) list.get(0);\r\n\t\t\tString userId = (String) o1[0];\r\n\t\t\tDate lockTimestamp = (Date) o1[1];\r\n\t\t\r\n\t\t\tif(userId != null) {\r\n\t\t\t\t//The message shown to the user\r\n\t\t\t\tString lockMsg = Constants.LOCK_REASON.replaceAll(\"@@USER@@\", userId);\r\n\r\n\t\t\t\t//if userId is present, then lockTimestamp will also be present\r\n\t\t\t\t//72000000 milliseconds equals to 2 hours\r\n\t\t\t\tif(sysTime.gettime() - locktimestamp.getTime() > 7200000) {\r\n\t\t\t\t\t//The new user should attain lock only in the first screen\r\n\t\t\t\t\t//If 2 hours expires when user is not present on 1st screen, then user Id...\r\n\t\t\t\t\tif(firstScreen \r\n\t\t\t\t\t\t|| userId.equalsIgnoreCase(user.getUserId())) {\r\n\t\t\t\t\t\t//to set the file access to write mode\r\n\t\t\t\t\t\tlock.setReadAccess(false);\r\n\t\t\t\t\t\tLogger.debug(\r\n\t\t\t\t\t\t\t\t\t \"Write access is permitted to the User for client {0}\",\r\n\t\t\t\t\t\t\t\t\tclientId);\r\n\t\t\t\t\t\treturn lock;\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t/*   ...  BLAH BLAH BLAH !!!  ...   */\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n```\r\n\r\nHow easy do you think it is to maintain this kind of code? \r\n\r\nLet's say you need to make a change in the piece of code shown above. Is it straightforward, or is it a difficult task?\r\n\r\nOne thing you can do with difficult code such as this, is to improve its structure, without changing its functionality. Such a transformation is called **refactoring**. \r\n\r\nHere is what the above code will look like when refactored:\r\n\r\n```java\r\n\r\n\tpublic Lock isLockAvailableForFile(boolean isFirstScreen, User user, List list) {\r\n\t\tif(isListEmpty(list)) {\r\n\t\t\treturn lockWithWriteAccess();\r\n\t\t}\r\n\t\tObject[] lockObject = (Object[]) list.get(0);\r\n\t\tString userId = (String) lockObject[0];\r\n\t\tDate lockTimestamp = (Date) lockObject[1];\r\n\r\n\t\tif(userId == null) {\r\n\t\t\treturn lockWithWriteAccess();\r\n\t\t}\r\n\r\n\t\tboolean userHasLockedEarlier = userId.equalsIgnoreCase(user.userId);\r\n\t\tboolean lockPeriodExceeded = new Date().getTime() -\r\n\t\t\t\t\t\t\t\t\t lockTimeStamp.getTime > 2 * 60 * 60 * 1000;\r\n\r\n\t\tif(userHasLockEarlier)\r\n\t\t\treturn lockWithWriteAccess();\r\n\t\tif(lockPeriodExceeded && isFirstScreen)\r\n\t\t\treturn lockWithWriteAccess();\r\n\r\n\t\treturn lockWithReadAccess(userId);\r\n\t}\r\n\r\n```\r\n\r\n### What is Refactoring?\r\n\r\n> Refactoring involves altering the structure of code, without changing its behavior. \r\n\r\nThe goals of refactoring include making the code have less duplication, and making it more readable. \r\n\r\nIt may sound very easy, but refactoring is actually a very difficult task. The most difficult part is deciding on a sequence of refactoring steps. \r\n\r\nIn the example we saw above, how can you be sure that making the alterations shown, will keep the functionality of the code intact?\r\n\r\n#### Build A Test Bed\r\n\r\nThe only way you can refactor with confidence, is by building a test bed.  Of course, this may not be necessary for very basic forms of refactoring, such as renaming a variable, or extracting a method. Except for such basic refactoring, one would need to make sure that there are very good unit tests in place, to test the code. \r\n\r\nIf such unit tests are not available, then you need to write tests first. When you have tests, you can improve the code in small steps. At each stage, make the changes, and run the set of tests. If everything turns out fine, then go ahead with the next refactoring step. \r\n\r\nDo check out our video on the same topic:\r\n\r\n[![image info](images/Capture-070-01.png)](https://www.youtube.com/watch?v=2kxgoBZw9Xc)\r\n\r\n### Summary\r\n\r\n**Continuous Refactoring**, aided by tests, leads to clean code. To be able to continuously refactor, you need good tests. With exprerience, you get better at refactoring, and will figure out a good sequence of steps to approach refactoring, in general.\r\n"
  },
  {
    "path": "_blog/articles/2019-11-15-Code-Quality-077-CodeSmells.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Code Quality Basics - What Are Code Smells?\r\ndate:    2019-11-14 12:31:19\r\nsummary: In this article, we have a closer look at code smells. We see what they are, and what you should do about them.\r\ncategories: SwCodeQuality\r\npermalink:  /code-quality-code-smells\r\nimage: /images/design-category.png\r\n---\r\n\r\nIn this article, we have a closer look at code smells. We see what they are, and what you should do about them.\r\n\r\n### You will learn\r\n- What Are Code Smells?\r\n- What are the typical code smells?\r\n- How do you identify code smells?\r\n- How do you react to code smells?\r\n\r\n\r\n\r\n## Article Series\r\n\r\nThis is the sixth article in a series of eight articles on Code Quality\r\n- [1 - Introduction To Code Quality](/introduction-to-code-quality){:target='_blank'}\r\n- [2 - Introduction To Coding Standards - Java examples](/coding-standards-with-java-examples){:target='_blank'}\r\n- [3 - Five Important Coding Standards](/code-quality-five-important-coding-standards){:target='_blank'}\r\n- [4 - Best Practices in Static Code Analysis with SonarQube](/static-code-analysis-and-code-quality-best-practices-sonarqube){:target='_blank'}\r\n- [5 - Code Review Best Practices](/code-review-best-practices){:target='_blank'}\r\n- [6 - What Are Code Smells?](/code-quality-code-smells){:target='_blank'}\r\n- [7 - What Is Refactoring?](/code-quality-basics-introduction-to-refactoring){:target='_blank'}\r\n- [8 - Continuous Integration - 5 Important Questions or Tips](/five-tips-on-continuous-integration-best-practices){:target='_blank'}\r\n\r\n\r\n### What Are Code Smells?\r\n\r\nA code smell refers to a certain pattern in the code that signals there could be a defect lurking somewhere. \r\n\r\nStatic analysis tools are very good at detecting code smells. They analyze the patterns, and then see if they could lead to a problem. \r\n\r\nFor example, if you assign a variable in Java a ```null``` value, and then immediate call a method on it, a ```NullPointerException``` would result. That is nothing but a code smell! \r\n\r\nIf you do static analysis of that part of code, the tool would indicate there is a high chance of a defect in the code at that point.  \r\n\r\nChoosing static analysis tools is the best way to detect code smells in your application:\r\n\r\n![image info](images/Capture-077-02.png)\r\n\r\nSonarQube has great tools for detecting code smells. what we see in the snapshot above are the rules for Java, and a profile where there are 194 code smells present.\r\n\r\n### Typical Code Smells\r\n\r\nWhat are examples of typical code smells? Let's take the example of Java programs:\r\n\r\n* You make use of a deprecated method definition, that is annotated by ```@Deprecated```\r\n* You make use of a ```for``` loop, but do not increment/decrement the loop counters\r\n* You access a ```static``` member using an instance variable\r\n* You make use of a ```switch``` statement, but do not have a ```default``` clause\r\n* You have a ```switch``` statement with just two ```case``` clauses\r\n* You call ```toString()``` on a ```String``` object\r\n* In a situation where you need to use a ```while``` loop, you use a ```for``` loop\r\n* You name a class as ```Exception```, but do not extend the built-in ```Exception``` class, or a subclass of it\r\n* You throw an exception in the ```finally``` clause\r\n* You throw very generic exceptions\r\n* You use a ```try```-```catch``` block, where a ```try```-with-resources might be a better option\r\n* You have unused private methods\r\n\r\nWhen you see instances of such smells, you conclude that the developer does not fully understand what he/she was trying to do. Such situations could cause hidden bugs to exist in the code. \r\n\r\n### Other Kinds Of Code Smells\r\n\r\nOther kinds of code smells could exists, especially in your JUnit code. These include:\r\n* Ignored unit tests\r\n* Empty test case\r\n* Test case without asserts\r\n\r\n### Handling Code Smells\r\n\r\nMake sure that having zero code smells is an integral part of your Definition Of Done. \r\n\r\nIt is important that you do static analysis and manual code review on a regular basis. \r\n\r\nStatic analysis should be part of continuous integration build.\r\n\r\nDo check out our video on the same topic:\r\n\r\n[![image info](images/Capture-077-01.png)](https://www.youtube.com/watch?v=r0CyMrZBYa4)\r\n\r\n### Summary\r\n\r\nCode smells are patterns in code that could indicate hidden bugs. The two ways to detect code smells are static analysis, and manual code reviews. It is important to do both systematically, to keep the application free of code smells. \r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-11-15-Code-Quality-078-5-Important-Coding-Standards.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Code Quality Basics - Five Important Coding Standards\r\ndate:    2019-11-14 12:31:19\r\nsummary: In this article, we talk about the five most important coding standards that I would recommend all developers to follow.\r\ncategories: SwCodeQuality\r\npermalink:  /code-quality-five-important-coding-standards\r\nimage: /images/design-category.png\r\n---\r\n\r\nIn this article, we talk about the five most important coding standards that I would recommend all developers to follow.\r\n\r\n\r\n\r\n### Article Series\r\n\r\nThis is the third article in a series of eight articles on Code Quality\r\n- [1 - Introduction To Code Quality](/introduction-to-code-quality){:target='_blank'}\r\n- [2 - Introduction To Coding Standards - Java examples](/coding-standards-with-java-examples){:target='_blank'}\r\n- [3 - Five Important Coding Standards](/code-quality-five-important-coding-standards){:target='_blank'}\r\n- [4 - Best Practices in Static Code Analysis with SonarQube](/static-code-analysis-and-code-quality-best-practices-sonarqube){:target='_blank'}\r\n- [5 - Code Review Best Practices](/code-review-best-practices){:target='_blank'}\r\n- [6 - What Are Code Smells?](/code-quality-code-smells){:target='_blank'}\r\n- [7 - What Is Refactoring?](/code-quality-basics-introduction-to-refactoring){:target='_blank'}\r\n- [8 - Continuous Integration - 5 Important Questions or Tips](/five-tips-on-continuous-integration-best-practices){:target='_blank'}\r\n\r\n\r\n### Great Names\r\n\r\nGiving great names to variables, methods and classes is, for me, the most important part of programming. \r\n\r\nTry and give bad names to your variables, methods and classes, and you will discover that it becomes very difficult to understand what's going on.\r\n\r\nThe name of a variable should represent what value it contains. The name of a method should represent what action it performs. The name of a class should be a noun that represents exactly what it is supposed to do.\r\n\r\nIf you are unable to give appropriate names to your variables/methods/classes, then it's a code smell.  Your are most probably doing too many things. Think about the Single Responsibility Principle and break it down. \r\n\r\nUnfortunately, there is no automated way to check if the names of different elements are appropriate. The only way to do so, is peer code reviews.\r\n\r\n### Complexity\r\n\r\nComplexity is generally measured by:\r\n* How many conditionals and loops are present in a single method in the code?\r\n\r\nCyclomatic complexity is a very good measure of how complex your method code is. The more complex the method is, the more difficult it is to understand. \r\n\r\nIdeally, the cyclomatic complexity of a method should be less than 10. \r\n\r\n### Size Of Methods And Classes\r\n\r\nIt is highly desirable to have as small a method definition as possible, as it leads to a much better naming of the method. The length of a method should not exceed whatever you can see on a single screen. \r\n\r\nThe same is the case with classes. The smaller a class definition, the better the name you can give it. The size of a class should never exceed 200 lines.\r\n\r\n### Duplication\r\n\r\nYou need to have as little duplication in your code as possible. Typically, the standard measure we go by, is to keep it under 5 per cent of the total code. \r\n\r\n### Readability Of Code\r\n\r\nWhen you look at a piece of code form an application, you should understand it very quickly. \r\n\r\n\r\nDo check out our video on the same topic:\r\n\r\n[![image info](images/Capture-078-01.png)](https://www.youtube.com/watch?v=xOPTwJyFnMM)\r\n\r\n\r\n### Summary\r\n\r\nIn this article, we has a look at the five most important coding standards. Of these 5 coding standards, the first and the last, namely naming and readability standards, are the most difficult to achieve. \r\n\r\nThe other 3 standards can be enforced by using an automated tool such as SonarQube. SonarQube can measure code complexity, estimate the sizes of methods and classes, and check for code duplication as well. These checks can be run as part of continuous integration builds.\r\n"
  },
  {
    "path": "_blog/articles/2019-11-15-Code-Quality-079-Code-Quality-Overview.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Introduction To Code Quality\r\ndate:    2019-11-14 12:31:19\r\nsummary: In this article, we discuss code quality and why you should have great code quality. \r\ncategories: SwCodeQuality\r\npermalink:  /introduction-to-code-quality\r\nimage: /images/design-category.png\r\n---\r\n\r\nIn this article, we discuss code quality and why you should have great code quality.\r\n\r\n## You will learn\r\n- What is Code Quality?\r\n- Why do you need to track Code Quality?\r\n- What are the approaches to evaluate Code Quality of an application?\r\n- What are the popular code quality tools? \r\n\r\n\r\n\r\n## Article Series\r\n\r\nThis is the first article in a series of eight articles on Code Quality\r\n- [1 - Introduction To Code Quality](/introduction-to-code-quality){:target='_blank'}\r\n- [2 - Introduction To Coding Standards - Java examples](/coding-standards-with-java-examples){:target='_blank'}\r\n- [3 - Five Important Coding Standards](/code-quality-five-important-coding-standards){:target='_blank'}\r\n- [4 - Best Practices in Static Code Analysis with SonarQube](/static-code-analysis-and-code-quality-best-practices-sonarqube){:target='_blank'}\r\n- [5 - Code Review Best Practices](/code-review-best-practices){:target='_blank'}\r\n- [6 - What Are Code Smells?](/code-quality-code-smells){:target='_blank'}\r\n- [7 - What Is Refactoring?](/code-quality-basics-introduction-to-refactoring){:target='_blank'}\r\n- [8 - Continuous Integration - 5 Important Questions or Tips](/five-tips-on-continuous-integration-best-practices){:target='_blank'}\r\n\r\n### What Is Code Quality?\r\n\r\nCode quality is a measure of how maintainable your code is. \r\n\r\nThe next question that comes up is - how do you measure code quality? \r\n\r\nThe way you do that is by having \r\n* Static Analysis\r\n* Peer code reviews\r\n\r\n### Setting the Right Coding Standards\r\n\r\nHaving the right coding standards is an important starting point to having great code. Most organizations have coding standards at the enterprise level as well. Coding standards ensure a certain level of code consistency, when a developer moves from one module to another within a project, or from one project to another within an organization.  \r\n\r\nYou can read more about it [here](/coding-standards-with-java-examples){:target='_blank'}\r\n\r\n\r\n### Static Analysis\r\n\r\nStatic analysis of code can be done by using tools such as SonarQube. A best practice that is recommended is to perform static analysis of your code at least once a day. \r\n\r\nAlso ensure that you have processes in place to keep reviewing them. \r\n\r\nMake sure that your code quality standards are set as part of you Definition Of Done. At the end of every sprint, evaluate your code against the set code quality standards, and see if it matches up to them. \r\n\r\n\r\n#### Static Analysis with SonarQube\r\n\r\nOne of the best ways to measure code quality is by using a tool such as SonarQube:\r\n\r\n![image info](images/Capture-079-02.png)\r\n\r\nSonarQube looks at your code form a wide variety of perspectives. It look at angles such as the types of:\r\n* Bugs\r\n* Security vulnerabilities\r\n* Code smells - patterns in code that could indicate hidden bugs\r\n* Code Coverage - How good are your unit tests, and how much code do they cover\r\n* Amount of Code Duplication\r\n\r\nAll these are good measures of code quality. \r\n\r\nYou can read more about static analysis here - [Code Quality Basics - Best Practices in Static Code Analysis with SonarQube](/static-code-analysis-and-code-quality-best-practices-sonarqube){:target='_blank'}\r\n\r\n### Peer Reviews\r\n\r\nStatic analysis is not a silver bullet. Use peer reviews to identify things that cannot be found in static analysis.\r\n\r\nCode Review is one of the most important components in ensuring great Code Quality in your projects.\r\n\r\nRemember that a code review is not a tool to find fault with others efforts. \r\n\r\nHere are a couple of important goals:\r\n- A code review is done to add value to the system and the people in the team. \r\n- It also adds to a list of best practices that team members can follow.\r\n\r\nYou can read more about [Code Review Best Practices](/code-review-best-practices){:target='_blank'}\r\n\r\nDo check out our video on the same topic:\r\n\r\n[![image info](images/Capture-079-01.png)](https://www.youtube.com/watch?v=aGQda_tlfdw)\r\n\r\n### Summary\r\n\r\nIn this article, we had an overview of what code quality is all about. We saw that it can be ensured by using static analysis tools, and by doing peer code reviews. There are several parameters to evaluate the quality of an application's code.\r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-11-15-Code-Quality-105-Introduction-To-Coding-Standards.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Introduction To Coding Standards with Java examples\r\ndate:    2019-11-14 12:31:19\r\nsummary: Having the right coding standards is an important starting point to having great code. What are coding standards? How do you ensure that you are following the best practices around coding standards? \r\ncategories: SwCodeQuality\r\npermalink:  /coding-standards-with-java-examples\r\nimage: /images/design-category.png\r\n---\r\n\r\nHaving the right coding standards is an important starting point to having great code. What are coding standards? How do you ensure that you are following the best practices around coding standards? \r\n \r\n## You will learn\r\n- What is a coding standard?\r\n- Why do you need coding standards?\r\n- What are the most important coding standards?\r\n- How do you ensure that coding standards are adhered to? \r\n- What are the best practices and processes?\r\n\r\n\r\n\r\n## Article Series\r\n\r\nThis is the second article in a series of eight articles on Code Quality\r\n- [1 - Introduction To Code Quality](/introduction-to-code-quality){:target='_blank'}\r\n- [2 - Introduction To Coding Standards - Java examples](/coding-standards-with-java-examples){:target='_blank'}\r\n- [3 - Five Important Coding Standards](/code-quality-five-important-coding-standards){:target='_blank'}\r\n- [4 - Best Practices in Static Code Analysis with SonarQube](/static-code-analysis-and-code-quality-best-practices-sonarqube){:target='_blank'}\r\n- [5 - Code Review Best Practices](/code-review-best-practices){:target='_blank'}\r\n- [6 - What Are Code Smells?](/code-quality-code-smells){:target='_blank'}\r\n- [7 - What Is Refactoring?](/code-quality-basics-introduction-to-refactoring){:target='_blank'}\r\n- [8 - Continuous Integration - 5 Important Questions or Tips](/five-tips-on-continuous-integration-best-practices){:target='_blank'}\r\n\r\n\r\n### What Is A Coding Standard?\r\nCoding standards are standards related to \r\n- How to use a programming language?\r\n- How to format your code?\r\n- How to structure your application?\r\n- How to use a framework or a utility?\r\n\r\nMost organizations have coding standards at the enterprise level as well. \r\n\r\nCoding standards ensure a certain level of code consistency, when a developer moves from one module to another within a project, or from one project to another within an organization. \r\n\r\n### What Are Coding Standards Like?\r\n\r\nCommon points that are addressed by coding standards include:\r\n* Formatting\r\n* Complexity of a method\r\n* Naming conventions for variables, methods and classes\r\n* The sizes of methods and classes\r\n* The number of parameters that a method is allowed to have\r\n\r\n### Important Coding Standards\r\n\r\nLet's quickly review some of the important coding stands.\r\n\r\n#### Sizes Of Methods And Classes    \r\n\r\nHave small methods and classes.\r\n\r\nIf you have a large method, then it is quite likely you have violated the Single Responsibility Principle (SRP). \r\n\r\n#### Complexity Of Methods And Classes\r\n\r\nMethods and Classes should have as low cyclomatic complexity as possible. A method that has a large number of conditionals and nested loops is difficult to maintain.\r\n\r\n#### Naming Variables / Methods / Classes\r\n\r\n> How you name the various program elements directly determines how readable your code is. \r\n\r\nIf you name your variables, methods and classes in a simple and intuitive manner, over 50% of code readability is achieved!\r\n\r\n#### The Number Of Parameters\r\n\r\nLimiting the number of parameters generally results in more maintainable code.\r\n\r\n#### Have good tests with great asserts and good code coverage\r\n\r\nHow do you ensure you have great tests? \r\n- Have readable tests\r\n- Have great asserts, to check for conditions in the test code\r\n\r\nIf you can have good code coverage with good asserts, then there's nothing like it! \r\n\r\nNote that code coverage is just a number. While having 100% code coverage is good, it is more important to have good asserts checking the functionality.\r\n\r\n### Verifying Coding Standards\r\n\r\n#### Using Static Analysis\r\n\r\nYou can do static analysis of your source code using tools such as SonarQube. Make sure that you run static analysis as part of your continuous integration builds.\r\n\r\nInclude static analysis goals in your sprint \"Definition of Done\".\r\n\r\nYou can read more about it [here](/static-code-analysis-and-code-quality-best-practices-sonarqube){:target='_blank'}.\r\n\r\n#### Performing Code Reviews\r\n\r\nStatic analysis has its limitations, since it is done in an automated manner. It cannot determine whether a variable, method or class is named appropriately. \r\n\r\nYou also need to have a process of periodically reviewing code, mainly through peer reviews. \r\n\r\nYou can read more about it [here](/code-review-best-practices){:target='_blank'}.\r\n\r\nDo check out our video on the same topic:\r\n\r\n[![image info](images/Capture-105-01.png)](https://www.youtube.com/watch?v=XRKDpQ3b27M)\r\n\r\n### Summary\r\n\r\nHaving the right coding standards is an important starting point to having great code. Having great process around static analysis and peer reviews will help your project meet its coding standards. \r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-11-15-Code-Quality-106-Code-Review-Best-Practices.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Code Review Best Practices\r\ndate:    2019-11-14 12:31:19\r\nsummary: Code Review is one of the most important components in ensuring great Code Quality in your projects. How do you ensure that code reviews in your projects yield expected results? \r\ncategories: SwCodeQuality\r\npermalink:  /code-review-best-practices\r\nimage: /images/design-category.png\r\n---\r\n\r\nCode Review is one of the most important components in ensuring great Code Quality in your projects. How do you ensure that code reviews in your projects yield expected results? \r\n \r\n## You will learn\r\n- What is code review?\r\n- Why do you do code reviews?\r\n- When should you do a code review?\r\n- How can you become a good code reviewer?\r\n- What are the things to look for in a code review?\r\n- What are the code review best practices?\r\n\r\n\r\n\r\n## Article Series\r\n\r\nThis is the fifth article in a series of eight articles on Code Quality\r\n- [1 - Introduction To Code Quality](/introduction-to-code-quality){:target='_blank'}\r\n- [2 - Introduction To Coding Standards - Java examples](/coding-standards-with-java-examples){:target='_blank'}\r\n- [3 - Five Important Coding Standards](/code-quality-five-important-coding-standards){:target='_blank'}\r\n- [4 - Best Practices in Static Code Analysis with SonarQube](/static-code-analysis-and-code-quality-best-practices-sonarqube){:target='_blank'}\r\n- [5 - Code Review Best Practices](/code-review-best-practices){:target='_blank'}\r\n- [6 - What Are Code Smells?](/code-quality-code-smells){:target='_blank'}\r\n- [7 - What Is Refactoring?](/code-quality-basics-introduction-to-refactoring){:target='_blank'}\r\n- [8 - Continuous Integration - 5 Important Questions or Tips](/five-tips-on-continuous-integration-best-practices){:target='_blank'}\r\n\r\n\r\n### Why Code Reviews\r\n\r\nWhat could be the reason for doing a code review? \r\n\r\n![image info](images/Capture-106-02.png)\r\n\r\nRemember that a code review is not a tool to find fault with others efforts. \r\n\r\nHere are a couple of important goals:\r\n- A code review is done to add value to the system and the people in the team. \r\n- It also adds to a list of best practices that team members can follow.\r\n\r\n#### Adding Value To The System\r\n\r\nCode reviews add value to your system. Aim of the code review is to make the system more maintainable. Your aim is to check for bugs in adhering to functional and non functional requirements - scalablity, performance, security etc.\r\n\r\n#### Adding Value To The People\r\n\r\nCode reviews should be used as a way to enhance the knowledge of the developers involved and a way to spread the best practices. \r\n\r\n#### Adding To Best Practices\r\n\r\nAn important step of code review should be to identify best practices. Common error patterns can be identified and documented.\r\n\r\n### When Should You Do Code Reviews?\r\n\r\n![image info](images/Capture-106-03.png)\r\n\r\n#### Review As Early As Possible\r\n\r\nIt is preferable to do code reviews **as early as possible**.\r\n\r\n##### Review with Normal Focus\r\n\r\nNormal focus refers to typical code review done during the course of a sprint for a run of the mill user story. \r\n\r\n##### Review with High Focus\r\n\r\nThere are times during development when peer reviews need to be done with high focus. \r\n\r\n###### New Developers Joining In\r\n\r\nA good example is when a new developer joins a team. A new developer takes time to get familiar and start implementing code that meets the team's coding standards. An effort should be made to encourage them to learn from code reviews.\r\n\r\n###### New Methodology Or Technology Implemented\r\n\r\nWhen a new methodology is being adopted, or a new technology is being brought into the code base, it is important to have focused code reviews.\r\n\r\n###### Building A Vertical Slice\r\n\r\nIn the initial stages of the project, you generally build a vertical slice. Vertical slice helps in solving technical challenges. \r\n\r\nVertical slice becomes a reference for the project. It is important to have focused code reviews for the vertical slice. \r\n\r\n### How To Do Code Reviews?\r\n\r\n![image info](images/Capture-106-04.png)\r\n\r\n#### Encourage Pair Programming\r\n\r\nIdeally, I would love to have pair programming reviews. A lot of times, it is much easier to refactor code almost immediately during the review, than at a later point in time.\r\n\r\n### Code Review Best Practices\r\n\r\nLet's quickly review a few other best practices related to code review.\r\n\r\n#### Use Static Analysis Tools\r\n\r\nMake use of static analysis tool such as SonarQube.\r\n\r\n* Check the components in code, their sizes, and their interactions with other components in the code. \r\n* Identify and look closely at certain types of code hot-spots, such as:\r\n\t* Large classes\r\n\t* Complex methods\r\n\t* Large components\r\n\t* Lot of dependencies\r\n\t* Uncovered code\r\n\r\n#### Review Junits\r\n\r\nReview the Junits for complex method and classes, and see how readable the code actually is. \r\n\r\n> Junits are often a very good signal of the readability of code. If the code is difficult to test, the code is definitely difficult to understand.\r\n\r\n#### Check Readability Of Code\r\n\r\nLook at the readability of the code, by focusing on the Four Principles Of Simple Design. \r\n\r\n### What do you look for in a code review?\r\n\r\nThere are various aspects to be considered while doing a review of the code.\r\n\r\n![image info](images/Capture-106-05.png)\r\n\r\n\r\n\r\n#### Review The Architecture\r\n\r\nHave a look at various points, such as:\r\n\r\n* The choice of frameworks in the code base\r\n* The way the code components communicate with other systems\r\n* How testable the code is?\r\n* The architecture of the components themselves\r\n* The extent of code reuse - Are common components are identified and abstracted away for use in other places?\r\n\r\n#### Review The Design\r\n\r\n![image info](images/Capture-106-06.png)\r\n\r\nReview the following aspects:\r\n* What is the nature of the interaction between the various classes? How loosely are the classes coupled, and what is the cohesion between them?\r\n* Have a look at the layer responsibilities, and see if the layers are clearly demarcated, and do not overlap in functionality. \r\n* How well are the core object oriented principles followed in the code design?\r\n* What is the nature of the unit tests? How easy or difficult is it to unit test the code under review?\r\n\r\n#### Review The Code\r\n\r\n![image info](images/Capture-106-07.png)\r\n\r\n* Make sure the code follows the Four Principles Of Simple Design\r\n* Ensure the code got the basics right\r\n\r\n![image info](images/Capture-106-08.png)\r\n\r\n* Will the code be scalable and performant?\r\n\r\n![image info](images/Capture-106-09.png)\r\n\r\n* How does the code handle important security concerns?\r\n* How well are the unit tests written, and are they readable?\r\n* Are language specific standards being adhered to? In Java foe example, the following language constructs have certain purposes:\r\n\r\n![image info](images/Capture-106-10.png)\r\n\r\nFor example, Enums are preferred to strings wherever possible, and this makes the code more readable.\r\n\r\n#### Review Engineering Practices\r\n\r\n![image info](images/Capture-106-11.png)\r\n\r\nThe quality of code in an application depends greatly on the kind of engineering practices followed in the team. You can check\r\n* How often the code is committed?\r\n* Review how often builds are broken\r\n* Review the entire continuous integration process\r\n\r\nDo check out our video on the same topic:\r\n[![image info](images/Capture-106-01.png)](https://www.youtube.com/watch?v=hVJGu0xdXII)\r\n\r\n### Summary\r\n\r\nIn this article, we had a good overview of code review best practices for a team, or organization. The core principle behind doing code reviews is to add value - to the system, to the people involved, and to the best practices as a whole.\r\n"
  },
  {
    "path": "_blog/articles/2019-11-15-Code-Quality-108-Static-Analysis-Best-Practices.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Code Quality Basics - Best Practices in Static Code Analysis with SonarQube\r\ndate:    2019-11-14 12:31:19\r\nsummary: Static code analysis is a great approach to check for code quality. There are a variety of static code analysis tools available to check for coding standard violations in your code. In this article, let's get introduced to static code analysis, different tool you have and also the limitations of static code analysis.\r\ncategories: SwCodeQuality\r\npermalink:  /static-code-analysis-and-code-quality-best-practices-sonarqube\r\nimage: /images/design-category.png\r\n---\r\n\r\nStatic code analysis is a great approach to check for code quality. There are a variety of static code analysis tools available to check for coding standard violations in your code. In this article, let's get introduced to static code analysis, different tool you have and also the limitations of static code analysis.\r\n \r\n## You will learn\r\n- What is Static Code Analysis?\r\n- When do you use Static Code Analysis?\r\n- How can you do Static Code Analysis with SonarQube?\r\n- What are the limitations of Static Code Analysis?\r\n- What are the best practices in using Static Code Analysis?\r\n\r\n\r\n\r\n## Article Series\r\n\r\nThis is the fourth article in a series of eight articles on Code Quality\r\n- [1 - Introduction To Code Quality](/introduction-to-code-quality){:target='_blank'}\r\n- [2 - Introduction To Coding Standards - Java examples](/coding-standards-with-java-examples){:target='_blank'}\r\n- [3 - Five Important Coding Standards](/code-quality-five-important-coding-standards){:target='_blank'}\r\n- [4 - Best Practices in Static Code Analysis with SonarQube](/static-code-analysis-and-code-quality-best-practices-sonarqube){:target='_blank'}\r\n- [5 - Code Review Best Practices](/code-review-best-practices){:target='_blank'}\r\n- [6 - What Are Code Smells?](/code-quality-code-smells){:target='_blank'}\r\n- [7 - What Is Refactoring?](/code-quality-basics-introduction-to-refactoring){:target='_blank'}\r\n- [8 - Continuous Integration - 5 Important Questions or Tips](/five-tips-on-continuous-integration-best-practices){:target='_blank'}\r\n\r\n\r\n### What is Static Code Analysis?\r\n\r\nStatic Analysis is awesome approach to automate your code quality checks. You run a tools like SonarQube on your source code and it gives a summary of what can be improved in your code. You don't run your code while doing static analysis.\r\n\r\n#### Static Code Analysis is not a silver bullet\r\n\r\nHowever, you need to remember that there are limitations to what static analysis can do:\r\n- It cannot check if you have given a meaningful name to your varible, method or class\r\n- It cannot check if there are other approaches to solving a problem.\r\n- It cannot check if a method or class are adhering to Single Responsibility Principle\r\n- It cannot check if your method is readable beyond a few formatting checks\r\n\r\nAll these can be only checked in peer review\r\n\r\n#### Static Analysis is a signal\r\n\r\nThe most important thing to keep in mind that the resulting metrics are never the goal of the analysis. Static analysis results are intended to be more of a signal. \r\n\r\nIf a code base has poor static analysis results, you can say that the code quality is pretty bad. However, if the static analysis results are good, the code might still not be readable. \r\n\r\n### What Is A Good Application?\r\n\r\n![image info](images/Capture-108-02.png)\r\n\r\nHere are the characteristics of a good application:\r\n* How maintainable is the application (This is the aspect where static analysis contributes in a very large way)?\r\n* How easily usable is the application?\r\n* How reliable is it?\r\n* What are the security features?\r\n* What is the performance of the application, and its efficiency?\r\n* What is the functional suitability?\r\n* How well does it port to other platforms?\r\n\r\n### Quick Review of Static Analysis Tools\r\n\r\nThere are a variety of static code analysis tools that are fairly popular in the programming world. Let's look at a few of them. \r\n\r\n![image info](images/Capture-108-03.png)\r\n\r\n####  SonarQube\r\n\r\nThe most popular static analysis tool in the Java world is SonarQube. It has a very informative dashboard in its interface, where it shows you a variety of metrics, and how your code fares against them. These includes the extent of code duplication, how big your components are, the code coverage statistics, how complex are your methods and classes, etc. \r\n\r\n#### Other Tools\r\n\r\nThere are a few other plugin based static analysis tools such as Simian, Findbugs, CheckStyle and PMD. However, SonarQube stands heads and shoulders above all of them.\r\n\r\n#### IDE Plugins\r\n\r\nIt is possible to install and configure plugins related to the above tools into your IDE, such as Eclipse. \r\n\r\n### Important Metrics from Static Analysis\r\n\r\n![image info](images/Capture-108-04.png)\r\n\r\nWhat are the important aspects you look at, when you analyze code from a static analysis point of view?\r\n\r\n#### Unit Size\r\n\r\nFrom the point of view of an architect, one would first start off by looking at the components. The SonarQube report clearly shows you the components that are present in code, as well as their sizes.\r\n\r\n#### Complexity Per Unit\r\n\r\nComplexity measure is a fair indicator of how well your code logic is organized. The cyclomatic complexity in the business layer should be typically high, and lower in the other layers.\r\n\r\n#### Duplication\r\n\r\nStatic analysis is generally able to indicate the extent of code duplication in the application, and also identifies the duplicate code blocks.\r\n\r\n#### Unit Testing\r\n\r\nAnalyzing the unit testing aspect is very important for any application. It is possible to measure how good the written tests are, by looking at the quality of the asserts, for example. You also get a measure of the extent of code coverage present in the application.\r\n\r\nYou could start off with that part of the code that is listed with the highest complexity, and examine the unit tests for that. \r\n\r\nIf these tests are simple to read, that's a great sign!\r\n\r\n###  Best Practices For Code Quality\r\n\r\n![image info](images/Capture-108-05.png)\r\n\r\n#### Peer Reviews Are A Must\r\n\r\nSince we have an understanding of the limitations of static analysis, having peer reviews is understandably a must. Peer reviews are still the best way to improve on the readability and maintainability of code. \r\n\r\nAn effective mode of peer review is to have pair programming reviews, which ensure the code is reviewed as soon as it's written. \r\n\r\n#### Integrate Into Continuous Integration\r\n\r\nIt is very important to have the static analysis part of code quality checks, as part of the continuous integration builds. You could have SonarQube for instance, look into code taken from the repository as part of a daily build. It is important to do this from day one, since it helps weed out code defects right from the start.\r\n\r\n#### Comply With The Four Principles Of Simple Design\r\n\r\nWith design decisions, you can always change it at a later point in time, if the need arises. Hence, adhere to the Four Principles Of Simple Design when making these decisions. Ensure that:\r\n\r\n* The code is as readable as possible\r\n* The tests written are really good\r\n* The complexity is reduced to a minimum\r\n* The individual components (methods/classes) are as small as possible\r\n\r\nOnce these four principles are well implemented, and you are backed up by effective static analysis, you can be confident that the design is quite good. \r\n\r\nIn case a design change needs to be made, having good tests ensures that the change will be smooth and will not break functionality.\r\n\r\n#### Separate Architecture From Design\r\n\r\nIf you are in an Agile project, you don't want the low level design of the code to be very complex. Now, anything that's easy to change, is design. Anything that's hard to change, is architecture. Separate your decisions into design decisions, and architecture decisions. \r\n\r\nFor architecture decisions, you need to put enough thought and effort, before going ahead with the changes. With design decisions, you can always change it at a later point in time, if the need arises.\r\n\r\nWhen it comes to it, make sure you make informed choices when you select which application framework to use, and how you organize the layers.  \r\n\r\nYou can check out our video on the same topic here\r\n\r\n[![image info](images/Capture-108-01.png)](https://www.youtube.com/watch?v=rB_BaftN3nE)\r\n\r\n### Summary\r\n\r\nIn this article, we had a close look at the best practices involved in ensuring good code quality in your application. We saw that static analysis is a very good tool to make use of. \r\n"
  },
  {
    "path": "_blog/articles/2019-11-15-Code-Quality-Terminology-069-Technical-Debt.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Code Quality Basics - What Is Technical Debt?\r\ndate:    2019-11-14 12:31:19\r\nsummary: As you make enhancements to your source code, how do you ensure that you are adhering to all the standards? Is there a way to measure how good your projects is? What is Technical Debt?\r\ncategories: SwCodeQuality\r\npermalink:  /introduction-to-technical-debt\r\nimage: /images/design-category.png\r\n---\r\n\r\nAs you make enhancements to your source code, how do you ensure that you are adhering to all the standards? Is there a way to measure how good your projects is? What is Technical Debt?\r\n\r\n## You will learn\r\n- What is technical debt?\r\n- What are the challenges with having large technical debt?\r\n- Why should reduce technical debt?\r\n- How do you track technical debt?\r\n- How do you deal with technical debt for old projects?\r\n- What are the best practices with handling technical debt?\r\n\r\n\r\n\r\n## Article Series\r\n\r\nThis is first article in a series of 6 articles on important code quality terminology:\r\n- [1 - What Is Technical Debt?](/introduction-to-technical-debt){:target='_blank'}\r\n- [2 - What Is Readability Of Code?](/code-quality-basics-introduction-to-readability-of-code){:target='_blank'}\r\n- [3 - What Is Code Complexity?](/code-quality-what-is-code-complexity){:target='_blank'}\r\n- [4 - What Is Code Duplication?](/code-quality-what-is-code-duplication){:target='_blank'}\r\n- [5 - What Is Code Coverage?](/code-quality-what-is-code-coverage){:target='_blank'}\r\n- [6 - What Is Legacy Code?](/introduction-to-legacy-code){:target='_blank'}\r\n\r\n### What is Technical Debt?\r\n\r\nNot all applications are designed and developed well. The gap that exists between the design and the code of your application, as compared to an ideal application, is called **technical debt**. \r\n\r\n> Amount of additional effort we have to put in future development and maintenance, in order to make up for the bad choices we made, and the shortcuts we took during initial design. \r\n\r\nMaking short-term bad decisions to meet deadlines can lead to technical debt. \r\n\r\nWriting bad code, or code that is not supported by unit tests, can lead to technical debt.  \r\n\r\n### Measuring Technical Debt\r\n\r\nIt is impossible to measure technical debt accurately. Its at best, a quick guess or a means comparison between projects.\r\n\r\nTypically the aim of estimating technical debt is not to come up with an absolute measure of the cost, such as USD 1 Billion or something similar. \r\n\r\nThe aim is to categorize your application within a set of other applications. For example, \"among this given group of applications, the technical debt of your application is **low**\".  \r\n\r\n#### Tools to measure Technical Debt - SonarQube\r\n\r\nA popular tool used to give estimates of technical debt is SonarQube:\r\n\r\n![image info](images/Capture-069-03.png)\r\n\r\nYou can see that the categories of technical debt parameters are:\r\n* Bugs : How many bugs are present in the code base?\r\n* Vulnerabilities : For example, what are security vulnerabilities of your program? \r\n* Code Smells : These describe the coding good practices that are not being followed.\r\n* Coverage : How many unit tests do you have, and how many lines of the total code do these tests cover?\r\n* Duplication : How many times are specific blocks of code repeated?\r\n\r\nThese parameters are a direct measure of application code quality as well. SonarQube calculates each of these parameters, and then estimates the technical debt that arises out of each of these. \r\n\r\n#### Running SonarQube Periodically\r\n\r\nWhen SonarQube is part of your Continuous Integration process, technical debt can be continuously tracked\r\n\r\nSometimes in a large project, it may not be possible to reduce the existing technical debt. However, it might be possible to tighten your practices to make sure you don't add fresh debt to your burden.\r\n\r\nIf you look at the Code Smells section of the SonarQube, it also measure newly introduced technical debt. \r\n\r\n### Reducing Technical Debt\r\n\r\nInclude Technical Debt in Definition of Done and monitor it during every sprint.\r\n\r\nThe things that you can do to reduce technical debt that you detect, include:\r\n* **Keep Architecture Simple**. Make use of the Four Principles of Simple Design extensively in your application.  \r\n* **Perform Continuous Refactoring**. For this, you need to have the confidence to change the code, which comes from the next point.\r\n* **Have Great Unit Tests**. They ensure that breaks and bugs in code can be detected and fixed.\r\n* **Follow Test Driven Development (TDD)**. Here, you write tests before you write the code, and these lead to good design.\r\n* **Perform Static Analysis Periodically**. We saw an instance of this in SonarQube, especially when used as part of CI.\r\n* **Perform Regular Peer Reviews**. Static analysis can find only certain kinds of defects. It cannot find things such as bad variable, class and method names. This is very essential to ensure readability of code.\r\n* **Maintain A Technical Backlog**. Keep a list of things that you need to fix, and prioritize them regularly. \r\n* **Have Periodic Cleanup Sprints**. \r\n\r\n### Challenges With Technical Debt\r\n\r\n#### Improving An Existing Project\r\n\r\nA big challenge with technical debt, is figuring out how to improve an existing project having a large debt. The following few steps can make this daunting task, a little simpler.\r\n* **Identify Potential Areas Of Improvement**. You can analyze the data that you get from static analysis and other means, and identify specific areas to improve the technical debt.\r\n* **Identify Areas OF Future Change**. You could also identify the areas of the project, where changes anticipated in say, the next 6 months. \r\n\r\nCombine the information from the above two points, and write unit tests for the areas of anticipated change for the next 6 months. This is very important, because we don't want to introduce bugs due to our changes, that go undetected.\r\n\r\nRefactor. With the confidence of having unit tests in place, go head an refactor over a period of time. \r\n\r\nBuild the test base over a period of time.\r\n\r\n### Technical Debt Best Practices\r\n\r\n#### Have Technical Debt As Part OF Definition Of Done\r\n\r\nIn each of the Sprint cycles of a project, do a measure of the technical debt, and add action items to a technical backlog. \r\n\r\n#### Measure Technical Debt From Inception\r\n\r\nMake sure that you measure project technical debt from day one of the project. There should be a focus on maintaining a low technical debt for the application. This means you do it for a prototype, and you do it for a vertical slice as well! \r\n\r\nDo check out our video on the same topic:\r\n\r\n[![image info](images/Capture-069-01.png)](https://www.youtube.com/watch?v=BUQuYy0upPE)\r\n\r\n### Summary\r\n\r\nIn this article, we had a reasonably close look at the concept of technical debt. It is a qualitative measure of the amount of effort required to take the current design state of an application, close to an ideal application. Technical debt can arise due to reasons such as bad design standards, design shortcuts, incorrect technology and bad coding practices. \r\n\r\nTechnical debt slows down productivity. It is important to measure technical debt using static analysis tools such as SonarQube. Measuring technical debt needs to be a continuous process. Once monitored and measured, specific steps can be taken to ensure it is reduced and that new debt does not pile up.\r\n"
  },
  {
    "path": "_blog/articles/2019-11-15-Code-Quality-Terminology-071-Readability-Of-Code.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Code Quality Basics - What Is Readability Of Code?\r\ndate:    2019-11-14 12:31:19\r\nsummary: One activity that you be doing a lot as a programmer, is reading code. That's where the concept of readability comes into the picture. How do you ensure that code written in a project is easily understandable?\r\ncategories: SwCodeQuality\r\npermalink:  /code-quality-basics-introduction-to-readability-of-code\r\nimage: /images/design-category.png\r\n---\r\n\r\nOne activity that you be doing a lot as a programmer, is reading code. That's where the concept of readability comes into the picture. How do you ensure that code written in a project is easily understandable?\r\n\r\n## You will learn\r\n- What is readability Of code?\r\n- What are the challenges with having bad code?\r\n- How do you improve readability of code?\r\n\r\n\r\n\r\n### Article Series\r\n\r\nThis is second article in a series of 6 articles on important code quality terminology:\r\n- [1 - What Is Technical Debt?](/introduction-to-technical-debt){:target='_blank'}\r\n- [2 - What Is Readability Of Code?](/code-quality-basics-introduction-to-readability-of-code){:target='_blank'}\r\n- [3 - What Is Code Complexity?](/code-quality-what-is-code-complexity){:target='_blank'}\r\n- [4 - What Is Code Duplication?](/code-quality-what-is-code-duplication){:target='_blank'}\r\n- [5 - What Is Code Coverage?](/code-quality-what-is-code-coverage){:target='_blank'}\r\n- [6 - What Is Legacy Code?](/introduction-to-legacy-code){:target='_blank'}\r\n\r\n\r\n### Readability Of Code - Example\r\n\r\nHave a look at the following code example:\r\n\r\n#### Example Code-1\r\n\r\n```java\r\n\r\n\tpublic Lock isLockAvailableForFile(long clientID, String status, boolean firstScreen, User user, List list) {\r\n\t\tDate sysTime = new Date();\r\n\t\tLock lock = new Lock();\r\n\t\tif(list.size() > 0 && list.get(0) != null) {\r\n\t\t\tObject[] o1 = (Object[]) list.get(0);\r\n\t\t\tString userId = (String) o1[0];\r\n\t\t\tDate lockTimestamp = (Date) o1[1];\r\n\t\t\r\n\t\t\tif(userId != null) {\r\n\t\t\t\t//The message shown to the user\r\n\t\t\t\tString lockMsg = Constants.LOCK_REASON.replaceAll(\"@@USER@@\", userId);\r\n\r\n\t\t\t\t//if userId is present, then lockTimestamp will also be present\r\n\t\t\t\t//72000000 milliseconds equals to 2 hours\r\n\t\t\t\tif(sysTime.gettime() - locktimestamp.getTime() > 7200000) {\r\n\t\t\t\t\t//The new user should attain lock only in the first screen\r\n\t\t\t\t\t//If 2 hours expires when user is not present on 1st screen, then user Id...\r\n\t\t\t\t\tif(firstScreen \r\n\t\t\t\t\t\t|| userId.equalsIgnoreCase(user.getUserId())) {\r\n\t\t\t\t\t\t//to set the file access to write mode\r\n\t\t\t\t\t\tlock.setReadAccess(false);\r\n\t\t\t\t\t\tLogger.debug(\r\n\t\t\t\t\t\t\t\t\t \"Write access is permitted to the User for client {0}\",\r\n\t\t\t\t\t\t\t\t\tclientId);\r\n\t\t\t\t\t\treturn lock;\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t/*   ...  BLAH BLAH BLAH !!!  ...   */\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n```\r\n\r\nTry and spend some time to see, whether this code is readable. \r\n\r\nWould you like to see such code as part of your application? \r\n\r\nWould you enjoy maintaining an applicaton that has code such as this?\r\n\r\n#### Example Code-2\r\n\r\n```java\r\n\r\n\tpublic Lock isLockAvailableForFile(boolean isFirstScreen, User user, List list) {\r\n\t\tif(isListEmpty(list)) {\r\n\t\t\treturn lockWithWriteAccess();\r\n\t\t}\r\n\t\tObject[] lockObject = (Object[]) list.get(0);\r\n\t\tString userId = (String) lockObject[0];\r\n\t\tDate lockTimestamp = (Date) lockObject[1];\r\n\r\n\t\tif(userId == null) {\r\n\t\t\treturn lockWithWriteAccess();\r\n\t\t}\r\n\r\n\t\tboolean userHasLockedEarlier = userId.equalsIgnoreCase(user.userId);\r\n\t\tboolean lockPeriodExceeded = new Date().getTime() -\r\n\t\t\t\t\t\t\t\t\t lockTimeStamp.getTime > 2 * 60 * 60 * 1000;\r\n\r\n\t\tif(userHasLockEarlier)\r\n\t\t\treturn lockWithWriteAccess();\r\n\t\tif(lockPeriodExceeded && isFirstScreen)\r\n\t\t\treturn lockWithWriteAccess();\r\n\r\n\t\treturn lockWithReadAccess(userId);\r\n\t}\r\n\r\n```\r\n\r\nThe second example is refactored from the first example.\r\n\r\nYou can immediately see, that the second code is much more readable than the first. \r\n\r\n\r\n### Improving Readability of Code\r\n\r\nWhat is the difference between these two examples?\r\n\r\n#### Readability Is About Proper Naming\r\n\r\nReadability of code is all about giving proper names. In general, the readability of code can be improved by 75% by properly naming variables, methods and classes. \r\n\r\nFor example, have a look at the extracted methods ```lockWithWriteAccess()``` and ```lockWithReadAccess()```. With proper names such as these, you can identify the functionality very easily. There is almost no need to peek into the implementation details of the method to understand what it does.\r\n\r\n#### Single Responsibility Principle\r\n\r\nThe next important factor is to ensure that we do only a single thing inside a particular method. If a method or a class does one thing only, then it is quite easy to give it a readable name. \r\n\r\n#### Ensure Great Unit Tests\r\n\r\nIf you have great unit tests in place, you have the freedom to refactor code. You would no longer be worried about breaking functionality.\r\n\r\n#### Adhere To Test-Driven Development (TDD)\r\n\r\nWith TDD, you write the tests before you write the code. You start with an outside-in perspective on your code. You are concerned about the interface, and that helps in writing great code.\r\n\r\nDo check out our video on the same topic:\r\n\r\n[![image info](images/Capture-071-01.png)](https://www.youtube.com/watch?v=DoX3UiYn85A)\r\n\r\n### Summary\r\n\r\nIn this article, we discussed readability of code and why it is important. We saw an example of code that has poor readability, and what it looked like after refactoring.\r\n"
  },
  {
    "path": "_blog/articles/2019-11-15-Code-Quality-Terminology-072-Legacy-Code.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Code Quality Basics - What Is Legacy Code?\r\ndate:    2019-11-14 12:31:19\r\nsummary: If you are working in a large software application or project, you will hear the term **legacy code** quite a lot. What does this term mean, and how can you avoid legacy code?\r\ncategories: SwCodeQuality\r\npermalink:  /introduction-to-legacy-code\r\nimage: /images/design-category.png\r\n---\r\n\r\nIf you are working in a large software application or project, you will often hear the term **legacy code** quite a lot. What does this term mean, and how can you avoid legacy code?\r\n\r\n## You will learn\r\n- What Is Legacy Code?\r\n- What are the challenges with Legacy Code?\r\n- How do you improve Legacy Code?\r\n\r\n\r\n\r\n### Article Series\r\n\r\nThis is last article in a series of 6 articles on important code quality terminology:\r\n- [1 - What Is Technical Debt?](/introduction-to-technical-debt){:target='_blank'}\r\n- [2 - What Is Readability Of Code?](/code-quality-basics-introduction-to-readability-of-code){:target='_blank'}\r\n- [3 - What Is Code Complexity?](/code-quality-what-is-code-complexity){:target='_blank'}\r\n- [4 - What Is Code Duplication?](/code-quality-what-is-code-duplication){:target='_blank'}\r\n- [5 - What Is Code Coverage?](/code-quality-what-is-code-coverage){:target='_blank'}\r\n- [6 - What Is Legacy Code?](/introduction-to-legacy-code){:target='_blank'}\r\n\r\n\r\n### What Is Legacy Code?\r\n\r\nThe popular definition of legacy code going around is \r\n\r\n> Old code - built in old technology. \r\n\r\nI would add one more element to it\r\n\r\n> Any code which is difficult to understand and improve the design is legacy code. \r\n\r\nIn other words, any code which does not have great design, which does not have the support of good unit tests, is legacy code. That's because you cannot refactor it to improve its design, as you are unsure if you break functionality.\r\n \r\n### What Make Code A Legacy?\r\n\r\n* Old code in outdated technologies\r\n* Code without tests\r\n* Code with a lot of technical debt\r\n\r\n### Challenges With Legacy Code\r\n\r\n#### Unexpected Impact\r\n\r\nOne of the biggest problems caused due to legacy code, is that changes in one part can lead to impact in other parts. This could lead to long release cycles.\r\n\r\n#### Extreme Caution During Maintenance\r\n\r\nEvery time a change is made in one part of the code, the entire code base needs to be tested extensively to check for unexpected impact. This attaches a large cost in time and manpower across the team.\r\n\r\n### Dealing With Legacy Code\r\n\r\n#### Have Good Code Review Processes\r\n\r\nMake sure that the code in the application is reviewed at regular intervals during the development cycle, to identify maintainability issues.\r\n\r\n#### Refactor Code\r\n\r\nIt is impossible to refactor and improve every part of a large legacy application.\r\n\r\nTo start with, identify critical areas that frequently change and improve their design. Try and build good unit tests as you refactor.\r\n\r\n#### Perform Static Analysis\r\n\r\nMake sure you use static analysis tools such as Sonar. Put them in continuous integration. Have processes to monitor new violations\r\n\r\n#### Have Automated Regression Testing\r\n\r\nIn general, it is difficult to write good unit tests for legacy code. \r\n\r\nA more practical optionis to write good automated integration and regression tests.\r\n\r\n#### Develop New Functionality in a New Component\r\n\r\nStart exploring new avenues. Instead of building everything into your legacy application, start thinking about creating new components and/or services and integrating with them.\r\n\r\nDo check out our video on the same topic:\r\n\r\n[![image info](images/Capture-072-01.png)](https://www.youtube.com/watch?v=5odeVADF2Og)\r\n\r\n### Summary\r\n\r\nIn this article, we saw that any code that is difficult to maintain, is legacy code. We had a look at what factors contribute to legacy code, and what challenges developers face due to it. We then explored different ways to deal with legacy code in a project.\r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-11-15-Code-Quality-Terminology-073-Code-Duplication.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Code Quality Basics - What Is Code Duplication?\r\ndate:    2019-11-14 12:31:19\r\nsummary: Having minimum code duplication is one of the Four Principles of Simple Design. In this article, we look at why we should worry about code duplication, and what are the best practices to follow to reduce it.\r\ncategories: SwCodeQuality\r\npermalink:  /code-quality-what-is-code-duplication\r\nimage: /images/design-category.png\r\n---\r\n\r\nHaving minimum code duplication is one of the Four Principles of Simple Design. In this article, we look at why we should worry about code duplication, and what are the best practices to follow to reduce it.\r\n\r\n### You will learn\r\n- What Is Code Duplication?\r\n- Why Is Code Duplication Bad?\r\n- How do you measure Code Duplication?\r\n- How can ensure that Code Duplication standards are Adhered to?\r\n\r\n\r\n\r\n### Article Series\r\n\r\nThis is fourth article in a series of 6 articles on important code quality terminology:\r\n- [1 - What Is Technical Debt?](/introduction-to-technical-debt){:target='_blank'}\r\n- [2 - What Is Readability Of Code?](/code-quality-basics-introduction-to-readability-of-code){:target='_blank'}\r\n- [3 - What Is Code Complexity?](/code-quality-what-is-code-complexity){:target='_blank'}\r\n- [4 - What Is Code Duplication?](/code-quality-what-is-code-duplication){:target='_blank'}\r\n- [5 - What Is Code Coverage?](/code-quality-what-is-code-coverage){:target='_blank'}\r\n- [6 - What Is Legacy Code?](/introduction-to-legacy-code){:target='_blank'}\r\n\r\n\r\n### What Is Code Duplication?\r\n\r\nSame block of code repeating multiple times is the most basic form of Code Duplication.\r\n\r\n### Why Is Code Duplication Bad?\r\n\r\nSuppose there is  a change needed in one of the places where a code block is used. When the change is made, it needs to be replicated at all other places where it occurs. If a code block of 40 lines occurs at 10 places in your application, there is a chance that a developer modifies it only in 8 places out of the 10. The code is now potentially broken!\r\n\r\nWhen you have code duplication, maintaining the code becomes very difficult. \r\n\r\n### How To Measure Code Duplication?\r\n\r\nThere are static analysis tools such as SonarQube that measure code duplication as part of estimating technical debt:\r\n\r\n![image info](images/Capture-073-02.png)\r\n\r\n![image info](images/Capture-073-03.png)\r\n\r\nAs you can see, code duplication is mentioned under \"Duplication\" at the bottom. It gives an idea of the percentage of duplicate code in the project. \r\n\r\nTypically, you have some extent of duplication in your code.  A general measure of controlled duplication is a limit of 5%. A project having less than 5% of code duplication is considered very good. \r\n\r\nIt is important to continously evaluate code duplication and identify improvements.\r\n\r\n### Looking At Code With Duplication\r\n\r\nHave a look at the following source file, from the project which we ran SonarQube on, previously:\r\n\r\n##### < ParenthesizedTreeImpl.java >\r\n\r\n![image info](images/Capture-073-04.png)\r\n\r\nYou can see that the duplicated block is highlighted by a bold-grey vertical line. We can click on it to see the duplicated blocks:\r\n\r\n![image info](images/Capture-073-05.png)  \r\n\r\nSonarQube indicates that SynchronizedStatementTreeImpl.java, SwitchStatementTreeImpl.java and ParenthesizedTreeImpl.java have the same code block duplicated across them. \r\n\r\n### Avoiding Code Duplication\r\n\r\n#### Make Use Of Inheritance\r\n\r\nThe simplest solution for the problem at hand is to define a super class, and define the duplicated blocks as code within its methods. \r\n\r\n#### Define A Utility Class Or Method\r\n\r\nThis is the alternative available when reuse by inheritance is not the option that works.\r\n\r\nThe catch is that there is no single solution! It depends on the duplicate code block, and the context in which it is being used. \r\n\r\nDo check out our video on the same topic:\r\n\r\n[![image info](images/Capture-073-01.png)](https://www.youtube.com/watch?v=uauZjxAu3p8)\r\n\r\n### Summary\r\n\r\nIn this article, we had a close look at code duplication. We explored why code duplication is  not good, and what are the ways in which it can be detected and measured. We also had a brief look at how to avoid it.\r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-11-15-Code-Quality-Terminology-074-Code-Coverage.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Code Quality Basics - What Is Code Coverage?\r\ndate:    2019-11-14 12:31:19\r\nsummary: In this article, we find out what code coverage is, and how we keep track of it.\r\ncategories: SwCodeQuality\r\npermalink:  /code-quality-what-is-code-coverage\r\nimage: /images/design-category.png\r\n---\r\n\r\nIn this article, we find out what code coverage is, and how we keep track of it.\r\n\r\n### You will learn\r\n- What Is Code Coverage?\r\n- How do you measure Code Coverage?\r\n- How can you ensure that you have great unit tests?\r\n- How do you ensure that you have great asserts in tests in addition to code coverage?\r\n- How can ensure that Code Coverage standards are Adhered to?\r\n\r\n\r\n\r\n### Article Series\r\n\r\nThis is fifth article in a series of 6 articles on important code quality terminology:\r\n- [1 - What Is Technical Debt?](/introduction-to-technical-debt){:target='_blank'}\r\n- [2 - What Is Readability Of Code?](/code-quality-basics-introduction-to-readability-of-code){:target='_blank'}\r\n- [3 - What Is Code Complexity?](/code-quality-what-is-code-complexity){:target='_blank'}\r\n- [4 - What Is Code Duplication?](/code-quality-what-is-code-duplication){:target='_blank'}\r\n- [5 - What Is Code Coverage?](/code-quality-what-is-code-coverage){:target='_blank'}\r\n- [6 - What Is Legacy Code?](/introduction-to-legacy-code){:target='_blank'}\r\n\r\n\r\n### What Is Code Coverage?\r\n\r\n#### Unit Tests Are Important\r\n\r\nA prerequisite for great code is having a set of great unit tests.\r\n\r\nAdhering to test driven development leads us to create great code. \r\n\r\nTDD ensures we have great low level design, and the set of unit tests we write tend to be reliable.\r\n\r\n#### Understanding Code Coverage\r\n\r\nThe result of great unit tests is great **code coverage**. Code coverage is a measure of what percentage of the lines of source code that are covered by unit tests. \r\n\r\nFor example, if your project has 1000 lines of source code, unit tests cover 900 lines, then the code coverage of your application is 90%. Typically, 85-90% is considered to be good code coverage.\r\n\r\n### Exploring Code Coverage\r\n\r\nHave a look at the snapshot of the SonarQube Dashboard:\r\n\r\n![image info](images/Capture-074-02.png)\r\n\r\nThe project being analyzed is being reported to have a code coverage of 97.1%. This means 97.1% of the source code is being covered by unit tests execution. That's awesome. \r\n\r\nYou can also see a ring beside the number estimate, as well as a shaded graph as the background. The project started off with approximately 80% coverage, and slowly built it up to the present figure.\r\n\r\nWhen you click on the link, you can see several source files, and their individual coverage:\r\n\r\n![image info](images/Capture-074-03.png)\r\n\r\nYou can see that a few of the files do not have any unit test written for them at all. These are the files with 0% coverage. \r\n\r\nLet's pick the file ListTreeImpl.java as an example:\r\n![image info](images/Capture-074-04.png)\r\n\r\nThis file has a coverage of around 72.1%. When you look at the code inside the file, you will see several vertical green bars. These indicate block of code that are fully covered by unit tests. The lines in red indicate those code blocks that are not covered by unit tests:\r\n![image info](images/Capture-074-05.png)\r\n\r\n### Why Is Code Coverage Important?\r\n\r\nGood unit tests can catch defects that could arise out of buggy code, even in the future! They are a kind of insurance policy for developers. These tests are automated, and keep running every time code is changed.\r\n\r\nCode coverage is a good measure to identify if all scenarios are being unit tested.\r\n\r\n#### Find Defects Early\r\n\r\nThe more number of tests you write, the less defects you will have in the future. Having great unit tests, gives you the confidence to refactor your code. Refactoring helps improve the design of the code over a period of time.\r\n\r\n### Challenges With Code Coverage\r\n\r\nHere are a few challenges one has to face while dealing with code coverage.\r\n\r\n#### Writing Tests Just For Coverage\r\n\r\nMany project teams make the mistake of having code coverage as a direct measure. If the focus is only on the number of lines covered by unit tests, the quality of tests could get neglected.\r\n\r\nCode coverage needs to be treated just as a result of great unit tests. \r\n\r\nHaving great code coverage does not mean you have great unit tests. If you end up writing tests that don't check the business logic, but only increase the lines of code covered, the purpose is defeated.\r\n\r\nThe focus needs to be on a combination of the quality of the unit tests written, plus the number of lines of code covered. \r\n\r\n#### Dealing With Legacy Code\r\n\r\nIn general, legacy code components are not loosely coupled, and hence writing unit tests for them becomes quite a challenge. You might need to refactor code to enable you to write unit tests. \r\n\r\nMost of the old frameworks - mainly the web and database ones - are not designed to be unit tested. \r\n\r\n### Measuring Code Coverage\r\n\r\n#### Use Sonar\r\n\r\nSonarQube is one of the most popular static analysis tools that is used to measure code coverage. \r\n\r\nIt is also possible to connect to SonarQube from an Eclipse plugin, and look at the measures from an Eclipse view itself. \r\n\r\n#### Use IDE Plugins\r\n\r\nYou can use Eclipse IDE plugins such as Cobertura and EclEmma to measure code coverage. \r\n\r\nThe IntelliJ IDE has in-built support to measure an application's code coverage.\r\n\r\n### Best Practices For Code Coverage\r\n\r\n#### Include Coverage In Definition Of Done\r\n\r\nMake sure that you constantly review your code coverage measures at the end of each sprint. Also ensure that the quality of asserts are reviewed. \r\n\r\n#### Measure Coverage From Day One\r\n\r\nYou need to be committed to measuring code coverage from the day of inception of the project. For that, you write unit tests for your code from the point where you start the prototype, and when you start developing the vertical slice as well. \r\n\r\nDo check out our video on the same topic:\r\n\r\n[![image info](images/Capture-074-01.png)](https://www.youtube.com/watch?v=Ra42js3AXIQ)\r\n\r\n### Summary\r\n\r\nCode coverage measures the lines of code covered by unit tests. Having good unit tests is important for any project, as they act as a safety net against defects in the future. Code Coverage can be measured by tools such as SonarQube, or common IDE plugins.\r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-11-15-Code-Quality-Terminology-075-Code-Complexity.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Code Quality Basics - What Is Code Complexity?\r\ndate:    2019-11-14 12:31:19\r\nsummary: In this article, we find out what code complexity is, and how we keep track of it.\r\ncategories: SwCodeQuality\r\npermalink:  /code-quality-what-is-code-complexity\r\nimage: /images/design-category.png\r\n---\r\n\r\nIn this article, we find out what code complexity is, and how we keep track of it.\r\n\r\n### You will learn\r\n- What Is Code Complexity?\r\n- What are a few examples of Code Complexity?\r\n- Why Is Code Complexity important?\r\n- What are the tools you can use to measure Code Complexity?\r\n- How can ensure that Code Complexity standards are Adhered to?\r\n\r\n\r\n\r\n### Article Series\r\n\r\nThis is third article in a series of 6 articles on important code quality terminology:\r\n- [1 - What Is Technical Debt?](/introduction-to-technical-debt){:target='_blank'}\r\n- [2 - What Is Readability Of Code?](/code-quality-basics-introduction-to-readability-of-code){:target='_blank'}\r\n- [3 - What Is Code Complexity?](/code-quality-what-is-code-complexity){:target='_blank'}\r\n- [4 - What Is Code Duplication?](/code-quality-what-is-code-duplication){:target='_blank'}\r\n- [5 - What Is Code Coverage?](/code-quality-what-is-code-coverage){:target='_blank'}\r\n- [6 - What Is Legacy Code?](/introduction-to-legacy-code){:target='_blank'}\r\n\r\n\r\n### What Is Code Complexity?\r\n\r\nCode Complexity is a measure of how difficult your code is to understand. \r\n\r\n* Suppose you have just written a method having 15 ```if``` conditions and 3 ```for``` loops. How easy do you think it is to understand? \r\n* Think of a class we have written that has 25 member variables and 75 methods, where some of these methods are huge, having a lot of ```if``` conditions and ```for``` loops. Is this an easy class to understand?\r\n\r\n### Measuring Code Complexity\r\n\r\n#### Measuring Cyclomatic And Cognitive Complexity\r\n\r\nCyclomatic complexity is a way of measuring complexity taking into account\r\n* The number of ```if``` ```else``` ```switch``` conditionals\r\n* The number of loops - ```for``` , ```while``` and ```do while``` \r\n\r\nThere is a way to measure the code complexity in SonarQube as well:\r\n\r\n![image info](images/Capture-075-02.png)\r\n\r\nYou can see that the TreeFactory.java has a cyclomatic complexity measure of 366. That means this class might be a little difficult to understand. \r\n\r\nLet's pick up another file which has a lower complexity listed:\r\n\r\n![image info](images/Capture-075-03.png)\r\n\r\nYou can see that the ```findMemberType()``` method is being highlighted. When you click on it, you get some additional info:\r\n\r\n![image info](images/Capture-075-04.png)\r\n\r\nIt says that the method has a different complexity measure, the **cognitive complexity**, that is bad for the code here. It suggests that we refactor this method to correct the complexity. \r\n\r\nIf you look at this method:\r\n![image info](images/Capture-075-05.png)\r\n\r\nIt has ```for``` loops, ```if```, conditional operator at multiple places, all in interesting combinations! \r\n\r\nA complex method is often a sign that the developer has not thought enough about the code.   \r\n\r\n### Understanding Code Complexity\r\n\r\nWhenever we write code, we need to keep things small. Simple methods, small classes, small packages, simple components all lead to small and simple applications. \r\n\r\nThe goal of writing code is not to write large amounts of it, but to achieve a certain functionality. The aim is to achieve that functionality with as little code and complexity as possible. \r\n\r\nPMD is also a good static analysis tool to assess code complexity, apart from Sonar.\r\n\r\n### Addressing Code Complexity\r\n\r\nIn order to address the problem of complexity, you need to identify it early and monitor it on a regular basis.\r\n\r\nYou need to include code complexity goals as a major part of your coding standards. These should be regularly tracked.\r\n\r\nDo check out our video on the same topic:\r\n\r\n[![image info](images/Capture-075-01.png)](https://www.youtube.com/watch?v=cE44izR3A5E)\r\n\r\n### Summary\r\n\r\nCode complexity is a measure of how difficult it is to understand your code. Generally, large method and classes are code smells. There are different measures for code complexity, and various tools to measure them as well. Keep Refactoring code to reduce complexity.\r\n"
  },
  {
    "path": "_blog/articles/2019-11-15-NFR-028-Portability.md",
    "content": "---\r\nlayout:  post\r\ntitle: Microservices Architectures - Non Functional Requirements - Portability\r\ndate:    2019-11-14 12:31:19\r\nsummary: In this article, we explore an important non functional requirement called Portability. \r\ncategories: SwArchitecture\r\npermalink:  /non-functional-requirements-in-microservices-introduction-to-portability\r\nimage: /images/architecture.png\r\n---\r\n\r\nIn this article, we explore the important non functional requirement called Portability. \r\n\r\n### What you will learn\r\n- What Is Portability?\r\n- Why is Portability important?\r\n\r\n\r\n\r\n### Non Functional Requirements and Microservices\r\n\r\nThis is the part of a series of articles on Non Functional Requirements:\r\n\r\n- [1 - Microservices Architectures - Non Functional Requirements](/non-functional-requirements-in-microservices-architectures){:target='_blank'}\r\n- [2 - Security](/non-functional-requirements-in-microservices-introduction-to-Security){:target='_blank'}\r\n- [3 - Web Application Security And OWASP - Top Ten Security Flaws](/web-application-security-owasp-top-ten){:target='_blank'}\r\n- [4 - Maintainability](/non-functional-requirements-in-microservices-introduction-to-Maintainability){:target='_blank'}\r\n- [5 - Scalability](/non-functional-requirements-in-microservices-introduction-to-Scalability){:target='_blank'}\r\n- [6 - Performance](/non-functional-requirements-in-microservices-introduction-to-performance){:target='_blank'}\r\n- [7 - Reusability](/non-functional-requirements-in-microservices-introduction-to-Reusability){:target='_blank'}\r\n- [8 - Reliability](/non-functional-requirements-in-microservices-introduction-to-Reliability){:target='_blank'}\r\n- [9 - Modularity](/modularity-non-functional-requirement-in-microservices){:target='_blank'}\r\n- [10 - Availability](/availability-non-functional-requirement-in-microservices){:target='_blank'}\r\n- [11 - Portability](/non-functional-requirements-in-microservices-introduction-to-portability){:target='_blank'}\r\n\r\n\r\n### What Is Portability?\r\n\r\nPortability is one of an application's non-functional requirements. \r\n\r\nThe question to ask is : What is the cost of migrating or supporting a new platform? What are the costs involved when you need to move to or support a new language, framework , database or cloud provider? \r\n\r\nIdeally, you want your application to be as portable as possible, as you don't want it to be tied to a specific infrastructure. \r\n\r\nLet's say you want to deploy your application to the cloud, and initially choose AWS as your provider. If the application is portable, it would be possible to easily migrate it in the future, to say Google Cloud or Microsoft Azure. \r\n\r\n#### Portability is a trade-off\r\n\r\nIt is very important to remember that there are costs involved in building portable applications. If we want our application to be deployable to AWS, Azure and GCP - it would limit the architecture choices that are available to you.\r\n- There might be an awesome AWS feature which you might not be able to leverage\r\n\r\nIt is always important to analyze the trade-offs and evaluate the costs when it comes to portability.\r\n\r\n### A Microservices Example\r\n\r\nYou can assess portability at multiple levels. Consider for example the following diagram of a microservices architecture:\r\n\r\n![image info](/images/Capture-028-02.png)\r\n\r\nThis is an infrastructure where a microservice is deployed. The factors that determine the portability of such a microservice depends on:\r\n\r\n* The language used to develop it\r\n* The framework employed to develop it\r\n* The interfaces that are written for it\r\n* The common components that it makes use of\r\n* The common infrastructure that it makes use of\r\n\r\n### Well Defined Interfaces\r\n\r\nIt is well documented that **well-defined interfaces** are a major factor in improving an application's portability. For example, if we write a well-defined interface to talk to the security component, switching to a different security implementation later will be much easier. \r\n\r\n### Platform Decoupling\r\n\r\nThe other important point is not to depend in a specific platform feature. \r\n\r\nIf your application uses a database feature specific to Oracle DB, then it is tied to Oracle DB. If you use a system feature specific to the UNIX OS, then you are again tied to it. If you are using a AWS specific feature, you are tied to AWS.\r\n\r\nAvoid platform coupling.\r\n\r\n### Interacting With Web Services\r\n\r\nAnother way of improving portability is for the application to have interactions with web services, to consume what they have to offer. This makes sure it is not tied to a particular technology or platform. This is kind of loosely related to the concept of interfaces.\r\n\r\nDo check out our video on this:\r\n\r\n[![image info](/images/Capture-028-01.png)](https://www.youtube.com/watch?v=2HWEde56mYM)\r\n\r\n### Summary\r\n\r\nIn this video, we looked at a non-functional requirement called portability. Portability is the cost that is involved in moving an application to a different platform. That could be a new language, framework, or database. We saw that there are multiple levels of portability involved.\r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-11-15-NFR-029-Performance.md",
    "content": "---\r\nlayout:  post\r\ntitle: Microservices Architectures - Non Functional Requirements - Performance\r\ndate:    2019-11-14 12:31:19\r\nsummary: In this article, we explore an important non functional requirement called performance. \r\ncategories: SwArchitecture\r\npermalink:  /non-functional-requirements-in-microservices-introduction-to-performance\r\nimage: /images/architecture.png\r\n---\r\n\r\nIn this article, we explore the important non functional requirement called performance. \r\n\r\n### What you will learn\r\n- What Is Performance?\r\n- Why is Performance important?\r\n- What are the best practices in building performant systems?\r\n\r\n\r\n\r\n### Non Functional Requirements and Microservices\r\n\r\nThis is the part of a series of articles on Non Functional Requirements:\r\n\r\n- [1 - Microservices Architectures - Non Functional Requirements](/non-functional-requirements-in-microservices-architectures){:target='_blank'}\r\n- [2 - Security](/non-functional-requirements-in-microservices-introduction-to-Security){:target='_blank'}\r\n- [3 - Web Application Security And OWASP - Top Ten Security Flaws](/web-application-security-owasp-top-ten){:target='_blank'}\r\n- [4 - Maintainability](/non-functional-requirements-in-microservices-introduction-to-Maintainability){:target='_blank'}\r\n- [5 - Scalability](/non-functional-requirements-in-microservices-introduction-to-Scalability){:target='_blank'}\r\n- [6 - Performance](/non-functional-requirements-in-microservices-introduction-to-performance){:target='_blank'}\r\n- [7 - Reusability](/non-functional-requirements-in-microservices-introduction-to-Reusability){:target='_blank'}\r\n- [8 - Reliability](/non-functional-requirements-in-microservices-introduction-to-Reliability){:target='_blank'}\r\n- [9 - Modularity](/modularity-non-functional-requirement-in-microservices){:target='_blank'}\r\n- [10 - Availability](/availability-non-functional-requirement-in-microservices){:target='_blank'}\r\n- [11 - Portability](/non-functional-requirements-in-microservices-introduction-to-portability){:target='_blank'}\r\n\r\n\r\n### What Is Performance?\r\n\r\nWhen we type in a web page URL in a browser, performance from a users perspective is the time it takes for the page to load. \r\n\r\nPerformance is essentially a measure of how much time a system takes to respond to a user request. \r\n\r\nConsider the following simple microservices architecture:\r\n\r\n![image info](/images/Capture-029-02.png)\r\n\r\nThere are three microservices in here, that communicate with several kinds of common components and other infrastructure. How would you go about improving the performance of a system such as this one? \r\n\r\nLet's look at different aspects of this goal.\r\n\r\n### Improve The Code\r\n\r\nThe first step would be to improve the performance of code written for each of these microservices. If for instance Microservice1 is written in Java, then make sure you follow the applicable Java best practices for its code, such as: \r\n* Making best possible use of Java collections \r\n* Not creating too many objects\r\n* Using the right efficient data structures and algorithms, in your business logic \r\n* Make sure that the microservices are profiles and performance tunes to the maximum possible extent\r\n\r\n### Fine-Tune Your Databases\r\n\r\nIf your application accesses a database in order to store and retrieve data, then such access needs to be efficient. For example, your microservice could be talking to a data service in order to manage its data, much like the following:  \r\n\r\n![image info](/images/Capture-029-03.png)\r\n\r\nFor that, you need to ensure that the databases used are fine-tuned to the kind of queries used by the microservices. This would include things such as: \r\n* Proper use of indexes\r\n\r\n### Cache Your Data\r\n\r\nParticularly in web applications, quite a few aspects of data handled by it can be cached. \r\n\r\nIf caching were not used, a lot of static content, including HTML/CSS/JavaScript would need to be transferred repeatedly between the server and the browsers. \r\n\r\nSimilarly, a microservice need not always fetch data from the data store. It could have a cache built in at the business logic, where it stores recently or frequently accessed data.\r\n\r\nAnother aspect to look at is the kind of caching mechanisms that can be used. The caching model could be a database-specific cache such as at the JPA level, or a distributed cache. \r\n\r\nIf you use a distributed cache, data accessed by different instances of a microservice could be cached centrally. \r\n\r\n### Build Redundancy\r\n\r\nThe next option available to improving application performance, is to build redundancy. \r\n\r\nIn our example, instead of having one instance each of Microservice1, Microservice2 and Microservice3, have say 10, 5 and 3 instances. The number of microservice instances created depends on the expected load on each such microservice. This would allow the application to handle a larger volume of requests within lesser time, and lighter load on the server in general. \r\n\r\nYou could also build redundancy by having multiple instances of each type of common infrastructure. \r\n\r\n### Improve System Capacity\r\n\r\nAnother option is to improve the configuration of each of the servers. This could involve arranging for better CPU processing power, and augmenting the amount of available physical memory. \r\n\r\n### Ensure Modular Design\r\n\r\nIn our microservices architecture example, you have noticed that we have built the system in a modular way. We have designed different types of components for different responsibilities, as well as organized infrastructure code into different modules. \r\n\r\nAt a design level, one of the ways to improve the performance of a large monolith application would be to make it more modular. For example, splitting it up into components would enable us to deploy them onto different servers. \r\n\r\n### Best Practices For Performance Improvement\r\n\r\nUntil now, we have looked at different options that are available to improve the performance of an application. Let's now look at a few best practices for improving an application's performance.\r\n\r\n#### Have Clear Guidelines\r\n\r\nYou must have clear performance guidelines from the start of a project. Do not wait until the end of the project to outline these. \r\n\r\nThe requirements should clearly list out the system parameters, such as the number of system users, the peak load, the expected response time, among others. \r\n\r\n#### Test Performance Early\r\n\r\nYou need to test your application's performance early, and not just leave it to the end.  Ideally, performance tests need to be part of your definition of done. \r\n\r\n#### Profile Your Code\r\n\r\nMake sure you profile your code at regular intervals of time, to identify places of improvement. After identifying them , effort should be put in to fine-tune the application to address this feedback. \r\n\r\n#### Ensure Visibility\r\n\r\nWhenever you find a performance problem with your application, you need to identify the root cause. Also, when you need to give a fix for this, the solution should be one that gives the best possible improvement. \r\n\r\nNailing down the root cause of a problem is only possible if you have great visibility of what is going on. \r\n\r\nYou would need clear visibility into what's happening with the request in the back ground\r\n- What microservices are involved? How much time is spent in each of them? \r\n- What infrastructure components are involved? How much time is spent in each of them? \r\n\r\nThe more visibility you have into an application, the easier it is to identify performance bottlenecks.\r\n\r\nDo check out our video on this:\r\n\r\n[![image info](/images/Capture-029-01.png)](https://www.youtube.com/watch?v=zjZ7-pmfezE)\r\n\r\n### Summary\r\n\r\nIn this video, we say that performance is a measure of how much time a system takes to respond to a user request. We saw that there are a number of aspects to how to improve application performance. \r\n\r\nThe first aspect refers to improving the code to adhere to the language, framework best practices. Then, you could work on fine-tuning the performance to databases to which the system has access to. A third option would be to introduce caching as a practice to store recently, or frequently accessed data. Introducing redundancy improves performance by distributing the load on a server, among different nodes.\r\n\r\nWe then looked at general best practices for performance improvement. These include having clear performance guidelines early on, testing regularly for performance, profiling code frequently, and improving traceability. \r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-11-15-NFR-030-Scalability.md",
    "content": "---\r\nlayout:  post\r\ntitle: Microservices Architectures - Non Functional Requirements - Scalability\r\ndate:    2019-11-14 12:31:19\r\nsummary: In this article, we explore an important non functional requirement called Scalability. \r\ncategories: SwArchitecture\r\npermalink:  /non-functional-requirements-in-microservices-introduction-to-Scalability\r\nimage: /images/architecture.png\r\n---\r\n\r\nIn this article, we explore the important non functional requirement called Scalability. \r\n\r\n### What you will learn\r\n- What Is Scalability?\r\n- Why is Scalability important?\r\n- What are the different types of Scalability?\r\n- What are the best practices in building Scalable systems?\r\n\r\n\r\n\r\n### Non Functional Requirements and Microservices\r\n\r\nThis is the part of a series of articles on Non Functional Requirements:\r\n\r\n- [1 - Microservices Architectures - Non Functional Requirements](/non-functional-requirements-in-microservices-architectures){:target='_blank'}\r\n- [2 - Security](/non-functional-requirements-in-microservices-introduction-to-Security){:target='_blank'}\r\n- [3 - Web Application Security And OWASP - Top Ten Security Flaws](/web-application-security-owasp-top-ten){:target='_blank'}\r\n- [4 - Maintainability](/non-functional-requirements-in-microservices-introduction-to-Maintainability){:target='_blank'}\r\n- [5 - Scalability](/non-functional-requirements-in-microservices-introduction-to-Scalability){:target='_blank'}\r\n- [6 - Performance](/non-functional-requirements-in-microservices-introduction-to-performance){:target='_blank'}\r\n- [7 - Reusability](/non-functional-requirements-in-microservices-introduction-to-Reusability){:target='_blank'}\r\n- [8 - Reliability](/non-functional-requirements-in-microservices-introduction-to-Reliability){:target='_blank'}\r\n- [9 - Modularity](/modularity-non-functional-requirement-in-microservices){:target='_blank'}\r\n- [10 - Availability](/availability-non-functional-requirement-in-microservices){:target='_blank'}\r\n- [11 - Portability](/non-functional-requirements-in-microservices-introduction-to-portability){:target='_blank'}\r\n\r\n\r\n#### What Is Scalabiity?\r\n\r\nLet's say we have an application A, that supports N number of users with its current infrastructure. \r\n\r\nIf we increase the infrastructure by a factor of 10, can we hope to support 10 times the current users? \r\n\r\nThis is at the heart of scalability. \r\n\r\n> How we can we support a multifold increase in number of users with a linear increase in infrastructure?\r\n\r\nThe question that naturally follows is \r\n- How do you build scalable applications? \r\n\r\nFor that, we need to understand the types of scalability.\r\n\r\n### Types Of Scalability\r\n\r\n At a high level, there are two kinds of scalability: \r\n\r\n* Vertical\r\n* Horizontal\r\n\r\n### What Is Vertical Scalability?\r\n\r\nVertical scalability is all about increasing the hardware and processing capacity available to a system. \r\n\r\nConsider the following microservice architecture:\r\n\r\n![image info](/images/Capture-030-02.png)\r\n\r\nSuppose Microservice1 is deployed on a specific system. Vertical scaling for Microservice1 system would be achieved by increasing the CPU processing power, or by augmenting the amount of main memory on the physical server. \r\n\r\nVertical scalability has limits - Its very expensive to purchase powerful hardware. Vertical Scalability can only help you to a certain extent.\r\n\r\n### What Is Horizontal Scalability?\r\n\r\nHow about having 5 instances of Microservice1 instead of just 1 instance? How about having 5 Naming Servers and 2 API Gateways?  This is the core thought process for Horizontal Scalability.\r\n\r\n> Most of the times that we talk of scalability, we refer to horizontal scalability. \r\n\r\nDiscussing horizontal scalability brings us to a very important question: **\"How do you build scalable applications?\"**\r\n\r\n### Building Scalable Applications\r\n\r\nLet's look at few of the important factors to consider when building an application which can scale.\r\n\r\n#### Have Modular Applications\r\n\r\nA very important factor in scalable applications is **modularity** of your applications. In our example microservice architecture, there are multiple modules or components, each of which can be independently deployed. For example, you can increase the number of instances of each of the microservices, independently.\r\n\r\nIf you have large **monolith** applications, or large monolith databases with huge amounts of data within them, they become huge bottlenecks. For example, it is very hard to replicate large databases, or to scale them, vertically or horizontally. Same is the case with monolith applications. \r\n\r\n> An important step in improving scalability is to make the application more modular, by adopting a microservice architecture, for example.\r\n\r\n#### Improve Caching\r\n\r\nIf part of the system has higher load, and we access certain data very frequently, **caching** is a viable option to improve scalability. \r\n\r\nEnterprise web applications generally have a lot of data available that can be cached. Microservice3 from our example above might be returning the list of all states for a particular user request. To improve efficiency for future requests, Microservice1 can cache this result, once a day. That can potentially reduce the load on Microservice3.\r\n\r\nAnother option would be to have a **built-in cache** for each of the microservices. For example, Microservice1 need not connect to a database to get results for a query; it can use an internal cache. \r\n\r\nA **distributed cache** caching data across different instances of a microservice might also be an option. \r\n \r\nDo check out our video on this:\r\n\r\n[![image info](/images/Capture-030-01.png)](https://www.youtube.com/watch?v=-aO7GNzvol4)\r\n\r\n### Summary\r\n\r\nIn this article, we introduced you to the concept of scalability. Scalability addresses the aspect of addressing increased load with minimal increase in system infrastructure. \r\n\r\nWe saw that there are two main kinds of scalability: vertical and horizontal. \r\n\r\nScalalbility of an application can be improved by designing it in a more modular manner. Different kinds of caches can also help with Scalability.\r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-11-15-NFR-031-Reusability.md",
    "content": "---\r\nlayout:  post\r\ntitle: Microservices Architectures - Non Functional Requirements - Reusability\r\ndate:    2019-11-14 12:31:19\r\nsummary: In this article, we explore an important non functional requirement called Reusability. \r\ncategories: SwArchitecture\r\npermalink:  /non-functional-requirements-in-microservices-introduction-to-Reusability\r\nimage: /images/architecture.png\r\n---\r\n\r\nIn this article, we explore the important non functional requirement called Reusability. \r\n\r\n### What you will learn\r\n- What Is Reusability?\r\n- Why is Reusability important?\r\n- How do you improve Reusability of your components?\r\n\r\n\r\n\r\n### Non Functional Requirements and Microservices\r\n\r\nThis is the part of a series of articles on Non Functional Requirements:\r\n\r\n- [1 - Microservices Architectures - Non Functional Requirements](/non-functional-requirements-in-microservices-architectures){:target='_blank'}\r\n- [2 - Security](/non-functional-requirements-in-microservices-introduction-to-Security){:target='_blank'}\r\n- [3 - Web Application Security And OWASP - Top Ten Security Flaws](/web-application-security-owasp-top-ten){:target='_blank'}\r\n- [4 - Maintainability](/non-functional-requirements-in-microservices-introduction-to-Maintainability){:target='_blank'}\r\n- [5 - Scalability](/non-functional-requirements-in-microservices-introduction-to-Scalability){:target='_blank'}\r\n- [6 - Performance](/non-functional-requirements-in-microservices-introduction-to-performance){:target='_blank'}\r\n- [7 - Reusability](/non-functional-requirements-in-microservices-introduction-to-Reusability){:target='_blank'}\r\n- [8 - Reliability](/non-functional-requirements-in-microservices-introduction-to-Reliability){:target='_blank'}\r\n- [9 - Modularity](/modularity-non-functional-requirement-in-microservices){:target='_blank'}\r\n- [10 - Availability](/availability-non-functional-requirement-in-microservices){:target='_blank'}\r\n- [11 - Portability](/non-functional-requirements-in-microservices-introduction-to-portability){:target='_blank'}\r\n\r\n\r\n### What Is Reusability?\r\n\r\nSuppose you have worked on a project to create a microservice - Microservice A - and you are now working on a new project - Microservice B. \r\n\r\nQuestion to ask is:\r\n> How much of the earlier implementation of Microservice A, how many modules and components (technical and infrastructure) can you reuse in the next microservice? \r\n\r\nYou would prefer your applications to be built with reusable components, because it avoids unnecessary duplication of code and effort.\r\n\r\n### Improving Reusability\r\n\r\nThe common approach to improving reusability involves one thing - \"Build your system in a modular manner\". \r\n\r\nHave a look at the following microservice architecture:\r\n![image info](/images/Capture-031-02.png)\r\n\r\nInstead of having a single monolith application, system is organized into modules. Over here, we have identified several common components, such as Security and Logging, which have logic that can be used across microservices.\r\n\r\nAlso visible are several common infrastructure components, such as NamingService, CentralizedLogging and APIGateway. These offer common services to several microservices. \r\n\r\nOnce you have such common modules organized, each microservice would only be responsible for its own business logic. That makes it very easy to augment the system by adding new microservices, because there is no need to replicate the common components logic any more. The new service also just needs to manage its own business logic. The functionality of the common component can be **reused**.\r\n\r\n#### Reusability at Code Level\r\n\r\nYou would want to avoid duplication in your code. The best way to ensure good low level design (methods and classes) is to ensure you are following the 4 Principles of Simple Design.\r\n- You have great tests\r\n- Your code is readable\r\n- Your code has minimum duplication\r\n- Your application, components, packages, classes and methods are as small as they can be\r\n\r\n### Summary\r\n\r\nIn this short article, we talked about application reusability as a measure of how much functionality can be reused indifferent scenarios. Reusability can reduce duplication of code and effort. The most suitable way to improve the reusability of an application is to make its design modular.  \r\n\r\nDo check out our video on this:\r\n\r\n[![image info](/images/Capture-031-01.png)](https://www.youtube.com/watch?v=xfHgYXENDkk)\r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-11-15-NFR-032-Reliability.md",
    "content": "---\r\nlayout:  post\r\ntitle: Microservices Architectures - Non Functional Requirements - Reliability\r\ndate:    2019-11-14 12:31:19\r\nsummary: In this article, we explore an important non functional requirement called Reliability. \r\ncategories: SwArchitecture\r\npermalink:  /non-functional-requirements-in-microservices-introduction-to-Reliability\r\nimage: /images/architecture.png\r\n---\r\n\r\nIn this article, we explore the important non functional requirement called Reliability. \r\n\r\n### What you will learn\r\n- What Is Reliability?\r\n- Why is Reliability important?\r\n- How do you improve Reliability of your system?\r\n\r\n\r\n\r\n### Non Functional Requirements and Microservices\r\n\r\nThis is the part of a series of articles on Non Functional Requirements:\r\n\r\n- [1 - Microservices Architectures - Non Functional Requirements](/non-functional-requirements-in-microservices-architectures){:target='_blank'}\r\n- [2 - Security](/non-functional-requirements-in-microservices-introduction-to-Security){:target='_blank'}\r\n- [3 - Web Application Security And OWASP - Top Ten Security Flaws](/web-application-security-owasp-top-ten){:target='_blank'}\r\n- [4 - Maintainability](/non-functional-requirements-in-microservices-introduction-to-Maintainability){:target='_blank'}\r\n- [5 - Scalability](/non-functional-requirements-in-microservices-introduction-to-Scalability){:target='_blank'}\r\n- [6 - Performance](/non-functional-requirements-in-microservices-introduction-to-performance){:target='_blank'}\r\n- [7 - Reusability](/non-functional-requirements-in-microservices-introduction-to-Reusability){:target='_blank'}\r\n- [8 - Reliability](/non-functional-requirements-in-microservices-introduction-to-Reliability){:target='_blank'}\r\n- [9 - Modularity](/modularity-non-functional-requirement-in-microservices){:target='_blank'}\r\n- [10 - Availability](/availability-non-functional-requirement-in-microservices){:target='_blank'}\r\n- [11 - Portability](/non-functional-requirements-in-microservices-introduction-to-portability){:target='_blank'}\r\n\r\n\r\n### What Is Reliability?\r\n\r\nThere are two important aspects to application reliability.\r\n\r\n* Whatever data that you present to the system user, how accurate is that data? Are there any bugs in the source of that data?\r\n* How reliable is the data present in your database? This is crucial, because such data could be provided to other systems, or be used to generate important analytics. \r\n\r\n### Improving Application Reliability\r\n\r\nLet's look at some of the things you can do to improve reliability of an application.\r\n\r\n#### Write Great Code\r\n\r\nWhen you write readable code, any bugs present in them would stand out. \r\n\r\n#### Write Great Tests\r\n\r\nIf you have writing good quality unit tests as part of the development process, it helps build robust software. Not only do they help improve the design, they also help find bugs very early. Following a development process such as Test Driven Development (TDD) is highly recommended for reliable applications.\r\n\r\nThe same logic extends to component-level and API-level testing as well.\r\n\r\n#### Automate The Testing Process\r\n\r\nThe integration and system tests must have a high degree of automation. When you depend on manual testing, the chance that a bug leaks over to production is very high. Properly configured automation leads to proper testing of builds, and gives clear and immediate feedback on the build status.\r\n\r\n#### Use Continuous Integration\r\n\r\nIt is highly recommended that the automated tests be run very frequently, in Continuous Integration, as soon as code is committed into the source repository.\r\n\r\n#### Ensure Proper Database Design\r\n\r\nMake sure that your database design is top-class. Normalizing your database helps in eliminating bad data at origin.\r\n\r\nDo check out our video on this:\r\n\r\n[![image info](/images/Capture-032-01.png)](https://www.youtube.com/watch?v=mF-c2xK8Lqk)\r\n\r\n### Summary\r\n\r\nIn this short article, we talked about the important concept of application reliability. There are two aspects to it - ensuring data shown to users is reliable, and ensuring data in our data stores is accurate. You can improve reliability by writing great code, writing and automating great unit and system tests, having frequent build testing, and ensuring proper database design.\r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-11-15-NFR-033-Maintainability.md",
    "content": "---\r\nlayout:  post\r\ntitle: Microservices Architectures - Non Functional Requirements - Maintainability\r\ndate:    2019-11-14 12:31:19\r\nsummary: In this article, we explore an important non functional requirement called Maintainability. \r\ncategories: SwArchitecture\r\npermalink:  /non-functional-requirements-in-microservices-introduction-to-Maintainability\r\nimage: /images/architecture.png\r\n---\r\n\r\nIn this article, we explore the important non functional requirement called Maintainability. \r\n\r\n### What you will learn\r\n- What Is Maintainability?\r\n- Why is Maintainability important?\r\n- How do you improve Maintainability of your system?\r\n\r\n\r\n\r\n### Non Functional Requirements and Microservices\r\n\r\nThis is the part of a series of articles on Non Functional Requirements:\r\n\r\n- [1 - Microservices Architectures - Non Functional Requirements](/non-functional-requirements-in-microservices-architectures){:target='_blank'}\r\n- [2 - Security](/non-functional-requirements-in-microservices-introduction-to-Security){:target='_blank'}\r\n- [3 - Web Application Security And OWASP - Top Ten Security Flaws](/web-application-security-owasp-top-ten){:target='_blank'}\r\n- [4 - Maintainability](/non-functional-requirements-in-microservices-introduction-to-Maintainability){:target='_blank'}\r\n- [5 - Scalability](/non-functional-requirements-in-microservices-introduction-to-Scalability){:target='_blank'}\r\n- [6 - Performance](/non-functional-requirements-in-microservices-introduction-to-performance){:target='_blank'}\r\n- [7 - Reusability](/non-functional-requirements-in-microservices-introduction-to-Reusability){:target='_blank'}\r\n- [8 - Reliability](/non-functional-requirements-in-microservices-introduction-to-Reliability){:target='_blank'}\r\n- [9 - Modularity](/modularity-non-functional-requirement-in-microservices){:target='_blank'}\r\n- [10 - Availability](/availability-non-functional-requirement-in-microservices){:target='_blank'}\r\n- [11 - Portability](/non-functional-requirements-in-microservices-introduction-to-portability){:target='_blank'}\r\n\r\n\r\n### What Is Maintainability?\r\n\r\nRequirements for a Software Applications often change. When you develop an application, you want to be able to easily enhance it easily in the future. \r\n\r\nThis could also be in the form of providing fixes to important bugs that are detected over time. \r\n\r\nTechnically speaking, what we call maintainability is typically two things \r\n- Maintainability \r\n- Extensibility\r\n\r\n#### Maintainability\r\n\r\nMaintainability is all about how easy it is to fix a bug found in the application. \r\n\r\n#### Extensibility\r\n\r\nExtensibility of a system describes how easy it is to incorporate new features into it.  \r\n\r\nBoth these concepts are quite deeply related, and are clubbed together under a single umbrella - maintainability. That's how we address them as well.\r\n\r\n### Enhancing Maintainability\r\n\r\nThe maintainability of an application can be enhanced by following some important guidelines.\r\n\r\n#### Have Great Low-Level Design\r\n\r\nIt is very important for your application have great low-level design, in order to be maintainable. \r\n\r\nAdhering to 4 Principles of Simple Design is a great starting point. \r\n\r\nTest Driven Development (TDD) usually leads to great tests and great low level design. With TDD, you first write tests and then write code to make these tests pass. The code is continuously refactored to meet 4 principles of simple design.\r\n\r\n#### Ensure Modular Design\r\n\r\nHave a look at the following microservices architecture:\r\n\r\n![image info](/images/Capture-033-02.png)\r\n\r\nEach of these microservices use common infrastructure components, such as Naming Service and API Gateway. It also makes use the features of common technical components, such as Security and Logging. \r\n\r\nHaving common components and infrastructure enable the microservices to focus on their specific responsibilities. \r\n\r\nIf Microservice1 has a need for user authentication or authorization, it interacts with the Security component through a well defined interface. Security component takes care of the inner implementation details.\r\n\r\nAs Microservice1 has lesser things to take care of, it becomes more maintainable. \r\n\r\nIn addition, it becomes easier to add additional microservices to the system at a later point in time.\r\n\r\n#### Ensure Great Automation Tests\r\n\r\nIt is important that all the unit, system, integration and API tests are of good quality, and equally important, are automated. Ideally, they need to be part of a Continuous Integration (CI) process, that is invoked whenever code is committed to the source repository. \r\n\r\nThe idea is to have immediate feedback on application reliability, while removing the dependency on manual testing.  \r\n\r\n#### Automate The Deployment Pipeline\r\n\r\nWith an automated deployment pipeline, the build moves through different stages such as development, QA, staging and production in a systematic and efficient manner.\r\n\r\n#### Greater Visibility\r\n\r\nGreater visibility of code across the modules in the system makes it easier to detect bugs, and shorten the time line in addressing them. \r\n\r\nHaving great traceability across microservices in a microservices architecture helps us understand what's happening in the background with a specific request\r\n- Which microservices are involved?\r\n- What are the requests and responses?\r\n- How much time was taken at each hop?\r\n\r\n[![image info](/images/Capture-033-01.png)](https://www.youtube.com/watch?v=q89zx2VOOvY)\r\n\r\n### Summary\r\n\r\nIn this article, we took a closer look at maintainability. We saw that it is a measure of two things : the amount of effort needed to fix bugs in the system, and the amount of effort needed to incorporate additional features into the application (also called extensibility). \r\n\r\nWe then looked at a few ways to enhance the maintainability of an application. The important ones are to have good low-level design, ensure a modular architecture, be equipped with great automation tests, have good system visibility.\r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-11-15-NFR-034-Security.md",
    "content": "---\r\nlayout:  post\r\ntitle: Microservices Architectures - Non Functional Requirements - Security\r\ndate:    2019-11-14 12:31:19\r\nsummary: In this article, we explore an important non functional requirement called Security. \r\ncategories: SwArchitecture\r\npermalink:  /non-functional-requirements-in-microservices-introduction-to-Security\r\nimage: /images/architecture.png\r\n---\r\n\r\nIn this article, we explore the important non functional requirement called Security. \r\n\r\n### What you will learn\r\n- What Is Security?\r\n- Why is Security important?\r\n- How do you improve Security of your system?\r\n\r\n\r\n\r\n### Non Functional Requirements and Microservices\r\n\r\nThis is the second article in a series of articles on Non Functional Requirements:\r\n\r\n- [1 - Microservices Architectures - Non Functional Requirements](/non-functional-requirements-in-microservices-architectures){:target='_blank'}\r\n- [2 - Security](/non-functional-requirements-in-microservices-introduction-to-Security){:target='_blank'}\r\n- [3 - Web Application Security And OWASP - Top Ten Security Flaws](/web-application-security-owasp-top-ten){:target='_blank'}\r\n- [4 - Maintainability](/non-functional-requirements-in-microservices-introduction-to-Maintainability){:target='_blank'}\r\n- [5 - Scalability](/non-functional-requirements-in-microservices-introduction-to-Scalability){:target='_blank'}\r\n- [6 - Performance](/non-functional-requirements-in-microservices-introduction-to-performance){:target='_blank'}\r\n- [7 - Reusability](/non-functional-requirements-in-microservices-introduction-to-Reusability){:target='_blank'}\r\n- [8 - Reliability](/non-functional-requirements-in-microservices-introduction-to-Reliability){:target='_blank'}\r\n- [9 - Modularity](/modularity-non-functional-requirement-in-microservices){:target='_blank'}\r\n- [10 - Availability](/availability-non-functional-requirement-in-microservices){:target='_blank'}\r\n- [11 - Portability](/non-functional-requirements-in-microservices-introduction-to-portability){:target='_blank'}\r\n\r\n\r\n## What Is Security?\r\n\r\nSecurity in general means one or more of the following intentions:\r\n* Protect the system from unintended use\r\n* Protect the application service from denial-of-service attacks\r\n* Protect the system from unauthorized access by external users\r\n* Restrict the authorized users to access only those modules of the application that they are allowed to. Other modules must be protected from the user.\r\n\r\nSecurity is all about: \r\n* **Authentication** - Is it the right user? \r\n* **Authorization** - Does the user have the rights to do an action?\r\n\r\n## Applying Security Principles\r\n\r\nThere are a few important principles that are the cornerstone for application security.\r\n\r\n#### Assign Least Privileges\r\n\r\nThe architects, designers and developers must start the design of the system with security requirements in mind. Security must feature as an important project requirement from the initial stages itself. There has to be clear picture of the roles of various users, and the accesses that they need. The idea is to have as few accesses to each role as possible.\r\n\r\nThis applies not just to the application, but also to the infrastructure. This includes the application database, the servers where the system is deployed, and other similar things. The concept of minimized mapping of access to roles for each user, is equally relevant here. \r\n\r\n#### Have Complete Mediation\r\n\r\nHow were King's forts protected in medieval times? By having one entrance that everyone has to pass through and making sure that the entrance is extremely secure.\r\n\r\nDo the same thing for securing your application.\r\n\r\nFor every request, apply a well-implemented security filter. Test the role and access of the user for each and every request. \r\n\r\n#### Have Defence In Depth\r\n\r\nThis concept boils down to having multiple levels of security. You would need to have security built into your architecture at application, network, hardware and operating system levels.\r\n\r\n#### Trust Nothing\r\n\r\nMake sure that you validate every piece of data or information that comes into the system . \r\n\r\nSanitize all data that comes from external sources.\r\n\r\n#### Have Economy Of Mechanism\r\n\r\nThis says that we need to keep the architecture of the system, simple. Simple systems are easier to protect.\r\n\r\n#### Ensure Openness Of Design\r\n\r\nAvoid trying to implement system security by making the design obscure. If that were the case, a hacker might identify a flaw and compromise the system. \r\n\r\nThis principle is the opposite of the misplaced idea of \"Security Through Obscurity\". \r\n\r\nThe more open a design, the easier it is to identify and address security flaws.\r\n\r\n## Handling Application Security\r\n\r\nThere are three important aspects of managing security threats to an application.\r\n\r\n#### Prevention\r\n\r\nThe best approach is to prevent security incidents from happening by following the principles discussed early.\r\n\r\n#### Detection\r\n\r\nIt is important to have mechanisms in place that detect security violations. When such a violation does happen, detecting it fairly early is worth its weight in gold. \r\n\r\n#### Reaction\r\n\r\nAfter you detect a security violation, the step that follows is the reaction. \r\n\r\nA major drawback when handling security violations is that more often than not, organizations are slow in both detecting, and reacting to them.\r\n\r\nMake sure you have clear policies on how to react to security violations.\r\n\r\n### Best Practices In Application Security\r\n\r\nLets look at some of best practices in building secure systems. \r\n\r\n#### Think Security From Day One \r\n\r\nThe business development, software development, QA and operations teams - all of them need to make security a high priority right from the initial stages. They need to be well educated about the various threats, and ways to prevent, detect and react to them as needed.\r\n\r\n#### Be Aware Of OWASP\r\n\r\nIt is important that there is proper awareness of OWASP and their recommendations. They regularly release a \"top 10\" list about current security threats for applications, as well as tips on how to prevent them.\r\n\r\n#### Use Analysis Tools\r\n\r\nUse static analysis tools such as checkmarks regularly, to identify potential security vulnerabilities in the code.\r\n\r\n#### Friendly Hacking\r\n\r\nFrequently have external security testers hack into your application software. This gives you a different perspective on security testing, and also find potential flaws earlier.\r\n\r\n#### Avoid Outdated Standards And Frameworks\r\n\r\nAN OWASP standard recommends that outdated software standards and frameworks having known vulnerabilities need to be eliminated from your architecture. \r\n\r\nOnly make use of an approved library/framework/platform that is certified by a security team. \r\n\r\nUse the latest versions of these software.\r\n\r\n#### Safeguard Your Infrastructure\r\n\r\nMake sure proper protection mechanisms are in place to secure your app server, web server, OS and hardware.\r\n\r\n\r\nDo check out our video on this:\r\n\r\n[![image info](/images/Capture-034-01.png)](https://www.youtube.com/watch?v=4cQE9DU_A9U)\r\n\r\n### Summary\r\n\r\nIn this article, we talked about what application security is all about. Essentially, security revolves round two things - authentication, and authorization. \r\n\r\nWe then looked at principles that help make your application more secure. These include assigning minimum privileges, having complete mediation, trusting nothing, have an economy of mechanism and  keeping an open design. We then looked at several best practices when it comes to improving application security.\r\n\r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-11-15-NFR-040-Non-Functional-Requirements.md",
    "content": "---\r\nlayout:  post\r\ntitle: Microservices Architectures - Non Functional Requirements\r\ndate:    2019-11-14 12:31:19\r\nsummary: In this article, we focus on the most important non functional requirements and why there are needed.\r\ncategories: SwArchitecture\r\npermalink:  /non-functional-requirements-in-microservices-architectures\r\nimage: /images/architecture.png\r\n---\r\n\r\nIn this article, we explore the important non functional requirement called Portability. \r\n\r\n### What you will learn\r\n- What are non functional requirements?\r\n- Why are non functional requirements important?\r\n- What are the different kinds of non functional requirements?\r\n- How do you ensure that you adhere to non functional requirements?\r\n- What are the best practices in implementing non functional requirements?\r\n\r\n\r\n\r\n### Non Functional Requirements and Microservices\r\n\r\nThis is the first article in a series of articles on Non Functional Requirements:\r\n\r\n- [1 - Microservices Architectures - Non Functional Requirements](/non-functional-requirements-in-microservices-architectures){:target='_blank'}\r\n- [2 - Security](/non-functional-requirements-in-microservices-introduction-to-Security){:target='_blank'}\r\n- [3 - Web Application Security And OWASP - Top Ten Security Flaws](/web-application-security-owasp-top-ten){:target='_blank'}\r\n- [4 - Maintainability](/non-functional-requirements-in-microservices-introduction-to-Maintainability){:target='_blank'}\r\n- [5 - Scalability](/non-functional-requirements-in-microservices-introduction-to-Scalability){:target='_blank'}\r\n- [6 - Performance](/non-functional-requirements-in-microservices-introduction-to-performance){:target='_blank'}\r\n- [7 - Reusability](/non-functional-requirements-in-microservices-introduction-to-Reusability){:target='_blank'}\r\n- [8 - Reliability](/non-functional-requirements-in-microservices-introduction-to-Reliability){:target='_blank'}\r\n- [9 - Modularity](/modularity-non-functional-requirement-in-microservices){:target='_blank'}\r\n- [10 - Availability](/availability-non-functional-requirement-in-microservices){:target='_blank'}\r\n- [11 - Portability](/non-functional-requirements-in-microservices-introduction-to-portability){:target='_blank'}\r\n\r\n\r\n\r\n# What are Non Functional Requirements?\r\n\r\nIn this article, we focus on the most important non functional requirements and why there are needed.\r\n\r\n### What Are Non Functional Requirements?\r\n\r\nWhenever you talk to a user who needs a web interface, he will mainly describe what needs to happen when the page loads, what it needs to look like, and what should happen when a button on it is clicked. These are the application's **functional requirements**. \r\n\r\nThere is also one other set of requirements that users might not typically specify. For instance:\r\n* You need to page to load up within 2 seconds (Performance)\r\n* You require the application to support up to 100,000 concurrent users (Scalability)\r\n* It should be easy to extend the functionality of the application (Maintainability)\r\n\r\nThere come under the category of **non functional requirements**. \r\n\r\nAs a developer, it is very important that you give due attention to these as well. \r\n\r\n### Categories Of Non Functional Requirements\r\n\r\nFollowing are some of the important non functional requirements:\r\n* Authentication & Authorization\r\n* Performance\r\n* Scalability\r\n* Availability\r\n* Resilience\r\n* Maintainability\r\n* Portability\r\n* Security\r\n\r\n### Adhering To Best Practices\r\n\r\nIt is important to adhere to a few best practices, when it comes to implementing the non functional requirements. Here is a list of the most important practices.\r\n\r\n* Have clearly stated non functional requirements\r\n* Build vertical slices wherever possible, with a view to eliminating non functional risks such as scalability and performance.\r\n* Make sure that the framework used in your application is able to withstand a particular load.\r\n* Check for compliance to security requirements right from the project inception stage.\r\n* Perform static analysis of the code right from project inception.\r\n* Use Secure Code static analysis tools right from the start of the project.\r\n\r\nDo check out our video on this:\r\n\r\n[![image info](/images/Capture-040-01.png)](https://www.youtube.com/watch?v=InXlzJjwgYw)\r\n\r\n### Summary\r\n\r\nIn this article, we discovered what non functional requirements are, and how they are different from the functional requirements. We had a brief look at the types of non functional requirements. Finally, we had a glimpse of the best practices to follow while implementing these requirements.\r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-11-15-NFR-041-Web-Application-Security-OWASP-Top-Ten-Flaws.md",
    "content": "---\r\nlayout:  post\r\ntitle: Web Application Security And OWASP - Top Ten Security Flaws\r\ndate:    2019-11-14 12:31:19\r\nsummary: In this article, we talk about one of the most important non functional requirements - security. We focus on OWASP Top 10.\r\ncategories: SwArchitecture\r\npermalink:  /web-application-security-owasp-top-ten\r\nimage: /images/architecture.png\r\n---\r\n\r\nIn this article, we talk about one of the most important non functional requirements - security. We focus on OWASP Top 10.\r\n\r\n### What you will learn\r\n- Why is Application Security Important?\r\n- What is OWASP?\r\n- What are the different OWASP best practices?\r\n- How do you prevent security flaws in your applications?\r\n- What are the important security principles to follow?\r\n\r\n\r\n\r\n\r\n### Non Functional Requirements and Microservices\r\n\r\nThis is the third in a series of articles on Non Functional Requirements:\r\n\r\n- [1 - Microservices Architectures - Non Functional Requirements](/non-functional-requirements-in-microservices-architectures){:target='_blank'}\r\n- [2 - Security](/non-functional-requirements-in-microservices-introduction-to-Security){:target='_blank'}\r\n- [3 - Web Application Security And OWASP - Top Ten Security Flaws](/web-application-security-owasp-top-ten){:target='_blank'}\r\n- [4 - Maintainability](/non-functional-requirements-in-microservices-introduction-to-Maintainability){:target='_blank'}\r\n- [5 - Scalability](/non-functional-requirements-in-microservices-introduction-to-Scalability){:target='_blank'}\r\n- [6 - Performance](/non-functional-requirements-in-microservices-introduction-to-performance){:target='_blank'}\r\n- [7 - Reusability](/non-functional-requirements-in-microservices-introduction-to-Reusability){:target='_blank'}\r\n- [8 - Reliability](/non-functional-requirements-in-microservices-introduction-to-Reliability){:target='_blank'}\r\n- [9 - Modularity](/modularity-non-functional-requirement-in-microservices){:target='_blank'}\r\n- [10 - Availability](/availability-non-functional-requirement-in-microservices){:target='_blank'}\r\n- [11 - Portability](/non-functional-requirements-in-microservices-introduction-to-portability){:target='_blank'}\r\n\r\n\r\n### Why is Application Security Important?\r\n\r\nAs they say, a chain is only as strong as its weakest link. Same is the case with application security, as a small security flaw can render an application with robust architecture, vulnerable.\r\n\r\n### Security And The OWASP Top 10\r\n\r\n**OWASP** stands for **Open Web Application Security Project**. It is a non-profit organization that regularly publishes the **OWASP Top 10**, a listing of the major security flaws in web applications.\r\n\r\n![image info](/images/Capture-041-02.png)\r\n\r\nFor example, one of the lists published by them in the year 2016, looks something like this:\r\n\r\n![image info](/images/Capture-041-03.png)\r\n\r\nFor each of the above flaws, we discuss what it exactly is, and how to build an application without this specific flaw.\r\n\r\n### SQL Injection\r\n\r\nSQL injection is one of the biggest vulnerabilities experienced across web applications. \r\n\r\n#### Example Of SQL Injection\r\n\r\nHave a look at the following piece of code:\r\n\r\n```java\r\n\r\n\tpublic Person find_Unsecure(String inputFromUser) {\r\n\t\treturn jdbcTemplate.queryForObject(\r\n\t\t\t\t\t\t\t\"select * from Person where name=\" + inputFromUser,\r\n\t\t\t\t\t\t\tnew BeanPropertyRowMapper<Person>(Person.class));\r\n\t}\r\n\r\n```\r\n\r\nIn the case of the method ```find_Unsecure()```, we are taking ```inputFromUser``` and directly appending it to the SQL query statement. \r\n\r\nWhat would happen if ```inputFromUser``` is given as ```\"Ranga or 1=1\"```? \r\n\r\nThe query would effectively become ```\"select * from Person where name=Ranga or 1=1\"```. Every row from the table Person would be returned!\r\n\r\nThis is what is known as **SQL injection**. \r\n\r\nIn a way we are protected, because we use the ```BeanPropertyRowMapper``` and we only try to map it to a single ```Person```. \r\n\r\nHowever if we use it to map to something like a ```List<Person>```, this code would have a serious security flaw.\r\n\r\n#### Avoiding SQL Injection\r\n\r\nOne way to avoid exposing such a security flaw would be to validate ```userInputData``` before making it part of the SQL query. SQL does offer you a way to do that - **parameterized queries**. \r\n\r\nBefore inserting the query parameter, you prefix it with a ```?```, and make sure the value in its entirety is passed in. \r\n\r\nCode to do that would look like this:\r\n\r\n```java\r\n\r\n\tpublic Person find_Secure(String inputFromUser) {\r\n\t\treturn jdbcTemplate.queryForObject(\r\n\t\t\t\t\t\t\t\"select * from Person where name=?\", \r\n\t\t\t\t\t\t\tnew Object[] {inputFromUser},\r\n\t\t\t\t\t\t\tnew BeanPropertyRowMapper<Person>(Person.class));\r\n\t}\r\n\r\n```\r\n\r\nIf ```inputFromUser``` is given as ```\"Ranga or 1=1\"``` to ```find_Secure()```, the query would get it as ```\"select * from Person where name='Ranga or 1=1'\"```. The parameter ```Ranga or 1=1``` is taken as a single entity.\r\n\r\nThis was one possible type of SQL injection, and a simple solution to resolve the same. \r\n\r\n#### Other Ways Of Injection\r\n\r\nThe fact of the matter is, SQL is just one of the ways injection can happen. There are a multitude of other ways in which injections occur: \r\n- XML & XPath can easily be used to cause injection.\r\n- If user data is received and saved in logs, then that can be a source of this flaw. \r\n- If user data is taken and used to form operating system commands, that can be misused too. \r\n- Malicious script can be injected into your frontend JavaScript code. This is called Cross Site Scripting (XSS). We look at it a little later.\r\n\r\n![image info](/images/Capture-041-04.png)\r\n\r\n#### Prevention \r\n\r\nWhat are the ways to prevent SQL Injection? \r\n\r\nWe just saw that using parameterized queries is one good way out. \r\n\r\nIn general, injection can be prevented by validating user input\r\n- You could for example, restrict the set of characters that a user can input to the application - using a white list.\r\n- Avoid directly inserting user input into system commands without preprocessing or checking.\r\n\r\n\r\n### Broken Authentication\r\n\r\nBroken authentication occurs when a user of your application takes the relevant information - possibly a user name and/or password from one website, and reuses it on other sites, including yours. \r\n\r\n#### Preventing Broken Authentication\r\n\r\nHow do we prevent broken authentication? \r\n\r\nThe following diagram outlines an approach for this:\r\n\r\n![image info](/images/Capture-041-05.png)\r\n\r\nHere are the details:\r\n* You can append a random string to user names. That ensures the resulting string is unique and not easily guessable. This prevents a user from having the same user name across multiple websites.\r\n* When a user provides an invalid user name or password, return as little information as possible. You could simply say \"Invalid Credentials\", instead of \"Invalid Username\" or \"Invalid Password\". Avoid providing detailed information in authentication-related messages.\r\n* Have an auto log-off feature for an application user, when a browser session is terminated. This prevents abuse of authentication credentials across websites. \r\n\r\n### Session Management\r\n\r\nWhenever we talk about web applications, we invariably discuss sessions. \r\n\r\nYou know that the internet is designed around the HTTP protocol, which is stateless. \r\n\r\nThe question is, how do we identify that a request on a time-line is coming from the same user?\r\n\r\n![image info](/images/Capture-041-06.png)\r\n\r\nWe have a number of mechanisms to do that:\r\n\r\n#### URL Rewrite\r\n\r\nWhat do we do during URL rewrite?\r\n\r\n![image info](/images/Capture-041-07.png)\r\n\r\nWhatever session ID is created for a user, is included in the URL itself. This is visible in the address field of a browser window that the user may be using to access the URL.\r\n\r\n##### Problems With URL Rewrite\r\n\r\nHere are the potential problems with this approach: \r\n* Vulnerable To Sniffing: Since it is part of the URL, its contents can be sniffed out by an agent listening into your computer or network. The session ID can then be extracted and misused. \r\n* Multiple Logging: Any request from a user to the web application goes through multiple intermediate systems. Since the request is logged at each node for diagnostic purposes, the session ID can be extracted from such logs and abused.\r\n* Whenever you visit a third party site, the URL is sent as a referral URl in a Request header. \r\n\r\n##### Solutions For URL Rewrite\r\n\r\nIf you want to do URL rewrite, atleast use the HTTPS protocol, instead of the vulnerable HTTP. This ensures that every part of your HTTP request is encrypted. \r\n\r\nThe recommended solution is to use other session management approaches.\r\n\r\n#### Basic Authentication\r\n\r\nThe second possibility is to use basic authentication.\r\n\r\n![image info](/images/Capture-041-08.png)\r\n\r\nIn this approach, we send Base 64 encoded user name and password along with the HTTP Request.  Base-64 is not recommended for web applications, since it has severe security flaws.\r\n\r\n#### Cookies\r\n\r\nThe last approach to session management we use is Cookies. This is one of the most popular approaches.\r\n\r\n![image info](/images/Capture-041-09.png)\r\n\r\nA cookie is nothing but a file in the browser, which is set to identify a session. When a cookie comes back from the user as part of a browser session, you identify the request as being associated to that user. \r\n\r\n##### Recommendations For Cookies\r\n\r\nCookies also have vulnerabilities. You can use the following options to minimize risk:\r\n\r\n###### Set Cookie Domain\r\n\r\nMake sure you set the domain on the cookie. The domain specifies the set of hosts, to which this cookie can be sent to. The cookie cannot be sent to other URLs.\r\n\r\n###### Set Cookie Path\r\n\r\nThe path specifies which parts of the website the cookie can be sent to.\r\n\r\n###### Set Expiration Date\r\n\r\nMake sure you set an expiration date on the cookie, as it prevents requests being associated with a user after the expiration date. Set it to a few hours at the most.\r\n\r\n###### Set Secure Flag\r\n\r\nIf you are running a HTTPS site, then make sure that the cookies are set as secure. This ensures the cookie can only be sent to secure websites running HTTPS, such as yours. \r\n\r\n### Cross Site Scripting (XSS)\r\n\r\nLet's now turn our attention towards Cross Site Scripting, also known as XSS. XSS is actually one form of injection, somewhat similar to the SQL injection we discussed earlier. \r\n\r\n![image info](/images/Capture-041-10.png)\r\n\r\nWe look at: \r\n* The causes of XSS \r\n* The types of XSS injections \r\n* The possible effects of XSS \r\n* The solutions available to tackle XSS\r\n\r\n#### The Causes Of XSS\r\n\r\n![image info](/images/Capture-041-11.png)\r\n\r\nThe major cause of XSS is invalid data. Invalid data could be coming in from the user, who has an intent of hacking the system, and that's where injection happens. Invalid data could be sourced from a database, which could be presented at a later point in time, out of context. Invalid data could also be passed into the system through external services. A security flaw in such a service could be sourcing malicious data to your application.\r\n\r\n#### Types Of XSS\r\n\r\n![image info](/images/Capture-041-12.png)\r\n\r\nThe possible types of XSS are:\r\n\r\n##### Stored XSS\r\n\r\nThis happens when invalid data entered by a user is stored in the database. The problem arises when this data is presented to the user, at a later point in time.\r\n\r\n##### Reflected XSS\r\n\r\nThis XSS happens when you take invalid data from a user, and directly present it on the screen at a later point in time.\r\n\r\n##### DOM XSS\r\n\r\nThis occurs when we take invalid data from a user and process it in JavaScript code, within the DOM.\r\n\r\n#### Possible Abuses With XSS\r\n\r\nLet's now look at the possible effects of XSS.\r\n\r\n![image info](/images/Capture-041-13.png) \r\n\r\n##### Stealing Session Cookies\r\n\r\nOne of the things a hacker can do using XSS, is steal your session cookies. He could insert some JavaScript code and try to compromise your data.\r\n\r\n##### Page Content Rewrite\r\n\r\nBecause a hacker has access to JavaScript through XSS, it is possible to rewrite the page contents. For example, if XSS is used to hack a financial application, the balance shown can be tampered with.\r\n\r\n##### Logging Keystrokes\r\n\r\nSince there is access to Javscript through XSS, it is possible to capture the keystrokes patterns. This could then be used to steal the user name and password by reconstructing them.\r\n\r\n#### Solutions To XSS\r\n\r\nLet's now look at the remedies available to tackle system abuse through XSS.\r\n\r\n![image info](/images/Capture-041-14.png) \r\n\r\n##### Validate Untrusted Data\r\n\r\nMake sure that you validate untrusted data against a white-list of characters. \r\n\r\n##### Encode All Data\r\n\r\nMake sure you encode all the data coming in, such as transforming ```<``` to ```&lt;```. This would prevent certain character sequences to be treated as special HTML tags, for example. Also, encode even trusted data.\r\n\r\nEncoding should also be contextual; the kind of encoding depending on where the data is going to. For example, the type of encoding depends on whether the data is being sent to CSS styling, HTML markup, or JavaScript logic.\r\n\r\nIdeally, contextual encoding should be built into the frameworks that you make use of in the application. \r\n\r\n##### Content Security Policy\r\n\r\nWhen in doubt about untrusted data, lookup the content security policy for your application.\r\n\r\n##### XSS Prevention Cheat Sheet\r\n\r\nWhen faced with doubt over how to detect or handle XSS, refer to the XSS prevention cheat sheet for your application.\r\n\r\n### Insecure Direct Object References\r\n\r\nInsecure direct object reference occurs when a user changes the browser link from a resource he has access to, to another that he has no access to. \r\n\r\nFor example, let's say the user has access to the resource at URL ```/account/123```. He changes the link in browser to ```/account/125```. \r\n\r\nIf the system allows him to access this other resource, then this is an insecure direct object reference. \r\n\r\n![image info](/images/Capture-041-15.png)\r\n\r\n#### Preventing This Vulnerability\r\n\r\nThe way you can prevent insecure direct object references is two-pronged:\r\n\r\n##### Authorization\r\n\r\nMake sure that before providing access to a resource, the user is authorized to access it. \r\n\r\n##### Use Object References In URLs\r\n\r\nAvoid using direct, readable IDs of resources within URLs. For example, the ID ```123``` is a bad component of the formed URL ```/account/123```. Use some kind of an object reference instead.\r\n\r\nTry and form a URL through obscure components, so that it is difficult to predict it from outside the system.\r\n\r\n### Security Misconfiguration\r\n\r\nOne of the things that a developer could say about security misconfiguration, is say \"It's not in my hands!\". They probably think it's up to the administrator, the server configuration team, or the operations team to handle such issues. They could say it's the responsibility of the team that deploys the operating environment.\r\n\r\n![image info](/images/Capture-041-16.png)\r\n\r\nThe truth is they should be very aware of it, and take all possible steps to prevent it. Not only that, you must pass on any information you have regarding security misconfiguration in the web servers, app servers or the deployment environment to the operations team, and follow it up with activities to patch up the flaws.\r\n\r\nWhat are the common instances of these flaws? \r\n\r\nThey include common configuration errors on the admin consoles. For  example, popularly use web servers such as WebSphere provide admin consoles, that having default accounts. \r\n- You could start off with deleting the default accounts from each of the deployment stages: development, qa, staging and production. \r\n- Make sure that the admin console is not available outside the enterprise. It should only be accessible from the intranet.\r\n\r\n#### Preventing Security Misconfiguration\r\n\r\n* Make sure you have the latest versions of software installations, for operating systems, languages, frameworks, etc. \r\n* Ensure that default accounts in admin consoles are eliminated throughout the deployment pipeline.\r\n* Have a similar execution environment throughout all stages of deployment - development, qa, staging and production. In all of these, employ the exact same security measures.  \r\n\r\n### Sensitive Data Exposure\r\n\r\nThe next security flaw we focus on is called Sensitive Data Exposure.\r\n\r\n![image info](/images/Capture-041-17.png)\r\n\r\n#### What Causes Sensitive Data Exposure?\r\n\r\n* One glaring instance of such a flaw is storing the user name and password credentials directly in a database, without using any encryption. Anyone who has sufficient access can read these credentials and compromise user accounts. \r\n* A related flaw could be that the encryption algorithm used on the credentials is not strong enough. As a result, anyone can decrypt the stored values.\r\n\r\n#### Preventing Sensitive Data Exposure\r\n\r\n##### Use One Way Functions\r\n\r\nWhen a one way function is used to encrypt data, it is not possible to recover the original data values in any way. \r\n\r\nThe way to use such a function is as follows: Store the encrypted password in the database. When user logs in, encrypt the candidate value and compare it the stored encrypted value. \r\n\r\n##### Add Salt During Hashing\r\n\r\nAnother way is to add some salt while computing the hash value. Salt refers to a random string that is appended to credentials entered by the user. If the password entered is \"abcdefgh\" (clearly a weak password), a salt such as \"12345678\" is appended to it, and the entire resulting string is hashed and stored in the database. The salt is generally also stored in the database, and can be used while validating the user.\r\n\r\nThe advantage of this approach is that even if the password used is the same on two websites, the encryption will be different on account of the salt.\r\n\r\n###  Missing Function Level Access Controls\r\n\r\n![image info](/images/Capture-041-18.png)\r\n\r\nWhenever we talk about user security, the focus has always been authentication and authorization. The attention is on determining: \r\n* Authentication: Is this the right user, and is he actually who he claims to be?\r\n* Authorization: Does this user have the access to the resource she requests?\r\n\r\nFlaws described as missing function level access controls, happens when you don't have proper authorizations in place. \r\n\r\n#### Preventing This Flaw\r\n\r\n##### Complete Mediation Principle\r\n\r\nImplement a Complete Mediation Principle. Before providing a resource to a user's request, check if the user has authorization for it. Implement such access checking in a centralized location. \r\n\r\n##### Have Well Defined Roles\r\n\r\nClearly lay out the roles of different users, and enumerate the resources for which access is approved. \r\n\r\n### Insufficient Transport Layer Security\r\n\r\n![image info](/images/Capture-041-19.png)\r\n\r\nThis flaw arises when the request that you send across the network, is not secure enough. Things such as session IDs, passwords and other sensitive data on the submission page need to be sent out with proper encryption. If such encryption is not done, then it poses a problem, especially with websites that have both secure (access only to privileged users) and unsecure parts (access to anybody). \r\n\r\n#### Preventing This Flaw\r\n\r\n![image info](/images/Capture-041-20.png)\r\n\r\n#### Use TLS\r\n\r\nMake sure you use the version of HTTP that uses transport layer security (TLS), namely HTTPS. \r\n\r\n* Ensure that you use TLS on popups\r\n* Always redirect only to HTTPs websites. That way, you will not end up sending a session ID or a cookie insecurely. on a redirect from a secure page.\r\n\r\n#### Use Secure Cookies\r\n\r\nMark all your cookies as secure, as this ensures they are sent only to trusted websites. Also, make it a point to have trusted certificates for your cookies.\r\n\r\n#### Regerate Session IDs And Reissue Tokens\r\n\r\nIt is a very secure practice to terminate a session and regenerate the session ID, when a user from a secure to an insecure part of the website. Also, it is good to reissue security tokens during this process.\r\n\r\n### Cross Site Request Forgery\r\n\r\n![image info](/images/Capture-041-21.png)\r\n\r\nLet's say you have already logged in to a website that offers banking services, and from there visit a forum page. What would happen if the forum uses the existing session ID to fire in an AJAX request, or fire a request to an unauthorized URL? \r\n\r\nThe banking website session and its cookies are active in your browser, as you haven't logged out. This can lead to abuse, called **Cross Site Request Forgery (CSRF)**. \r\n\r\n#### Preventing CSRF\r\n\r\n##### Generate Unique Token\r\n\r\nMake sure you generate a random unique token with every request, which cannot be predicted by a system from outside. Allow the next request, only if the token has the right value.\r\n\r\nThis token is called a CSRF Protection token, and is typically a hidden form field. Such a hidden field is present in a response generated by the website for the initial request. Unless you send that form field back, the next request cannot be successful. \r\n\r\n#####  Re-authenticate Users\r\n\r\nThe second approach is to re-authenticate the user when a significant action is requested to be performed. Such important actions could be a transfer of USD 100,000 in a banking application,  for instance.\r\n\r\n##### Use Security Frameworks\r\n\r\nWhile building the web application, make sure to use frameworks such as Spring Security, or OWASP Security Guard. These help you automate the implementation of remedial measures for CSRF flaws.\r\n\r\n### Avoid Using Known Vulnerable Components\r\n\r\n![image info](/images/Capture-041-22.png)\r\n\r\nIf your web application makes use of a framework or component with a well known security flaw, then a hacker can exploit that flaw to compromise your system. \r\n\r\nAll he needs to know is that you make use of that framework or component. \r\n\r\n#### Preventing These Flaws\r\n\r\n##### Use Latest Versions\r\n\r\nKeep track of successive software releases of the frameworks and components you use in your application. Install updated versions whenever they release.\r\n\r\n##### Approved Version Lists\r\n\r\nIt is a good practice to only use software and frameworks from an approved list of versions of software, that are known to be secure. Such a list could be maintained by the Security Team, and updated from time to time.\r\n\r\n##### Create Wrapper Services around frameworks\r\n\r\nCreate Wrapper service around frameworks without exposing complete framework features. Expose/Enable only the features that are used in your application.\r\n\r\n### Unavailed Redirects And Forwards\r\n\r\n![image info](/images/Capture-041-23.png)\r\n\r\nThe next flaw we concern ourselves with is that of unavailed redirects and forwards. A lot of web page URLs also have a redirect component within them. An example would be ```www.trustedsite.com/redirect.jsp?url=HACKER_URL```. The URL to which the redirect is done could be a malicious one. \r\n\r\nAny hacker could easily exploit it. The original link appears to be describing a secure site such as bank website. But in effect, it would redirect the request to a malicious URL, where a hacker might be waiting. \r\n\r\n#### Preventing These Flaws\r\n\r\n##### Validate Redirect URLs\r\n\r\nMake sure you also validate the redirect URL that is provided with the original URL. \r\n\r\nPreferably, avoid using direct URL mappings. Use an object mapping, to a stored string identifier instead. Based on the content of the string, redirect only to another secure URL that you trust. \r\n\r\n##### Show Messages\r\n\r\nShow a message to the user regarding the redirect. \r\n\r\nFor example, you may want to indicate to the user that he is being redirected to an insecure website, by pausing any further progress. You then ask him to confirm going ahead, or to abandon the request altogether.\r\n\r\n### Principles Of Application Security\r\n\r\nThere are six underlying principles of application security, that are made use of while suggesting recommendations for the OWASP Top 10.\r\n\r\n![image info](/images/Capture-041-24.png)\r\n\r\nLet us look at each of them in some detail.\r\n\r\n#### Assign Least Privileges\r\n\r\nThe architects and designers must start the design of the system with security requirements in mind. Security must feature as an important project requirement from the initial stages itself. There has to be clear picture of the roles of various users, and the accesses that they need. The idea is to have as few accesses to each role as possible, for any given user.\r\n\r\nThis applies not just to the application, but also to the infrastructure. This includes the application database, the servers where the system is deployed, and other similar things. The concept of minimized mapping of access to roles for each user, is equally relevant here. \r\n\r\n#### Have Complete Mediation\r\n\r\nHave an approach to application security that is similar to a King's Fort, where everyone everyone has to pass through one main gate. Apply a well-implemented security filter at that gate, to test the role and access of each user. \r\n\r\n#### Have Defence In Depth\r\n\r\nThis concept boils down to having multiple levels of security. For instance, you need to have security built into your architecture at the application, network and operating system levels. \r\n\r\n#### Trust Nothing\r\n\r\nMake sure that you validate every piece of data or information that comes into the system . It does not matter if it came from the user domain, or from another system. Ensure that you sanitize all external data.\r\n\r\n#### Have Economy Of Mechanism\r\n\r\nThis says that we need to keep the architecture of the system, simple. The idea is that simple systems are easier to protect.\r\n\r\n#### Ensure Openness Of Design\r\n\r\nAvoid trying to implement system security by making the design obscure. If that were the case, a hacker might identify a flaw and compromise the system. \r\n\r\nThis principle is the opposite of the misplaced idea of \"Security Through Obscurity\". \r\n\r\nThe more open a design, the easier it is to identify and address security flaws.\r\n\r\nDo check out our video on this:\r\n\r\n[![image info](/images/Capture-041-01.png)](https://www.youtube.com/watch?v=j5PuYFCS0Iw)\r\n\r\n### Summary\r\n\r\nIn this article, we looked ath the various security flaws listed in OWASP Top 10. For each type of security flaw, we looked at what the flaw was, how it could be exploited by malicious users, and also the mechanisms and good practices to follow to prevent them.\r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-11-15-NFR-045-Modularity.md",
    "content": "---\r\nlayout:  post\r\ntitle: Microservices Architectures - Non Functional Requirements - Modularity\r\ndate:  2019-11-14 12:31:19\r\nsummary: In this article, we explore an important non functional requirement called Modularity. \r\ncategories: SwArchitecture\r\npermalink:  /modularity-non-functional-requirement-in-microservices\r\nimage: /images/architecture.png\r\n---\r\n\r\nIn this article, we explore the important non functional requirement called Modularity. \r\n\r\n### What you will learn\r\n\r\n- What Is Modularity?\r\n- Why is Modularity important?\r\n- How can you build more Modular systems?\r\n\r\n\r\n\r\n### Non Functional Requirements and Microservices\r\n\r\nThis is the part of a series of articles on Non Functional Requirements:\r\n\r\n- [1 - Microservices Architectures - Non Functional Requirements](/non-functional-requirements-in-microservices-architectures){:target='_blank'}\r\n- [2 - Security](/non-functional-requirements-in-microservices-introduction-to-Security){:target='_blank'}\r\n- [3 - Web Application Security And OWASP - Top Ten Security Flaws](/web-application-security-owasp-top-ten){:target='_blank'}\r\n- [4 - Maintainability](/non-functional-requirements-in-microservices-introduction-to-Maintainability){:target='_blank'}\r\n- [5 - Scalability](/non-functional-requirements-in-microservices-introduction-to-Scalability){:target='_blank'}\r\n- [6 - Performance](/non-functional-requirements-in-microservices-introduction-to-performance){:target='_blank'}\r\n- [7 - Reusability](/non-functional-requirements-in-microservices-introduction-to-Reusability){:target='_blank'}\r\n- [8 - Reliability](/non-functional-requirements-in-microservices-introduction-to-Reliability){:target='_blank'}\r\n- [9 - Modularity](/modularity-non-functional-requirement-in-microservices){:target='_blank'}\r\n- [10 - Availability](/availability-non-functional-requirement-in-microservices){:target='_blank'}\r\n- [11 - Portability](/non-functional-requirements-in-microservices-introduction-to-portability){:target='_blank'}\r\n\r\n\r\n### What Is Modularity?\r\n\r\nWhat you are looking at is an instance of a microservices architecture:\r\n\r\n![image info](/images/Capture-045-02.png)\r\n\r\nHow would you build such a system? \r\n\r\nA decade back, the entire functionality of what you see in the picture, would be provided by a single monolith application.\r\n\r\nAs we moved on from monolith to service-oriented to microservices architecture, we build more modular applications. \r\n\r\nWe focus on identifying multiple microservices, common components that have well defined interfaces, and common infrastructure components that are the building blocks of the application's technical capabilities. This is what is called a **modular architecture**. \r\n\r\nModularity applies at multiple levels:\r\n- How do you architect your applications?\r\n- How do you design your components?\r\n- How do you design your classes?\r\n\r\n### What is Separation of Concerns?\r\n\r\nThe cornerstone of modular architecture is **separation of concerns**. \r\n\r\n> This involves identifying a functionality that can be handled separately, and defining an application, a component, a package or a class  to do it. \r\n\r\nFor example, the security component handles the low-level details of user authentication and authorization. These include the specifics of how user credentials are stored, how user's access related information is stored, and the like. \r\n\r\nSecurity component provides a well-defined, consistent interface. When a microservice needs to authenticate the user, it would send a request to the security component. The microservice will not need to worry about how the authentication is done.\r\n\r\nWhile implementing modularity, you try and create components with separate responsibilities. This makes reusing the components and creating new microservices easy. \r\n\r\n### Building reusable components\r\n\r\nLet's look at an example.\r\n\r\nSuppose Microservice1 wants to check of the user has provided the right credentials, and whether he has access to a particular resource. It clearly needs to make use of the Security component. If it finds the need to log a message, it makes use of the Logging component. If Microservice1 wants to find out where Microservice3 is deployed, it submits a query to the NamingServer infrastructure component. The component in turn, provides a response with the location. \r\n\r\nThere are essentially two kinds of components:\r\n- Common Utility Components and Frameworks : There are very technical in nature, each of them being implemented as separate modules. In Java applications, these would be JARs. Microservice1 would call methods in the JARs and use their functionality. \r\n- Infrastructure Common Components : These are independently deployable common applications - Naming Servers, API Gateways etc.\r\n\r\n> The term component is used to describe a part of the application, that is independently reusable. \r\n\r\nDo check out our video on this:\r\n\r\n[![image info](/images/Capture-045-01.png)](https://www.youtube.com/watch?v=v-0ClsJ5UcI)\r\n\r\n### Summary\r\n\r\nIn this article, we explored the meaning of the term modularity, when applied to application architecture. We saw that modern microservices implement something separation of concern, to achieve modularity. They do this by identifying and extracting out functionality into common components, both technical and infrastructure. These components have well defined interfaces, and makes the addition of new microservices to the application, relatively easy. \r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-11-15-NFR-047-Availability.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Microservices Architectures - Non Functional Requirements - Availability\r\ndate:    2019-11-14 12:31:19\r\nsummary:  In this article, we explore an important non functional requirement called Availability. \r\ncategories: SwArchitecture\r\npermalink:  /availability-non-functional-requirement-in-microservices\r\nimage: /images/architecture.png\r\n---\r\n\r\nIn this article, we explore an important non functional requirement called Availability. \r\n\r\n### What you will learn\r\n\r\n- What Is Availability?\r\n- Why is Availability important?\r\n- How can you build more available systems?\r\n\r\n\r\n\r\n### Non Functional Requirements and Microservices\r\n\r\nThis is the part of a series of articles on Non Functional Requirements:\r\n\r\n- [1 - Microservices Architectures - Non Functional Requirements](/non-functional-requirements-in-microservices-architectures){:target='_blank'}\r\n- [2 - Security](/non-functional-requirements-in-microservices-introduction-to-Security){:target='_blank'}\r\n- [3 - Web Application Security And OWASP - Top Ten Security Flaws](/web-application-security-owasp-top-ten){:target='_blank'}\r\n- [4 - Maintainability](/non-functional-requirements-in-microservices-introduction-to-Maintainability){:target='_blank'}\r\n- [5 - Scalability](/non-functional-requirements-in-microservices-introduction-to-Scalability){:target='_blank'}\r\n- [6 - Performance](/non-functional-requirements-in-microservices-introduction-to-performance){:target='_blank'}\r\n- [7 - Reusability](/non-functional-requirements-in-microservices-introduction-to-Reusability){:target='_blank'}\r\n- [8 - Reliability](/non-functional-requirements-in-microservices-introduction-to-Reliability){:target='_blank'}\r\n- [9 - Modularity](/modularity-non-functional-requirement-in-microservices){:target='_blank'}\r\n- [10 - Availability](/availability-non-functional-requirement-in-microservices){:target='_blank'}\r\n- [11 - Portability](/non-functional-requirements-in-microservices-introduction-to-portability){:target='_blank'}\r\n\r\n\r\n### What Is Availability?\r\n\r\nConceptually, availability is easy to understand. Suppose you wanted to access a website but you found that it is down. That is an indication of low availability of the website. \r\n\r\n> **Availability** is a measure of how frequently your system provides the desired functionality, to your users. \r\n\r\nTypically, you want a 99.9999% or 100% availability for your system. Actually, this might not be true. \r\n\r\nDepending on the category of an application, there might be different needs for its availability. If it is an internal application to be used within an enterprise, then it might not be needed beyond office hours.\r\n\r\nFor most system that are available over the internet, the availability needs are quite high. \r\n\r\n### Improving Availability\r\n\r\nConsider the following system with a microservices architecture:\r\n\r\n![image info](/images/Capture-047-02.png)\r\n\r\nHow would you go about improving the availability of this system?\r\n\r\n#### Modularity Improves Availability\r\n\r\nMicroservice architectures have high modularity. We don't build such a system as a monolith. Instead, we break it down in to smaller components (technical and infrastructure), each of which provides a well defined interface. \r\n\r\nEach of them is also independently deployable. Such applications will not be very bulky, nor will they need to access huge databases. That is a good head-start in giving the system high availability, since common bottlenecks are removed.\r\n\r\n#### Redundancy Improves Availability\r\n\r\nIn the application example above, having multiple instances of each of Microservice1, Microservice2 and Microservice3 helps improve service availability to users. \r\n\r\nNot just the microservices, redundancy at other levels is beneficial too. Having multiple instances of the Infrastructure components such as the NamingServer and APIGateway improves availability. \r\n\r\nThe key to high availability is to eliminate single points of failure. Ensure that all your infrastructure components have enough redundancy built in.\r\n\r\n#### Monitoring Improves Availability\r\n\r\nIf an API Gateway goes down, you should NOT get to know of it from your users. \r\n\r\nIf Microservice1 crashes for some reason, you should know of it first through your internal automated mechanisms. \r\n\r\nThere needs to a facility for monitoring each of the microservices and components in the system. \r\n\r\nOn any instance of failure, the operations team needs to be alerted by some mechanism, for diagnosis and recovery. \r\n\r\nDo check out our video on this:\r\n\r\n[![image info](/images/Capture-047-01.png)](https://www.youtube.com/watch?v=R3j0Z1c-0qY)\r\n\r\n### Summary\r\n\r\nIn this video, we talked about the availability of an application. Availability measures how frequently the system provides the desired service, to all the users. We took the example of a microservice architecture to describe how you can improve availability.\r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-11-15-REST-API-007-REST-WhatIs-HATEOAS.md",
    "content": "---\r\nlayout:  post\r\ntitle:  REST API - What is HATEOAS?\r\ndate:    2019-11-14 12:31:19\r\nsummary: While viewing a web page, you can see data in the page and perform actions with it. How about a REST API? Typically when you ask for a REST Resource, you get the details of the resource back. How about sending the operations that you can do with the resource in the response? \r\ncategories: RestAPI\r\npermalink:  /rest-api-what-is-hateoas\r\nimage: /images/rest-api-category.png\r\n---\r\n\r\nWhile viewing a web page, you can see data in the page and perform actions with it. How about a REST API? Typically when you ask for a REST Resource, you get the details of the resource back. How about sending the operations that you can do with the resource in the response?\r\n\r\n### What will you learn?\r\n* What is HATEOAS?\r\n* Why do you need to use HATEOAS?\r\n* When do you make use of HATEOAS?\r\n\r\n\r\n\r\n### REST API\r\n\r\nThis is the fifth article in a series of articles on REST APIs:\r\n\r\n- [1 - Introduction to REST API - RESTful Web Services](/introduction-to-rest-api){:target='_blank'}\r\n- [2 - REST v SOAP - A few perspectives](/rest-vs-soap-web-services){:target='_blank'}\r\n- [3 - Designing REST API - What is Contract First?](/rest-api-contRact-first-approach){:target='_blank'}\r\n- [4 - Designing REST API - What is Code First Approach?](/rest-api-code-first-approach){:target='_blank'}\r\n- [5 - REST API - What is HATEOAS?](/rest-api-what-is-hateoas){:target='_blank'}\r\n- [6 - REST API Best Practices - With Design Examples from Java and Spring Web Services](/rest-api-best-practices-with-java-and-spring){:target='_blank'}\r\n\r\n\r\n\r\n### What Does HATEOAS Stand For?\r\n\r\nThe term **HATEOAS** stands for the phrase **H**ypermedia **A**s **T**he **E**ngine **O**f **A**pplication **S**tate. To understand this further, we first need to understand the meaning of **Hypermedia**.\r\n\r\n### What Does Hypermedia Mean?\r\n\r\nHave a look at the following web page:\r\n\r\n![image info](/images/Capture-07-01.png)\r\n\r\nWhen the browser load the page, you definitely can see all the content that page has to offer. More interestingly, the page also allows you to perform a lot of actions around that data, such as: \r\n\r\n* Clicking on buttons (the green \"Clone or Download\") \r\n* Clicking on tabs (to view the \"Issues\", for instance), \r\n\r\nand several  more.\r\n\r\nNow let's look at how our REST API's behave:\r\n\r\nIf you look at a typical GET request to a RESTful server, such as this one:\r\n\r\n![image info](/images/Capture-07-02.png)\r\n\r\nThe request to ```GET http://localhost:8080/users``` retrieves a set of three users details in this case.  Sending a request with ```GET http://localhost:8080/users/1``` will retrieve details of just the first user.\r\n\r\nTypically, when we perform a REST request, we only get the data, and not any actions around it. This is where HATEOAS comes in the fill in the gap. \r\n\r\nA HATEOAS request allows you to not only send the data but also specify the related actions:\r\n\r\n![image info](/images/Capture-07-03.png)\r\n\r\nThis example was in the JSON format. An XML format for another example would look something like this:\r\n\r\n![image info](/images/Capture-07-04.png)\r\n\r\nWhen you send out this request to retrieve account details, you get both:\r\n\r\n* Account number and balance details\r\n* Links that provide actions to do a deposit/withdrawal/transfer/closure\r\n\r\nWith HATEOAS, a request for a REST resource gives me both data, and actions related to the data.\r\n\r\n### Why Do We Need HATEOAS?\r\n\r\nThe single most important reason for HATEOAS is **loose coupling**. If a consumer of a REST service needs to hard-code all the resource URLS, then it is tightly coupled with your service implementation. Instead, if you return the URLs it could use for the actions, then it is loosely coupled. There is no tight dependency on the URI structure, as it is specified and used from the response. \r\n\r\n### Some Important Related Topics\r\n\r\nA few significant topics related to HATEOAS are:\r\n\r\n#### HAL - Hypertext Application Language\r\n\r\nWhen you design a RESTful service, there is need to specify how to return data and links corresponding to a request. HAL is a simple format that gives a easy, consistent way to hyperlink between resources in your REST API.\r\nHere is an example:\r\n\r\n![image info](/images/Capture-07-05.png)\r\n\r\nWith HAL, you have a few categories of representations:\r\n\r\n* Links: Specified as combination of\r\n\t* Target - Given as a URI\r\n\t* Relation - A name\r\n* Embedded Resources: Other resources contained within a given REST resource\r\n* State: The actual resource data\r\n\r\nIf you happen to use the Spring Framework to develop your REST service, then Spring HATEOAS is a good engine to use for your service.\r\n\r\nDo check out our video on this:\r\n\r\n[![image info](/images/Capture-07-06.png)](https://www.youtube.com/watch?v=gCNAudrbWCo)\r\n\r\n### Summary\r\n\r\nIn this article, we looked at what HATEOAS stands for. With HATEOAS, responses to REST requests return not just the data, but also actions that can be performed with the resource. This helps in making the applications loosely coupled.\r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-11-15-REST-API-013-REST.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Introduction to REST API - RESTful Web Services\r\ndate:    2019-11-14 12:31:19\r\nsummary: REST stands for REpresentational State Transfer. It is a popular architectural approach to create your API's in todays world.\r\ncategories: RestAPI\r\npermalink:  /introduction-to-rest-api\r\nimage: /images/rest-api-category.png\r\n---\r\n\r\n**REST** stands for **RE**presentational **S**tate **T**ransfer. It is a popular architectural approach to create your API's in todays world. \r\n\r\n## You will Learn\r\n- What is REST?\r\n- What are the fundamentals of REST APIs?\r\n- How do you make use of HTTP when building REST API?\r\n- What is a Resource?\r\n- How do you identify REST API Resources?\r\n- What are some of the best practices in designing REST API?\r\n\r\n\r\n\r\n### REST API\r\n\r\nThis is the first article in a series of articles on REST APIs:\r\n\r\n- [1 - Introduction to REST API - RESTful Web Services](/introduction-to-rest-api){:target='_blank'}\r\n- [2 - REST v SOAP - A few perspectives](/rest-vs-soap-web-services){:target='_blank'}\r\n- [3 - Designing REST API - What is Contract First?](/rest-api-contRact-first-approach){:target='_blank'}\r\n- [4 - Designing REST API - What is Code First Approach?](/rest-api-code-first-approach){:target='_blank'}\r\n- [5 - REST API - What is HATEOAS?](/rest-api-what-is-hateoas){:target='_blank'}\r\n- [6 - REST API Best Practices - With Design Examples from Java and Spring Web Services](/rest-api-best-practices-with-java-and-spring){:target='_blank'}\r\n\r\n\r\n### What Is REST?\r\n\r\nThe acronym **REST** stands for **RE**presentational **S**tate **T**ransfer. It was term originally coined by Roy Fielding, who was also the inventor of the HTTP protocol. The striking feature of REST services is that they want to make the best use of HTTP. Let's now have a quick overview of HTTP.\r\n\r\n### A Relook At HTTP\r\n\r\nLet's open up the browser and visit a web page first:\r\n\r\n![image info](/images/Capture-013-01.png)\r\n\r\nAnd then click on one of the result pages:\r\n\r\n![image info](/images/Capture-013-02.png)\r\n\r\nNext, we can click on the link on the page we end up in:\r\n\r\n![image info](/images/Capture-013-03.png)\r\n\r\nAnd land up on another page:\r\n\r\n![image info](/images/Capture-013-04.png)\r\n\r\nThis is how we typically browse the web. \r\n\r\nWhen we browse the internet, there are a lot of things that happen behind the scenes. The following is a simplified view of what happens between the browser, and the servers running on the visited websites:\r\n\r\n![image info](/images/Capture-013-05.png)\r\n\r\n#### The HTTP Protocol\r\n\r\nWhen you enter a URL such as ```https://www.google.com``` in the browser, a request is sent to the server on the website identified by the URL. That server then responds with a response. The important thing is the formats of these requests and responses. These formats are defined by a protocol called **HTTP** - **Hyper Text Transfer Protocol**. \r\n\r\nWhen you type in an URL at the browser, it sends out a **GET** request to the identified server. The server then replies with a HTTP response, that contains data in **HTML** - **Hyper Text Markup Language**. The browser then takes this HTML and displays it on your screen. \r\n\r\nLet's say you are filling in a form present on a web page, with a list of details. In such a scenario when you click the Submit button, a HTTP **POST** request gets sent out to the server. \r\n\r\n\r\n### HTTP and RESTful Web Services\r\n\r\nHTTP provides the base layer for building web services. Therefore, it is important to understand HTTP. Here are a few key abstractions\r\n\r\n### Resource\r\n\r\nA resource is a key abstraction that HTTP centers round. A resource is anything you want to expose to the outside world, through your application. For instance, if we write a todo management application, instances of resources are:\r\n\r\n* A specific user\r\n* A specific todo\r\n* A list of todos\r\n\r\n#### Resource URIs\r\n\r\nWhen you develop RESTful services, you need to focus your thinking on the resources in the application. The way we identify a resource to expose, is to assign a **URI** - **Uniform Resource Identifier** - to it. For example:\r\n\r\n* The URI for the user Ranga is ```/user/ranga```\r\n* The URI for all the todos belonging to Ranga is ```/user/Ranga/todos```\r\n* The URI for the first todo that Ranga has is ```/user/Ranga/todos/1```\r\n\r\n#### Resource Representation\r\n\r\nREST does not worry about how you represent your resource. It could be XML, HTML, JSON or something entirely different! The only important thing is you clearly define your resource, and perform whatever actions that are supported on it by making use of features already provided by HTTP. Examples are:\r\n\r\n* Create a user: ```POST /users```\r\n* Delete a user: ```DELETE /users/1```\r\n* Get all users: ```GET /users```\r\n* Get a single user: ```GET /users/1```\r\n\r\n### REST And Resources\r\n\r\nA significant point to note is that with REST, you need to think about your application in terms of resources : \r\n\r\n* Identify what resources you want to expose to the outside world\r\n* Make use of the verbs already specified by HTTP, to perform operations on these resources\r\n\r\nHere is how a REST service is generally implemented:\r\n\r\n* **Data Exchange Format**: No restriction is imposed over here. JSON is a highly popular format, although other such as XML can be used as well\r\n* **Transport**: Always HTTP. REST is completely built on top of HTTP.\r\n* **Service Definition** : There is not standard to specify this, and REST is flexible. This could be a drawback in some scenarios, as it might be necessary for the consuming application to understand the request and response formats. There are widely used ones however, such as WADL (Web Application Definition Language) and Swagger.\r\n\r\nREST focuses on resources, and how effectively you perform operations on them using HTTP.\r\n\r\n### The Components Of HTTP\r\n\r\nHTTP defines the following for a request:\r\n\r\n* **Method**\r\n* **Headers**\r\n* **Body**\r\n\r\nFor the response, HTTP defines the\r\n\r\n* **Headers**\r\n* **Body**\r\n\r\n#### HTTP Request Methods\r\n\r\nThe method used in a HTTP request indicates what action you want to perform with that request. Important examples are:\r\n\r\n* GET: Retrieve details of a resource\r\n* POST : Create a new resource\r\n* PUT: Update an existing resource\r\n* DELETE: Delete a resource\r\n\r\n#### HTTP Response Status Code\r\n\r\nA status code is always present in a HTTP response. Common examples are: \r\n\r\n* 200: Success\r\n* 404: Page not found\r\n\r\nDo check out our video on this:\r\n\r\n[![image info](/images/Capture-013-06.png)](https://www.youtube.com/watch?v=ONelFjri_j0)\r\n\r\n### Summary\r\n\r\nIn this article, we had a high-level look at REST. We stressed on the fact that HTTP is the building block of REST services. HTTP is a protocol that is used to define the structure of browser requests and responses. We saw that HTTP deals mainly with resources that are exposed on web servers. Resources are identified using URIs, and operations on these resources are performed using verbs defined by HTTP.\r\n\r\nFinally, we looked at how REST services make best use of features offered by HTTP, to expose resources to the outside world. REST does not put any restrictions on the resource representation formats, or on the service definition.\r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-11-15-REST-API-014-SOAP-v-REST.md",
    "content": "---\r\nlayout:  post\r\ntitle:  REST v SOAP - A few perspectives\r\ndate:    2019-11-14 12:31:19\r\nsummary: In this article, we look at the major differences between SOAP and REST. OOPS actually, comparing the two is a little like comparing apples to oranges, as SOAP is a protocol format based on XML, whereas REST is an architectural approach.\r\ncategories: RestAPI\r\npermalink:  /rest-vs-soap-web-services\r\nimage: /images/rest-api-category.png\r\n---\r\n\r\nIn this article, we look at the major differences between SOAP and REST. OOPS.. actually, comparing the two is a little like comparing apples to oranges, as SOAP is a protocol format based on XML, whereas REST is an architectural approach.\r\n\r\n## You will Learn\r\n- What is REST?\r\n- What is SOAP?\r\n- How are REST and SOAP different?\r\n\r\n\r\n### REST API\r\n\r\nThis is the second article in a series of articles on REST APIs:\r\n\r\n- [1 - Introduction to REST API - RESTful Web Services](/introduction-to-rest-api){:target='_blank'}\r\n- [2 - REST v SOAP - A few perspectives](/rest-vs-soap-web-services){:target='_blank'}\r\n- [3 - Designing REST API - What is Contract First?](/rest-api-contRact-first-approach){:target='_blank'}\r\n- [4 - Designing REST API - What is Code First Approach?](/rest-api-code-first-approach){:target='_blank'}\r\n- [5 - REST API - What is HATEOAS?](/rest-api-what-is-hateoas){:target='_blank'}\r\n- [6 - REST API Best Practices - With Design Examples from Java and Spring Web Services](/rest-api-best-practices-with-java-and-spring){:target='_blank'}\r\n\r\n\r\n\r\n### REST vs SOAP\r\n\r\nREST vs SOAP are not really comparable. REST is an architectural style. SOAP is a message exchange format.\r\n\r\nLet’s compare the popular implementations of REST and SOAP styles.\r\n\r\n- RESTful Sample Implementation : JSON over HTTP\r\n- SOAP Sample Implementation : XML over SOAP over HTTP\r\n\r\nAt a high level, SOAP is about restrictions on your message structures while REST is an architectural approach focused on using HTTP Transport.\r\n- SOAP is particular about the **Data Exchange Format**. With SOAP, this is always SOAP-XML, which is an XML with envelope, header and body. Both the request and response should adhere to the SOAP structure.\r\n- REST is very particular about using HTTP as the transport protocol. It intends to make the best use of the features provided by HTTP - Request methods, Request headers, Response, Response headers etc.\r\n\r\n### Message interchange format\r\n- With SOAP, you use SOAP XML format for Request and Response\r\n- With REST, there is no such fixed format. You could exchange messages based on XML, JSON or any other convenient format. JSON is the most popular among the used formats.\r\n\r\n### Service Definitions\r\n- SOAP makes use of **Web Service Definition Language (WSDL)**. \r\n- REST does not have a standard service definition language. Even though WADL was one of the first standards to be proposed, it is not very popular. Swagger or Open API is another popular approach.\r\n\r\n\r\n### Transport\r\n- SOAP does not place any restrictions on the kind of transport protocol. You could either use Web (which is HTTP), or MQ. \r\n- REST intends to make the best use of HTTP Transport Protocol\r\n\r\n### Ease of Implementation\r\nRESTFful services are typically a lot easier to implement than SOAP based web services. \r\n* REST typically uses JSON, which is easier to parse and process. In addition to that, REST does not require you to have a service definition in place to provide a web service. \r\n* However with SOAP, you are needed to define your service using WSDL, and greater overhead is involved in processing and parsing the SOAP-XML messages.\r\n\r\nDo check out our video on this:\r\n\r\n[![image info](/images/Capture-014-01.png)](https://www.youtube.com/watch?v=PbIT0yppvW8)   \r\n\r\n### Summary\r\n\r\nIn this article, we broadly looked the differences between REST and SOAP.\r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-11-15-REST-API-018-Contract-First.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Designing REST API - What is Contract First?\r\ndate:    2019-11-14 12:31:19\r\nsummary: Designing Great REST API is important to have great microservices. Contract First approach helps you in designing a great contract before implementing it. However, it does not come easy!\r\ncategories: RestAPI\r\npermalink:  /rest-api-contRact-first-approach\r\nimage: /images/spring-boot-application.png\r\n---\r\n\r\nDesigning Great REST API is important to have great microservices. Contract First approach helps you in designing a great contract before implementing it. However, it does not come easy!\r\n\r\n![image info](/images/Capture-018-05.png)\r\n \r\n## You will learn\r\n- What is Contract First approach of designing REST API?\r\n- What are advantages of Contract First approach?\r\n- What are disadvantages of Contract First approach?\r\n- When do you adopt Contract First approach?\r\n\r\n\r\n### REST API\r\n\r\nThis is the third article in a series of articles on REST APIs:\r\n\r\n- [1 - Introduction to REST API - RESTful Web Services](/introduction-to-rest-api){:target='_blank'}\r\n- [2 - REST v SOAP - A few perspectives](/rest-vs-soap-web-services){:target='_blank'}\r\n- [3 - Designing REST API - What is Contract First?](/rest-api-contRact-first-approach){:target='_blank'}\r\n- [4 - Designing REST API - What is Code First Approach?](/rest-api-code-first-approach){:target='_blank'}\r\n- [5 - REST API - What is HATEOAS?](/rest-api-what-is-hateoas){:target='_blank'}\r\n- [6 - REST API Best Practices - With Design Examples from Java and Spring Web Services](/rest-api-best-practices-with-java-and-spring){:target='_blank'}\r\n\r\n\r\n\r\n### Understanding Web Services\r\n\r\nThere are several kinds of web services that are offered - REST, SOAP - among others. \r\n\r\nFor every services, there is a\r\n* The service provider, which provides the service\r\n* The service consumer, which makes use of it\r\n\r\nA consumer needs to know the details of the service provided. For this reason, a contract needs to be in place. A service contract specifies:\r\n* What are the inputs and the outputs of/from the service?\r\n* What is the URL at which the service is available?\r\n* How do you send authorization?\r\n\r\n\r\n### Contract First Approach\r\n\r\nIn a Contract-First approach, you first define the contract, and then implement the service. \r\n\r\nLet's look at an example.\r\n\r\n#### WSDL\r\n\r\nLet us first take up the case of WSDL - Web Service Definition Language format. Here is an example in use:\r\n\r\n![image info](/images/Capture-018-02.png)\r\n\r\nWSDL is typically used with SOAP/XML web services. In such a definition, you typically define:\r\n\r\n* The formats of the request and response\r\n\r\n![image info](/images/Capture-018-03.png)\r\n\r\n* Where the services are exposed\r\n\r\n![image info](/images/Capture-018-04.png)\r\n\r\n* The URL where the serviced can be called\r\n\r\n![image info](/images/Capture-018-05.png)\r\n\r\n* The headers that are part of the request\r\n\r\n### What Contract-First Implies\r\n\r\nWhen we start out with establishing a contract, we define a WSDL, and then share it with our consumer. All this can happen even before we implement the service and make it available. \r\n\r\nThe contract tells the consumer what the request and response communication is expected to be. Once the contract is in place, the service provider can work on providing a service that adheres to the contract. The service consumer can work on developing an application to consume it.\r\n\r\n### Advantages Of Contract First\r\n\r\n#### Teams Can Develop In Parallel\r\n\r\nSince coding happens based on the contract, the service provider and service consumer teams are clear about the communication approach and details. Hence, development can happen at the same time.\r\n\r\n#### Teams Know What To Expect\r\n\r\nSince coding happens based on contract, the producer and consumer teams have an idea of each others' expectations. As a result, if cross team testing is not possible due to different pace of development, stub software can be used to mock the others behavior, all based on the contract.\r\n\r\n#### Cross Platform Compatible\r\n\r\nOnce the service parameters depend only on the contract, the actual software framework used to develop the service does not matter that much. The service provider and service consumer can use different technologies.  \r\n\r\n#### Enables Reuse Of Schemas\r\n\r\nThe schemas that are used to define the contract for a service, are well defined in the WSDL. Therefore, if parts of services are repeated across other services, then the corresponding schemas can be reused as well.\r\n\r\n### Disadvantages Of Contract First\r\n\r\n#### Requires Initial Additional Effort\r\n\r\nMost of this effort would center round agreement on a service contract. You need to make sure that the contract is well defined and does not change very often. \r\n\r\n#### Mechanism For Contract Update And Sharing\r\n\r\nOver the course of using a service, if you update a contract, it affects all the other stakeholders. Therefore, there has to be a proper mechanism to communicate the changes to the various consumers. \r\n\r\n\r\nDo check out our video on this:\r\n\r\n[![image info](/images/Capture-018-01.png)](https://www.youtube.com/watch?v=SKEuvFyBYdE)\r\n\r\n### Summary\r\n\r\nIn this article, we discussed about the Contract-First approach, in the context of web services.\r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-11-15-REST-API-021-Code-First.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Designing REST API - What is Code First Approach?\r\ndate:    2022-08-14 12:31:19\r\nsummary: Designing Great REST API is important to have great microservices. Code First approach focuses on generating the contract from code. Is it the best possible approach? \r\ncategories: RestAPI\r\npermalink:  /rest-api-code-first-approach\r\nimage: /images/spring-boot-application.png\r\n---\r\n\r\n![image info](/images/Capture-021-04.png)\r\n\r\nDesigning Great REST API is important to have great microservices. Code First approach focuses on generating the contract from code. Is it the best possible approach? \r\n\r\n![image info](/images/Capture-021-05.png)\r\n\r\n## You will learn\r\n- What is Code First approach of designing REST API?\r\n- What are advantages of Code First approach?\r\n- What are disadvantages of Code First approach?\r\n- When do you adopt Code First approach?\r\n\r\n\r\n### REST API\r\n\r\nThis is the fourth article in a series of articles on REST APIs:\r\n\r\n- [1 - Introduction to REST API - RESTful Web Services](/introduction-to-rest-api){:target='_blank'}\r\n- [2 - REST v SOAP - A few perspectives](/rest-vs-soap-web-services){:target='_blank'}\r\n- [3 - Designing REST API - What is Contract First?](/rest-api-contRact-first-approach){:target='_blank'}\r\n- [4 - Designing REST API - What is Code First Approach?](/rest-api-code-first-approach){:target='_blank'}\r\n- [5 - REST API - What is HATEOAS?](/rest-api-what-is-hateoas){:target='_blank'}\r\n- [6 - REST API Best Practices - With Design Examples from Java and Spring Web Services](/rest-api-best-practices-with-java-and-spring){:target='_blank'}\r\n\r\n\r\n\r\n### What Is Code First?\r\n\r\nWhenever you develop service, such as a REST API or a SOAP API, there are two approaches you could choose from:\r\n\r\n* Code First, and generate the contract out of the code\r\n* Contract First, and develop the code based on the contract\r\n\r\nLet's start with a quick example for Code First\r\n\r\n### Spring Boot Code First REST API Example\r\n\r\nWe are developing a RESTful web service, by making use of the Spring Boot Framework to generate the API. For example, in the ```retrieveAllUsers()``` API, we expose the ```\"/users\"``` URI and return all the user resources by calling a service method. when we hit this URL, we get these users returned:\r\n\r\n![image info](/images/Capture-021-02.png)\r\n\r\nIn a similar manner, there are other service methods defied, each with their own URI. What we are doing with this example is taking the code, and generating documentation from it. That documentation lists out how a user can use the service. For this, we use a documentation format called Swagger:\r\n\r\n![image info](/images/Capture-021-03.png)\r\n\r\nSwagger enables us to generate documentation from the code. For example, the following is what Swagger generates for a request to retrieve all users:\r\n\r\n![image info](/images/Capture-021-04.png)\r\n\r\nIt lists out the kind of response message we get, and the response status accompanying it as well. You can even call that service from Swagger, leading to:\r\n\r\n![image info](/images/Capture-021-05.png)\r\n\r\nYou can also send a POST request to ```\"/users\"```:\r\n\r\n![image info](/images/Capture-021-06.png)\r\n\r\nSwagger tells us how to structure the request message, and specify the individual field formats inside. It will also tell you the type of response you get back, along with the response code.\r\n\r\nWhat Swagger generates out of the code, is called a **contract**. \r\n\r\n### Advantages Of Code First\r\n\r\nThe advantages of this approach are mainly:\r\n\r\n* **Low-effort contracts**: Generating the contract does not require any additional effort. It is just a by-product of the service development, as it can be automatically generated from the code \r\n* **Contract, code in-sync**: As the contract is generated from the code, the two always in sync with each other\r\n\r\n### Disadvantages Of Code-First\r\n\r\nThe disadvantages of this approach are as follows:\r\n\r\n#### No Parallel Development\r\n\r\nThe service producer and the service consumers cannot be developed in parallel. First the service needs to be developed, then the contract is generated, and only after that, consumer code can be written to adhere to the contract. Without understanding the contract, a consumer cannot be developed.\r\n\r\n#### No Target For Teams\r\n\r\nAs the contract cannot be known before the service is developed, there is no target for the various stakeholders in development. Hence, there is every chance that directions go wayward, and unnecessary changes are made, leading to wastage of effort.\r\n\r\n#### No Cross-Platform Compatibility\r\n\r\nIn some older frameworks, it is not that easy to generate the contract from the code. As a result, it is quite common for the contracts generated not being compatible across platforms.\r\n\r\nDo check out our video on this:\r\n\r\n[![image info](/images/Capture-021-01.png)](https://www.youtube.com/watch?v=yDAujtMk2oQ)\r\n\r\n### Summary\r\n\r\nIn this article, we explored the code first approach of building REST API. While code first approach is efficient from a developer perspective, it has significant challenges when it comes to developing the service provider and consumer together.\r\n"
  },
  {
    "path": "_blog/articles/2019-11-15-REST-API-098-REST-API-Web-Services-Best-Practices.md",
    "content": "---\r\nlayout:  post\r\ntitle:  REST API Best Practices - With Design Examples from Java and Spring Web Services\r\ndate:       2022-01-02 12:31:19\r\nsummary: Designing Great REST API is important to have great microservices. How do you design your REST API? What are the best practices?\r\ncategories: SwJavaProgrammers\r\npermalink:  /rest-api-best-practices-with-java-and-spring\r\nimage: /images/architecture.png\r\n---\r\n\r\n![image info](images/Capture-098-03.png)\r\n\r\nDesigning Great REST API is important to have great microservices. How do you design your REST API? What are the best practices?\r\n\r\n![image info](images/Capture-098-04.png)\r\n \r\n## You will learn\r\n- How do you design great REST API?\r\n- What should you think about when designing REST API?\r\n- What are the best practices in designing RESTful Web Services?\r\n\r\n\r\n### REST API\r\n\r\nThis is the last article in a series of articles on REST APIs:\r\n\r\n- [1 - Introduction to REST API - RESTful Web Services](/introduction-to-rest-api){:target='_blank'}\r\n- [2 - REST v SOAP - A few perspectives](/rest-vs-soap-web-services){:target='_blank'}\r\n- [3 - Designing REST API - What is Contract First?](/rest-api-contRact-first-approach){:target='_blank'}\r\n- [4 - Designing REST API - What is Code First Approach?](/rest-api-code-first-approach){:target='_blank'}\r\n- [5 - REST API - What is HATEOAS?](/rest-api-what-is-hateoas){:target='_blank'}\r\n- [6 - REST API Best Practices - With Design Examples from Java and Spring Web Services](/rest-api-best-practices-with-java-and-spring){:target='_blank'}\r\n\r\n\r\n\r\n### Use A Consumer First Approach\r\n\r\nWho is going to use your service? The Service Consumer. \r\n\r\nAre you looking at it from the consumer perspective?\r\n* If you design an API, will your consumer be able to understand your API?\r\n* If you expose your resources, will the consumer be able to locate and access them?\r\n* Will the consumer be able to understand your URIs?\r\n* What is the type of service that you provide? Is it a mobile application, or is a web based application? What are the kinds of consumers you expect, and are these consumer types likely to change in the future? \r\n* If you implement something like HATEOAS, think about how your consumers would use it, before you implement it.\r\n\r\n> The most important thing is to have great documentation. Make things easy for your consumers, so that it saves your own time. The more consumers can do on their own, the less work there is for you. \r\n\r\nWhenever you have a discussion or review meeting, put the requirements of the consumer first. \r\n\r\n### Use A Contract First Approach\r\n\r\nWhat is a contract? \r\n\r\nThe creator of the web service is considered as the **service provider**. The application the consumes the web service is the **service consumer**. \r\n\r\nA **contract** is an agreement between a service provider and a service consumer about a service.\r\n\r\n![image info](images/Capture-098-03.png)\r\n\r\nIn order the utilize the service well, the service consumer needs to understand the contract fully. A contract includes details of many aspects of the service, such as:\r\n* How to call the web service?\r\n* What transport is being used?\r\n* What are the request and response structures?\r\n\r\nThis is also called the **service definition**. \r\n\r\nIn a **contract first** approach, you define the service contract first, and only then implement the service. \r\n\r\n#### Contract First With WSDL\r\n\r\nFor example, when you define SOAP web services, you use WSDL to define the contract.\r\n\r\n![image info](images/Capture-098-04.png)\r\n\r\nWSDL defines what are the service endpoints, the operations that you are exposing, and the request and response structures. \r\n\r\n#### Contract First With Swagger/Open API\r\n\r\nWhen you use RESTful web services, Swagger is a popular tool used to document your web services.\r\n\r\n![image info](images/Capture-098-05.png)\r\n\r\n![image info](images/Capture-098-06.png)\r\n\r\nSwagger allows you to define what are the resources you are exposing as part of your API. It includes the details of each operation, such as whether it consumes XML, JSON or both. The schema of the responses is also present there.\r\n\r\n![image info](images/Capture-098-07.png)\r\n\r\nIt also gives the details of the response codes it supports. You can also see that this particular resource, ```/jpa/users```:\r\n\r\n![image info](images/Capture-098-08.png)\r\n\r\nsupports a GET operation. In fact also supports a POST operation:\r\n\r\n![image info](images/Capture-098-09.png)\r\n\r\nThe response schema if this resource is seen to be:\r\n\r\n![image info](images/Capture-098-10.png)\r\n\r\nThe definition of User is present in the Swagger contract as:\r\n\r\n![image info](images/Capture-098-11.png)\r\n\r\nIt includes a ```birthDate```, an ```id```, a ```name``` and an array of ```posts```. Some fields also include a ```description``` field within them.  \r\n\r\nIn a contract first approach, you create such a Swagger definition, either by hand or by using an application, before the service is implemented. \r\n\r\n#### Advantages Of A Contract First Approach\r\n\r\nBy using a contract first approach, you are thinking about your consumers, and how they can use the service. You are initially not worrying about the implementation details. \r\n\r\nIf you give importance to the implementation early on, then technical details creedp into your service definition. \r\n\r\nYou need your service definition to be independent of the platform being used, be it Java, .NET or whatever.\r\n\r\n\r\n\r\n### Define Organizational Standards For REST API\r\n\r\nAn important reference for your organizational standards is YARAS. \r\n\r\n![image info](images/Capture-098-12.png)\r\n\r\n**YARAS** stands for **Yet Another RESTful API Standard**. YARAS provides standards, guidelines and conventions to be followed while developing RESTful web services. It defines tips for things such as:\r\n* How you should name your services?\r\n* How you should structure your request and response?\r\n* How you should implement filtering, sorting, paging and other actions?\r\n* How you should approach versioning?\r\n* How you need to approach API documentation?\r\n\r\n#### Have A Single Approach To Design Services\r\n\r\nWith RESTful web services , you need to address a lot of complex issues before you start designing them. All the things listed above need to be figured out. \r\n\r\nAs an organization, you don't want teams that handle different resources, to approach things differently. \r\n\r\nFor example, it is not good to have Team-A adopt request parameter based versioning, and Team-B to use URI based versioning. \r\n\r\nTherefore, it is important you have a clearly defined organizational standards to approach RESTful services. \r\n\r\n#### Customizing YARAS To Organizational Needs\r\n\r\nThe good thing about YARAS is, it can be customized to meet the needs specific to an organization. For example, you can \r\n* Customize what the request and response bodies need to look like\r\n* Choose a specific kind of versioning system\r\n\r\nSince YARAS is quite comprehensive in its coverage, you can be sure you haven't missed out on any important decision.\r\n\r\n### Build A Standard Organization wide REST API Framework\r\n\r\nThe typical frameworks that are used to build RESTful web services in the Java world, are Spring MVC, Spring REST and JAX-RS. \r\n\r\nIf you build a organization specific framework/archetype/reference application adhering to the common organization standards on top of your preferred REST API framework, it would make it easy for teams to adhere to your standards. \r\n\r\nTypical features include:\r\n* Request and response structures\r\n* Error handling\r\n* Filtering\r\n* Searching\r\n* Versioning\r\n* Support for mock responses\r\n* HATEOAS\r\n\r\nA standard framework ensures a standard way of approaching service design and implementation across the organization. \r\n\r\n### Have Decentralized Governance Of REST APIs\r\nCreate an expert group of representatives from teams building REST API and form a governance team. The team is responsible for \r\n* Improving REST API standards \r\n* Building/Designing your REST API Frameworks\r\n\r\n### Make Great Use Of HTTP\r\n\r\nWhenever you think RESTful web services, think HTTP.\r\n\r\nHTTP has all the features that support you to build great web services. \r\n\r\n#### Use Proper HTTP Request Methods\r\n\r\nThink about the HTTP request methods that you need to make use of. When you think of implementing any operation, identify the resource on which it is to be performed, and then seek out the relevant HTTP request method. Are you retrieving a detail, creating something, updating something that exists, or deleting a thing that exists? \r\n\r\nUse \r\n* GET for retrieving \r\n* POST for creating\r\n* PUT for updating\r\n* DELETE for deleting\r\n* PATCH for partial updates\r\n\r\n#### Use Appropriate HTTP Response Status\r\n\r\nWhen you implement an operation, make sure you return the correct response status. \r\n\r\nFor example, when a particular resource is not found, don't throw a server exception, Instead, send out the appropriate response code in the response message, such as ```404```. \r\n\r\nWhen there is actually a server exception, send back a ```500``` code. \r\n\r\nWhen there is a validation error, send the code for a bad request. \r\n\r\n### Focus On Representation\r\n\r\nEach resource can have multiple representations - XML or JSON format. Service consumer can choose the representation of their choice.\r\n\r\nThe service returns three users when we submit a GET request to it. In this case, we receive the JSON representation of the resource ```/users```.\r\n\r\n![image info](images/Capture-098-14.png)\r\n\r\n When consumer does not specify a preferred representation, we use JSON.\r\n\r\n![image info](images/Capture-098-15.png)\r\n\r\n![image info](images/Capture-098-16.png)\r\n\r\nConsumer can send an Accept header specify the representation.\r\n\r\n![image info](images/Capture-098-17.png)\r\n\r\nThe response body now has XML content:\r\n\r\n![image info](images/Capture-098-18.png)\r\n\r\n### Use Plurals\r\n\r\nAlways use plurals when you name resources. \r\n\r\nLet's look at a simple example. Suppose we have a service that hosts a ```users``` resource. The following describe to consumers how to access them:\r\n\r\n* Create a user: ```POST /users```\r\n* Delete a user: ```DELETE /users/1```\r\n* Get all users: ```GET /users```\r\n* Get one user: ```GET /users/1```\r\n\r\nPrefering a plural ```users``` to ```user``` makes URI more readable.\r\n- For example, If we use ```/user``` instead of ```/users``` for the retreive - ```GET /user``` - does not convey the right message to the reader. \r\n\r\n### Have Great Documentation\r\n\r\nConsumers need to understand how to make best use of the service, and and the best way to help them is by creating great documentation.\r\n\r\nSOAP web services can utilize the functionality of WSDL, while RESTful web services have options of Swagger (now Open API Documentation Standard). \r\n\r\nChoosing the format is just one part of generating good documentation. What also matters is putting in the right amount of information to be of assistance to the consumer. \r\n\r\nThe documentation needs to be complete, and should cover the following points: \r\n* What are the Request and Response Structures?\r\n* How the consumer needs to authenticate himself?\r\n* What are the usage limits?\r\n* Specify all the response message types, and the related status codes, that can be expected out of the service\r\n\r\n#### Have A Common REST API Documentation Portal\r\n\r\nA beneficial thing to do would be to have a common REST API documentation portal, across the organization. Have a look at one such portal:\r\n\r\n![image info](images/Capture-098-19.png)\r\n\r\nSuch a portal consolidates all the resources present in the organization. Having a user interface such as Swagger UI would have its added benefits. Using Swagger UI, you can actually look at the documentation in more detail:\r\n\r\n![image info](images/Capture-098-21.png)\r\n\r\nThis is usable even by non-technical users. The information seen here includes:\r\n\r\n* The expected response format\r\n* The content type\r\n* The response codes supported\r\n\r\nToy can also try out the format of the documentation, in a live request/response pair.\r\n\r\n### Support Versioning\r\n\r\nVersioning brings in a lot of complexity for a web service. Maintaining several differing versions of the same web service is a pain. Try avoiding it, when possible.\r\n\r\nHowever, in certain scenarios, versioning is unavoidable.\r\n\r\nLet us start off by looking at an example service. Suppose we have initially defined a service to have a class named ```PersonV1```, in this manner:\r\n\r\n```java\r\n\r\n\tpublic class PersonV1 {\r\n\t\tprivate String name;\r\n\r\n\t\tpublic PersonV1() {\r\n\t\t\tsuper();\r\n\t\t}\r\n\r\n\t\tpublic PersonV1(String name) {\r\n\t\t\tsuper();\r\n\t\t\tthis.name = name;\r\n\t\t}\r\n\r\n\t\tpublic String getName() {\r\n\t\t\treturn this.name;\r\n\t\t}\r\n\r\n\t\tpublic setName(String name) {\r\n\t\t\tthis.name = name;\r\n\t\t}\r\n\t}\r\n\r\n``` \r\n\r\nThis version of the class does not take into account that a name could have many sub-parts, such as first name and last name. Have a look a this:\r\n\r\n```java \r\n\r\n\t\tpublic class Name {\r\n\t\t\tprivate String firstName;\r\n\t\t\tprivate String lastName;\r\n\r\n\t\t\tpublic Name() {\r\n\t\t\t}\r\n\r\n\t\t\tpublic Name(String firstName, String lastName) {\r\n\t\t\t\tthis.firstName = firstName;\r\n\t\t\t\tthi.lastName = lastName;\r\n\t\t\t}\r\n\r\n\t\t\tpublic String getFirstName() {\r\n\t\t\t\treturn this.firstName;\r\n\t\t\t}\r\n\r\n\t\t\tpublic String getLastName() {\r\n\t\t\t\treturn this.lastName;\r\n\t\t\t}\r\n\t\t}\r\n\r\n``` \r\n\r\nThe second version of the original class was updated to correct this anomaly:\r\n\r\n```java\r\n\r\n\tpublic class PersonV2 {\r\n\t\tprivate Name name;\r\n\r\n\t\tpublic PersonV1() {\r\n\t\t\tsuper();\r\n\t\t}\r\n\r\n\t\tpublic PersonV1(Name name) {\r\n\t\t\tsuper();\r\n\t\t\tthis.name = name;\r\n\t\t}\r\n\r\n\t\tpublic String getName() {\r\n\t\t\treturn this.name.getFirstName() + \" \" + this.name.getLastName();\r\n\t\t}\r\n\r\n\t\tpublic setName(Name name) {\r\n\t\t\tthis.name = name;\r\n\t\t}\r\n\t}\t\r\n\r\n```\r\n\r\nWe cannot migrate the entire service to use ```PersonV2```, immediately! There might be other consumers who are expecting responses in the format of ```PersonV1```. \r\n\r\nThis is where versioning is needed. \r\n\r\nLet us now look at the options we have to version these two resources.\r\n\r\n#### Use Different URIs \r\n\r\nOne option that we have is to use different URIs for these different resources. In the exampel code below, we use the URIs ```v1/person``` and ```v2/person``` to differentiate them:\r\n\r\n```java\r\n\r\n\t@RestController\r\n\tpublic class PersonVersioningController {\r\n\r\n\t\t@GetMapping(\"v1/person\")\r\n\t\tpublic PersonV1 personV1() {\r\n\t\t\treturn new PersonV1(\"Bob Charlie\");\r\n\t\t}\r\n\r\n\t\t@GetMapping(\"v2/person\")\r\n\t\tpublic PersonV2 personV2() {\r\n\t\t\treturn new PersonV2(new Name(\"Bob\", \"Charlie\"));\r\n\t\t}\r\n\t}\r\n\r\n``` \r\n\r\nIf you execute a GET request for the resource ```v1/person```:\r\n\r\n![image info](images/Capture-098-22.png)\r\n\r\nYou will get the information corresponding to ```v1```. For the other resource:\r\n\r\n![image info](images/Capture-098-23.png)\r\n\r\n### Use A Request Parameter\r\n\r\nThe second versioning method uses a request parameter:\r\n\r\n```java\r\n\r\n\t@RestController\r\n\tpublic class PersonVersioningController {\r\n\r\n\t\t@GetMapping(value=\"/person/param\" params=\"version=1\")\r\n\t\tpublic PersonV1 personV1() {\r\n\t\t\treturn new PersonV1(\"Bob Charlie\");\r\n\t\t}\r\n\r\n\t\t@GetMapping(value=\"/person/param\" params=\"version=2\")\r\n\t\tpublic PersonV2 personV2() {\r\n\t\t\treturn new PersonV2(new Name(\"Bob\", \"Charlie\"));\r\n\t\t}\r\n\t}\r\n\r\n``` \r\n\r\nTo the URI ```/person/param```, if we send a parameter with ```version=1```, then we return the resource of type ```PersonV1```: \r\n\r\n![image info](images/Capture-098-24.png)\r\n\r\nFor the same URI, a parameter with ```version=2``` returns a resource of type ```PersonV2```:\r\n\r\n![image info](images/Capture-098-25.png)\r\n\r\nThis method is called **request parameter versioning**. \r\n\r\n### Use A Header\r\n\r\nAnother way you can do versioning is by specifying a header. \r\n\r\n```java\r\n\r\n\t@RestController\r\n\tpublic class PersonVersioningController {\r\n\r\n\t\t@GetMapping(value=\"/person/header\" headers=\"X-API-VERSION=1\")\r\n\t\tpublic PersonV1 personV1() {\r\n\t\t\treturn new PersonV1(\"Bob Charlie\");\r\n\t\t}\r\n\r\n\t\t@GetMapping(value=\"/person/header\" headers=\"X-API-VERSION=1\")\r\n\t\tpublic PersonV2 personV2() {\r\n\t\t\treturn new PersonV2(new Name(\"Bob\", \"Charlie\"));\r\n\t\t}\r\n\t}\r\n\r\n``` \r\n\r\nHere, we use a header named ```X-API-VERSION```, and have labeled the URI as ```/person/header```. When the header value is ```1```, the resource of type ```PersonV1``` is returned: \r\n\r\n![image info](images/Capture-098-26.png)\r\n\r\nWhen its value is ```2```,  a resource of type ```PersonV2``` is retrieved:\r\n\r\n![image info](images/Capture-098-27.png)\r\n\r\nWe are using an attribute on a request header, to perform the versioning for us. \r\n\r\n### Use The Accept Header\r\n\r\nThe last method for achieving versioning makes use of the Accept header.  \r\n\r\n```java\r\n\r\n\t@RestController\r\n\tpublic class PersonVersioningController {\r\n\r\n\t\t@GetMapping(value=\"/person/produces\" produces=\"application/vnd.company.app-v1+json\")\r\n\t\tpublic PersonV1 personV1() {\r\n\t\t\treturn new PersonV1(\"Bob Charlie\");\r\n\t\t}\r\n\r\n\t\t@GetMapping(value=\"/person/produces\" produces=\"application/vnd.company.app-v2+json\")\r\n\t\tpublic PersonV2 personV2() {\r\n\t\t\treturn new PersonV2(new Name(\"Bob\", \"Charlie\"));\r\n\t\t}\r\n\t}\r\n\r\n``` \r\n\r\nIf the consumer includes the first versioning information in the Accept header of the GET request, the following resource comes back:\r\n\r\n![image info](images/Capture-098-28.png)\r\n\r\nOtherwise, the resource of type ```PersonV2``` is returned: \r\n\r\n![image info](images/Capture-098-29.png)\r\n\r\nThis is called **Accept Header Versioning**, or **Media Type Versioning**, because mime types are the usually the contents of an Accept header.  \r\n\r\n### Comparing The Versioning Techniques\r\n\r\nWe have so far seen four types of versioning techniques:\r\n\r\n* URI versioning\r\n* Request Param versioning\r\n* Header versioning\r\n* Media Type versioning\r\n\r\nWhich of these is the best one? \r\n\r\nThe truth is, there is no single answer to this question. \r\n\r\nThe fact of the matter is that different types of versioning are patronized by different internet giants. \r\n* URI versioning -  Twitter\r\n* Request Param versioning - Amazon\r\n* Header Parameter versioning - Microsoft\r\n* Media Type versioning - GitHub\r\n\r\nYou need to evaluate these four choices, accroding to your specific needs. There are a number of important factors to consider:\r\n* **URI Pollution** : With URI versioning and request parameter versioning, we end up polluting the URI space. This is because we add prefixes and suffixes to the core URI strings. Header versioning avoids that.\r\n* **Misuse Of HTTP Headers**: In the case of Header versioning and Media Type versioning, there is a misuse of HTTP headers, since they were not originally meant for versioning.\r\n* **Caching**: A resource is defined by its URI. However, if you are not using the URI to determine its version, but using a header-based mechanism, the versioning information cannot be cached. If HTTP caching is important to you, use the URI or Request Parameter versioning. \r\n* **Browser Request Executability**: Both Header and Media Type versioning need the use of tools such as Postman to execute the browser request. However, if the consumers of the service are not technically well versed, then URI or Request Parameter versioning would be preferable. \r\n* **API Documentation**: You also need to think about how you want to document your APIs. The URI and Request Parameter versioning are easier to document than the other two versioning types. \r\n\r\nRealize that there is no single perfect solution!   \r\n\r\n### Think About Error Handling\r\n\r\nWhen a consumer sends a request to a service, it is important that he gets the right response.  Whenever something goes wrong, it is important to send an appropriate response.\r\n\r\n#### When Consumer Requests a Non Existing Resource\r\n\r\nIf we send a GET request to search for an existing user, we get the following response:\r\n\r\n![image info](images/Capture-098-30.png)\r\n\r\nIf you search for a non-existent user:\r\n\r\n![image info](images/Capture-098-31.png)\r\n\r\nWhat you get back is a status of ```404 Not Found```. This is good error handling, because it correctly identifies that the resource is not found, and does not return a Server Error.\r\n\r\nLet's now send a GET request to a non-existent URI:\r\n\r\n![image info](images/Capture-098-32.png)\r\n\r\nYou can see that you get a ```404 Not Found```. A wrong URL indicates a non-existent resource. \r\n\r\n#### A Look At Important Response Statuses\r\n\r\n* 200 - Success\r\n* 404 - Resource Not Found\r\n* 400 - Bad Request (such as validation error)\r\n* 201 - Created\r\n* 401 - Unauthorized (when authorization fails)\r\n* 500 - Server Error\r\n\r\n#### Error Details In Response Body\r\n\r\nIt helps if you have a standard exception structure when designing your service. \r\n\r\n![image info](images/Capture-098-33.png)\r\n\r\nFor specific errors, specific response structures can be returned to the consumer, and this can be a standard across the organization. Make sure that the error response is also readable to the consumers, without confusion. \r\n\r\n### USe Swagger or Open API Documentation\r\n\r\nSwagger is one of the most popular documentation formats for RESTful web services. It is today supported by a wide variety of organizations, and used in a large number of services. We look at two main aspects of Swagger here:\r\n\r\n* The Swagger documentation format\r\n* Swagger UI, which enables you to look at the Swagger documentation in a visually pleasing manner\r\n\r\n#### Swagger Documentation\r\n\r\nHave a look at the following Swagger JSON:\r\n\r\n![image info](images/Capture-098-34.png)\r\n\r\nAt a high level, it looks very similar to a WSDL definition. it has several important attributes:\r\n\r\n* ```host``` : Where the service is hosted\r\n* ```basePath```: The path where the service is hosted\r\n* ```consumes```: What kinds of requests are accepted\r\n\r\n![image info](images/Capture-098-36.png)\r\n\r\n* ```produces```: What kinds of responses are generated\r\n\r\n![image info](images/Capture-098-37.png)\r\n\r\n* ```paths```\" the different resources present\r\nIn this case, you have several types of resources listed:\r\n\r\n![image info](images/Capture-098-35.png)\r\n\r\nWhen you look at the Swagger documentation, you can quickly determine the resources that are present, the operations that are supported, and the operations that are relevant for each resource:\r\n\r\n![image info](images/Capture-098-38.png)\r\n\r\nThe resource ```/users``` supports both ```GET``` and ```POST``` operations. For ```GET```, you can see the supported request and response types. You also see the different response types it has:\r\n\r\n![image info](images/Capture-098-39.png)\r\n\r\nNotice that for a ```200``` response, a schema is also mentioned, as an array of ```User```. ```User``` is part of the ```definitions``` section at the bottom of the document:  \r\n\r\n![image info](images/Capture-098-40.png)\r\n\r\nSwagger is completely independent of the technology you use to implement your RESTful web service. It is all basic JSON at work. \r\n\r\n#### Introducing Swagger UI\r\n\r\nSwagger is a great UI tool that is useful to visualize Swagger documentation for a RESTful web service. Have a look at the screen grab below:\r\n\r\n![image info](images/Capture-098-41.png)\r\n\r\nNote that we have chosen a particular version of a web service to view its documentation. Here is the same screen in better detail:   \r\n\r\n![image info](images/Capture-098-42.png)\r\n\r\nWhen we come to the homepage, it describes the resources that are listed:\r\n\r\n![image info](images/Capture-098-43.png)\r\n\r\nAlso, the set of operations supported for the resource URLs can be seen:\r\n\r\n![image info](images/Capture-098-44.png)\r\n\r\nWhen you click on the GET operation of a particular resource, you get its details:\r\n\r\n![image info](images/Capture-098-45.png)\r\n\r\nYou can see the Model Schema is described visually. The attributes ```birthDate```, ```id```, ```links```, ```name``` and ```posts``` are also shown. You can also execute a sample request, and view the response:\r\n\r\n![image info](images/Capture-098-46.png)\r\n\r\n#### Using Swagger (Open API Standard) Tools\r\n\r\nThe great thing about Swagger is there are a lot of tools available around it. Have a look at the following service which we had used earlier, to explain versioning:\r\n\r\n```java\r\n\r\n\t@RestController\r\n\tpublic class PersonVersioningController {\r\n\r\n\t\t@GetMapping(\"v1/person\")\r\n\t\tpublic PersonV1 personV1() {\r\n\t\t\treturn new PersonV1(\"Bob Charlie\");\r\n\t\t}\r\n\r\n\t\t@GetMapping(\"v2/person\")\r\n\t\tpublic PersonV2 personV2() {\r\n\t\t\treturn new PersonV2(new Name(\"Bob\", \"Charlie\"));\r\n\t\t}\r\n\r\n\t\t@GetMapping(value=\"/person/param\" params=\"version=1\")\r\n\t\tpublic PersonV1 personV1() {\r\n\t\t\treturn new PersonV1(\"Bob Charlie\");\r\n\t\t}\r\n\r\n\t\t@GetMapping(value=\"/person/param\" params=\"version=2\")\r\n\t\tpublic PersonV2 personV2() {\r\n\t\t\treturn new PersonV2(new Name(\"Bob\", \"Charlie\"));\r\n\t\t}\r\n\r\n\t\t@GetMapping(value=\"/person/header\" headers=\"X-API-VERSION=1\")\r\n\t\tpublic PersonV1 personV1() {\r\n\t\t\treturn new PersonV1(\"Bob Charlie\");\r\n\t\t}\r\n\r\n\t\t@GetMapping(value=\"/person/header\" headers=\"X-API-VERSION=1\")\r\n\t\tpublic PersonV2 personV2() {\r\n\t\t\treturn new PersonV2(new Name(\"Bob\", \"Charlie\"));\r\n\t\t}\r\n\r\n\t\t@GetMapping(value=\"/person/produces\" produces=\"application/vnd.company.app-v1+json\")\r\n\t\tpublic PersonV1 personV1() {\r\n\t\t\treturn new PersonV1(\"Bob Charlie\");\r\n\t\t}\r\n\r\n\t\t@GetMapping(value=\"/person/produces\" produces=\"application/vnd.company.app-v2+json\")\r\n\t\tpublic PersonV2 personV2() {\r\n\t\t\treturn new PersonV2(new Name(\"Bob\", \"Charlie\"));\r\n\t\t}\r\n\r\n\t}\r\n\r\n```  \r\n\r\nHere's a look at the automatically generated documentation for this service: \r\n\r\n![image info](images/Capture-098-47.png)\r\n\r\nThere is support in Swagger for both a contract-first approach, and a code-first approach.   \r\n\r\nDo check out our video on the same topic:\r\n\r\n[![image info](images/Capture-098-01.png)](https://www.youtube.com/watch?v=NzgFdEGI8sI)\r\n\r\n### Summary\r\n\r\nIn this article, we had a look at best practices for building and designing RESTful web services."
  },
  {
    "path": "_blog/articles/2019-11-15-Software-Design-Principles-005-SingleResponsibilityPrinciple.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Software Design - Single Responsibility Principle - with examples\r\ndate:    2019-11-14 12:31:19\r\nsummary: For me, Single Responsibility Principle is the most important design principle. What is Single Responsibility Principle? How do you use it? How does it help with making your software better? Let's get started.\r\ncategories: SwDesign\r\npermalink:  /software-design-single-responsibility-principle\r\nimage: /images/design-category.png\r\n---\r\n\r\nFor me, Single Responsibility Principle (SRP) is the most important design principle. \r\n\r\nWhat is Single Responsibility Principle? How do you use it? How does it help with making your software better? Let's get started.\r\n\r\n\r\n### What will you learn?\r\n* What is the Single Responsibility Principle?\r\n* How do you apply this principle in developing and designing software applications?\r\n\r\n### Software Design Principles\r\n\r\nThis is the fourth article in a series of articles on important Software Design Principles:\r\n\r\n- [1 - Introduction to Four Principles Of Simple Design](/four-principles-of-simple-design){:target='_blank'}\r\n- [2 - Software Design - Separation Of Concerns - with examples](/software-design-seperation-of-concerns-with-examples){:target='_blank'}\r\n- [3 - Object Oriented Software Design - Solid Principles - with examples](/software-design-solid-principles){:target='_blank'}\r\n- [4 - Software Design - Single Responsibility Principle - with examples](/software-design-single-responsibility-principle){:target='_blank'}\r\n- [5 - Software Design - Open Closed Principle - with examples](/software-design-open-closed-principle){:target='_blank'}\r\n- [6 - Software Design - What is Dependency Inversion Principle?](/software-design-dependency-inversion-principle){:target='_blank'}\r\n\r\n\r\n## What Is The Single Responsibility Principle (SRP)?\r\n\r\nAs the term says, this principle is all about having single responsibility. \r\n\r\nIn any software system, this principle is applicable at multiple levels \r\n- a variable\r\n- a method\r\n- a class\r\n- a package\r\n- a component\r\n- application layers or \r\n- the entire application itself\r\n\r\n## SRP For Methods\r\n\r\nAny method that you write should have a single responsibility -  it should either be a high-level method, or a low-level one. Only when a method has a single responsibility, you will be able to give it an appropriate name.\r\n\r\n## SRP For Classes\r\n\r\n> \"A class should have one, and only one reason to change\"\r\n\r\nLet's now have a look at a few examples of classes that violate this principle, and then look at how to correct the violation.\r\n\r\n### Example 1: The ```Task``` class\r\n\r\n```java\r\n\r\n\tpublic class Task {\r\n\t\tpublic void downloadFile(Strign location) {\r\n\t\t\t//...\r\n\t\t}\r\n\r\n\t\tpublic void parseTheFile(File file) {\r\n\t\t\t//...\r\n\t\t}\r\n\r\n\t\tpublic void persistTheData(Data data) {\r\n\t\t\t//...\r\n\t\t}\r\n\t}\r\n\r\n```\r\n\r\nDoes the class ```Task``` adhere to the single responsibility principle? Not at all, because it does a lot of different things:\r\n\r\n* ```downloadFile()``` downloads the file, by communicating over the internet\r\n* ```parseTheFile()``` parses the file contents\r\n* ```persistTheData()``` saves the data into a database\r\n\r\nA better solution would be to have separate classes for each of the responsibilities currently taken up by ```Task```. Here is one such solution.\r\n\r\n#### Identifying The Low-level Classes\r\n\r\n```java\r\n\r\n\tpublic class FileDownloader {\r\n\t\tpublic void downloadFile() {\r\n\t\t\t//...\r\n\t\t}\r\n\t}\r\n\r\n\tpublic class DataParser {\r\n\t\tpublic void parseData() {\r\n\t\t\t//...\r\n\t\t}\r\n\t}\r\n\r\n\tpublic class DatabaseStorer {\r\n\t\tpublic void storeIntoDatabase() {\r\n\t\t\t//...\r\n\t\t}\r\n\t}\r\n\r\n```\r\n\r\n* ```FileDownloader``` only downloads the file from the internet\r\n* ```DataParser``` only parses the downloaded file\r\n* ```DatabaseStorer``` only stores the parsed data, into the database\r\n\r\nThese are all low-level classes here. \r\n\r\n#### Adding A High-Level Class\r\n\r\n```java\r\n\tpublic class DownloadAndStore {\r\n\t\tpublic void doEverything() {\r\n\t\t\tnew FileDownloader().downloadFile();\r\n\t\t\tnew DataParser().parseData();\r\n\t\t\tnew DatabaseStorer().storeIntoDatabase();\r\n\t\t}\r\n\t}\r\n\r\n```\r\n\r\nThen, you can create a high-level class such as ```DownloadAndStore``` that invokes the functionality of these low-level classes to perform the complete task. Such an organization ensures that the low-level classes are reusable. \r\n\r\n### Example 2: The Employee Class\r\n\r\nConsider next, the ```Employee``` class shown below:\r\n\r\n```java\r\n\r\n\tpublic class Employee {\r\n\t\tpublic Money calculatePay() {\r\n\t\t\t//...\r\n\t\t}\r\n\t\tpublic String reportHours() {\r\n\t\t\t//...\r\n\t\t}\r\n\t\tpublic void save() {\r\n\t\t\t//...\r\n\t\t}\r\n\t}\r\n\r\n```\r\n\r\n```Employee``` concerns itself with not just calculating the pay of an employee, but also reporting hours for work, and saving these details to the database. \r\n\r\nI will leave it as an exercise to fix the Employee class to adhere to SRP.\r\n\r\n## SRP For Components\r\n\r\nEvery enterprise application has parts of its functionality organized as Components. For example, have a look at the diagram below:\r\n\r\n![image info](/images/Capture-05-02.png)\r\n\r\nHere, the following components are of note:\r\n\r\n* Security component  takes care of user authentication and authorization. Designing such a component helps abstract applications from the low-level security details. All microservices can interact with this component to find out if a user has access. \r\n* The Logging component - does the low level logging functionality\r\n* The Archetype component - Can be used to create new microservices\r\n\r\nEach of these components have a single responsibility. If the Security component takes care of logging, it would become less reusable. Therefore, at the component level, a well-defined single responsibility is highly desirable.\r\n\r\n### Using SRP For Common Infrastructure\r\n\r\n![image info](/images/Capture-05-02.png)\r\n\r\nIn the diagram shown above, you can identify the following infrastructure components:\r\n\r\n* Naming Service - Has the responsibility to retrieve the service location based on its name\r\n* API Gateway - All requests go through the API Gateway. Common features like authentication, logging, rate limiting can be implemented in an API Gateway.\r\n* Centralized Logging - Centralized store for logs from all microservices so that we can easily debug problems\r\n\r\nEven with these sub-systems, a single responsibility for each of them is most desirable. \r\n\r\n### Using SRP For Application Layering\r\n\r\nSingle responsibility is also an important factor in how you layer your application. Have a look at the following conceptual layers in a web application: \r\n\r\n![image info](/images/Capture-05-03.png)\r\n\r\n* Web Layer: All functionality concerned with direct user interaction sits here\r\n* Business Layer: Houses the core business logic\r\n* Data layer: All the functionality dealing with storing and retrieving data goes here\r\n\r\nIf you had the need to talk to other systems, there would have been an additional Enterprise Messaging Layer added onto this setup.\r\n\r\n### Summary\r\n\r\nIn this article, we talked about the Single Responsibility Principle. It is applicable at multiple levels to the parts of an application. This includes methods, classes, packages, components and application layers. With regards to classes, at a low level it means a class has only one reason to change. \r\n\r\nIn general, **Single Responsibility ensures high cohesion, low coupling and enhanced reusability**.\r\n\r\nDo check out our video on this:\r\n\r\n[![image info](/images/Capture-05-01.png)](\thttps://www.youtube.com/watch?v=eympIQPQLx4) \r\n"
  },
  {
    "path": "_blog/articles/2019-11-15-Software-Design-Principles-009-PrinciplesOfSimpleDesign.md",
    "content": "---\r\nlayout:  post\r\ntitle: Introduction to Four Principles Of Simple Design\r\ndate:    2019-11-14 12:31:19\r\nsummary: With agile and extreme programming, the focus is on keeping your design simple. How do you keep your design simple? How do you decide whether your code is good enough?\r\ncategories: SwDesign\r\npermalink:  /four-principles-of-simple-design\r\nimage: /images/design-category.png\r\n---\r\n\r\nWith agile and extreme programming, the focus is on keeping your design simple. How do you keep your design simple? How do you decide whether your code is good enough?\r\n\r\n\r\n\r\n### Software Design Principles\r\n\r\nThis is the first article in a series of articles on important Software Design Principles:\r\n\r\n- [1 - Introduction to Four Principles Of Simple Design](/four-principles-of-simple-design){:target='_blank'}\r\n- [2 - Software Design - Separation Of Concerns - with examples](/software-design-seperation-of-concerns-with-examples){:target='_blank'}\r\n- [3 - Object Oriented Software Design - Solid Principles - with examples](/software-design-solid-principles){:target='_blank'}\r\n- [4 - Software Design - Single Responsibility Principle - with examples](/software-design-single-responsibility-principle){:target='_blank'}\r\n- [5 - Software Design - Open Closed Principle - with examples](/software-design-open-closed-principle){:target='_blank'}\r\n- [6 - Software Design - What is Dependency Inversion Principle?](/software-design-dependency-inversion-principle){:target='_blank'}\r\n\r\n\r\n### What is Simple Design?\r\n\r\nIt is very important to keep the design of your application simple. \r\n\r\nIn almost all agile projects, the aim is to meet today's requirements, with clean code. \r\n\r\n> You go for complex design, only when simple design does not solve your problem.\r\n\r\n### The Four Principles Of Simple Design\r\n\r\nA software application is said to have a simple design if it:\r\n* **Runs all tests**\r\n* **Contains no duplication**\r\n* **Expresses intent of programmers**\r\n* **Minimizes number of classes and methods**\r\n\r\nLet's now look at these aspects a little closely, by turn.\r\n\r\n#### Runs All Tests\r\n\r\nWe want to keep running all the tests continuously, because we want the code to work, at all times. \r\n\r\nAn important corollary of this principle is you need to have a large number of automation tests. All unit, integration and API tests must be automated. \r\n\r\nYou should launch these tests as part of your build, and they should also be a part of Continuous Integration (CI). \r\n\r\nWith CI, you commit code into the repository, all the tests are run, and immediate feedback is there for you to act on. \r\n\r\nSince the software is being tested all the time, it is stable.\r\n\r\n#### Contains No Duplication\r\n\r\nThe second principle stresses on the fact that your code should have as little duplication as possible. \r\n\r\nA good example is to create common components, whereever possible, in the design of large applications. This helps centralize the logic and allow other applications to reuse them.\r\n\r\nWhy do we hate duplication? \r\n\r\nIf there is a need for a change, the same change needs to repeated at all these locations. The result : More effort and also possibilities of more defects when you miss making the change in every location. That is a sign of bad design. \r\n\r\n#### Expresses Intent Of Programmers\r\n\r\nYour code should be easy to read, and your design, simple to understand. This principle is also called **Clarity Of Code**. \r\n\r\nHave a look at the following piece of code:\r\n\r\n##### Example-01 v1\r\n\r\n![image info](/images/Capture-09-01.png) \r\n\r\nDo you understand what it does? \r\n\r\nNow look at the following version of the same program: \r\n\r\n##### Example-01 v2\r\n\r\n![image info](/images/Capture-09-02.png)\r\n\r\nDo you understand what it's trying to do?\r\n\r\nActually, Example-01 v2 results from applying the Four Principles of Simple Design to Example-01 v1. \r\n\r\nStart with creating good names for variables, methods and classes. That improves clarity.\r\n\r\n#### Minimize number of classes and methods\r\n\r\nYou should have \r\n* Small methods\r\n* Small classes\r\n* Minimum number classes and methods\r\n\r\nIsn't it simple.\r\n\r\nLesser code you have, lesser code you have to maintain.\r\n\r\nAlways aim to keep things simple.\r\n\r\nDo check out our video on this:\r\n\r\n[![image info](/images/Capture-09-03.png)](https://www.youtube.com/watch?v=jQIJkzCmUvo)   \r\n\r\n### Summary\r\n\r\nIn this article, we looked at the four principles of simple design. These are the first steps to ensure that the design of your application remains simple. It lays the foundation for applying more advanced principles to improving your design.\r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-11-15-Software-Design-Principles-015-Dependency-Inversion-Principle.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Software Design - What is Dependency Inversion Principle?\r\ndate:    2019-11-14 12:31:19\r\nsummary: Dependency Inversion Principle is one of the important SOLID Principles. Dependency Inversion Principle is implemented by one of the most popular Java frameworks - Spring. What is it all about? How does it help you design good applications?\r\ncategories: SwDesign\r\npermalink:  /software-design-dependency-inversion-principle\r\nimage: /images/design-category.png\r\n---\r\n\r\nDependency Inversion Principle is one of the important SOLID Principles. Dependency Inversion Principle is implemented by one of the most popular Java frameworks - Spring. What is it all about? How does it help you design good applications?\r\n\r\n### You will Learn\r\n- What is Dependency Inversion Principle?\r\n- How are Dependency Inversion Principle and Spring Framework related?\r\n- A few examples of Dependency Inversion Principle in action\r\n\r\n\r\n### Software Design Principles\r\n\r\nThis is the last article in a series of articles on important Software Design Principles:\r\n\r\n- [1 - Introduction to Four Principles Of Simple Design](/four-principles-of-simple-design){:target='_blank'}\r\n- [2 - Software Design - Separation Of Concerns - with examples](/software-design-seperation-of-concerns-with-examples){:target='_blank'}\r\n- [3 - Object Oriented Software Design - Solid Principles - with examples](/software-design-solid-principles){:target='_blank'}\r\n- [4 - Software Design - Single Responsibility Principle - with examples](/software-design-single-responsibility-principle){:target='_blank'}\r\n- [5 - Software Design - Open Closed Principle - with examples](/software-design-open-closed-principle){:target='_blank'}\r\n- [6 - Software Design - What is Dependency Inversion Principle?](/software-design-dependency-inversion-principle){:target='_blank'}\r\n\r\n\r\n### What Is Dependency Inversion principle (DIP)?\r\n\r\n> \"Depend Upon Abstractions (interfaces), not Implementations (concrete classes)\"\r\n\r\nWhat does this statement mean? Let's try understanding that with an example:\r\n\r\nLet's look at an example of what this means:\r\n\r\n```\r\n\r\nabstract class OutputDevice {\r\n\tvoid copy(String device) {\r\n\t\tKeyboard keyboard = new Keyboard();\r\n\t\tint character;\r\n\t\twhile ((character = keyboard.read()) != -1) {\r\n\t\t\tif (device.equals(\"Printer\")) {\r\n\t\t\t\twriteToPrinter(character);\r\n\t\t\t} else {\r\n\t\t\t\twriteToDevice(character);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tprivate void writeToDevice(int character) {\r\n\t\t// TODO Auto-generated method stub\r\n\t\t\r\n\t}\r\n\r\n\tprivate void writeToPrinter(int c) {\r\n\t\t// TODO Auto-generated method stub\r\n\t\t\r\n\t}\r\n}\r\n\r\n\r\n```\r\n\r\nWhat does the ```copy()``` method do?\r\n\r\nIt reads a character from the keyboard, and then decides where this character needs to go. If it's a printer, write to the printer. Else, send it to the disk.  \r\n\r\nThe problem here is that as the number of ```OutputDevice``` types increase, the logic of ```copy()``` needs to change every single time. \r\n\r\nLet's look at an alternate implementation:\r\n\r\n```\r\n\r\n\tpublic interface Reader {\r\n\t\tpublic char read();\r\n\t}\r\n\r\n\tpublic interface Writer {\r\n\t\tpublic void write(char ch);\r\n\t}\r\n\r\n\tvoid copy(Reader r, Writer w) {\r\n\t\tint c;\r\n\r\n\t\twhile((c = r.read()) != EOF) {\r\n\t\t\tw.write(c);\r\n\t\t}\r\n\t}\r\n\r\n```\r\n\r\nWhat we have done here is define two separate interfaces, one to provide the ```read()```, and the other to define the ```write()``` methods. \r\n\r\nThe responsibility of the ```copy()``` method is quite clear here: it reads from the ```Reader``` ```interface```, and writes whatever it gets to the ```Writer``` ```interface```. \r\n\r\n```copy()``` now focuses only on the actual operation, and it does so by identifying everything else as its dependencies. \r\n\r\nIt can now work with any implementation of ```Reader``` and ```Writer``` interfaces.\r\n\r\n### DIP and The Spring Framework\r\n\r\nDIP is one of the core principles that the Spring Framework enables. Have a look at this example:\r\n\r\n```java\r\n\r\n\tpublic class BinarySearchImpl {\r\n\t\tpublic int binarySearch(int[] numbers, int numberToSearchFor) {\r\n\t\t\tBubbleSortAlgorithm bubbleSortAlgorthm = new BubbleSortAlgorithm();\r\n\t\t\tint[] sortedNumbers = bubbleSortAlgorithm.sort(numbers);\r\n\r\n\t\t\t//...\r\n\t\t}\r\n\t}\r\n\r\n```\r\n\r\n```BinarySearchImpl``` directly creates an instance of the ```BubbleSortAlgorithm```. Note that ```BubbleSortAlgorithm``` is a dependency of ```BinarySearchImpl```, and as we saw in our previous example, directly accessing it is not a great idea. If you want to switch from a bubble-sort to a quicksort algorithm later, you need to change quite a lot of code inside ```BinarySearchImpl```. \r\n\r\nBetter Approach for ```BinarySearchImpl``` is to make use of an interface - sort algorithm. Here is how our modified code would look like:\r\n\r\n```java\r\n\r\n\tpublic intrface SortAlgorithm {\r\n\t\tpublic int[] sort(int[] numbers);\r\n\t}\r\n\r\n\t@Component\r\n\tpublic class BinarySearchImpl {\r\n\t\t@Autowired\r\n\t\tprivate SortAlgorithm sortAlgorithm;\r\n\r\n\t\tpublic BinarySearchImpl(SortAlgorithm sortAlgorithm) {\r\n\t\t\tsuper();\r\n\t\t\tthis.sortAlgorithm = sortAlgorithm;\r\n\t\t}\r\n\r\n\t\tpublic int[] binarySearch(int[] numbers, int numberToSearchFor) {\r\n\t\t\tint[] sortedNumbers = sortAlgorithm.sort(numbers);\r\n\t\t\t//...\r\n\t\t}\r\n\t}\r\n\r\n```\r\n\r\nUser of the ```BinarySearchImpl``` class, can also pass in a specific implementation of ```SortAlgorithm```, such as a bubble-sort or a quick-sort implementation. \r\n\r\n> ```BinarySearchImpl``` is **decoupled** from which ```SortAlgorithm``` to use.\r\n\r\n> If you use the Spring framework, you could use the ```@Autowired``` annotation with the ```BinarySearchImpl``` class, to automatically auto wire an implementation of an available sort algorithm.\r\n\r\n> By applying the DIP, you make your code more testable. The test code could pass in dependency mocks to properly test the code. \r\n\r\nDo check out our video on this:\r\n\r\n[![image info](/images/Capture-015-01.png)](https://www.youtube.com/watch?v=PdQ4xAUGitk)   \r\n\r\n### Summary\r\n\r\nDependency Inversion is about identifying dependencies and externalizing them. You can use a framework like Spring to simplify Dependency Inversion. DIP makes your code more maintainable, reusable and testable.\r\n\r\n"
  },
  {
    "path": "_blog/articles/2019-11-15-Software-Design-Principles-017-Open-Closed-Principle.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Software Design - Open Closed Principle - with examples\r\ndate:    2019-11-14 12:31:19\r\nsummary: Open Closed Principle is one of the SOLID Principles. You want your code to be easily extended. How do you achieve it with minimum fuss? Let's get started.\r\ncategories: SwDesign\r\npermalink:  /software-design-open-closed-principle\r\nimage: /images/design-category.png\r\n---\r\n\r\nOpen Closed Principle is one of the SOLID Principles. You want your code to be extensible. How do you achieve it with minimum fuss? Let's get started.\r\n\r\n### What will you learn?\r\n* What is the Open Closed Principle?\r\n* How do you apply this principle in developing and designing software applications?\r\n\r\n\r\n### Software Design Principles\r\n\r\nThis is the fifth article in a series of articles on important Software Design Principles:\r\n\r\n- [1 - Introduction to Four Principles Of Simple Design](/four-principles-of-simple-design){:target='_blank'}\r\n- [2 - Software Design - Separation Of Concerns - with examples](/software-design-seperation-of-concerns-with-examples){:target='_blank'}\r\n- [3 - Object Oriented Software Design - Solid Principles - with examples](/software-design-solid-principles){:target='_blank'}\r\n- [4 - Software Design - Single Responsibility Principle - with examples](/software-design-single-responsibility-principle){:target='_blank'}\r\n- [5 - Software Design - Open Closed Principle - with examples](/software-design-open-closed-principle){:target='_blank'}\r\n- [6 - Software Design - What is Dependency Inversion Principle?](/software-design-dependency-inversion-principle){:target='_blank'}\r\n\r\n## Open Closed Principle\r\n\r\n> Your classes should be open to extension, but closed to modification\r\n\r\nWhat does this mean? Let's look at a simple example to understand what this means. \r\n\r\n### An example of Poor Design\r\n\r\nLet's take a quick look at the calculateArea method in the Shape class.\r\n\r\n```\r\nclass Shape {\r\n\tpublic double calculateArea(Shape[] shapes) {\r\n\t\tdouble area = 0;\r\n\t\tfor(Shape shape:shapes) {\r\n\t\t\tif(shape instanceof Rectangle) {\r\n\t\t\t\t//Calculate Area of Rectange\r\n\t\t\t}\r\n\t\t\telse if(shape instanceof Circle) {\r\n\t\t\t\t//Calculate Area of Circle\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn area;\r\n\t}\r\n}\r\n\r\nclass Rectangle extends Shape {\r\n\t\r\n}\r\n\r\nclass Circle extends Shape {\r\n\t\r\n\t\r\n}\r\n\r\n```\r\n\r\nIs there a problem with ```calculateArea()``` method?\r\n\r\nWhat if we add a new shape? What if we remove a shape? What if we want to change the area algorithm for one of the shapes.\r\n\r\nFor all these modifications, ```calculateArea()``` method needs to change.\r\n\r\nHow can we make it better?\r\n\r\n> Parts of the above code below pseudo code, for ease of explanation\r\n\r\n```\r\n\r\nabstract class Shape {\r\n\r\n\t\r\n    abstract double area();\r\n}\r\n\r\nclass Rectangle extends Shape {\r\n\r\n\t@Override\r\n\tdouble area() {\r\n\t\t// Area implementation for Rectangle\r\n\t\treturn 0;\r\n\t}\r\n\t\r\n}\r\n\r\nclass Circle extends Shape {\r\n\r\n\t@Override\r\n\tdouble area() {\r\n\t\t// Area implementation for Rectangle\r\n\t\treturn 0;\r\n\t}\r\n\t\r\n}\r\n\r\n```  \r\n\r\nA better solution would be to allow each of the shapes, to define their own ```area()``` method. We have created an abstract class called ```Shape``` (which could also have been an interface), and have each of the different shapes extend it. Each shape also overrides ```Shape```'s abstract ```area()``` method, to compute its specific area. \r\n\r\nThe standalone ```calculateArea()``` method would now look like this:\r\n\r\n```\r\nabstract class Shape {\r\n\t\r\n\t\r\n\tpublic double calculateArea(Shape[] shapes)\r\n\t{\r\n\t\tdouble area = 0;\r\n\t\tfor(Shape shape:shapes) {\r\n\t\t\tarea += shape.area();\r\n\t\t}\r\n\t\treturn area;\r\n\t}\r\n\t\r\n    abstract double area();\r\n}\r\n\r\n```\r\n\r\n```calculateArea()``` is now responsible just for looping around the shapes, and invoking the ```area()``` method of individual shapes. \r\n\r\nThis is a very good example of the OCP. \r\n\r\nIf you now want to add another shape, then you need to extend the ```Shape``` class, and override its ```area()``` method:. That's it.\r\n\r\nHere, ```Shape``` class is open to extension, and ```calculateArea()``` is closed to modification.\r\n\r\nDo check out our video on this:\r\n\r\n[![image info](/images/Capture-017-02.png)](https://www.youtube.com/watch?v=pjDphh9OBVk)\r\n\r\n### Summary\r\n\r\nIn this article, we focused on Open Closed Principle. \r\n\r\nDesign should be open for extension, but closed for modification.\r\n"
  },
  {
    "path": "_blog/articles/2019-11-15-Software-Design-Principles-022-SOLID-Principles.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Object Oriented Software Design - Solid Principles - with examples\r\ndate:    2019-11-14 12:31:19\r\nsummary: Software design is typically complex. Object oriented design takes it to the next level. There are a number of design patterns and other stuff to be aware of. Can we make things simple? What are the goals to aim for when you are doing object oriented design? SOLID Principles is a great starting point for Object Oriented Design. \r\ncategories: SwDesign\r\npermalink:  /software-design-solid-principles\r\nimage: /images/design-category.png\r\n---\r\n\r\nSoftware design is typically complex. Object oriented design takes it to the next level. There are a number of design patterns to be aware of. Can we make things simple?\r\n\r\nSOLID Principles is a great starting point for Object Oriented Design.\r\n\r\n### What will you learn?\r\n* What are SOLID Principles?\r\n* What are the best practices in designing objected oriented software?\r\n\r\n\r\n### Software Design Principles\r\n\r\nThis is the third article in a series of articles on important Software Design Principles:\r\n\r\n- [1 - Introduction to Four Principles Of Simple Design](/four-principles-of-simple-design){:target='_blank'}\r\n- [2 - Software Design - Separation Of Concerns - with examples](/software-design-seperation-of-concerns-with-examples){:target='_blank'}\r\n- [3 - Object Oriented Software Design - Solid Principles - with examples](/software-design-solid-principles){:target='_blank'}\r\n- [4 - Software Design - Single Responsibility Principle - with examples](/software-design-single-responsibility-principle){:target='_blank'}\r\n- [5 - Software Design - Open Closed Principle - with examples](/software-design-open-closed-principle){:target='_blank'}\r\n- [6 - Software Design - What is Dependency Inversion Principle?](/software-design-dependency-inversion-principle){:target='_blank'}\r\n\r\n\r\n### What Are The SOLID Principles?\r\n\r\nPlainly listed out, the SOLID principles are:\r\n\r\n* **SRP**: Single Responsibility Principle\r\n* **OCP**: Open Closed Principle\r\n* **LSP**: Liskov Substitution Principle\r\n* **ISP**: Interface Segregation Principle\r\n* **DIP**: Dependency Inversion Principle\r\n\r\nLet's look at each of these by turn.\r\n\r\n### Single Responsibility Principle (SRP)\r\n\r\n> \"A class should have one, and only one reason to change\"\r\n\r\nThis principle is not just applicable to a class, but also at the level of a package, a component, an application, or a service. Each of these should each have just one responsibility. \r\n\r\n> You should be able to state what each element does in a single sentence. \r\n\r\nWhen your class or component or application has single responsibility, the options for reuse increases significantly. \r\n\r\nHave a look at the following class:\r\n\r\n```\r\n\r\n\tpublic class Task {\r\n\t\tpublic void downloadFile(String location) {\r\n\t\t\t//...\r\n\t\t}\r\n\t\t\r\n\t\tpublic void parseTheFile(File file) {\r\n\t\t\t//...\r\n\t\t}\r\n\r\n\t\tpublic void persistTheData(Data data) {\r\n\t\t\t//...\r\n\t\t}\r\n\t}\r\n\r\n```\r\n\r\n```Task``` has three main responsibilities: \r\n\r\n* Download a file from a location\r\n* Parse the contents of the file\r\n* Save the data obtained to a database\r\n\r\nIt clearly does not satisfy SRP. Let's look at another example:\r\n\r\n```\r\n\r\n\tpublic class Employee {\r\n\t\tpublic Money calculatePay() {\r\n\t\t\t//...\r\n\t\t}\r\n\r\n\t\tpublic String reportHours() {\r\n\t\t\t//...\r\n\t\t}\r\n\r\n\t\tpublic void save() {\r\n\t\t\t//...\r\n\t\t}\r\n\t}\r\n\r\n```\r\n\r\n```Employee``` has multiple responsibilities as well:\r\n\r\n* Calculate the employee's pay\r\n* Create a report of hours of work put in\r\n* Save the employee details to a database\r\n\r\nAbove examples need re-design to meet Single Responsibility Principle.\r\n\r\n### Open Closed Principle (OCP)\r\n\r\n\r\n> \"Software entities should be open for extension, but closed for modification\"\r\n\r\nLet's take a quick look at the calculateArea method in the Shape class.\r\n\r\n```\r\nclass Shape {\r\n\tpublic double calculateArea(Shape[] shapes) {\r\n\t\tdouble area = 0;\r\n\t\tfor(Shape shape:shapes) {\r\n\t\t\tif(shape instanceof Rectangle) {\r\n\t\t\t\t//Calculate Area of Rectange\r\n\t\t\t}\r\n\t\t\telse if(shape instanceof Circle) {\r\n\t\t\t\t//Calculate Area of Circle\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn area;\r\n\t}\r\n}\r\n\r\nclass Rectangle extends Shape {\r\n\t\r\n}\r\n\r\nclass Circle extends Shape {\r\n\t\r\n\t\r\n}\r\n\r\n```\r\n\r\nIs there a problem with ```calculateArea()``` method?\r\n\r\nWhat if we add a new shape? What if we remove a shape? What if we want to change the area algorithm for one of the shapes.\r\n\r\nFor all these modifications, ```calculateArea()``` method needs to change.\r\n\r\nHow can we make it better?\r\n\r\n> Parts of the above code below pseudo code, for ease of explanation\r\n\r\n```\r\n\r\nabstract class Shape {\r\n\r\n\t\r\n    abstract double area();\r\n}\r\n\r\nclass Rectangle extends Shape {\r\n\r\n\t@Override\r\n\tdouble area() {\r\n\t\t// Area implementation for Rectangle\r\n\t\treturn 0;\r\n\t}\r\n\t\r\n}\r\n\r\nclass Circle extends Shape {\r\n\r\n\t@Override\r\n\tdouble area() {\r\n\t\t// Area implementation for Rectangle\r\n\t\treturn 0;\r\n\t}\r\n\t\r\n}\r\n\r\n```  \r\n\r\nA better solution would be to allow each of the shapes, to define their own ```area()``` method. We have created an abstract class called ```Shape``` (which could also have been an interface), and have each of the different shapes extend it. Each shape also overrides ```Shape```'s abstract ```area()``` method, to compute its specific area. \r\n\r\nThe standalone ```calculateArea()``` method would now look like this:\r\n\r\n```\r\nabstract class Shape {\r\n\t\r\n\t\r\n\tpublic double calculateArea(Shape[] shapes)\r\n\t{\r\n\t\tdouble area = 0;\r\n\t\tfor(Shape shape:shapes) {\r\n\t\t\tarea += shape.area();\r\n\t\t}\r\n\t\treturn area;\r\n\t}\r\n\t\r\n    abstract double area();\r\n}\r\n\r\n```\r\n\r\n```calculateArea()``` is now responsible just for looping around the shapes, and invoking the ```area()``` method of individual shapes. \r\n\r\nThis is a very good example of the OCP. \r\n\r\nIf you now want to add another shape, then you need to extend the ```Shape``` class, and override its ```area()``` method:. That's it.\r\n\r\nHere, ```Shape``` class is open to extension, and ```calculateArea()``` is closed to modification.\r\n\r\n\r\n\r\n### Liskov Substitution Principle (LSP)\r\n\r\nAccording to this principle:\r\n\r\n> \"Subtypes must be substitutable for their base types\"\r\n\r\nOne of the things people try to do with object oriented programming, is to use inheritance even when it is not appropriate. They may do it just for the sake of reusing the code. Have a look at this example:\r\n\r\n```\r\n\r\n\tclass Rectangle {\r\n\t\tvoid setWidth(double w)\r\n\t\tvoid setHeight(double h)\r\n\r\n\t\tdouble getWidth()\r\n\t\tdouble getHeight()\r\n\t}\r\n\r\n\tclass Square extends Rectangle {\r\n\t\tvoid setWidth(double w) \t// Set both width and height to w\r\n\t\tvoid setHeight(double h) \t// Set both height and width to h\r\n\r\n\t\tdouble getWidth()\r\n\t\tdouble getHeight()\r\n\t}\r\n\r\n``` \r\n\r\nWe have a ```Rectangle``` class that has methods to set and get its width and height. Suppose we have a fresh requirement for a ```Square``` class.  \r\n\r\nInstead of implementing it as a separate class, Let's say we extend ```Rectangle``` (as we know from school geometry that a square is a rectangle). ```Square``` redefines all the set and get methods that it inherits from ```Rectangle``` to set both height and width to the same values. \r\n\r\n> Note that the pair of setters and the pair of getters inside ```Square```  are redundant.\r\n\r\nConsider a piece of client code such as this:\r\n\r\n```\r\n\r\n\tvoid test(Rectangle r) {\r\n\t\tr.setWidth(5);\r\n\t\tr.setHeight(4);\r\n\r\n\t\tassertEquals(5*4, r.getWidth() * r.getHeight());\r\n\t}\r\n\r\n```\r\n\r\n```test()``` is a method to test rectangles. A ```Square``` is a ```Rectangle```, hence ```test()``` can be called on a ```Square``` object as well. Unfortunately, since both ```setWidth()``` and ```setHeight()``` modify both the width and height to be equal, the expression ```r.getWidth() * r.getHeight()``` always amounts to ```4 * 4```, as that was the last value set. ```test()``` always fails for a ```Square```!\r\n\r\nLSP states that inheritance should be used very carefully. Make sure that the super class is always fully replaceable by each of its sub classes.\r\n\r\n### Interface Segregation Principle (ISP)\r\n\r\n> If two systems are communicating to each other, then the dependency should be in the smallest possible interface. \r\n\r\nClients should not be forced to implement interfaces that they don't use\r\n\r\nInstead of one fat interfaces, a group of smaller interfaces is preferred, each one addressing a sub-module.\r\n\r\nLet's look at an example: \r\n\r\n```\r\n\t\r\n\tpublic abstract class Animal {\r\n\t\tpublic abstract void feed();\r\n\t}\r\n\r\n\tpublic class Dog extends Animal {\r\n\t\tpublic void feed() {\r\n\t\t\t//...\r\n\t\t}\r\n\t}\r\n\r\n\tpublic class Tiger extends Animal {\r\n\t\tpublic void feed() {\r\n\t\t\t//...\r\n\t\t}\r\n\t}\r\n\r\n```\r\n\r\nLet's say we now need to add a feature called ```groom()``` to each  kind of ```Animal```. \r\n\r\nOne option is to add it to ```Animal``` as an abstract method:\r\n\r\n```\r\n\t\r\n\tpublic abstract class Animal {\r\n\t\tpublic abstract void feed();\r\n\t\tpublic abstract void groom();\r\n\t}\r\n\r\n\tpublic class Dog extends Animal {\r\n\t\tpublic void feed() {\r\n\t\t\t//...\r\n\t\t}\r\n\t\t\r\n\t\tpublic void groom() {\r\n\t\t\t//...\r\n\t\t}\r\n\t}\r\n\r\n\tpublic class Tiger extends Animal {\r\n\t\tpublic void feed() {\r\n\t\t\t//...\r\n\t\t}\r\n\r\n\t\t// DUMMY implementation, to keep compiler happy\r\n\t\tpublic void groom() {\r\n\t\t\t//...\r\n\t\t}\r\n\t}\r\n\r\n```\r\n\r\nIn that case, both ```Dog``` and ```Tiger``` need to provide implementations for ```groom()```. \r\n\r\nNow, ```groom()``` makes sense for a ```Dog```, but not so much for a ```Tiger```. \r\n\r\nHowever, we are forced to provide a dummy implementation in ```Tiger``` to make the code compile.\r\n\r\nAbove example does not adhere to ISP.\r\n\r\nLet's see how to fix this:\r\n\r\n```\r\n\t\r\n\tpublic abstract class Animal {\r\n\t\tpublic abstract void feed();\r\n\t}\r\n\r\n\tpublic class Pet extends Animal {\r\n\t\tpublic abstract void groom();\r\n\t\tpublic void feed() {\r\n\t\t\t//...\r\n\t\t}\r\n\t}\r\n\r\n\tpublic class Dog extends Pet {\r\n\t\tpublic void feed() {\r\n\t\t\t//...\r\n\t\t}\r\n\t\t\r\n\t\tpublic void groom() {\r\n\t\t\t//...\r\n\t\t}\r\n\t}\r\n\r\n\tpublic class Tiger extends Animal {\r\n\t\tpublic void feed() {\r\n\t\t\t//...\r\n\t\t}\r\n\t}\r\n\r\n```\r\n\r\nThe new interface ```Pet``` extends the existing ```Animal```, and also adds its own abstract method ```groom()```. Now, ```Dog``` will extend ```Pet```, as it needs both ```feed()``` and ```groom()```, whereas ```Tiger``` chooses to extend just ```Animal``` for ```feed()```.\r\n\r\nISP recommends that you keep your interfaces as small as possible. \r\n\r\nThe moment you have a fat interface, any changes to that interface will result in changes in all your implementations. \r\n\r\n### Dependency Inversion Principle (DIP)\r\n\r\nThe Dependency Inversion Principle states that:\r\n\r\n> \"Depend upon abstract classes (interfaces), not upon concrete classes\"\r\n\r\nLet's look at an example of what this means:\r\n\r\n```\r\n\r\nabstract class OutputDevice {\r\n\tvoid copy(String device) {\r\n\t\tKeyboard keyboard = new Keyboard();\r\n\t\tint character;\r\n\t\twhile ((character = keyboard.read()) != -1) {\r\n\t\t\tif (device.equals(\"Printer\")) {\r\n\t\t\t\twriteToPrinter(character);\r\n\t\t\t} else {\r\n\t\t\t\twriteToDevice(character);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tprivate void writeToDevice(int character) {\r\n\t\t// TODO Auto-generated method stub\r\n\t\t\r\n\t}\r\n\r\n\tprivate void writeToPrinter(int c) {\r\n\t\t// TODO Auto-generated method stub\r\n\t\t\r\n\t}\r\n}\r\n\r\n\r\n```\r\n\r\nWhat does the ```copy()``` method do?\r\n\r\nIt reads a character from the keyboard, and then decides where this character needs to go. If it's a printer, write to the printer. Else, send it to the disk.  \r\n\r\nThe problem here is that as the number of ```OutputDevice``` types increase, the logic of ```copy()``` needs to change every single time. \r\n\r\nLet's look at an alternate implementation:\r\n\r\n```\r\n\r\n\tpublic interface Reader {\r\n\t\tpublic char read();\r\n\t}\r\n\r\n\tpublic interface Writer {\r\n\t\tpublic void write(char ch);\r\n\t}\r\n\r\n\tvoid copy(Reader r, Writer w) {\r\n\t\tint c;\r\n\r\n\t\twhile((c = r.read()) != EOF) {\r\n\t\t\tw.write(c);\r\n\t\t}\r\n\t}\r\n\r\n```\r\n\r\n```copy()``` method explicitly states its dependencies - ```Reader``` and ```Writer``` interfaces.\r\n\r\nIt inverts responsibility, and leaves the creation of ```Reader``` and ```Writer``` to its users. \r\n\r\n```copy()``` will not change even when there are new ```Writer``` or ```Reader``` implementations.\r\n\r\nThis is called Dependency Inversion principle.\r\n\r\nFrameworks like Spring make it easy to implement Dependency Inversion.\r\n\r\nDo check out our video on this:\r\n\r\n[![image info](/images/Capture-022-02.png)](https://www.youtube.com/watch?v=yxf2spbpTSw)\r\n\r\n### Summary\r\n\r\nIn this article, we looked at the five SOLID principles: SRP, OCP, LSP, ISP and DIP. We also looked at a few code examples to understand more about each one of them."
  },
  {
    "path": "_blog/articles/2019-11-15-Software-Design-Priniples-039-Separation-Of-Concerns.md",
    "content": "---\r\nlayout:  post\r\ntitle:  Software Design - Separation Of Concerns - with examples\r\ndate:    2019-11-14 12:31:19\r\nsummary: Software architects and programmers love having Separation of Concerns. What is it? Why is it important? Let's get started.\r\ncategories: SwDesign\r\npermalink:  /software-design-seperation-of-concerns-with-examples\r\nimage: /images/design-category.png\r\n---\r\n\r\nSoftware architects and programmers love having Separation of Concerns. What is it? Why is it important? Let's get started.\r\n\r\n### You will learn\r\n\r\n* What is Separation Of Concerns?\r\n* What are common examples of implementing Separation Of Concerns in software?\r\n\r\n### Software Design Principles\r\n\r\nThis is the second article in a series of articles on important Software Design Principles:\r\n\r\n- [1 - Introduction to Four Principles Of Simple Design](/four-principles-of-simple-design){:target='_blank'}\r\n- [2 - Software Design - Separation Of Concerns - with examples](/software-design-seperation-of-concerns-with-examples){:target='_blank'}\r\n- [3 - Object Oriented Software Design - Solid Principles - with examples](/software-design-solid-principles){:target='_blank'}\r\n- [4 - Software Design - Single Responsibility Principle - with examples](/software-design-single-responsibility-principle){:target='_blank'}\r\n- [5 - Software Design - Open Closed Principle - with examples](/software-design-open-closed-principle){:target='_blank'}\r\n- [6 - Software Design - What is Dependency Inversion Principle?](/software-design-dependency-inversion-principle){:target='_blank'}\r\n\r\n\r\n### What Is Separation Of Concerns?\r\n\r\nSeparation Of Concerns is an important design and architectural principle.\r\n\r\n> Every element of a software application - a component, a layer,a package,a class or a method should have one concern and implement it well. \r\n\r\nAll methods with similar concerns will grouped into a class. \r\n\r\nAll classes with similar concerns will be grouped into packages. \r\n\r\nSo on and so forth.\r\n\r\n### Separation Of Concerns In Action\r\n\r\n#### Layered Architecture\r\n\r\nOrganizing an application into separate layers is one way of separating out concerns. \r\n\r\nFor example, the following is the typical architecture of a web application:\r\n\r\n![image info](/images/Capture-039-02.png)\r\n\r\nHere are some of the important responsibilities of each of these layers\r\n- The Web layer only bothers about how to present data to its users \r\n- The Business layer focuses on implementing the core application logic, correctly and efficiently\r\n- The Data layer takes responsibility of talking to the data store. \r\n\r\nYou can see that each layer has a concern and implements it well.\r\n\r\n#### Organizing Microservices\r\n\r\nAnother good example of Separation Of Concerns is how you split your microservices. Have a look at the diagram below: \r\n\r\n![image info](/images/Capture-039-03.png)\r\n\r\nAll the microservices shown are part of a movie application. But each one of them has its own independent concern. \r\n\r\n#### Identifying Common Components\r\n\r\nSeparation of concerns is also an important factor in building common application and infrastructure components.\r\n\r\nSince a large part of the functionality of microservices is common to all of them, it makes sense to extract out the common components. Here is an example:\r\n\r\n![image info](/images/Capture-039-04.png)\r\n\r\nAll microservices need features such as security and logging. By identifying common components in your service such as Security and Logging, and providing well defined interfaces with each microservice, the implementation of the microservices gets simpler.\r\n\r\nThe same is the case with common infrastructure components. Any microservice can interact with them and use their functionality. \r\n\r\nA few examples of Separation of Concern in infrastructure components\r\n- Naming Server - Microservice3 can locate the identity of Microservice2.\r\n- API Gateway - Centralized access to all microservices. You can implement cross cutting microservice concerns here.\r\n- Distributed Tracing and Centralized Logging - You can trace microservices and find out what's happening behind the scenes.\r\n\r\nDo check out our video on this:\r\n\r\n[![image info](/images/Capture-039-01.png)](https://www.youtube.com/watch?v=GRTQ896UWaI)\r\n\r\n### Summary\r\n\r\nIn this article, we looked at separation of concerns, and several examples of it in action - such as in a layered architecture, in the way microservices are split and organized, and in the way common components and infrastructure are identified and extracted out in a microservices architecture."
  },
  {
    "path": "_blog/articles/2020-01-01-Taking-Spring-Boot-To-Cloud.md",
    "content": "---\r\nlayout:  post\r\ntitle: Deploy Java Spring Boot Applications to AWS, Azure, GCP with Docker and Kubernetes\r\ndate:    2022-01-03 12:31:19\r\nsummary:  In this article, we focus our attention on the cloud. How to learn the cloud and deploy Java Spring Boot Applications to AWS, Azure, GCP with Docker and Kubernetes?\r\ncategories:  SpringBootMicroservices\r\npermalink:  /spring-boot-applications-to-aws-azure-gcp-docker-kubernetes\r\nimage: /images/spring-boot-application.png\r\n---\r\n\r\n[![Image](https://www.springboottutorial.com/images/devops-06-teams.png \"DevOps Teams\")](https://links.in28minutes.com/DevOps-SBT)\r\n\r\nIn this article, we focus our attention on the cloud. Why do we need the cloud? And how can you learn the cloud?\r\n\r\n## You will learn\r\n- What is Cloud?\r\n- Why do we need the Cloud?\r\n- What are the popular cloud providers?\r\n- What is IAAS and PAAS?\r\n- What is Docker?\r\n- What is Kubernetes?\r\n- What are the PAAS offerings provided by AWS, Azure and GCP?\r\n- How can you learn about the cloud?\r\n\r\n## Introduction\r\n\r\nYou want to learn about the cloud. But you don't know where to start. \r\n\r\nOne of the best option to learn the cloud is to deploy some of the applications that you have developed to different cloud providers.\r\n\r\nWhen we talk about the Java Spring Boot world, typically we talk about\r\n- Web Applications\r\n- REST APIs\r\n- Microservices\r\n- Full Stack Applications\r\n\r\nHow about deploying these applications to different cloud platforms?\r\n\r\nThat's the kind of courses that we would be talking about in the article.\r\n\r\n## Introduction to Cloud\r\n\r\nLet's start with understanding why we need the cloud.\r\n\r\n### Why do we need the cloud?\r\n\r\nThe three reasons are\r\n- On Demand Resource Provisioning\r\n- Avoid \"Undifferentiated Heavy Lifting\"\r\n- Improved Latency and Availability\r\n\r\n#### On Demand Resource Provisioning\r\n\r\nIf you are amazon or a startup, the load on your application varies a lot during the year. Load during peak season like holidays might 2-10 times the regular load. If you provision infrastructure in your data center for peak load, then what would it be doing during the rest of year? Sitting Idle!\r\n\r\nThat's the problem cloud solves!\r\n\r\nYou can provision and release resources on demand.\r\n\r\n#### Avoid \"Undifferentiated Heavy Lifting\"\r\n\r\nWhat is the focus of a business? \r\n\r\nTo create amazing solutions and provide great service to their customers. \r\n\r\nIf business focus on automation, tools and infrastructure, the focus shifts from their core job. \r\n\r\nWhy not leave the \"Undifferentiated Heavy Lifting\" to the cloud providers?\r\n\r\n#### Improved Latency and Availability\r\n\r\nEach of the cloud providers have multiple data centers available in multiple continents and multiple countries.\r\n\r\nIt would be difficult for businesses to set up such wide spread infrastructure. \r\n\r\nHowever, to have high availability and low latency for end users, you would need to have multiple deployments around the world.\r\n\r\nCloud Providers make it easy for you to have multiple deployments of your application across the world.\r\n\r\n\r\n### IAAS vs PAAS\r\n\r\nNow, you want to go the cloud. You have an important choice to make.\r\n\r\nDo you want to deploy your applications the same way you deploying while using your data center or do you want to use facilities provided by your cloud provider?\r\n\r\nFor example, if you are using AWS (Amazon Web Services), you have two options\r\n- Approach 1 - You can create virtual servers (EC2 - Elastic Compute Cloud) and deploy your applications to the virtual servers.\r\n- Approach 2 - You can use a service provided by AWS - for example, AWS Elastic Beanstalk - to deploy your application and not worry about the virtual servers.\r\n\r\nApproach 1 is typically called IAAS - Infrastructure as a Service. You are getting the infrastructure from the cloud provider and deploying the applications the usual way you do. The cloud provider is responsible only for providing the virtual servers. You are responsible for installing OS, OS Upgrades, Installing Runtime, Runtime upgrades and everything that goes along with them.\r\n\r\nDifferent clouds provide different IAAS Services. The virtual servers are also called differently in different clouds\r\n- AWS calls them EC2 (Elastic Compute Cloud)\r\n- Azure Virtual Machines\r\n- Google Compute Engines\r\n\r\nApproach 2 is called PAAS - Platform as a Service. You are only responsible for your application deployable unit. The cloud provider is responsible for Platform Upgrades, Runtime Upgrades and OS Upgrades.\r\n\r\nPAAS Examples are Managed Services provided by different cloud providers. A good examples are the database management services provided.\r\n- AWS provides RDS - Relational Database Service\r\n- Azure provides DB for MySQL\r\n\r\nGreat thing about these managed services is that the cloud provider would take care of most non functional requirements.\r\n- Reliability\r\n- Availability\r\n- Backups\r\n\r\n\r\n### Platform as a Service in Depth\r\n\r\nIf we look at PAAS in depth, there are a number of application PAAS services offered by different cloud providers\r\n- AWS Elastic Beanstalk\r\n- Google App Engine\r\n- Azure Web Apps\r\n\r\nThese services make it easy to deploy Java applications, Containers and a wide variety of applications to the cloud.\r\n\r\nThese PAAS offering come with Support for\r\n- Multiple Environments\r\n- Multiple Platforms and Language Support\r\n- Container and Multi Container Support\r\n- Deployment Strategies - Blue Green Deployment\r\n- Auto Scaling\r\n- Load Balancing\r\n- CI/CD (AWS Code Pipeline, AWS Code Build, Azure DevOps, Google Cloud Build)\r\n\r\n\r\n#### Cloud Specific Container Orchestration Solutions\r\n\r\nOne of the important developments of the last few years is the evolution of containers as a platform neutral, language neutral deployment options.\r\n\r\nCloud providers provide PAAS options around containers and container orchestration. The most important offerings are\r\n- AWS Fargate or ECS (Elastic Container Service)\r\n- Azure Container Instance - Azure is actually moving towards AKS (Azure Kubernetes Service)\r\n\r\n\r\n#### Cloud Neutral Kubernetes Based Container Orchestration Solutions\r\n\r\nOther important evolution of last few years is the evolution of Kubernetes as the Cloud Neutral Container Orchestration Service.\r\n\r\nEach of the cloud providers provide Container Orchestration Solution around Kubernetes.\r\n- GKE (Google Kubernetes Engine)\r\n- AKS (Azure Kubernetes Service)\r\n- EKS (AWS Container Services for Kubernetes)\r\n\r\n\r\n## Spring Boot to AWS, Azure, GCP, Docker and Kubernetes\r\n\r\nHere are some of the amazing courses that help you learn cloud, containers and orchestration by deploying a variety of Spring Boot applications to the cloud.\r\n\r\n\r\n### Docker for Java Developers - with Spring Boot Microservices\r\n\r\nDocker is the No 1 Tool to Containerize your Java Spring Boot Applications. Learning Docker would help you streamline your deployment processes and experiment easily with new frameworks and tools.\r\n\r\nThe first course we are going to talk about is \"Docker for Java Developers - with Spring Boot Microservices\".\r\n\r\n[![Image](https://www.springboottutorial.com/images/Course-DockerCrashCourseForJavaSpringBootDevelopers.png \"Docker Crash Course for Java Spring Boot Developers\")](https://links.in28minutes.com/MISC-DOCKER)\r\n\r\nIn this hands-on course, you will containerize - create docker images and create containers - a variety of Spring Boot Applications:\r\n- REST APIs - Hello World and Todo - Jar\r\n- Todo Web Application War\r\n- Full Stack Application with React and Spring Boot\r\n- CCS and CES Microservices\r\n- Eureka Naming Server and Zuul API Gateway\r\n\r\nThis course would be a perfect first step as an introduction to Docker.\r\n\r\nYou will Learn Docker Architecture and the Fundamentals of Docker - Registry, Repository, Tag, Image, Container and Volumes and also learn the important Docker commands.\r\n\r\nYou will learn to use `Dockerfile` to Automate Building of your Docker Image and also use various maven plugins - `Dockerfile` Spotify Plugin, JIB Plugin and Fabric8 Docker Maven Plugin - to create Docker images. You will also learn to follow the best practices with creating Docker Images - Improve Caching of Docker Images and create Multi Stage Docker Builds.\r\n\r\n### Learn AWS - Deploy Java Spring Boot to AWS Elastic Beanstalk\r\n\r\nAWS is the most popular cloud and AWS Elastic Beanstalk makes it easy to deploy a variety of applications to AWS.\r\n\r\n\"Learn AWS - Deploy Java Spring Boot to AWS Elastic Beanstalk\" is another amazing hands-on course on AWS to help you deploy Spring Boot applications to AWS.\r\n\r\n[![Image](https://www.springboottutorial.com/images/Course-Deploy-Java-Spring-Boot-Apps-To-AWS.png \"Deploying Spring Boot Apps to AWS using Elastic Beanstalk\")](https://links.in28minutes.com/MISC-AWS-BEANSTALK)\r\n\r\nIn this course, you will learn to deploy a variety of Spring Boot Applications to the Cloud:\r\n- REST APIs - Hello World and Todo - Jar\r\n- Todo Web Application War\r\n- Full Stack Application with React and Spring Boot\r\n- Single Container with Java REST API\r\n- Multi Container with Todo REST API talking to MySQL\r\n\r\nThis course would be a perfect first step as an introduction to AWS and the Cloud, especially for Java Developers.\r\n\r\nYou will learn about automating deployments with Elastic Beanstalk CLI and creating a continuous delivery pipeline with AWS Code Pipeline. You will learn how to Auto Scale applications based on load as well as deploy multiple instances behind a load balancer using Elastic Beanstalk.\r\n\r\nYou will be using a number of AWS Services - EC2, S3, AWS CodePipeLine, AWS CodeBuild, SQS, IAM, CloudWatch.\r\n\r\n\r\n### Master AWS Fargate & ECS with Java Spring Boot Microservices\r\n\r\nWe learnt about docker earlier. AWS Elastic Container Service and AWS Fargate are the container orchestration services provided by AWS.\r\n\r\n\"Master AWS Fargate & ECS with Java Spring Boot Microservices\" is another awesome course to help you learn AWS and container orchestration.\r\n\r\n[![Image](https://www.springboottutorial.com/images/Course-Deploy-Java-Spring-Boot-Microservices-To-ECS.png \"Deploying Spring Boot Microservices to AWS using ECS and AWS Fargate\")](https://links.in28minutes.com/MISC-FARGATE)\r\n\r\nThis course would be a perfect first step as an introduction to Amazon Web Services - AWS and the Cloud.\r\n\r\nIn this course, you will deploy a variety of Java Spring Boot Microservices to Amazon Web Services using AWS Fargate and ECS - Elastic Container Service.\r\n\r\nYou will learn the basics of implementing Container Orchestration with ECS (Elastic Container Service) - Cluster, Task Definitions, Tasks, Containers and Services. You will learn about the two launch types of ECS - EC2 and AWS Fargate. In this course, we would focus extensively on AWS Fargate to simplify your Container Orchestration. You will learn to deploy multiple containers in the same ECS task.\r\n\r\nYou will learn to Build Container Images for your Java Spring Boot Microservice Projects.\r\n\r\nYou will implement the following features for your Microservices\r\n- Centralized Configuration Management with AWS Parameter Store\r\n- Distributed Tracing with AWS X Ray\r\n- Auto Scaling and Load Balancing with ECS, Elastic Load Balancers and Target Groups\r\n- Service Mesh using AWS App Mesh. You will learn the basics of AWS App Mesh - Mesh, Virtual Nodes and Virtual Services. You will learn to perform Canary Deployments using AWS AppMesh.\r\n- Service Discovery with Route 53 Hosted Zones and DNS.\r\n- Continuous Integration and Continuous Deployment with AWS Code Pipeline\r\n\r\nYou will learn to debug problems with deploying containers using Service events and AWS CloudWatch logs.\r\n\r\nYou will learn about automating deployments and creating a continuous delivery pipeline with AWS Code Pipeline. You will learn how to Auto Scale applications based on load as well as deploy multiple instances behind a load balancer using AWS ECS Fargate.\r\n\r\nYou will be using a number of AWS Services - ECS - Elastic Container Services, AWS Fargate, EC2 - Elastic Compute Cloud, S3, AWS CodePipeLine, AWS CodeBuild, IAM, CloudWatch, ELB, Target Groups, X Ray, AWS Parameter Store, AWS App Mesh and Route 53.\r\n\r\n\r\n### Master Pivotal Cloud Foundry with Spring Boot Microservices\r\n\r\nPivotal Cloud Foundry (PCF) provides a great cloud-native platform to deploy Spring Boot Applications. \r\n\r\n\r\nMaster Pivotal Cloud Foundry with Spring Boot Microservices is a great course to learn about PCF and get a feel for how you deploy application to Cloud using PCF.\r\n\r\n[![Image](https://www.springboottutorial.com/images/Course-pivotal-cloud-foundry-pcf-deploying-spring-boot-apps.png \"Deploying Spring Boot Microservices to PCF Pivotal Cloud Foundry\")](https://links.in28minutes.com/MISC-PCF)\r\n\r\nIn this course, you will learn the basics of Pivotal Cloud Foundry by deploying several full featured Spring Boot applications to PCF. You will deploy a REST API, a web application, a full stack application built using Spring Boot and React. You will learn to deploy Java Spring Boot applications containerized using Docker to PCF. \r\n\r\nThis course also focuses on help you deploy amazing Spring Boot microservices to PCF using several Spring Cloud Services like Service Registry, Config Server and Hystrix.\r\n\r\nYou will learn how to Auto Scale applications based on load as well as deploy multiple instances behind a load balancer using Pivotal Cloud Foundry.\r\n\r\nThis course would be a perfect first step as an introduction to PCF and the Cloud.\r\n\r\n### Master Azure Web Apps - Take Java Spring Boot Apps to Azure\r\n\r\nMicrosoft Azure is the second most popular cloud platform today. Azure Web App is a PAAS offering from Azure to help you deploy applications easily to the Cloud.\r\n\r\nMaster Azure Web Apps - Take Java Spring Boot Apps to Azure is an amazing course to help you get started with Azure.\r\n\r\n[![Image](https://www.springboottutorial.com/images/Course-Deploy-SpringBoot-To-Azure-Web-Apps.png \"Azure Crash Course for Java Spring Boot Developers\")](https://links.in28minutes.com/MISC-AZURE)\r\n\r\nIn this course, you will deploy a variety of Spring Boot Applications to the Cloud:\r\n- REST APIs - Hello World and Todo - Jar\r\n- Todo Web Application War\r\n- Full Stack Application with React and Spring Boot\r\n- Single Container with Java REST API\r\n- Multi Container with Todo REST API talking to MySQL\r\n\r\nThis course would be a perfect first step as an introduction to Azure and the Cloud, especially for Java Developers.\r\n\r\nYou will learn about automating deployments with Azure and creating a continuous delivery pipeline with Azure DevOps. You will learn how to Auto Scale applications based on load as well as deploy multiple instances behind a load balancer using Azure App Service.\r\n\r\nYou will be using a number of Azure Services - Azure App Service, Azure Web Apps, Azure DevOps, Azure Database for MySQL Services, Resource Groups, Azure App Service Plans, and Azure Subscriptions.\r\n\r\n### Kubernetes Crash Course for Java Developers on Google Cloud\r\n\r\nKubernetes makes it easy to manage clusters with 1000's of containers running 1000's of microservices. Google Kubernetes Engine (GKE) makes it super easy to create Kubernetes Clusters.\r\n\r\nHow about getting them all together and deploying Spring Boot Microservices to Kubernetes Clusters created on Google Cloud Platform using Google Kubernetes Engine (GKE)?\r\n\r\nKubernetes Crash Course for Java Developers on Google Cloud is an amazing course to help you get started with Kubernetes.\r\n\r\n[![Image](https://www.springboottutorial.com/images/Course-KubernetesCrashCourse.png \"Kubernetes Crash Course for Java Spring Boot Developers\")](https://links.in28minutes.com/MISC-KUBERNETES)\r\n\r\nIn this hands-on course, you will use Docker and Kubernetes to deploy a variety of Spring Boot Applications on Google Cloud using Google Kubernetes Engine:\r\n- REST APIs - Hello World\r\n- Todo Web Application War\r\n- Spring Boot Microservices\r\n\r\nYou will implement Service Discovery, Centralized Configuration, Distributed Tracing and Load Balancing for Spring Boot Microservices deployed in Kubernetes Clusters.\r\n\r\nYou will learn to use Helm Charts, Istio Service Mesh, Google Stackdriver, and Spring Cloud Kubernetes to play with Spring Boot Java Microservices on Kubernetes.\r\n\r\nThis course would be a perfect first step as an introduction to Kubernetes.\r\n"
  },
  {
    "path": "_blog/articles/2020-02-24-DevOps.md",
    "content": "---\r\nlayout:  post\r\ntitle: Devops Tutorial | DevOps with Docker, Kubernetes and Azure DevOps\r\ndate:    2020-02-24 12:31:19\r\nsummary:  What is DevOps? How is it different from Agile? What are the popular DevOps Tools? What is the role of Docker, Kubernetes and Azure DevOps in DevOps. Let's get started with a simple Usecase.\r\ncategories:  SpringBootMicroservices\r\npermalink:  /devops-tutorial-with-docker-kubenetes-and-azure-devops\r\nimage: /images/architecture.png\r\n---\r\n\r\n[![Image](https://www.springboottutorial.com/images/devops-06-teams.png \"DevOps Teams\")](https://links.in28minutes.com/DevOps-SBT)\r\n\r\nWhat is DevOps? How is it different from Agile? What are the popular DevOps Tools? What is the role of Docker, Kubernetes and Azure DevOps in DevOps?\r\n\r\nLet's get started with a simple use case.\r\n\r\n## You will learn\r\n- What is DevOps?\r\n- Why do we need DevOps?\r\n- How is DevOps different from Agile?\r\n- What are the important DevOps tools?\r\n- How does Docker help DevOps?\r\n- How does Kubernetes help DevOps?\r\n- How does Azure DevOps help DevOps?\r\n- What is Continuous Integration, Continuous Delivery?\r\n- What is Infrastructure as Code?\r\n- How do Terraform and Ansible help DevOps?\r\n\r\n\r\n## What is DevOps?\r\n\r\nAs with most buzzwords around software development, there is no accepted definition for DevOps.\r\n\r\nDefinitions vary from simple ones, like these two, to complex definitions that last a complete page of a book. \r\n\r\n>**DevOps** is the combination of **cultural philosophies, practices, and tools** \r\nthat **increases** an organization’s ability to **deliver applications and services** at **high velocity** - Amazon Web Services(AWS)\r\n\r\n> **DevOps** is a **collaborative and multidisciplinary** effort within an organization to **automate continuous delivery** of new software versions, while **guaranteeing** their **correctness and reliability** - A Survey of DevOps Concepts and Challenges - L Leite \r\n\r\n\r\n**Instead of trying define DevOps**, let's understand how Software Development evolved to DevOps.\r\n\r\n### Waterfall Model\r\n\r\nFirst few decades of software development was centered around the water fall model. \r\n\r\nWaterfall model approached software development the same way that you would approach building a real estate project - for example, building an amazing bridge. \r\n\r\nYou will build software in multiple phases that can go on for a period any where between a few weeks to a few months. \r\n\r\n[![Image](https://www.springboottutorial.com/images/devops-01-waterfall.png \"Waterfall Model\")](https://links.in28minutes.com/DevOps-SBT)\r\n\r\nIn most waterfall projects, it would be months before the business sees a working version of an application. \r\n\r\n### Key Elements to Build Great Software\r\n\r\nWhile working in the waterfall model for a few decades, we understood a few key elements around developing great software:\r\n- Communication\r\n- Feedback\r\n- Automation\r\n\r\n#### Importance of Communication\r\n\r\nSoftware Development is a multi disciplinary effort involving a variety of skills. \r\n\r\n[![Image](https://www.springboottutorial.com/images/devops-06-teams.png \"DevOps Teams\")](https://links.in28minutes.com/DevOps-SBT)\r\n\r\nCommunication between people is essential for the success of a software project. \r\n\r\nIn the waterfall model, we tried to enhance communication by trying to prepare 1000 page documents on Requirements, Design, Architecture and Deployment. \r\n\r\nBut, over a period of time, we understood that \r\n- The best way to enhance communication within the team, is to get the team together. Get a variety of skills in the same team. \r\n- Cross functional teams - with wide range of skills - work great.\r\n\r\n#### Importance of Early Feedback\r\n\r\nGetting Feedback Quickly is important. Building great software is all about getting quick feedback.\r\n\r\n> Are we building an application which meets the business expections? \r\n\r\nYou cannot wait for months to get feedback. You would want to know quickly. \r\n\r\n> Will your application have problems if it is deployed to production? \r\n\r\nYou don't want to know it after a few months. You want to find it out as early as possible.\r\n\r\nThe earlier we find a problem, the easier it is to fix it.\r\n\r\nWe found that the best software teams are structured to enable quick feedback. Anything I'm working on, I would like to know if I'm doing the right thing as early as possible . \r\n\r\n\r\n#### Importance of Automation\r\n\r\nAutomation is critical. Software Development involves a wide range of activities. Doing things manually is slow and error prone. We understood that it's essential to always look for opportunities to introduce Automation.\r\n\r\n[![Image](https://www.springboottutorial.com/images/devops-05-continuous-delivery.png \"DevOps Continuous Delivery\")](https://links.in28minutes.com/DevOps-SBT)\r\n\r\n\r\nHaving understood the key elements to develop great software, lets look at how we evolved to Agile and DevOps.\r\n\r\n### Evolution to Agile\r\n\r\n\r\nAgile was the first step in evolution towards implementing our learnings with enhanced communication between teams, getting feedback and bringing in automation.\r\n\r\n[![Image](https://www.springboottutorial.com/images/devops-06-teams.png \"DevOps Teams\")](https://links.in28minutes.com/DevOps-SBT)\r\n\r\nAgile brought the business and development teams together into one team which works to build great software in small iterations called sprints. \r\n\r\n[![Image](https://www.springboottutorial.com/images/devops-02-agile-2.png \"Agile & DevOps\")](https://links.in28minutes.com/DevOps-SBT)\r\n\r\n\r\nInstead of spending weeks or months on each phase of development, agile focuses on taking small requirements called user stories through the development cycle within a few days, sometimes within the same day.\r\n\r\n[![Image](https://www.springboottutorial.com/images/devops-02-agile-1.png \"Agile & DevOps\")](https://links.in28minutes.com/DevOps-SBT)\r\n\r\n#### How did Agile enhance communication between teams? \r\n\r\nAgile brought the business and development teams together. \r\n- Business is responsible for defining what to build? What are the requirements? \r\n- Development is responsible for building a product that meets the requirements. Development includes everybody involved in Design, Coding, Testing and Packaging of your software. \r\n\r\nIn Agile, a representative from Business, called a Product Owner, is always present with the team, the team understands the business objectives clearly. \r\n\r\nWhen the development team does not understand the requirements well and is going in a wrong path, Product Owner helps them do course correction and stay on the correct path. \r\n\r\n> Result : The final product the team builds is something that the business wants.\r\n\r\nAnother important factor is that Agile Teams have cross functional skills - coding skills - front end, api and databases, testing skills and business skills. This enhances communication between people that have to work together to build great software.\r\n\r\n\r\n\r\n#### Agile and Automation\r\n\r\nWhat are the Automation areas where Agile Teams focused on? \r\n\r\nSoftware Products can have a variety of defects. \r\n- Functional Defects mean the product does not work as expected. \r\n- Technical Defects make the maintainence of the software difficult. For example, code quality problems. \r\n\r\nIn general, agile teams were focused on using automation to find technical and functional defects as early as possible.\r\n\r\nAgile teams focused on automation tests. Writing great unit tests to test your methods and classes. Writing great integration tests to test your modules and applications. Agile teams also focused extensively on code quality. Tools like SONAR were used to assess the code quality of applications. \r\n\r\n[![Image](https://www.springboottutorial.com/images/devops-05-continuous-integration.png \"Agile & Continuous Integration\")](https://links.in28minutes.com/DevOps-SBT)\r\n\r\nIs it sufficient if you have great automation tests and great code quality checks? You would want to run them as often as possible. Agile Teams focused on Continuous Integration. You make a commit to version control. Your Unit Tests, Automation Tests and Code Quality Checks were automatically executed in a Continuous Integration Pipeline. Most popular CI/CD tool during the early agile time period was Jenkins.\r\n\r\n#### How did Agile promote immediate feedback? \r\n\r\nMost important factor is that Business does not need to wait for months to see the final product.  At the end of every sprint, the product is demoed to all stakeholders including Architecture and Business Teams. All feedback is taken in while prioritizing user stories for the next sprint. Result : The final product the team builds is something that the business wants. \r\n\r\nAnother important factor that enables immediate feedback is continuous integration. Let's say I commit some code into version control. Within 30 minutes, I get feedback if my code causes a unit test failure or a integration test failure. I will get feedback if my code does not meet code quality standards or does not have enough code coverage in the unit tests.\r\n\r\nWas agile successful? Yes. For sure. By focusing on improving the communication between business and development teams, and focusing on finding a variety of defects early, Agile took software development to the next level. \r\n\r\nI, personally, had a wonderful experience working with some amazing teams in the Agile model. Software Engineering, which for me represents all the efforts in building software from requirements to taking applications live, for the first time, was as enjoyable as programming.\r\n\r\nBut, does evolution stop? Nope.\r\n\r\nNew challenges emerged.\r\n\r\n### Evolution of Microservices Architectures\r\n\r\nWe started moving towards a microservices architecture and we started building a number of small api's instead of building large monolith applications. \r\n\r\nWhat was the new challenge? \r\n\r\nOperations becomes more important. Instead of doing 1 monolith release a month, you are doing hundreds of small microservice releases every week. Debugging problems across microservices and getting visibility into what's happening with the microservices became important. \r\n\r\n[![Image](https://www.springboottutorial.com/images/devops-06-microservices.png \"DevOps and Microservices\")](https://links.in28minutes.com/DevOps-SBT)\r\n\r\nIt was time for a new buzzword in software development. DevOps.\r\n\r\n\r\n### Emergence of DevOps\r\n\r\nWhat was the focus of DevOps? \r\n\r\nFocus of DevOps was on enhancing the communication between the Development and the Operations Team. \r\n- How do we make deployments easier? \r\n- How do we make the work operations team does more visible to the development team?\r\n\r\n\r\n#### How did DevOps enhance communication between teams? \r\n\r\nDevOps brought Operations Teams closer to the Development Teams. \r\n- In more mature enterprises, Development and Operations Teams worked as one Team. They started sharing common goals and both teams started to understand the challenges the other team faces. \r\n- In enterprises in the early stages of devops evolution, a representative from the operations team can be involved in the sprints - standups and retrospectives.\r\n\r\n[![Image](https://www.springboottutorial.com/images/devops-06-teams.png \"DevOps Teams\")](https://links.in28minutes.com/DevOps-SBT)\r\n\r\n\r\n#### What are the Automation areas where DevOps Teams focused on? \r\n\r\nIn addition to the focus areas of agile - Continuous Integration and Test Automation, the DevOps teams were focused on helping automate several of the Operation Teams Activities - Provisioning Servers, Configuring Software on Servers, Deploying Applications and Monitoring Production Environments. A few key terminology are Continuous Deployment, Continuous Delivery and Infrastructure as Code. \r\n\r\nContinuous Deployment is all about continuously deploying new version of software on Test Environments. In even more mature organizations like Google, Facebook, Continuous Delivery helps in continuously deploying software to production - maybe hundreds of production deployments per day. \r\n\r\n[![Image](https://www.springboottutorial.com/images/devops-05-continuous-delivery.png \"DevOps Continuous Delivery\")](https://links.in28minutes.com/DevOps-SBT)\r\n\r\nInfrastructure as Code is all about treating your Infrastructure like you treat your application code. You create your infrastructure - servers, load balancers and database - in an automated way using configuration. You would version control your infrastructure - so that you can track your infrastructure changes over a period of time. \r\n\r\n[![Image](https://www.springboottutorial.com/images/devops-06-iaac-2-overview.png \"DevOps and Infrastructure as Code\")](https://links.in28minutes.com/DevOps-SBT)\r\n\r\n\r\n#### How did DevOps promote immediate feedback? \r\n\r\nDevOps brings Operations and Development Teams Together. Because Operations and Development are part of the same team, the entire team understands the challenges associated with Operations and Development. \r\n- Any operational problems get quick attention of the developers. \r\n- Any challenges in taking software live get early attention of operations team.\r\n\r\nDevOps encouraged Continuous Integration, Continuous Delivery and Infrastructure as Code.\r\n- Because of Continous Delivery, If I make a code change or a configuration change that might break a test or a staging environment, I would know it within a few hours.\r\n- Because of Infrastructure As Code, Developers can self provision environments, deploy code and find problems on their own, without any help from operations team. \r\n\r\nWhile we talk as if agile and devops are two different things to make things simple, in reality, there is no accepted definition for what devops means. \r\n\r\nI see agile and devops as two phases that helped us improve how build great software. They don't compete against each other but together they help us build amazing software products.\r\n\r\nAs far as iam concerned the objective of Agile and DevOps together is to do things that \r\n- Promote Communication and Feedback between Business, Development and Operations Teams\r\n- Ease the painpoints with Automation. We will discuss about Unit Tests, Integration Tests, Code Quality Checks, Continuous Integration, Continuous Delivery, Infrastructure as Code and Standardization through Containerization during this amazing journey in this course.\r\n\r\n## A DevOps Story\r\n\r\nHere's an amazing story:\r\n\r\nYou are the star developer in a team and you would need to make a quick fix. You go to a github repository! \r\n\r\nYou quickly checkout the project. \r\n\r\nYou quickly create your local environment. \r\n\r\nYou make a change. You test it. You update the unit and automation tests.\r\n\r\nYou commit it.\r\n\r\n[![Image](https://www.springboottutorial.com/images/devops-05-continuous-delivery.png \"DevOps Continuous Delivery\")](https://links.in28minutes.com/DevOps-SBT)\r\n\r\nYou get an email saying it is deployed to QA. \r\n\r\nA few integration tests are automatically run.\r\n\r\nYour QA team gets an email asking for approval. They do a manual test and approve.\r\n\r\nYour code is live in production in a few minutes.\r\n\r\nYou might think this is an ideal scenario. But, do you know that this is what is happening in innovative enterprises like Netflix, Amazon and Google day in and day out!\r\n\r\nThis is the story of DevOps. \r\n\r\n\r\n### DevOps = Development + Operations\r\n\r\nDevOps is a Natural Evolution of Software Development. DevOps is NOT JUST a tool, a framework or just automation. It is a combination of all these. \r\n\r\nDevOps focuses on People, Process and Products. People aspects of DevOps are all about Culture and Create a Great Mindset. A culture which promotes open communication and values quick feedback. A culture that value high quality software. \r\n\r\nAgile helped in bridging the gap between the business and development teams. Development Teams understood the priorities of the business and worked with the business to deliver the stories providing most value first. However, the Dev and Ops teams were not aligned.\r\n\r\nThey had different goals.\r\n\r\n> The goal of Dev team is to take as many new features to production as possible.\r\n\r\n> The goal of Ops team was to keep the production environment as stable as possible.\r\n\r\nAs you can see, if taking things to production is difficult, dev and ops are unaligned.\r\n\r\n> DevOps aims to align the Dev and Ops teams with shared goals. \r\n\r\nDev team works with the Ops team to understand and solve operational challenges. Ops team is part of the scrum team and understands the features under development.\r\n\r\n> How can we make this possible?\r\n\r\n> Break down the wall between Dev and Ops! \r\n\r\n#### Getting Dev and Ops Together - Option 1\r\n\r\nIn matured Dev Ops enterprises, Dev and Ops work as part of the same scrum team and share each other responsibilities. \r\n\r\n#### Getting Dev and Ops Together - Option 2\r\n\r\nHowever, if you are in the early stages of devops evolution, how can you get Dev and Ops have common objectives and work together?\r\n\r\nHere are some of the things you can do:\r\n- One of the things you can start with is to have the development team share some of the responsibilities of the operation team. For example, the dev team can take the responsibility of new release for the first week after production deployment. This helps the development team understand the challenges faced by operations in taking new releases live and help them come together and find better solutions.\r\n- Other thing you can do is to involve a representative of the operations team in the Scrum activities. Involve them in Stand ups and Retrospectives of the team.\r\n- The next thing you can do is to make the challenges faced by Operations team more visible to the Development team. When you face any challenges in operations, make development teams part of the teams working on solutions.\r\n\r\nWhich way you take, find ways of breaking the wall and get the Development and Operations team together.\r\n\r\nAnother interesting option emerges because of automation. By using Infrastructure as Code and enabling Self Provisioning for Developers, You can create common language that operations and development teams understand - code. More about this in the next couple of steps.\r\n\r\n### A DevOps Use Case\r\n\r\nConsider the picture below:\r\n\r\n[![Image](https://www.springboottutorial.com/images/devops-usecases-1-and-2.png \"DevOps Use case with Docker and Kubernetes\")](https://links.in28minutes.com/DevOps-SBT)\r\n\r\nThis picture show cases two simple workflows\r\n- No 1 : Infrastructure as Code using Terraform and Azure DevOps to provision Kubernetes Clusters\r\n- No 2 : Continuous Deployment of Microservices using Azure DevOps to build and deploy Docker images for microservices into Kubernetes Clusters\r\n\r\nDoes this sound complex?\r\n\r\nLet's break it down and try and understand them.\r\n\r\nLet's start with No 2 - Continuous Deployment first.\r\n\r\n#### No 2 : DevOps Continuous Deployment with Azure DevOps and Jenkins\r\n\r\nWhat is the use of having great tests and code quality checks if you don't run them often?\r\n\r\nWhat is the use of deployment automation if you don't deploy software often enough?\r\n\r\nAs soon as a developer commits code into the version control system, the following steps are executed:\r\n- Unit Tests \r\n- Code Quality Checks \r\n- Integration Tests \r\n- Application Packaging - Building a deployable version of application. Tools - Maven, Gradle, Docker\r\n- Application Deployment - Putting new applications or new versions of application live.\r\n- An email to the testing team to test the application.\r\n\r\nAs soon as there is an approval from the test team, the app is immediately deployed to the  Next Environment.\r\n\r\nThis is called Continuous Deployment. If you continuously deploy upto production, it is called Continuous Delivery.\r\n\r\nThe most popular CI CD Tools are Azure DevOps and Jenkins\r\n\r\n#### No 1 : DevOps Infrastructure as Code with Terraform\r\n\r\nIn older days, we used to create environments and deploy applications manually.\r\n\r\n[![Image](https://www.springboottutorial.com/images/devops-06-iaac-1-manual.png \"DevOps and Iac - Manual\")](https://links.in28minutes.com/DevOps-SBT)\r\n\r\nEverytime you create a server, this needs to be done manually. \r\n- What if Java version needs to be updated? \r\n- A security patch needs to be applied?\r\n\r\nYou do it manually.\r\n\r\nWhat is the result of this?\r\n- High Chance of Errors.\r\n- Replication environments is difficult.\r\n\r\n\r\n#### Infrastructure as Code\r\n\r\nInfrastructure as Code - Treat Infrastructure the same way as application code\r\n\r\nHere are some of the important things to understand with Infrastructure as Code\r\n- Infra team focuses on value added work (instead of routine work)\r\n- Less Errors and Quick Recovery from Failures\r\n- Servers are Consistent (Avoids Configuration Drift)\r\n\r\n[![Image](https://www.springboottutorial.com/images/devops-06-iaac-2-overview.png \"DevOps and Iac - Automated\")](https://links.in28minutes.com/DevOps-SBT)\r\n\r\nThe most popular IaC tools are Ansible and Terraform.\r\n\r\nTypically these are the steps in IaC\r\n- Provision Servers(Enabled by Cloud) from a Template\r\n- Install Software \r\n- Configure Software\r\n\r\n##### Server Provisioning\r\n\r\nTypically Provisioning Tools are used to provision servers and get new server ready with networking capabilities. The most popular provisioning tools are CloudFormation and Terraform. \r\n\r\nUsing Terraform, you can provision servers and rest of your infrastructure, like load balancers, databases, networking configuration, etc. You can create servers using pre created images created using tools like Packer and AMI (Amazon Machine Image).\r\n\r\n##### Configuration Management\r\n\r\nConfiguration Management tools are used to \r\n- Install Software \r\n- Configure Software\r\n\r\nPopular Configuration management tools are Chef, Puppet, Ansible, and SaltStack. These are designed to install and manage software on existing servers.\r\n\r\n### Role of Docker and Kubernetes in DevOps\r\n\r\nWhat is the role of Docker and Kubernetes in DevOps?\r\n\r\n[![Image](https://www.springboottutorial.com/images/docker-intro.png \"Docker\")](https://links.in28minutes.com/DevOps-SBT)\r\n\r\nIn the microservices world, a few microservices might be built with Java, a few with Python and a few with JavaScript.\r\n\r\nDifferent microservices will have different ways of building applications and deploying them to servers.\r\n\r\nThis makes operations team's job difficult.\r\n\r\nHow can we have similar way of deploying multiple types of applications? Enter Containers and Docker.\r\n\r\nUsing Docker you can build images of microservices - irrespective of their language - Java, Python or JavaScript. You can run these images the same way on any infrastructure.\r\n\r\nThis simplifies operations.\r\n\r\nKubernetes adds on to this by helping to orchestrate different types of containers and deploying them to clusters.\r\n\r\n[![Image](https://www.springboottutorial.com/images/kubernetes-01-intro.png \"Kubernetes\")](https://links.in28minutes.com/DevOps-SBT)\r\n\r\nKubernetes also provides\r\n- Service Discovery\r\n- Load Balancing\r\n- Centralized Configuration\r\n\r\nDocker and Kubernetes make DevOps easy.\r\n\r\n[![Image](https://www.springboottutorial.com/images/devops-06-iaac-4-containers.png \"Devops with Docker and Kubernetes\")](https://links.in28minutes.com/DevOps-SBT)\r\n\r\n\r\n### Important DevOps Metrics\r\n\r\nFollowing are some of the important DevOps metrics you can track and improve over a period of time.\r\n- Deployment Frequency - How often are applications deployed to production?\r\n- Time To Market - How long do you need to take a feature from coding to production?\r\n- Failure Rate of New Releases - How many of your releases fail?\r\n- Lead Time to Fixes - How long do you need to make a production fix and release it to production?\r\n- Mean Time to Recovery  - How long do you take to recover your production environment from a major issue?\r\n\r\n### DevOps Best Practices\r\n\r\nFollowing are some of the best practices with DevOps\r\n- Standardization \r\n- Teams with Cross Function Skills \r\n- Focus on Culture \r\n- Automate, Automate and ..  \r\n- Immutable Infrastructure \r\n- Dev Prod Parity \r\n- Version Control Everything \r\n- Self Provisioning \r\n\r\n### DevOps Maturity Signals\r\n\r\nHow do you measure the maturity of your DevOps Implementations. Here are some of the important questions to ask.\r\n\r\n#### Development\r\n- Does every commit trigger automated tests and automated code quality checks?\r\n- Is your code continuously delivered to production?\r\n- Do you use pair programming?\r\n- Do you use TDD and BDD? \r\n- Do you have a lot of re-usable modules?\r\n- Can development teams self provision environments?\r\n- How long does it take to deliver a quick fix to production?\r\n\r\n#### Test\r\n- Are your tests full automated with high quality production like test data?\r\n- Does your builds fail when your automated tests fail?\r\n- Are your testing cycles small?\r\n- Do you have automated NFR tests?\r\n\r\n#### Deployment\r\n- Do you have Dev Prod Parity?\r\n- Do you use A/B Testing?\r\n- Do you use canary deployments?\r\n- Can you deploy at the click of a button?\r\n- Can you rollback at the click of a button?\r\n- Can you provision and release infrastructure at the click of a button?\r\n- Do you use IAC and version control your infrastructure?\r\n\r\n#### Monitoring\r\n- Does the team use a centralized monitoring system?\r\n- Can development team get access to logs at the click of a button?\r\n- Does the team get an automated alert if something goes wrong in production?\r\n\r\n#### Teams and Processes\r\n- Is the team looking to continuously improve?\r\n- Does the team have all the skills it needs from Business, Development and Operations?\r\n- Does the team track the key devops metrics and improve on them?\r\n- Do you have the culture of take Local Discoveries and using them to make Global Improvements?\r\n\r\n### DevOps Transformation Best Practices\r\n- Leadership Buy-in is Critical \r\n- Involves Upfront Costs\r\n- Setup COEs to help teams\r\n- Choose the right application and team\r\n- Start Small \r\n- Sharing Learnings (Newsletters, Communication, COEs) \r\n- Encourage People with Exploration and Automation Mindset \r\n- Recognize DevOps Teams\r\n\r\n## Before You Go - Our Amazing DevOps Course\r\n\r\nIf you loved this article, you will love our course on DevOps\r\n- 200+ Videos. \r\n- 20+ Hours. \r\n- 6 DevOps Tools - Docker, Kubernetes, Azure DevOps, Jenkins, Terraform, and Ansible. \r\n- 3 Different Clouds - AWS, Azure and Google Cloud.\r\n\r\n[![Image](https://www.springboottutorial.com/images/Course-DevOps.png \"DevOps Course\")](https://links.in28minutes.com/DevOps-SBT)\r\n[![Image](https://www.springboottutorial.com/images/Course-go-serverless.png \"Go Serverless with AWS Lambda and Azure Functions\")](https://links.in28minutes.com/serverless-sbt)\r\n"
  },
  {
    "path": "_blog/articles/2020-03-14-Docker.md",
    "content": "---\r\nlayout:  post\r\ntitle: Docker Tutorial for Beginners - with Java and Spring Boot\r\ndate:    2020-03-14 12:31:19\r\nsummary:  Learn about Docker - What is Docker? Why Is Docker Popular? How to create Docker Image for a Java Spring Boot App?\r\ncategories:  SpringBootMicroservices\r\npermalink:  /docker-tutorial-for-beginners-java-spring-boot\r\nimage: /images/architecture.png\r\n---\r\n\r\nIn this article, we focus our attention on the Docker. Let's learn the fundamentals of Docker with a hand example building and running Docker Image for a Java Spring Boot Application.\r\n\r\n![alt text](images/docker-vs-VM-02.png)\r\n\r\n## You will learn\r\n\r\n- What is Docker?\r\n- Why Is Docker Popular?\r\n- Understand Docker Architecture\r\n- How to install Docker?\r\n- What is Docker Registry?\r\n- How to create Docker Hello World Rest API Image and Pull from Registry?\r\n- Deploy Hello World Spring Boot Application on Docker\r\n- Docker Commands\r\n\r\n### What is Docker?\r\n\r\nMicroservices in microservices architectures are written in multiple languages - Java, Python, JavaScript and more. However, you do not want to have deployment processes to be different for each type of microservices.\r\n\r\nHow can we have the flexibility of building microservices in multiple languages while having the same runtime and deployment process?\r\n\r\nHow about creating an application package that contains\r\n- Microservice application package (jar or war or js or python code)\r\n- and the runtime it needs (JRE or Python or NodeJS)\r\n\r\nThis package contains everything that a microservice needs to run. \r\n\r\nWhat does Docker do?\r\n- Docker provides a common approach and format for building self contained packages for your microservices. Docker calls this package an image.\r\n- Docker provides a runtime for running your image.\r\n\r\nWhat does this enable?\r\n- You can create Docker images for a wide variety of applications irrespective of their language, runtime or operating system.\r\n- You can run Docker images (as containers) where ever Docker runtime is available.   \r\n\r\nAre you ready to jump into the world of Docker?\r\n\r\n### Why is Docker Popular?\r\n\r\nDocker is popular because of the possibilites it opens for software delivery and deployment. Many common problems and inefficiences are resolved with containers.\r\n\r\nThe awesome thing about Docker is, you can easily install Docker on Cloud. Most of the cloud providers provide container based services\r\n\r\nThey provide services where you just need to provide a docker Image and it would automatically run on the cloud.\r\n\r\n### The Virtual Machine Legacy\r\n\r\nBefore Docker, virutal machines were very popular.\r\n\r\nThe image below shows the typical architecture with a Virtual Machine\r\n![alt text](images/vm-architecture.png)\r\n\r\nAs you can see there are two operating systems present one is Guest OS and another is Host OS.\r\n\r\nDue to this, virutal machine architecture becomes heavyweight. Hence you will not be able to benefit from the entire power of your hardware because of virutalization.\r\n\r\n![alt text](images/docker-vs-VM-02.png)\r\n\r\nWith Docker, all that you need to run containers is a Docker Engine. Other main reasons why Docker is popular is:\r\n\r\n#### Docker Images Are Self Sufficient\r\n\r\nThe Docker image contains all that is needed to run a container: the libraries, the software are directly part of these containers.\r\n\r\n#### Docker is Light Weight\r\n\r\nBecause there is just one OS, the host OS, Docker is relatively lightweight and therefore, is very efficient. \r\n\r\n#### Docker Is Convenient For Cloud\r\n\r\nAll the cloud providers provide a number of container orchestration services around Docker.\r\n- Azure provides a service called Azure Container Service. \r\n- AWS, Amazon Web Services, provides a service called Elastic Container Service and also AWS Fargate. \r\n\r\nKubernetes is a popular container orchestration platform. All Cloud Providers provide services around Kubernetes.\r\n\r\nThe rise of microservice architecture also one of the reason for Docker popularity.\r\n\r\n### Understand Docker Architecture\r\n\r\nDocker uses a client-server architecture. The Docker client talks to the Docker `daemon`, which does the heavy lifting of building, running, and distributing your Docker containers. The Docker client and daemon can run on the same system, or you can connect a Docker client to a remote Docker daemon. The Docker client and daemon communicate using a REST API, over UNIX sockets or a network interface. \r\n\r\n![Docker Architecture](images/docker-architecture.png)\r\n\r\n#### Docker daemon\r\n\r\nThe Docker daemon(dockerd) listens for Docker API requests and manages Docker objects such as images, containers, networks, and volumes. A daemon can also communicate with other daemons to manage Docker services.\r\n\r\nIt is responsible for \r\n- Managing Containers\r\n- Managing local Images\r\n- Pulling images from the image registry if you need it\r\n- Pushing a locally created image to an image registry\r\n\r\n#### Docker Client\r\n\r\nThe Docker client``(docker)`` is the primary way that many Docker users interact with Docker. When you use commands such as ``docker run``, the client sends these commands to ``dockerd``, which carries them out. The ``docker`` command uses the Docker API. The Docker client can communicate with more than one daemon.\r\n\r\n\r\n#### Docker Registry\r\n\r\nA Docker ``registry`` stores Docker images. Docker Hub is a public registry that anyone can use, and Docker looks for images on Docker Hub by default. \r\n\r\nWhen you use the ``docker pull`` or ``docker run`` commands, the required images are pulled from your configured registry. When you use the ``docker push`` command, your image is pushed to your configured registry.\r\n\r\n### How to install Docker?\r\n\r\nDocker makes the life of a developers and operations team simple.\r\n\r\nInstalling Docker today on most of the operating systems is really a cakewalk!\r\n\r\nWe recommend installing Docker Desktop on Mac and Windows.\r\n- Mac - https://docs.docker.com/docker-for-mac/install/\r\n- Windows - https://docs.docker.com/docker-for-windows/install/\r\n\r\nOn Linux, you can find instructions for your specific distribution at https://docs.docker.com/install/.\r\n\r\nFor verify whether it has been installed or not, open command prompt and type following command:\r\n\r\n``$ docker --version``\r\n\r\n``Docker version 19.03.5, build 633a0ea``\r\n\r\n### What is Docker Registry?\r\n\r\nA Docker registry contains a lot of repositories, different versions of various applications. Since Docker Hub is a public registry, anybody can access it.\r\n\r\nTypically, when we work in an enterprise, we use private repositories, so that our images can only be accessed by somebody who has the right credentials.\r\n\r\n### Docker Container for Spring Boot Hello World Application\r\n\r\nThe complete project is located at https://github.com/in28minutes/docker-crash-course/tree/master/01-hello-world-rest-api.\r\n\r\nYou can clone or download the entire github repository and import this project as a maven project into eclipse.\r\n\r\nHere is the screenshot of the project setup in Eclipse.\r\n\r\n![alt text](images/04-containerizing-java-spring-boot-hello-world-rest-api-step01-001.png)\r\n\r\nIf you are new to Spring and Spring Boot, you can watch these - [Spring in 10 Steps](https://courses.in28minutes.com/p/spring-framework-for-beginners) and [Spring Boot in 10 Steps](https://courses.in28minutes.com/p/spring-boot-for-beginners-in-10-steps) to understand how Spring and Spring Boot work together.\r\n\r\nLet's now build a Docker image for the Hello World Rest API. Let's start with following a manual approach to create the image.\r\n\r\n### Step 1 : Create a JAR File\r\n\r\nThe first thing we need to do is build a JAR for the application. This particular application is packaged as a JAR file.\r\n\r\nBuilding a JAR file should be really easy. All that you need to is do a clean Maven build, by say saying ```mvn clean package```. \r\n\r\n**pom.xml :**\r\n\r\n```\r\n\r\n\t\t<groupId>com.in28minutes.rest.webservices</groupId>\r\n\t\t<artifactId>01-hello-world-rest-api</artifactId>\r\n\t\t<version>0.0.1-SNAPSHOT</version>\r\n\t\t<packaging>jar</packaging>\r\n\t\t<description>Demo project for Spring Boot</description>\r\n\t\t<name>hello-world-rest-api</name>\r\n\t\t<parent>\r\n\t\t\t<groupId>org.springframework.boot</groupId>\r\n\t\t\t<artifactId>spring-boot-starter-parent</artifactId>\r\n\t\t\t<version>2.1.7.RELEASE</version>\r\n\t\t\t<relativePath /> <!-- lookup parent from repository -->\r\n\t\t</parent>\r\n```\r\n\r\nThis would compile the code, run the unit tests, and finally, a JAR would be packaged. \r\n\r\n![image info](images/04-containerizing-java-spring-boot-hello-world-rest-api-step02-003.png)\r\n![image info](images/04-containerizing-java-spring-boot-hello-world-rest-api-step02-004.png)\r\n\r\nThe name of the JAR is ```hello-world-rest-api.jar```, and it is under the ```target``` folder. \r\n\r\nThe name of the JAR is coming in from ```pom.xml```. If you search for something called ```FinalName``` in the build, we are configuring a name for this specific JAR, hello-world-rest-api.jar. \r\n\r\n**pom.xml :**\r\n\r\n```\r\n\r\n\t<build>\r\n\t\t<finalName>hello-world-rest-api</finalName>\r\n\t\t<plugins>\r\n\t\t\t<plugin>\r\n\t\t\t\t<groupId>org.springframework.boot</groupId>\r\n\t\t\t\t<artifactId>spring-boot-maven-plugin</artifactId>\r\n\t\t\t</plugin>\r\n\t\t</plugins>\r\n\r\n\t</build>\r\n\r\n\r\n```\r\n### Step 2 : Decide the right base image\r\n\r\nThe second thing would be to setup the prerequisites for running the JAR file.\r\n\r\nWe need Java installed, and we'll use a ```OpenJDK``` image, such as ```openjdk:8-jdk-alpine```. This is the most popular image used to run Java 8. \r\n\r\n> Alpine images is based on AlpineLinux to keep the size of the image down.\r\n\r\nLet's now run the alpine jdk image.\r\n\r\n`docker run -dit openjdk:8-jdk-alpine`.\r\n\r\n> ```-dit``` > ```-d``` is actually something which allows us to run the container in a detached mode. The container is running but we want to be able to execute the commands in using an interactive shell. With `-it`, we are attaching a interactive shell to the running container. This allows us to execute a command against the running container.\r\n\r\n```openjdk:8-jdk-alpine``` image will be dowloaded from Docker Hub. It would take a little while as it is a large - ```100 MB``` download. \r\n\r\nYou can run `docker images` to see the downloaded image.\r\n![alt text](images/04-containerizing-java-spring-boot-hello-world-rest-api-step02-007.png)\r\n\r\nRun ```docker container ls``` to see the running container -  ```naughty_knuth```. \r\n\r\n### Step 3 : Copy the JAR File into Docker Image\r\n\r\nThe third step is to copy the JAR into the specific image. Then, we would want to be able to run the JAR as part of the container. Let's get started with all that right now. \r\n\r\n#### Copying The JAR File\r\n\r\nHere's the command to copy a jar file into the container:\r\n\r\n`docker container cp target/hello-world-rest-api.jar naughty_knuth:/tmp`\r\n![image info](images/04-containerizing-java-spring-boot-hello-world-rest-api-step02-008.png)\r\n![image info](images/04-containerizing-java-spring-boot-hello-world-rest-api-step02-009.png)\r\n![image info](images/04-containerizing-java-spring-boot-hello-world-rest-api-step02-010.png)\r\n\r\nYou can also use the ID of the container. \r\n\r\n`docker container cp target/hello-world-rest-api.jar 54cf414254e48d5f68c4d468b2dd4cbdd95d17f9e2074fdb9df7f64987697f2b:/tmp`\r\n\r\nThe command successfully executed, which means our JAR file is now copied into the running container. \r\n\r\nLet's see what is inside the container:\r\n\r\n```docker container exec naughty_knuth ls /tmp```. \r\n\r\nYou will see the jar file - ```hello-world-rest-api.jar```\r\n\r\n### Step 4 : Running The JAR Within The Container \r\n\r\nNow, we would want to run this JAR. Before that, we need to do two simple steps. \r\n\r\n#### Saving The Container Image\r\n\r\nThe first step is, actually to save the container which we have created, as a image. \r\n\r\nHere's the command:\r\n```docker container commit naughty_knuth in28min/hello-world-rest-api:manual1```\r\n\r\nWe are giving a repository name of ```in28min/hello-world-rest-api``` and a tag of ```manual1```.\r\n\r\nIf you run `docker images` you would see a new image.\r\n\r\n#### Running The Image\r\n\r\nLet's see if we can run this image. \r\n\r\n```docker run in28min/hello-world-rest-api:manual1```\r\n\r\nLet's see if there are anything running at this point in time.\r\n\r\n```docker container ls```. \r\n\r\nYou will see that the container which we launched just is not really running at all!\r\n\r\nHow can we get it to run the application?\r\n\r\n#### Attaching The JAR To Startup\r\n\r\nThe reason it is not running is we did not attach anything to run at launch of the container. \r\n\r\nWe would want to launch a java application jar at startup of the container. We copied the JAR file into this image, but did not specify that the JAR file has to be launched at startup. \r\n\r\nHow can we do that?\r\n\r\n`docker container commit --change='CMD [\"java\",\"-jar\",\"/tmp/hello-world-rest-api.jar\"]' naughty_knuth in28min:hello-world-rest-api:manual2`\r\n\r\nWe are adding a startup command by using an option ```--change```. \r\n\r\n![image info](images/04-containerizing-java-spring-boot-hello-world-rest-api-step02-011.png)\r\n\r\n#### Running The Container Again\r\n\r\nLet's do ```docker images```, and a new image is seen to be created with tag as ```manual2```. Now, we can run it saying ```docker run in28min/hello-world-rest-api:manual2```. We would also want to publish the port, as in ```8080:8080```. \r\n\r\n```docker run -p 8080:8080 in28min/hello-world-rest-api:manual2```\r\n\r\n> If you have any container running on 8080, you can stop it.\r\n\r\n![image info](images/04-containerizing-java-spring-boot-hello-world-rest-api-step02-013.png)\r\n\r\nIf we go to the browser and refresh, the URL continues to work. \r\n\r\n![image info](images/04-containerizing-java-spring-boot-hello-world-rest-api-step02-014.png)\r\n\r\nThis image we can share with anyone in the world and they can run in all environment they would wish to.\r\n\r\n#### Creating the Image using Dockerfile\r\n\r\nThe command is shown below:\r\n\r\n`docker build -t in28min/hello-world-rest-api:dockerfile1 .`\r\n\r\nCouple of important things to note:\r\n- `-t` option is to specify the repository name and the tag\r\n- `.` is used to specify build context\r\n\r\n![image info](images/04-containerizing-java-spring-boot-hello-world-rest-api-step03-005.png)\r\n\r\nThe build context (current folder) is sent to Docker Daemon and after that, different steps are executed. Finally, we have a image built, and the image is also tagged with this specific tag name that we gave it. \r\n\r\n#### Running The Container\r\n\r\nLet's run the command\r\n\r\n`docker run -p 8080:8080 in28min/hello-world-rest-api:dockerfile1`\r\n\r\nThe application is up and running. Let's see what we have in the browser at the URL ```localhost:8080/hello-world```. \r\n\r\n![image info](images/04-containerizing-java-spring-boot-hello-world-rest-api-step03-007.png)\r\n\r\nCool! We have the application up and running in the browser as well. \r\n\r\nWe have now created a ```Dockerfile```, and used that ```Dockerfile``` to build a image.\r\n\r\n### 2. Using Jib Plugin To Create Docker Images\r\n\r\nThe Dockerfile Maven plugin is from Spotify, and the great thing about it, is it provides a clear separation between what the ```Dockerfile``` does, and what the Spotify Dockerfile Maven plugin does. \r\n\r\n#### Building a Docker Image with Spotify Maven plugin\r\n\r\nHere are the important steps:\r\n- Instructions are specified in the ```Dockerfile```\r\n- Spotify Dockerfile Maven plugin is responsible for integrating the building of image with the Maven build process\r\n\r\n\r\n#### Jib - Alternative To ```Dockerfile```\r\n\r\nOne of the popular alternatives to Spotify Dockerfile Maven Plugin is ```JIB```. \r\n\r\nHomepage of Jib is [https://github.com/GoogleContainerTools/jib](https://github.com/GoogleContainerTools/jib).\r\n\r\n> Jib is a Maven plugin for building Docker and OCI images for your Java applications. \r\n\r\n#### Understanding The Open Container Initiative (OCI)\r\n\r\n**OCI** is **Open Container Initiative**. Just like you have interfaces and you have implementations, OCI is like an interface, and Docker image is an implementation of OCI. \r\n\r\nOCI is a specification, and any container image creator can choose to adhere to the OCI standards. Docker has taken active part in creating the OCI specification, and also adheres to the OCI specification. \r\n\r\n#### Getting Started With Jib\r\n\r\nThe most important point you need to remember about Jib is, you don't need ```Dockerfile``` at all. \r\n\r\nHere's a project ready to use with JIB Plugin - https://github.com/in28minutes/docker-crash-course/blob/master/01-hello-world-rest-api/code-backup/02-jib.md\r\n\r\nImportant configuration is shown below:\r\n\r\n```\r\n<plugin>\r\n\t<groupId>com.google.cloud.tools</groupId>\r\n\t<artifactId>jib-maven-plugin</artifactId>\r\n\t<version>1.6.1</version>\r\n\t<configuration>\r\n\t\t<container>\r\n\t\t\t<creationTime>USE_CURRENT_TIMESTAMP</creationTime>\r\n\t\t</container>\r\n\t</configuration>\r\n\t<executions>\r\n\t\t<execution>\r\n\t\t\t<phase>package</phase>\r\n\t\t\t<goals>\r\n\t\t\t\t<goal>dockerBuild</goal>\r\n\t\t\t</goals>\r\n\t\t</execution>\r\n\t</executions>\r\n</plugin>\r\n```\r\n\r\nA few important things to note:\r\n- In the configuration, we are using `USE_CURRENT_TIMESTAMP`. By default, JIB adds a constant timestamp to ensure reproducibility of images. We are overriding it to use the current timestamp.\r\n- `package` - We are configuring the JIB plugin to run during the package phase \r\n\r\n> If we have some source code and generate a image today, and then use the same source code to generate another image one year later, we should get the same image. This is called reproducibility of images. The thing is, if you have different creation timestamp on these images, the final hash for these images will be different. By default, Jib puts a creation date of ```1-1-1970```. In computer terminology, that's what is called the **\"Epoch\"**, the start of time for computers. \r\n\r\n\r\nYou can now run ```mvn clean package```, and see the magic unfold. \r\n\r\n![image info](images/04-containerizing-java-spring-boot-hello-world-rest-api-step08-005.png)\r\n\r\n![image info](images/04-containerizing-java-spring-boot-hello-world-rest-api-step08-006.png)\r\n\r\nThe first time with Jib, the build will be a little slow because it is downloading a lot of stuff. \r\n\r\nThe artifact id is being used as the repository name, and the version is being used as the tag. \r\n\r\n#### Jib does not need Dockerfile\r\n\r\nOne interesting thing you'd note in here is, Jib is able to automatically detect that ```RestfulWebServicesApplication```, is the class that we would want to run. \r\n\r\nRemember, that we don't have a Dockerfile configured at all. So, Jib is automatically able to detect the type of project and identify the class to run as ENTRYPOINT.\r\n\r\n#### Examining The Jib generated Image\r\n\r\nNow, before we go any further, let's see actually what's inside that image. If we do a ```docker history``` and use the image name created by Jib, there are multiple images present. \r\n\r\n![image info](images/04-containerizing-java-spring-boot-hello-world-rest-api-step08-007.png)\r\n\r\nThe base image which is viewed by Jib is something called distroless Java. We can change the base image as well, a little later.For now, the important thing to remember is Jib builds the images in multiple layers. \r\n\r\nInstead of copying a fat JAR in, JIB explodes the fat JAR, copies the dependencies first, and the classes later:\r\n- The dependencies are being copied in first - ```16.9 MB```\r\n- then the resources - which are the property files\r\n- and after that, the actual classes\r\n\r\n#### Running The Jib Generated Image\r\n\r\nYou can also run this image.\r\n\r\n`docker run -p 8080:8080 webservices/01-hello-world-rest-api`\r\n\r\n![image info](images/04-containerizing-java-spring-boot-hello-world-rest-api-step08-008.png)\r\n\r\nWe have seen that Jib makes it very easy to generate your Docker images. All that we needed to do was, add a simple plugin in and that's it. No ```Dockerfile``` is required. \r\n\r\n#### Configurations Supported By Jib\r\n\r\nJib also supports a lot of configuration.\r\n\r\nThe default base image for Jib is distroless Java. To specify that you want to use ```openjdk:alpine```, you can configure the image name as well. You can configure the tags as well. \r\n\r\nIt is possible to configure JVM options, and the main class. If the default main class picked up by Jib is not the right one, you can configure the main class as well. You can also configure the container port for the image. \r\n\r\nIf your needs are very very simple, Jib is an awesome tool. It adheres to all the best practices of generating container images. \r\n\r\n### Jib Is Java Specific\r\n\r\nHowever, Jib is Java-specific. If you want to build container images for projects outside Java, Jib is not the right option. We would recommend you explore the FAQ around Jib for more information on the Jib plugin.\r\n\r\n[](https://github.com/GoogleContainerTools/jib/blob/master/docs/faq.md)\r\n\r\n### 3. Using Fabric8 Docker Maven Plugin To Create Docker Images\r\n\r\nWith Spotify Dockerfile Maven plugin, we needed a Dockerfile, and the plugin would integrate the creation of the image with the Maven build process. \r\n\r\nWith Jib, we don't really need a Dockerfile at all. The plugin would automatically create the container image based on the best practices. \r\n\r\n### Introducing The Fabric8 Docker Maven Plugin\r\n\r\nThe next plugin which we will quickly look at is something called Fabric8 Docker Maven Plugin. The home page is [dmp.fabric8.io](dmp.fabric8.io). \r\n\r\n> One interesting fact is that this was one of the first Maven plugins integrated well with Docker. \r\n\r\nThe original intention for the Docker Maven plugin was as a replacement of ```Dockerfile```. \r\n\r\nToday, almost everybody uses ```Dockerfile``` to specify the instructions to create the image. When this plugin came in in 2015, ```Dockerfile``` was not as popular as it is today. \r\n\r\n### The Options With The Fabric8 Plugin \r\n\r\nHere's a simple configuration of the plugin to use an existing Dockerfile:\r\n\r\n```\r\n\t\t<!-- To build the image - \"mvn clean package\" -->\r\n\t\t\t<!-- Successfully tagged webservices/01-hello-world-rest-api -->\r\n\t\t\t<!-- docker run -p 8080:8080 webservices/01-hello-world-rest-api -->\r\n\t\t\t<plugin>\r\n\t\t\t\t<groupId>io.fabric8</groupId>\r\n\t\t\t\t<artifactId>docker-maven-plugin</artifactId>\r\n\t\t\t\t<version>0.26.0</version>\r\n\t\t\t\t<executions>\r\n\t\t\t\t\t<execution>\r\n\t\t\t\t\t\t<id>docker-build</id>\r\n\t\t\t\t\t\t<phase>package</phase>\r\n\t\t\t\t\t\t<goals>\r\n\t\t\t\t\t\t\t<goal>build</goal>\r\n\t\t\t\t\t\t</goals>\r\n\t\t\t\t\t</execution>\r\n\t\t\t\t</executions>\r\n\t\t\t</plugin>\r\n```\r\n\r\nThe complete project is present here:\r\n\r\n[https://github.com/in28minutes/docker-crash-course/blob/master/01-hello-world-rest-api/code-backup/03-fabric8-docker-plugin-using-dockerfile.md](https://github.com/in28minutes/docker-crash-course/blob/master/01-hello-world-rest-api/code-backup/03-fabric8-docker-plugin-using-dockerfile.md)\r\n\r\nYou can add the plugin and specify that in the package phase, we want to execute the build goal. It then uses the ```Dockerfile``` present in the root of the project. When you execute ```mvn clean package```, it would build the image using that ```Dockerfile```. \r\n\r\nIn that sense, it's similar to Spotify Docker Maven plugin. \r\n\r\nYou can also configure the name of the final jar file as a maven property. \r\n```\r\n<!-- Needed by io.fabric8 docker-maven-plugin-->\r\n<jar>${project.build.directory}/${project.build.finalName}.jar</jar>\r\n```\r\n\r\n### Configuring The ```pom.xml``` - Options\r\n\r\nThe other possibility with the Fabric8 Docker Maven plugin is to specify the ```Dockerfile``` instructions directly inside your plugin configuration. \r\n\r\nThis was a popular way of doing it before ```Dockerfile``` really became famous, and is not common today. \r\n\r\nHere's an example:\r\n\r\n```\r\n<plugin>\r\n\t<groupId>io.fabric8</groupId>\r\n\t<artifactId>docker-maven-plugin</artifactId>\r\n\t<version>0.26.0</version>\r\n\t<extensions>true</extensions>\r\n\t<configuration>\r\n\t\t<verbose>true</verbose>\r\n\t\t<images>\r\n\t\t\t<image>\r\n\t\t\t\t<name>${project.artifactId}</name>\r\n\t\t\t\t<build>\r\n\t\t\t\t\t<from>java:8-jdk-alpine</from>\r\n\t\t\t\t\t<entryPoint>\r\n\t\t\t\t\t\t<exec>\r\n\t\t\t\t\t\t\t<args>java</args>\r\n\t\t\t\t\t\t\t<args>-jar</args>\r\n\t\t\t\t\t\t\t<args>/maven/${project.build.finalName}.jar</args>\r\n\t\t\t\t\t\t</exec>\r\n\t\t\t\t\t</entryPoint>\r\n\t\t\t\t\t<assembly>\r\n\t\t\t\t\t\t<descriptorRef>artifact</descriptorRef>\r\n\t\t\t\t\t</assembly>\r\n\t\t\t\t</build>\r\n\t\t\t</image>\r\n\t\t</images>\r\n\t</configuration>\r\n\t<executions>\r\n\t\t<execution>\r\n\t\t\t<id>docker-build</id>\r\n\t\t\t<phase>package</phase>\r\n\t\t\t<goals>\r\n\t\t\t\t<goal>build</goal>\r\n\t\t\t</goals>\r\n\t\t</execution>\r\n\t</executions>\r\n</plugin>\r\n```\r\n\r\n### Why So Many Plugins?\r\n\r\nOne question does arise: why do we need these many plugins? The most important thing is, you don't really need to be an expert in all these plugins. \r\n\r\nThe documentation of these plugins is quite good. If you face a problem, you should be able to easily fix it by looking at the documentation. It's very important, at a high-level, to be aware of the important things behind each plugin. \r\n\r\n### The essential Differences Among Plugins\r\n\r\nThe Dockerfile Maven plugin provides you a clear separation. You specify all the build instructions in the ```Dockerfile```, and the plugin integrates the build of the Docker image into your Maven's lifecycle. \r\n\r\nJib, on the other hand, takes complete control. It doesn't need the Dockerfile at all, and creates the image for you. \r\n\r\nThe Fabric8 Docker Maven plugin, on the other hand, provides two options. It says, either you can use the Dockerfile, or you can specify XML configuration telling what needs to be done. \r\n\r\nIf you look at the industry today, most of the people use external ```Dockerfile``` configuration. \r\n\r\nUsing an external ```Dockerfile``` gives us complete control over the Docker image that is being created.\r\n\r\nThe other important thing is, this is language-independent. We can use this Dockerfile whether we are trying to build a Java project, a Python project, or a frontend project. \r\n\r\n\r\n## Docker Commands\r\n\r\n| Docker Command        | Description   |  Usage with an Example |\r\n| :-------------------- |:---           |:-                      |\r\n| ``docker version``     | Show the docker CLI version  | ``$ docker --version`` ``Docker version 19.03.5, build 633a0ea``  |\r\n| ``docker build``       | Build an image from a Dockerfile | ``$ docker build -t in28min/hello-world-rest-api:dockerfile1 .`` |\r\n| ``docker commit``\t      | Create a new image from a container’s changes | ``$ docker container commit --change='CMD [\"java\",\"-jar\",\"/tmp/hello-world-rest-api.jar\"]' unruffled_tereshkova in28min:hello-world-rest-api:manual2`` |\r\n| ``docker images``       | List images  | ``$ docker images``  |\r\n| ``docker attach``       | Attach local standard input, output, and error streams to a running container  |   |\r\n| ``docker builder``      | Manage builds  |   |\r\n| ``docker checkpoint``   | Create a new image from a container's changes   |   |\r\n| ``docker config``  |  Manage Docker configs |   |\r\n| ``docker container``  |  Manage containers |   |\r\n| ``docker run`` |  Run a command in a new container | ``$ docker run -p 8080:8080 in28min/hello-world-rest-api:manual`` OR ``$ docker run -p 8080:8080 webservices/01-hello-world-rest-api``  |\r\n| ``docker ps``  | Shows list of containers  | ``$ docker ps``  |\r\n| ``docker pull`` | Pull an  image or a repository from a docker registry and specify an image  |   |\r\n| ``docker push``  | Push an image or a repository to a hub registry |   |\r\n| ``docker rm``  | Remove one or more containers by specifying ``container Id`` separating by ``(,)``  | ``$ docker rm <CONTAINERID(S)>``  |\r\n| ``docker rmi`` | Remove one or more images by specifying ``image id `` separating by ``(,)`` | ``$ docker rmi <IMAGEID(S)>``  |\r\n| ``docker start``  |  Start one or more stopped containers  | ``$ docker start``  |\r\n| ``docker stop`` | Stop one or more running containers  | ``$ docker stop``  |\r\n| ``docker inspect`` | Displays granular level information about Docker object | ``$ docker inspect in28min/hello-world-rest-api:dockerfile1`` |\r\n| ``docker history`` | Show the history of an image | ``$ docker history in28min/hello-world-rest-api:dockerfile1`` |\r\n| ``docker network ls`` | List of networks | ``$ docker network ls`` |\r\n| ``docker network create`` | Create a network | ``$ docker network create web-application-mysql-network`` |\r\n| ``docker network inspect`` | Display detailed information on one or more networks | ``$ docker network inspect <NETWORKD ID>`` |\r\n\r\n\r\n\r\n## Before You Go - Our Amazing DevOps Course\r\n\r\nIf you loved this article, you will love our course on DevOps\r\n- 200+ Videos\r\n- 20+ Hours\r\n- 6 DevOps Tools - Docker, Kubernetes, Azure DevOps, Jenkins, Terraform, and Ansible\r\n- 3 Different Clouds - AWS, Azure and Google Cloud\r\n\r\n[![Image](https://www.springboottutorial.com/images/Course-DevOps.png \"DevOps Course\")](https://links.in28minutes.com/DevOps-SBT)"
  },
  {
    "path": "_blog/articles/2020-09-28-best-practices-in-microservices.md",
    "content": "---\nlayout:  post\ntitle:  Best practices in Microservices\ndate:    2022-06-09 12:31:19\nsummary: In this post, we will look at best practices for microservices architecture.\ncategories: SpringBootMicroservices\npermalink:  /best-practices-in-microservices-architecture\nimage: /images/microservices-category.png\n---\n\n\nLet's look at some of the most frequent best practices to keep in mind while establishing or maintaining ***Microservices***. Let's get started.\n\n## Separate Data Storage\n\nThis is a key consideration when constructing microservices since we want to separate data storage for each microservice. This remark frequently refers to the *Command and Query Responsibility Segregation (CQRS)*, in which we define the microservices to have distinct reading and writing into the various models. However, there is always a conflict of interest among certain developers who favour the shared database strategy when creating microservices, yet best practises dictate that each microservice have its own persistent storage.\n\n## Dedicated Teams\n\nIt is tough for a single developer in the microservices era to comprehend the entire enterprise-based programme. Because microservices are autonomous entities, it is simple to grasp 10 or 15 microservices, but having a complete set is tough because technology sets span from backend to frontend and continuous integration to deployment. As a result, switching technologies might require time and effort. So, in a microservice environment, the ideal way is to have specialised teams to keep them conversant with the complexities of management while guaranteeing optimum efficiency.\n\n## Automation of Deployment\n\nAs they are independent, the terms Continuous Integration and Continuous Deployment (CI/CD) are highly popular in today's environment for the microservices architecture. As a result, we must design a build and release automation system to decrease overall lead time.\n\n## REST API Implementation\n\nDevelopers nowadays choose to use the REST API to accomplish business-related processes via software evolution. They don't dislike frontend, it's simply that REST API installation is quick and straightforward because there is no framework to learn and then apply. So I'd want to make the point here that one may simply start at level 0 and work their way up to level 3 of the [Richarson maturity model](https://martinfowler.com/articles/richardsonMaturityModel.html).\n\n## Following the Design Patterns\n\nThere are several design patterns that may help developers design microservices correctly, but one of the greatest is the *Decomposition Design Pattern*, which helps to break down a monolithic programme into smaller independent microservices. Using the strangler or vine design patterns, the decomposition design pattern assists in breaking down a monolithic application either by business or domain capability or by service by service.\n\n## Isolation of Runtime Processes\n\nWe require isolation at the runtime level since we have distinct microservices. Isolation means that we need some kind of distributed computing resources to pull this off from a pool of accessible resources, such as container orchestration, multiple HTTP techniques, Service Meshes, Circuit Breakers for fault tolerance, and so on.\n\n## Consider using Domain-Driven Design Technique\n\nAs microservices are usually structured around business domains, it is as easy as *Object-oriented programming*, which uses practical principles and concepts to represent the object-oriented model. This design method is frequently used by content delivery network(CDN) services such as Netflix, Hotstar, Amazon Prime, and others.\n\n## Wrapping Up\n\nWhen you begin the process of converting your system to a microservices design, it is critical to have a clear knowledge of the best practices and the true motivation for doing so. In addition to these best practices, the project's capacity to handle end-to-end service-oriented architecture migrations and development must be considered.\n"
  },
  {
    "path": "_blog/articles/2020-09-28-demoposition-design-pattern-microservices.md",
    "content": "---\nlayout:  post\ntitle:  Design Pattern in Microservices\ndate:    2022-06-09 12:31:19\nsummary: In this post, we will look at the decomposition design pattern in the context of microservices architecture\ncategories: SpringBootMicroservices\npermalink:  /decomposition-design-pattern-in-microservices-architecture\nimage: /images/microservices-category.png\n---\n\n# Design Pattern in Microservices\n\nHello and welcome to [in28minutes.com](https://courses.in28minutes.com/). We'll look at some of the intriguing *Decomposition Design Patterns* in a microservices architecture in this article.\n\n## Decomposition Design Patterns\n\nThe deconstruction design pattern (i.e. breaking down an application into tiny independent microservices) is based on the following capabilities in the actual world of microservices: -\n\n - Business capacity decomposition\n - Subdomain decomposition\n - Transactional decomposition\n - Strangler or the Vine pattern\n - Bulkhead pattern\n\nThe primary goal of this design pattern is to - \n\n - Obtain an independent team and services\n - Stay away from distributed monolithic architecture.\n - Avoid application-wide cascade failures.\n - Reduce the complexity of business logic.\n\nNow let us go ahead and understand the important ones.\n\n### Business capacity decomposition\n\n - This is the simplest of all patterns accessible under the deconstruction design pattern umbrella, as far as architects are concerned -\n\t - Determine the company's capabilities.\n\t - Define the services required for those business capabilities.\n\n### Subdomain decomposition\n\n - It is a design pattern that adheres to the domain-driven approach, in which the individual microservices are loosely connected and less coherent.\n - This pattern is composed of four stages, namely\n\t - *Analyze the Domain* - Choose a specific region, component, or problem that will be addressed through software enhancement.\n\t - *Identify SubDomain* - Break Download the specific item in smaller portions to discover the issues that need the adoption of a software solution.\n\t - *Define the Bounded Contexts* - Bounded context refers to determining the limit of a certain business capability. This stage aids in the identification of domain models and qualities required in each model. Remember that this phase aids in the definition of the **Domain Model Pattern** and **Aggregate Pattern**.\n\t - *Design Microservices* - Each constrained context generated in Step 3 corresponds to a separate microservice that is reliant on a business context. Each microservice should not have any overlap with other constrained contexts.\n\n### Strangler Design Pattern\n\n - The **Strangler** design pattern is one of many that allows you to quickly divide a large monolithic application into smaller independent microservices.\n - Allows for the progressive disintegration of a monolithic programme by replacing a specific component with a standalone microservice.\n - Aids in the implementation of test-driven development with the greatest level of Code Quality, Business Logic, and Sonar Analysis.\n - Follow the Transform, Co-exist, and Eliminate strategy.\n\t - *Transform* refers to the creation of a new independent component.\n\t - *Co-exists* refers to both new and old components operating in tandem.\n\t - *Eliminate* means to remove the old component and replace it with the new component.\n - Monolithic component selection for refractor -\n\t - If you're a beginner, start with the simplest component or,\n\t - Choose a sonar component with high coverage and little technical debt or,\n\t - Choose the component that is most appropriate for cloud architecture and has scalability needs. or,\n\t - Choose the component that has the least amount of business effect and requires frequent deployment.\n\n### Bulkhead Design Pattern\n\n - The Bulkhead design pattern is one of several that aids in the creation of failure-tolerant programmes.\n - Application elements are segregated into pools in this design so that if one fails, the others will continue to operate.\n - This pattern aids in the resolution of quality concerns like as -\n\t - Failure propagation occurs because the elements are separated and do not share resources (like Storage, Synchronous Service-to-Service calls, Hardware, etc.)\n\t - Noisy neighbours are those in which the aberrant use of resources by one element has no effect on the other parts of the bulkhead design pattern.\n\t - Unusual demands from elements with unexpected requirements\n - Provides benefits such as -\n\t - Consumer and service isolation against cascade failures\n\t - Allows for the preservation of certain functionality in the case of an element failure while other elements continue to function normally.\n\t - Allows for the deployment of services that provide varying levels of service quality to application consumers.\n"
  },
  {
    "path": "_blog/articles/2020-10-06-oauth2-authorization-grant-flowchart.md",
    "content": "﻿---\nlayout:  post\ntitle: Oauth2.0 - Authorization grant workflow\ndate:    2020-10-06 20:40:00\nsummary:  Let us understand the Oauth2.0 authorization grant workflow\ncategories:  SpringBootMicroservices\npermalink:  /oauth2-authorization-grant-workflow\nimage: /images/rest-api-category.png\n---\n\n# OAUTH2.0 - Authorization Grant Workflow\n\nGreetings from [in28minutes.com](https://courses.in28minutes.com/).\n\nIn this read, we will take a look at OAUTH2.0 and under the authorization grant in the simplest manner (i.e. via a workflow)\n\n## What is OAuth2.0\nIt is an open authorization protocol that allows accessing the resource owner resources by enabling the client applications (like Facebook, GitHub, etc.) on HTTP services. This protocol was made famous by HTTP Basic authentication wherein the user is required to enter the username and password and was created as a response to the direct authentication pattern. It allows the exchange of resources stored on one site with another site by using the credentials token. It used - \n\n - To read the user data from another application\n - Supplies the authorization workflow for web and desktop applications along with mobile devices\n - It uses the authorization code and does not interact with the user credentials\n\n### OAuth2.0 Roles\n\n 1. *Resource Owner* - It is the person who authorizes an application to access their account. The application's access to the user's account is limited to the \"*scope*\" of the authorization granted (e.g. read or  write access)\n 2. *Authorization Server* - Hosts the protected user accounts, and the authorization server verifies the user identity and then issues the access token to the application\n 3. *Client* - It is the application that wants to access the user's account\n\n### OAuth2.0 Advantages\n\n - It is a flexible protocol that relies on SSL to save the user access token\n - It relies on SSL to ensure cryptography protocol is used to ensure the data integrity\n - Allows limited access to the user's data\n - Allows the ability to share user's data without releasing the PI information for the users\n - It is easier to implement and provides stronger authentication\n\n### OAuth2.0 Disadvantages\n\n - Adding more extensions to the application will require a separate piece of code for each extension\n\n## Authorization Grant\n\n - It is used with the server-side applications where the source code is not publicly exposed and the client secret confidentiality is maintained\n - This is based on redirection where the application must be capable of interacting with the user's web browser\n\nNow we will describe the authorization code flow.\n\n![](/images/oauth2-markdowns/authorization-grant-flowchart.jpeg)\n"
  },
  {
    "path": "_blog/articles/2020-10-07-oauth2-client-credentials-grant-flowchart.md",
    "content": "﻿---\nlayout:  post\ntitle: Oauth2.0 - Client Credentials grant workflow\ndate:    2020-10-07 19:40:00\nsummary:  Let us understand the Oauth2.0 client credentials grant workflow\ncategories:  SpringBootMicroservices\npermalink:  /oauth2-client-credentials-grant-workflow\nimage: /images/rest-api-category.png\n---\n\n# OAUTH2.0 - Client Credentials Grant Workflow\n\nGreetings from [in28minutes.com](https://courses.in28minutes.com/).\n\nIn this read, we will take a look at OAUTH2.0 and under the client credentials grant in the simplest manner (i.e. via a workflow)\n\n## What is OAuth2.0\nIt is an open authorization protocol that allows accessing the resource owner resources by enabling the client applications (like Facebook, GitHub, etc.) on HTTP services. This protocol was made famous by HTTP Basic authentication wherein the user is required to enter the username and password and was created as a response to the direct authentication pattern. It allows the exchange of resources stored on one site with another site by using the credentials token. It used - \n\n - To read the user data from another application\n - Supplies the authorization workflow for web and desktop applications along with mobile devices\n - It uses the authorization code and does not interact with the user credentials\n\n### OAuth2.0 Roles\n\n 1. *Resource Owner* - It is the person who authorizes an application to access their account. The application's access to the user's account is limited to the \"*scope*\" of the authorization granted (e.g. read or  write access)\n 2. *Authorization Server* - Hosts the protected user accounts, and the authorization server verifies the user identity and then issues the access token to the application\n 3. *Client* - It is the application that wants to access the user's account\n\n### OAuth2.0 Advantages\n\n - It is a flexible protocol that relies on SSL to save the user access token\n - It relies on SSL to ensure cryptography protocol is used to ensure the data integrity\n - Allows limited access to the user's data\n - Allows the ability to share user's data without releasing the PI information for the users\n - It is easier to implement and provides stronger authentication\n\n### OAuth2.0 Disadvantages\n\n - Adding more extensions to the application will require a separate piece of code for each extension\n\n## Client Credentials Grant\n\n - This grant provides an application a way to access its own service accounts. The best example of this grant includes when an application wants to access the data stores in its service account via an API. In this grant, the application requests the access token by sending its credentials, client-id, and client-secret to an authorization-server. If the credentials are valid, the access token is returned by the authorization server to the application and the application is authorized to use its own service account. A sample `HTTP POST` request for this grant type will look this -\n\nhttps://someoauth2.somecompany.com/token?grant_type=client_credentials&client_id=CLIENT_ID&client_secret=CLIENT_SECRET\n\nLet us understand this via a workflow diagram.\n\n![](/images/oauth2-markdowns/client-credentials-grant-flowchart.jpeg)\n"
  },
  {
    "path": "_blog/articles/2020-10-08-oauth2-implicit-grant-flowchart.md",
    "content": "﻿---\nlayout:  post\ntitle: Oauth2.0 - Implicit grant workflow\ndate:    2020-10-08 14:47:00\nsummary:  Let us understand the Oauth2.0 implicit grant workflow\ncategories:  SpringBootMicroservices\npermalink:  /oauth2-implicit-grant-flowchart\nimage: /images/rest-api-category.png\n---\n\n# OAUTH2.0 - Implicit Grant Workflow\n\nGreetings from [in28minutes.com](https://courses.in28minutes.com/).\n\nIn this read, we will take a look at OAUTH2.0 and under the implicit grant in the simplest manner (i.e. via a workflow)\n\n## What is OAuth2.0\nIt is an open authorization protocol that allows accessing the resource owner resources by enabling the client applications (like Facebook, GitHub, etc.) on HTTP services. This protocol was made famous by HTTP Basic authentication wherein the user is required to enter the username and password and was created as a response to the direct authentication pattern. It allows the exchange of resources stored on one site with another site by using the credentials token. It used - \n\n - To read the user data from another application\n - Supplies the authorization workflow for web and desktop applications along with mobile devices\n - It uses the authorization code and does not interact with the user credentials\n\n### OAuth2.0 Roles\n\n 1. *Resource Owner* - It is the person who authorizes an application to access their account. The application's access to the user's account is limited to the \"*scope*\" of the authorization granted (e.g. read or  write access)\n 2. *Authorization Server* - Hosts the protected user accounts, and the authorization server verifies the user identity and then issues the access token to the application\n 3. *Client* - It is the application that wants to access the user's account\n\n### OAuth2.0 Advantages\n\n - It is a flexible protocol that relies on SSL to save the user access token\n - It relies on SSL to ensure cryptography protocol is used to ensure the data integrity\n - Allows limited access to the user's data\n - Allows the ability to share user's data without releasing the PI information for the users\n - It is easier to implement and provides stronger authentication\n\n### OAuth2.0 Disadvantages\n\n - Adding more extensions to the application will require a separate piece of code for each extension\n\n## Implicit Grant\n\n - This grant is used for mobile and web applications where the confidentiality of the client-secret is not guaranteed\n - It is a redirection-based flow where the access token is given to the user-agent to forward to the application so it may be exposed to the user and other applications on the user’s device\n - This flow does not authenticate the identity of the application and relies on the redirect URI\n - Does not support the refresh tokens\n - Basically works as follows: \n\t - The user is asked to authorize the application, then the authorization server passes the access token back to the user-agent, which passes it to the application.\n\nLet us understand this via a workflow diagram.\n\n![](/images/oauth2-markdowns/implicit-grant-flowchart.jpeg)\n\n"
  },
  {
    "path": "_blog/articles/2020-10-09-oauth2-resource-owner-password-credentials-grant-flowchart.md",
    "content": "﻿---\nlayout:  post\ntitle: Oauth2.0 - Resource Owner Password Credentials grant workflow\ndate:    2020-10-09 15:30:00\nsummary:  Let us understand the Oauth2.0 Resource Owner Password Credentials grant workflow\ncategories:  SpringBootMicroservices\npermalink:  /oauth2-resource-owner-password-credentials-grant-flowchart\nimage: /images/rest-api-category.png\n---\n\n# OAUTH2.0 - Resource Owner Password Credentials Grant Workflow\n\nGreetings from [in28minutes.com](https://courses.in28minutes.com/).\n\nIn this read, we will take a look at OAUTH2.0 and under the resource owner password credentials grant in the simplest manner (i.e. via a workflow)\n\n## What is OAuth2.0\nIt is an open authorization protocol that allows accessing the resource owner resources by enabling the client applications (like Facebook, GitHub, etc.) on HTTP services. This protocol was made famous by HTTP Basic authentication wherein the user is required to enter the username and password and was created as a response to the direct authentication pattern. It allows the exchange of resources stored on one site with another site by using the credentials token. It used - \n\n - To read the user data from another application\n - Supplies the authorization workflow for web and desktop applications along with mobile devices\n - It uses the authorization code and does not interact with the user credentials\n\n### OAuth2.0 Roles\n\n 1. *Resource Owner* - It is the person who authorizes an application to access their account. The application's access to the user's account is limited to the \"*scope*\" of the authorization granted (e.g. read or  write access)\n 2. *Authorization Server* - Hosts the protected user accounts, and the authorization server verifies the user identity and then issues the access token to the application\n 3. *Client* - It is the application that wants to access the user's account\n\n### OAuth2.0 Advantages\n\n - It is a flexible protocol that relies on SSL to save the user access token\n - It relies on SSL to ensure cryptography protocol is used to ensure the data integrity\n - Allows limited access to the user's data\n - Allows the ability to share user's data without releasing the PI information for the users\n - It is easier to implement and provides stronger authentication\n\n### OAuth2.0 Disadvantages\n\n - Adding more extensions to the application will require a separate piece of code for each extension\n\n## Resource Owner Password Credentials Grant\n\n - In this grant the user provides their username and password details directly to the application's login page which in turn uses these credentials to create the access token for the application from the authorization server. This grant is only enabled on the authorization server if the other flows not viable. The important point to remember is that this grant is only used if the application is trusted by the user. A sample `HTTP POST` request for this grant type will look this -\n \nhttps://someoauth2.somecompany.com/token?grant_type=password&username=USERNAME&password=PASSWORD&client_id=CLIENT_ID\n\nLet us understand this via a workflow diagram.\n\n![](/images/oauth2-markdowns/OAUTH2.0 - Resource owner username password grant workflow.jpeg)\n"
  },
  {
    "path": "_blog/articles/2020-11-02-single-signon-flowchart.md",
    "content": "﻿---\nlayout:  post\ntitle: Single sign-on workflow\ndate:    2020-11-02 15:37:00\nsummary:  Let us understand the single sign-on workflow\ncategories:  SpringBootMicroservices\npermalink:  /single-sign-on-workflow\nimage: /images/rest-api-category.png\n---\n\n# Single Sign-on Workflow\n\nGreetings from [in28minutes.com](https://courses.in28minutes.com/).\n\nIn this read, we will take a look at single sign-on workflow. Single sign-on is a facility of authenticating an user only once and sharing that authentication across multiple applications of the same owner. Following workflow diagram will help you understand the workflow of single sign-on.\n\n![](/images/single-signon-markdown/single-signon-flowchart-diagram.jpeg)\n"
  },
  {
    "path": "_blog/articles/2020-11-12-understanding-json-web-token.md",
    "content": "﻿---\nlayout:  post\ntitle: Understanding jwt token\ndate:    2020-11-12 13:00:00\nsummary:  Let us understand the json web tokens\ncategories:  SpringBootMicroservices\npermalink:  /understanding-jwt-token\nimage: /images/rest-api-category.png\n---\n\n# Understanding JWT token\n\nGreetings from [in28minutes.com](https://courses.in28minutes.com/). In this read, we will take a look at the basic overview to JWT (i.e. JSON Web tokens).\n\n# What is the JWT token?\n\nJSON Web tokes also known as \"*jot*\" are the easy to send read-only signed \"claims\" between the different services. *Claims* in the jot token are the bits of user data that is required by someone else for the verification purpose but not alter it. These claims in the JWT token are signed by a key for the protection purpose\n\n# How the JWT token looks like?\n\nThe JWT token structure consists of three parts i.e. Header, Payload, and Signature separate by a period (`.`) symbol.\n```\neyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9           // Header\n.eyJrZXkiOiJ2YWwiLCJpYXQiOjE0MjI2MDU0NDV9      // Payload\n.eUiabuiKv-8PYk2AkGY4Fb5KMZeorYBLw261JPQD5lM   // Signature\n```\nLet us go ahead and understand each part in a little brief -\n\n - **Header** - It is the first encoded string part of the jot token that describes the token along with the hashing algorithm uses\n - **Payload** - It is the second encoded string part of the jot token that describes the token core. It basically contains the data you want to store in the jot token. It contains information like the audience, subject, token expiration time, etc\n - **Signature** - It is the final encoded string part of the jot token that describes a signature generated based on the header and the payload and will be used to verify whether the jot token is valid or not\n\n# Claims in JWT token?\n\n**Claims** are the predefined key and their values in the JWT/jot token -\n\n 1. ***iss*** - Refer to the issuer of the jot token\n 2. ***exp*** - Refer to the expiration time (in seconds) of the jot token\n 3. ***iat*** - Refer to the issuance time of the jwt token. Can be used to determine the age of the jot token\n 4. ***nbf*** - Refer to the field in the jwt token that determines the future time when the jot token will become active\n 5. ***sub*** - Refer to the subject field\n 6. ***aud*** - Refer to the audience field\n 7. ***jti*** - Refer to the unique identifier of the jot token so that the token can't be reused\n\nIn case you would like to read more take a look at this [link](http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#RegisteredClaimName).\n"
  },
  {
    "path": "_blog/index.md",
    "content": "---\nlayout: blog\ntitle: Blog\n---\n"
  },
  {
    "path": "_blog/java-programming.md",
    "content": "---\nlayout: category\ntitle: Java Programming\nslug: SwJavaProgrammers\nimage: /images/java-category.png\n---\n"
  },
  {
    "path": "_blog/programming.md",
    "content": "---\nlayout: category\ntitle: Programming\nslug: SwProgramming\nimage: /images/programming-category.png\n---\n"
  },
  {
    "path": "_blog/restapi.md",
    "content": "---\nlayout: category\ntitle: Rest API\nslug: RestAPI\nimage: /images/rest-api-category.png\n---\n"
  },
  {
    "path": "_blog/software-design.md",
    "content": "---\nlayout: category\ntitle: Software Design\nslug: SwDesign\nimage: /images/design-category.png\n---\n"
  },
  {
    "path": "_blog/swcodequality.md",
    "content": "---\nlayout: category\ntitle: Software Code Quality\nslug: SwCodeQuality\nimage: /images/design-category.png\n---\n"
  },
  {
    "path": "_config.yml",
    "content": "title: Spring Boot Tutorial\nemail: ranga@in28minutes.com\ndescription: 1 MILLION learners learning Programming, Cloud and DevOps. Check out our roadmaps!\nurl: 'https://www.in28minutes.com/'\nplugins:\n  - jekyll-feed\n  - jekyll-seo-tag\n  # - jekyll-analytics\n\n# Products\nproducts:\n  - name: Articles\n    url: /blog\n  - name: Roadmaps\n    url: https://www.in28minutes.com/roadmaps\n\n# Articles\narticles:\n  - name: Spring Boot\n    url: https://www.springboottutorial.com/blog\n  - name: Cloud\n    url: https://cloud.in28minutes.com/blog\n\ncollections:\n  blog:\n    output: true\n\nauthor:\n  name: Ranga Karanam\n  image: assets/images/about/ranga-karanam-profile-nobg.png\n  about: Ranga Karanam, founder of in28minutes, has 2 decades of experience with technology - architecture, design, and programming.  We are helping learners take their first steps into modern cloud native technology and gain expertise on AWS, Azure, Google Cloud, Docker, Kubernetes amongst others.\n  description: 10X certified on AWS, Azure and Google Cloud.\n\nsocial:\n  twitter: https://twitter.com/in28minutes\n  linkedin: http://linkedin.com/in/rangakaranam/\n  github: http://github.com/in28minutes/roadmaps\n  udemy: http://udemy.com/user/in28minutes\n  facebook: https://www.facebook.com/in28Minutes\n  youtube: https://www.youtube.com/user/rithustutorials\n\ngoogle_analytics: G-VCB8BXNMPL\n\n# jekyll_analytics:\n#   GoogleAnalytics:\n#     id: UA-32942307-5\n\nmarkdown: kramdown\nhighlighter: rouge\nkramdown:\n  input: GFM\n  syntax_highlighter: rouge\n"
  },
  {
    "path": "_includes/footer.html",
    "content": "<!-- ====== Footer Start ====== -->\n<footer class=\"ud-footer wow fadeInUp pt-5\" data-wow-delay=\".15s\">\n    <div class=\"shape shape-1\">\n        <img src=\"{{'assets/images/footer/shape-1.svg' | relative_url}}\" alt=\"shape\" />\n    </div>\n    <div class=\"shape shape-2\">\n        <img src=\"{{'assets/images/footer/shape-2.svg' | relative_url}}\" alt=\"shape\" />\n    </div>\n    <div class=\"shape shape-3\">\n        <img src=\"{{'assets/images/footer/shape-3.svg' | relative_url}}\" alt=\"shape\" />\n    </div>\n    <div class=\"ud-footer-widgets\">\n        <div class=\"container\">\n            <div class=\"row\">\n                <div class=\"col\">\n                    <div class=\"ud-widget\">\n                        <a href=\"index.html\" class=\"ud-footer-logo\">\n                            <!-- <img src=\"{{site.logo | default: 'assets/images/logo/logo.svg' | relative_url}}\"\n                                alt=\"logo\" /> -->\n                            <span class=\"fw-bold fs-1 text-white\">in28minutes</span>\n                        </a>\n                        <p class=\"ud-widget-desc\">\n                            {{site.description}}\n                        </p>\n                        <ul class=\"ud-widget-socials\">\n                            <li>\n                                <a href=\"{{site.social.facebook}}\" target=\"_blank\">\n                                    <i class=\"lni lni-facebook-filled\"></i>\n                                </a>\n                            </li>\n                            <li>\n                                <a href=\"{{site.social.twitter}}\" target=\"_blank\">\n                                    <i class=\"lni lni-twitter-filled\"></i>\n                                </a>\n                            </li>\n                            <li>\n                                <a href=\"{{site.social.youtube}}\" target=\"_blank\">\n                                    <i class=\"lni lni-youtube\"></i>\n                                </a>\n                            </li>\n                            <li>\n                                <a href=\"{{site.social.linkedin}}\" target=\"_blank\">\n                                    <i class=\"lni lni-linkedin-original\"></i>\n                                </a>\n                            </li>\n                        </ul>\n                    </div>\n                </div>\n\n                <div class=\"col-xl-2 col-lg-2 col-md-6 col-sm-6\">\n                    <div class=\"ud-widget\">\n                        <h5 class=\"ud-widget-title\">Keep Learning</h5>\n                        <ul class=\"ud-widget-links\">\n                            <li>\n                                <a href=\"{{'/' | relative_url}}\">Home</a>\n                            </li>\n                            <li>\n                                <a href=\"{{'/blog/2-spring-framework.html' | relative_url}}\">Spring</a>\n                            </li>\n                            <li>\n                                <a href=\"{{'/blog/1-springboot.html' | relative_url}}\">Spring Boot</a>\n                            </li>\n                            <li>\n                                <a href=\"{{'/blog' | relative_url}}\">All Articles</a>\n                            </li>\n                        </ul>\n                    </div>\n                </div>\n                <div class=\"col-xl-2 col-lg-3 col-md-6 col-sm-6\">\n                    <div class=\"ud-widget\">\n                        <h5 class=\"ud-widget-title\">Our Products</h5>\n                        <ul class=\"ud-widget-links\">\n                            {% for product in site.products %}\n                            <li>\n                                <a href=\"{{product.url | relative_url}}\" rel=\"nofollow noopner\">\n                                    {{product.name}}\n                                </a>\n                            </li>\n                            {% endfor %}\n                        </ul>\n                    </div>\n                </div>\n            </div>\n        </div>\n    </div>\n    <div class=\"ud-footer-bottom\">\n        <div class=\"container\">\n            <div class=\"row\">\n                <div class=\"col-md-8\">\n                    <ul class=\"ud-footer-bottom-left\">\n                        <li>\n                            <a href=\"https://www.privacypolicygenerator.info/live.php?token=oMRFWSatCvLhaKHNpUcF9IEVhKc3FSu6\">Privacy policy</a>\n                        </li>\n                    </ul>\n                </div>\n            </div>\n        </div>\n    </div>\n</footer>\n<!-- ====== Footer End ====== -->\n\n<!-- ====== Back To Top Start ====== -->\n<a href=\"javascript:void(0)\" class=\"back-to-top\">\n    <i class=\"lni lni-chevron-up\"></i>\n</a>\n<!-- ====== Back To Top End ====== -->\n\n<!-- ====== All Javascript Files ====== -->\n<script src=\"{{'assets/js/bootstrap.bundle.min.js' | relative_url}}\"></script>\n<script src=\"{{'assets/js/wow.min.js' | relative_url}}\"></script>\n<script src=\"{{'assets/js/main.js' | relative_url}}\"></script>\n<script>\n    // section menu active\n    function onScroll(event) {\n        const sections = document.querySelectorAll('.ud-menu-scroll')\n        const scrollPos =\n            window.pageYOffset ||\n            document.documentElement.scrollTop ||\n            document.body.scrollTop\n\n        const navbarBrand = document.querySelector('.navbar-brand');\n\n        try {\n            for (let i = 0; i < sections.length; i++) {\n                const currLink = sections[i]\n                const value = currLink.getAttribute('href')\n                const refElement = document.querySelector(value)\n                const scrollTopMinus = scrollPos + 73\n                if (\n                    refElement.offsetTop <= scrollTopMinus &&\n                    refElement.offsetTop + refElement.offsetHeight > scrollTopMinus\n                ) {\n                    document.querySelector('.ud-menu-scroll').classList.remove('active')\n                    currLink.classList.add('active')\n                    navbarBrand.classList.remove('text-dark')\n                    navbarBrand.classList.add('text-white')\n                } else {\n                    navbarBrand.classList.remove('text-white')\n                    navbarBrand.classList.add('text-dark')\n                    currLink.classList.remove('active')\n                }\n            }\n        }\n        catch (_) { }\n    }\n\n    window.document.addEventListener('scroll', onScroll)\n</script>"
  },
  {
    "path": "_includes/head.html",
    "content": "<meta charset=\"UTF-8\">\n<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n{% seo %}\n<link rel=\"stylesheet\" href=\"{{'assets/css/bootstrap.min.css' | relative_url}}\" />\n<link rel=\"stylesheet\" href=\"{{'assets/css/animate.css' | relative_url}}\" />\n<link rel=\"stylesheet\" href=\"{{'assets/css/lineicons.css' | relative_url}}\" />\n<link rel=\"stylesheet\" href=\"{{'assets/css/ud-styles.css' | relative_url}}\" />\n<link rel=\"stylesheet\" href=\"{{'assets/css/syntax.css' | relative_url}}\" />\n<link rel=\"stylesheet\" href=\"{{'assets/css/custom.css' | relative_url}}\" />\n<script async src=\"https://www.googletagmanager.com/gtag/js?id={{ site.google_analytics }}\"></script>\n<script>\n    window.dataLayer = window.dataLayer || [];\n    function gtag() { dataLayer.push(arguments); }\n    gtag('js', new Date());\n\n    gtag('config', '{{ site.google_analytics }}');\n</script>\n\n<!-- <script type=\"text/javascript\">\n   (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){\n   (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),\n   m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)\n   })(window,document,'script','//www.google-analytics.com/analytics.js','ga');\n   ga('create', '{{ UA-32942307-5 }}', 'auto');\n   ga('send', 'pageview');\n</script>\n\n\n{% if site.google_tag_manager %}\n    <noscript><iframe src=\"https://www.googletagmanager.com/ns.html?id={{ site.google_tag_manager }}\"\nheight=\"0\" width=\"0\" style=\"display:none;visibility:hidden\"></iframe></noscript>\n{% endif %} -->\n"
  },
  {
    "path": "_includes/nav.html",
    "content": "<!-- ====== Header Start ====== -->\n<header class=\"ud-header\">\n    <div class=\"container\">\n        <div class=\"row\">\n            <div class=\"col-lg-12\">\n                <nav class=\"navbar navbar-expand-lg\">\n                    <a class=\"navbar-brand fs-3 fw-bold text-white\" href=\"{{'/' | relative_url}}\">\n                        <!-- <img src=\"{{'assets/images/logo/logo.svg' | relative_url}}\" alt=\"Logo\" /> -->\n                        <!-- <span class=\"fw-bold fs-1 text-white\">in28minutes</span> -->\n                        in28minutes\n                    </a>\n                    <button class=\"navbar-toggler\">\n                        <span class=\"toggler-icon\"> </span>\n                        <span class=\"toggler-icon\"> </span>\n                        <span class=\"toggler-icon\"> </span>\n                    </button>\n\n                    <div class=\"navbar-collapse\">\n                        <ul id=\"nav\" class=\"navbar-nav mx-auto\">\n                            <li class=\"nav-item\">\n                                <a class=\"ud-menu-scroll\" href=\"{{'/' | relative_url}}\">Home</a>\n                            </li>\n\n                            {% for product in site.products %}\n                            <li class=\"nav-item\">\n                                <a class=\"ud-menu-scroll\" href=\"{{product.url | relative_url}}\">{{product.name}}</a>\n                            </li>\n                            {% endfor %}\n\n\n                            <!-- <li class=\"nav-item nav-item-has-children\">\n                                <a href=\"javascript:void(0)\"> Articles </a>\n                                <ul class=\"ud-submenu\">\n                                    {% for article in site.articles %}\n                                    <li class=\"ud-submenu-item\">\n                                        <a href=\"{{article.url | relative_url}}\" class=\"ud-submenu-link\">\n                                            {{article.name}}\n                                        </a>\n                                    </li>\n                                    {% endfor %}\n                                </ul>\n                            </li> -->\n                        </ul>\n                        <div class=\"navbar-btn d-none d-sm-inline-block\">\n                            <a class=\"ud-main-btn ud-white-btn fw-bold\" href=\"#subscribe\">\n                                Subscribe\n                            </a>\n                        </div>\n                    </div>\n                </nav>\n            </div>\n        </div>\n    </div>\n</header>\n<!-- ====== Header End ====== -->"
  },
  {
    "path": "_includes/newsletter.html",
    "content": "<section class=\"subscribe-wrapper\" id=\"subscribe\">\n    <div class=\"container\">\n        <div class=\"row text-center\">\n            <div class=\"col-12 col-md-10 offset-md-1 col-lg-8 offset-lg-2\" x-data=\"subscriptionData\">\n                <div class=\"ud-newsletter-box newsletter-box-large rounded\">\n                    <img src=\"{{'assets/images/blog/dotted-shape.svg' | relative_url}}\" alt=\"shape\"\n                        class=\"shape shape-1\" />\n                    <img src=\"{{'assets/images/blog/dotted-shape.svg' | relative_url}}\" alt=\"shape\"\n                        class=\"shape shape-2\" />\n                    <div class=\"ud-newsletter-form\">\n                        <a target=\"_blank\" href=\"https://links.in28minutes.com/community-sb\"><img src=\"/images/discord.gif\"/></a>\n                    </div>\n                </div>\n            </div>\n        </div>\n    </div>\n    </div>\n</section>"
  },
  {
    "path": "_includes/trustedby.html",
    "content": "<div class=\"row\">\n</div>"
  },
  {
    "path": "_layouts/about.html",
    "content": "---\nlayout: page\n---\n<section id=\"about\" class=\"ud-about\">\n    <div class=\"container\">\n        <div class=\"ud-about-wrapper wow fadeInUp\" data-wow-delay=\".2s\">\n            <div class=\"ud-about-content-wrapper\">\n                <div class=\"ud-about-content\">\n                    <span class=\"tag\">About Us</span>\n                    {{content}}\n                </div>\n            </div>\n            <div class=\"ud-about-image\">\n                <img src=\"{{'assets/images/about/about-image.png' | relative_url}}\" alt=\"about-image\" />\n            </div>\n        </div>\n    </div>\n</section>\n<section id=\"team\" class=\"ud-team\">\n    <div class=\"container\">\n        <div class=\"row\">\n            <div class=\"col-lg-12\">\n                <div class=\"ud-section-title mx-auto text-center\">\n                    <span>Meet Our Instructor</span>\n                    <h2>{{site.author.name}}</h2>\n                    <p>\n                        {{site.author.about}}\n                    </p>\n                </div>\n            </div>\n        </div>\n\n        <div class=\"row\">\n            <div class=\"col-12 col-md-6 col-lg-4 offset-md-3 offset-lg-4 text-center\">\n                <div class=\"ud-single-team wow fadeInUp\" data-wow-delay=\".1s\">\n                    <div class=\"ud-team-image-wrapper\">\n                        <div class=\"ud-team-image\">\n                            <img src=\"{{'/assets/images/about/ranga-karanam-profile-nobg.png' | relative_url}}\"\n                                alt=\"team\" />\n                        </div>\n\n                        <img src=\"{{'assets/images/team/dotted-shape.svg' | relative_url}}\" alt=\"shape\"\n                            class=\"shape shape-1\" />\n                        <img src=\"{{'assets/images/team/shape-2.svg' | relative_url}}\" alt=\"shape\"\n                            class=\"shape shape-2\" />\n                    </div>\n                    <div class=\"ud-team-info\">\n                        <h5>{{site.author.description | markdownify}}</h5>\n                    </div>\n                    <ul class=\"ud-team-socials\">\n                        <li>\n                            <a href=\"https://facebook.com/in28minutes\">\n                                <i class=\"lni lni-facebook-filled\"></i>\n                            </a>\n                        </li>\n                        <li>\n                            <a href=\"https://twitter.com/in28minutes\">\n                                <i class=\"lni lni-twitter-filled\"></i>\n                            </a>\n                        </li>\n                        <li>\n                            <a href=\"https://instagram.com//in28minutes\">\n                                <i class=\"lni lni-instagram-filled\"></i>\n                            </a>\n                        </li>\n                    </ul>\n                </div>\n            </div>\n        </div>\n    </div>\n</section>\n\n{% include newsletter.html %}"
  },
  {
    "path": "_layouts/blog.html",
    "content": "---\nlayout: page\n---\n<section class=\"ud-blog-grids\">\n    <div class=\"container\">\n        <div class=\"row row-cols-1 row-cols-md-2 row-cols-lg-3\">\n            {% for item in site.blog %}\n            {% if item.layout == 'category' %}\n            <div class=\"col\">\n                <div class=\"ud-single-blog\">\n                    <div class=\"ud-blog-image\">\n                        <a href=\"{{item.url | relative_url}}\">\n                            <img src=\"{{item.image}}\" alt=\"Image\" style=\"max-height: 200px;\" />\n                        </a>\n                    </div>\n                    <div class=\"ud-blog-content text-center\">\n                        <h3 class=\"ud-blog-title\">\n                            <a href=\"{{item.url | relative_url}}\" class=\"fw-bold fs-3\">\n                                {{item.title}}\n                            </a>\n                        </h3>\n                        <p class=\"ud-blog-desc\">\n                            {{item.description}}\n                        </p>\n                    </div>\n                </div>\n            </div>\n            {% endif %}\n            {% endfor %}\n\n        </div>\n    </div>\n</section>\n{% include newsletter.html %}"
  },
  {
    "path": "_layouts/category.html",
    "content": "---\nlayout: page\n---\n<section class=\"ud-blog-grids\">\n    <div class=\"container\">\n        <div class=\"row row-cols-1 row-cols-md-2 row-cols-lg-3\">\n            {% for item in site.blog %} {% if item.layout == 'post' and item.categories[0] == page.slug%}\n            <div class=\"col\">\n                <div class=\"ud-single-blog\">\n                    <div class=\"ud-blog-image\">\n                        <a href=\"{{item.url | relative_url}}\">\n                            <img src=\"{{item.image | default: 'assets/images/blog/blog-details-01.jpg' | relative_url}}\"\n                                alt=\"Image\" />\n                        </a>\n                    </div>\n                    <div class=\"ud-blog-content text-center\">\n                        <h3 class=\"ud-blog-title\">\n                            <a href=\"{{item.url | relative_url}}\" class=\"fw-bold fs-3\">\n                                {{item.title}}\n                            </a>\n                        </h3>\n                        <p class=\"ud-blog-desc\">\n                            {{item.summary | truncate}}\n                        </p>\n                    </div>\n                </div>\n            </div>\n            {% endif %} {% endfor %}\n        </div>\n    </div>\n</section>\n{% include newsletter.html %}"
  },
  {
    "path": "_layouts/default.html",
    "content": "<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n    {%include head.html %}\n</head>\n\n<body>\n    {% if page.layout != \"resources\" %}\n    {% include nav.html %}\n    {% endif %}\n    {{content}}\n    {% include footer.html %}\n</body>\n\n</html>"
  },
  {
    "path": "_layouts/home.html",
    "content": "---\nlayout: default\n---\n<!-- ====== Hero Start ====== -->\n<section class=\"ud-hero\" id=\"home\">\n    <div class=\"container\">\n        <div class=\"row\">\n            <div class=\"col-lg-12\">\n                <div class=\"ud-hero-content wow fadeInUp\" data-wow-delay=\".2s\">\n                    <h1 class=\"ud-hero-title\">\n                        {{page.header.title}}\n                    </h1>\n                    <p class=\"ud-hero-desc\">\n                        {{page.header.description}}\n                    </p>\n                    <ul class=\"ud-hero-buttons\">\n                        <li>\n                            <a href=\"{{page.header.main_button.url | relative_url}}\" rel=\"nofollow noopener\"\n                                target=\"_blank\" class=\"ud-main-btn ud-white-btn\">\n                                {{page.header.main_button.title}}\n                            </a>\n                        </li>\n                        <li>\n                            <a href=\"{{page.header.secondary_button.url | relative_url}}\" rel=\"nofollow noopener\"\n                                target=\"_blank\" class=\"ud-main-btn ud-link-btn\">\n                                {{page.header.secondary_button.title}} <i class=\"lni lni-arrow-right\"></i>\n                            </a>\n                        </li>\n                    </ul>\n                </div>\n                <div class=\"ud-hero-brands-wrapper wow fadeInUp\" data-wow-delay=\".3s\">\n                    <img src=\"assets/images/hero/brand.svg\" alt=\"brand\" />\n                </div>\n                <div class=\"ud-hero-image wow fadeInUp\" data-wow-delay=\".25s\">\n                    <img src=\"assets/images/hero/hero-image.png\" alt=\"hero-image\" />\n                    <img src=\"assets/images/hero/dotted-shape.svg\" alt=\"shape\" class=\"shape shape-1\" />\n                    <img src=\"assets/images/hero/dotted-shape.svg\" alt=\"shape\" class=\"shape shape-2\" />\n                </div>\n            </div>\n        </div>\n    </div>\n</section>\n<!-- ====== Hero End ====== -->\n\n<!-- ====== Features Start ====== -->\n<section id=\"features\" class=\"ud-features\">\n    <div class=\"container\">\n        <div class=\"row\">\n            <div class=\"col-lg-12\">\n                <div class=\"ud-section-title\">\n                    <span>Features</span>\n                    <h2>{{page.features.title}}</h2>\n                    <p>\n                        {{page.features.description}}\n                    </p>\n                </div>\n            </div>\n        </div>\n        <div class=\"row row-cols-1 row-cols-md-2 row-cols-lg-4\">\n            {% for feature in page.features.items %}\n            <div class=\"col\">\n                <div class=\"ud-single-feature wow fadeInUp\" data-wow-delay=\".1s\">\n                    <div class=\"ud-feature-icon\">\n                        <i class=\"lni {{feature.icon}}\"></i>\n                    </div>\n                    <div class=\"ud-feature-content\">\n                        <h3 class=\"ud-feature-title\">{{feature.title}}</h3>\n                        <p class=\"ud-feature-desc\">\n                            {{feature.description}}\n                        </p>\n                    </div>\n                </div>\n            </div>\n            {% endfor %}\n        </div>\n    </div>\n</section>\n<!-- ====== Features End ====== -->\n\n<!-- ====== About Start ====== -->\n<section id=\"about\" class=\"ud-about\">\n    <div class=\"container\">\n        <div class=\"ud-about-wrapper wow fadeInUp\" data-wow-delay=\".2s\">\n            <div class=\"ud-about-content-wrapper\">\n                <div class=\"ud-about-content\">\n                    <span class=\"tag\">About Us</span>\n                    <h2>{{page.about.title}}</h2>\n                    <p>{{page.about.description}}</p>\n                    <a href=\"{{'/about' | relative_url}}\" class=\"ud-main-btn\">Learn More</a>\n                </div>\n            </div>\n            <div class=\"ud-about-image\">\n                <img src=\"assets/images/about/about-image.png\" alt=\"about-image\" />\n            </div>\n        </div>\n    </div>\n</section>\n<!-- ====== About End ====== -->\n\n\n<!-- ====== Testimonials Start ====== -->\n<section id=\"testimonials\" class=\"ud-testimonials\">\n    <div class=\"container\">\n        <div class=\"row\">\n            <div class=\"col-lg-12\">\n                <div class=\"ud-section-title mx-auto text-center\">\n                    <span>Testimonials</span>\n                    <h2>{{page.testimonials.title}}</h2>\n                    <p>\n                        {{page.testimonials.description}}\n                    </p>\n                </div>\n            </div>\n        </div>\n\n        <div class=\"row row-cols-1 row-cols-lg-3 g-3\">\n            {% for item in page.testimonials.items %}\n            <div class=\"col\">\n                <div class=\"ud-single-testimonial wow fadeInUp\" data-wow-delay=\".1s\">\n                    <div class=\"ud-testimonial-ratings\">\n                        <i class=\"lni lni-star-filled\"></i>\n                        <i class=\"lni lni-star-filled\"></i>\n                        <i class=\"lni lni-star-filled\"></i>\n                        <i class=\"lni lni-star-filled\"></i>\n                        <i class=\"lni lni-star-filled\"></i>\n                    </div>\n                    <div class=\"ud-testimonial-content\">\n                        <p>\n                            \"{{item.comment}}\"\n                        </p>\n                    </div>\n                    <div class=\"ud-testimonial-info\">\n                        <div class=\"ud-testimonial-image\">\n                            <img src=\"assets/images/testimonials/author-01.png\" alt=\"author\" />\n                        </div>\n                        <div class=\"ud-testimonial-meta\">\n                            <h4>{{item.name}}</h4>\n                        </div>\n                    </div>\n                </div>\n            </div>\n            {% endfor %}\n        </div>\n    </div>\n</section>\n<!-- ====== Testimonials End ====== -->\n\n\n<!-- ====== Subscribe Start ====== -->\n\n{% include newsletter.html %}\n\n<!-- ====== Subscribe End ====== -->"
  },
  {
    "path": "_layouts/page.html",
    "content": "---\nlayout: default\n---\n<section class=\"ud-page-banner\">\n    <div class=\"container\">\n        <div class=\"row\">\n            <div class=\"col-lg-12\">\n                <div class=\"ud-banner-content\">\n                    <h1>{{page.title}}</h1>\n                </div>\n            </div>\n        </div>\n    </div>\n</section>\n{{content}}"
  },
  {
    "path": "_layouts/post.html",
    "content": "---\nlayout: default\n---\n<style>\n    #content {\n        padding-top: 2em;\n        padding-bottom: 2em;\n    }\n\n    #content>p,\n    li {\n        line-height: 2em;\n        color: var(--body-color);\n    }\n\n    #content>p {\n        line-height: 2em;\n    }\n\n    #content>h2,\n    h3,\n    h4 {\n        margin-top: 2em;\n        font-weight: bold;\n        margin-bottom: 1em;\n        color: var(--heading-color);\n    }\n\n    div.highlight {\n        margin-top: 2em;\n        padding: 1em;\n        font-family: monospace !important;\n        margin-bottom: 2em;\n        padding-bottom: 0.25em;\n    }\n\n    pre.highlight {\n        margin-bottom: none !important;\n        padding-bottom: none !important;\n    }\n\n    #content>ul {\n        padding-left: 2em;\n        margin-bottom: 1em;\n    }\n\n    #content>ul>li {\n        list-style: disc;\n    }\n</style>\n<section class=\"ud-page-banner\">\n    <div class=\"container\">\n        <div class=\"row\">\n            <div class=\"col-lg-12\">\n                <div class=\"ud-banner-content\">\n                    <h1>{{page.title}}</h1>\n                </div>\n            </div>\n        </div>\n    </div>\n</section>\n<section class=\"ud-blog-details\">\n    <div class=\"container\">\n        <div class=\"row\">\n            <div class=\"col-lg-12\">\n                <div class=\"ud-blog-details-image\">\n                    <img src=\"{{page.image | default: '/images/default-image-wide.png' | relative_url}}\"\n                        alt=\"blog details\"/>\n                    <div class=\"ud-blog-overlay\">\n                        <div class=\"ud-blog-overlay-content\">\n                            <div class=\"ud-blog-author\">\n                                <img src=\"{{site.author.image | relative_url}}\" alt=\"author\" />\n                                <i class=\"lni lni-pencil text-white me-2\"></i> <span class=\"me-2\">\n                                    <a href=\"javascript:void(0)\"> {{site.author.name}} </a>\n                                </span>\n                                <i class=\"lni lni-calendar text-white me-2\"></i> <span class=\"me-2\">{{page.date | date:\n                                    '%B\n                                    %d,\n                                    %Y'}}</span>\n                                {% assign minutes = content | strip_html | number_of_words | divided_by: 180 %}\n                                {% if minutes == 0 %}\n                                {% assign minutes = 1 %}\n                                {% endif %}\n                                <i class=\"lni lni-eye text-white me-2\"></i> <span>{{minutes}} minutes</span>\n                            </div>\n                        </div>\n                    </div>\n                </div>\n            </div>\n\n            <div class=\"col-lg-8\">\n                <div id=\"content\">\n                    {{content | markdownify}}\n\n                    <h3 class=\"ud-articles-box-title\">Just Released</h3>\n                    <div class=\"ud-banner-ad\">\n                        <a href=\"https://links.in28minutes.com/sb\" target=\"_blank\">\n                            <img src=\"/images/master-spring-boot-course.png\" alt=\"ad banner\" />\n                        </a>\n                    </div>\n\n                </div>\n            </div>\n            <div class=\"col-lg-4\">\n                <div class=\"ud-blog-sidebar\">\n\n                    <div class=\"ud-about-image\">\n                        <img src=\"{{'assets/images/about/about-image.png' | relative_url}}\" alt=\"about-image\" />\n                    </div>\n\n                    <div class=\"ud-articles-box\">\n                        <h3 class=\"ud-articles-box-title\">Related Articles</h3>\n                        <ul class=\"ud-articles-list\">\n                            {% assign posts = site.blog | where_exp: \"post\", \"post.categories == page.categories\"%}\n                            {% for relatedPost in posts  limit: 15 %}\n                            <li>\n                                <div class=\"ud-article-image\">\n                                    <img src=\"{{relatedPost.image | default: 'assets/images/blog/blog-details-01.jpg' | relative_url}}\"\n                                        alt=\"author\" />\n                                </div>\n                                <div class=\"ud-article-content\">\n                                    <h5 class=\"ud-article-title\">\n                                        <a href=\"{{relatedPost.url | relative_url}}\">\n                                            {{relatedPost.title}}\n                                        </a>\n                                    </h5>\n                                </div>\n                            </li>\n                            {% endfor %}\n                        </ul>\n                    </div>\n                    \n                    <h3 class=\"ud-articles-box-title\">Related Courses</h3>\n                    \n                    <div class=\"ud-banner-ad\">\n                        <a href=\"https://links.in28minutes.com/sb\" target=\"_blank\">\n                            <img src=\"/images/master-spring-boot-course.png\" alt=\"ad banner\" />\n                        </a>\n                    </div>\n\n\n                    <div class=\"ud-banner-ad\">\n                        <a href=\"https://www.udemy.com/course/microservices-with-spring-boot-and-spring-cloud/\" target=\"_blank\">\n                            <img src=\"/images/microservices-course.png\" alt=\"ad banner\" />\n                        </a>\n                    </div>\n\n                    <div class=\"ud-banner-ad\">\n                        <a href=\"https://www.udemy.com/course/cloud-computing-aws/\" target=\"_blank\">\n                            <img src=\"/images/aws-course.png\" alt=\"ad banner\" />\n                        </a>\n                    </div>\n                </div>\n            </div>\n        </div>\n    </div>\n</section>\n\n{% include newsletter.html %}\n\n<script>\n    document.querySelectorAll('table').forEach(table => {\n        table.classList.add('table');\n    })\n    document.querySelectorAll('p').forEach(p => {\n        p.classList.add('ud-blog-details-para');\n    })\n</script>"
  },
  {
    "path": "_layouts/resources.html",
    "content": "---\nlayout: page\nshow_header: false\n---\n<div class=\"container\">\n    <div class=\"row py-5\">\n        <div class=\"col text-center\">\n            <div class=\"fs-2\">Thank you for enrolling! We're excited to have you here!</div>\n            <div class=\"fs-2\"><strong>{{page.resources.size}} steps</strong> to get ready for the course.</div>\n        </div>\n    </div>\n    <div class=\"row mb-2\">\n        <div class=\"col border-right\">\n\n            <div class=\"wrapper\">\n                <div class=\"timeline\">\n                    {% for item in page.resources %}\n                    <div class=\"timeline--entry ud-single-feature wow fadeInUp p-3 bg-white\" data-wow-delay=\".1s\"\n                        style=\"visibility: visible; animation-delay: 0.1s; animation-name: fadeInUp;\">\n                        <a target=\"_blank\" href=\"{{item.url}}\" class=\"btn btn-link\">\n                            <div class=\"ud-feature-icon\">\n                                <i class=\"lni {{item.icon | default: 'lni-download'}}\"></i>\n                            </div>\n                        </a>\n                        <div class=\"ud-feature-content\">\n                            <h3 class=\"ud-feature-title\">{{item.title}}</h3>\n                            <p class=\"ud-feature-desc\">\n                                {{item.description}}\n                            </p>\n                        </div>\n                    </div>\n                    {% endfor %}\n\n                </div>\n            </div>\n        </div>\n    </div>\n    {% include newsletter.html %}\n</div>"
  },
  {
    "path": "about.md",
    "content": "---\nlayout: about\npermalink: /about\ntitle: About\n---\n\n## YOUR FIRST STEP into Programming, Cloud & DevOps\n\nRanga Karanam, the founder of in28minutes, has 2 decades of experience with technology - architecture, design, and programming.\n\nWe are helping learners take their first steps into modern cloud native technology and gain expertise on AWS, Azure, Google Cloud, Docker, Kubernetes amongst others.\n"
  },
  {
    "path": "assets/css/animate.css",
    "content": "@charset \"UTF-8\";\n\n/*!\n * animate.css -https://daneden.github.io/animate.css/\n * Version - 3.7.2\n * Licensed under the MIT license - http://opensource.org/licenses/MIT\n *\n * Copyright (c) 2019 Daniel Eden\n */\n\n@-webkit-keyframes fadeIn {\n  from {\n    opacity: 0;\n  }\n\n  to {\n    opacity: 1;\n  }\n}\n\n@keyframes fadeIn {\n  from {\n    opacity: 0;\n  }\n\n  to {\n    opacity: 1;\n  }\n}\n\n.fadeIn {\n  -webkit-animation-name: fadeIn;\n  animation-name: fadeIn;\n}\n\n@-webkit-keyframes fadeInDown {\n  from {\n    opacity: 0;\n    -webkit-transform: translate3d(0, -20px, 0);\n    transform: translate3d(0, -20px, 0);\n  }\n\n  to {\n    opacity: 1;\n    -webkit-transform: translate3d(0, 0, 0);\n    transform: translate3d(0, 0, 0);\n  }\n}\n\n@keyframes fadeInDown {\n  from {\n    opacity: 0;\n    -webkit-transform: translate3d(0, -20px, 0);\n    transform: translate3d(0, -20px, 0);\n  }\n\n  to {\n    opacity: 1;\n    -webkit-transform: translate3d(0, 0, 0);\n    transform: translate3d(0, 0, 0);\n  }\n}\n\n.fadeInDown {\n  -webkit-animation-name: fadeInDown;\n  animation-name: fadeInDown;\n}\n\n@-webkit-keyframes fadeInLeft {\n  from {\n    opacity: 0;\n    -webkit-transform: translate3d(-20px, 0, 0);\n    transform: translate3d(-20px, 0, 0);\n  }\n\n  to {\n    opacity: 1;\n    -webkit-transform: translate3d(0, 0, 0);\n    transform: translate3d(0, 0, 0);\n  }\n}\n\n@keyframes fadeInLeft {\n  from {\n    opacity: 0;\n    -webkit-transform: translate3d(-20px, 0, 0);\n    transform: translate3d(-20px, 0, 0);\n  }\n\n  to {\n    opacity: 1;\n    -webkit-transform: translate3d(0, 0, 0);\n    transform: translate3d(0, 0, 0);\n  }\n}\n\n.fadeInLeft {\n  -webkit-animation-name: fadeInLeft;\n  animation-name: fadeInLeft;\n}\n\n@-webkit-keyframes fadeInRight {\n  from {\n    opacity: 0;\n    -webkit-transform: translate3d(20px, 0, 0);\n    transform: translate3d(20px, 0, 0);\n  }\n\n  to {\n    opacity: 1;\n    -webkit-transform: translate3d(0, 0, 0);\n    transform: translate3d(0, 0, 0);\n  }\n}\n\n@keyframes fadeInRight {\n  from {\n    opacity: 0;\n    -webkit-transform: translate3d(20px, 0, 0);\n    transform: translate3d(20px, 0, 0);\n  }\n\n  to {\n    opacity: 1;\n    -webkit-transform: translate3d(0, 0, 0);\n    transform: translate3d(0, 0, 0);\n  }\n}\n\n.fadeInRight {\n  -webkit-animation-name: fadeInRight;\n  animation-name: fadeInRight;\n}\n\n@-webkit-keyframes fadeInUp {\n  from {\n    opacity: 0;\n    -webkit-transform: translate3d(0, 20px, 0);\n    transform: translate3d(0, 20px, 0);\n  }\n\n  to {\n    opacity: 1;\n    -webkit-transform: translate3d(0, 0, 0);\n    transform: translate3d(0, 0, 0);\n  }\n}\n\n@keyframes fadeInUp {\n  from {\n    opacity: 0;\n    -webkit-transform: translate3d(0, 20px, 0);\n    transform: translate3d(0, 20px, 0);\n  }\n\n  to {\n    opacity: 1;\n    -webkit-transform: translate3d(0, 0, 0);\n    transform: translate3d(0, 0, 0);\n  }\n}\n\n.fadeInUp {\n  -webkit-animation-name: fadeInUp;\n  animation-name: fadeInUp;\n}\n\n.animated {\n  -webkit-animation-duration: 1s;\n  animation-duration: 1s;\n  -webkit-animation-fill-mode: both;\n  animation-fill-mode: both;\n}\n\n.animated.infinite {\n  -webkit-animation-iteration-count: infinite;\n  animation-iteration-count: infinite;\n}\n\n.animated.delay-1s {\n  -webkit-animation-delay: 1s;\n  animation-delay: 1s;\n}\n\n.animated.delay-2s {\n  -webkit-animation-delay: 2s;\n  animation-delay: 2s;\n}\n\n.animated.delay-3s {\n  -webkit-animation-delay: 3s;\n  animation-delay: 3s;\n}\n\n.animated.delay-4s {\n  -webkit-animation-delay: 4s;\n  animation-delay: 4s;\n}\n\n.animated.delay-5s {\n  -webkit-animation-delay: 5s;\n  animation-delay: 5s;\n}\n\n.animated.fast {\n  -webkit-animation-duration: 800ms;\n  animation-duration: 800ms;\n}\n\n.animated.faster {\n  -webkit-animation-duration: 500ms;\n  animation-duration: 500ms;\n}\n\n.animated.slow {\n  -webkit-animation-duration: 2s;\n  animation-duration: 2s;\n}\n\n.animated.slower {\n  -webkit-animation-duration: 3s;\n  animation-duration: 3s;\n}\n\n@media (print), (prefers-reduced-motion: reduce) {\n  .animated {\n    -webkit-animation-duration: 1ms !important;\n    animation-duration: 1ms !important;\n    -webkit-transition-duration: 1ms !important;\n    transition-duration: 1ms !important;\n    -webkit-animation-iteration-count: 1 !important;\n    animation-iteration-count: 1 !important;\n  }\n}\n"
  },
  {
    "path": "assets/css/custom.css",
    "content": ".subscribe-wrapper {\n  margin-bottom: -15em !important;\n  z-index: 10000;\n  position: relative;\n}\n.newsletter-box-large {\n  -webkit-box-shadow: 0px 5px 20px -5px rgba(0, 0, 0, 0.5);\n  -moz-box-shadow: 0px 5px 20px -5px rgba(0, 0, 0, 0.5);\n  box-shadow: 0px 5px 20px -5px rgba(0, 0, 0, 0.5);\n}\n.ud-footer {\n  padding-top: 15em !important;\n}\n.ud-header > .navbar-brand {\n  color: white;\n}\n\n.ud-header.sticky > .navbar-brand {\n  color: black;\n}\n\n.course-rating i {\n  color: #fbb040;\n}\n/*- Screen Sizes*/\n/*import fonts*/\n@import url('https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css');\n/*media queries*/\n.wrapper,\n.wrapper:before,\n.wrapper:after {\n  box-sizing: inherit;\n}\n\n.wrapper {\n  margin: 3.125em auto;\n  padding: 1em 5em 1em;\n  max-width: 1000px;\n  box-sizing: border-box;\n}\n\n.wrapper > h1 {\n  color: white;\n  font-family: 'Open Sans', 'Lucida Grande', Tahoma, Verdana, Arial, sans-serif;\n  text-align: center;\n}\n\n/* - &:nth-child(1) {\n\t\t\t grid-area: entry1;\n\t\t }\n   - useful timesaver if there is a lengthy list\n*/\n.timeline {\n  line-height: 1.5em;\n  font-size: 14px;\n  transition: all 0.4s ease;\n  position: relative;\n  counter-reset: section;\n}\n.timeline:before {\n  content: '';\n  width: 10px;\n  height: 100%;\n  background: var(--primary-color);\n  position: absolute;\n  top: 0;\n  left: -3.313em;\n  border-radius: 40px 40px;\n}\n\n.timeline--entry {\n  position: relative;\n  background-color: #eeeeee;\n}\n.timeline--entry__title {\n  color: white;\n  background-color: var(--primary-color);\n  font-weight: 300;\n  font-size: 1rem;\n  padding: 1em;\n}\n.timeline--entry__title:before {\n  content: '';\n  display: inline-block;\n  width: 1em;\n  height: 1em;\n  position: absolute;\n  border-top: 10px solid transparent;\n  border-bottom: 10px solid transparent;\n  left: -1em;\n  border-right: 10px solid var(--primary-color);\n}\n.timeline--entry__detail {\n  background-color: #dddddd;\n  padding: 1em;\n  margin: 0;\n}\n.timeline--entry:before {\n  content: '';\n  color: #ffffff;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  width: 3em;\n  height: 3em;\n  /* background-color: var(--primary-color); */\n  background-color: #84a1ff;\n  border: 0.2em solid white;\n  border-radius: 50%;\n  position: absolute;\n  counter-increment: section;\n  content: counter(section);\n  text-shadow: 0 1px 0 #424242;\n  left: -4.5em;\n  font-weight: bold;\n}\n\n@supports (display: grid) {\n  @media (min-width: 768px) {\n    .timeline {\n      display: grid;\n      grid-gap: 4.75em;\n      grid-template-areas: '.  entry1' 'entry2  .' '. entry3' 'entry4 .' '. entry5';\n    }\n    .timeline:before {\n      left: 49.5%;\n    }\n\n    .timeline--entry:nth-child(1) {\n      grid-area: entry1;\n    }\n    .timeline--entry:nth-child(2) {\n      grid-area: entry2;\n    }\n    .timeline--entry:nth-child(3) {\n      grid-area: entry3;\n    }\n    .timeline--entry:nth-child(4) {\n      grid-area: entry4;\n    }\n    .timeline--entry:nth-child(5) {\n      grid-area: entry5;\n    }\n    .timeline--entry:nth-of-type(odd):before {\n      left: -3.8em;\n    }\n    .timeline--entry:nth-of-type(even):not(:nth-of-type(odd))\n      .timeline--entry__title:before {\n      left: 100%;\n      border-left: 10px solid var(--primary-color);\n      border-right: 0;\n    }\n    .timeline--entry:nth-of-type(even):before {\n      left: 103%;\n    }\n  }\n}\n"
  },
  {
    "path": "assets/css/lineicons.css",
    "content": "/*--------------------------------\n\nLineIcons Web Font\nAuthor: lineicons.com\n\n-------------------------------- */\n@font-face {\n  font-family: 'LineIcons';\n  src: url('../fonts/LineIcons.eot');\n  src: url('../fonts/LineIcons.eot') format('embedded-opentype'), url('../fonts/LineIcons.woff2') format('woff2'), url('../fonts/LineIcons.woff') format('woff'), url('../fonts/LineIcons.ttf') format('truetype'), url('../fonts/LineIcons.svg') format('svg');\n  font-weight: normal;\n  font-style: normal;\n}\n/*------------------------\n\tbase class definition\n-------------------------*/\n.lni {\n  display: inline-block;\n  font: normal normal normal 1em/1 'LineIcons';\n  color: inherit;\n  flex-shrink: 0;\n  speak: none;\n  text-transform: none;\n  line-height: 1;\n  vertical-align: -.125em;\n  /* Better Font Rendering */\n  -webkit-font-smoothing: antialiased;\n  -moz-osx-font-smoothing: grayscale;\n}\n/*------------------------\n  change icon size\n-------------------------*/\n/* relative units */\n.lni-sm {\n  font-size: 0.8em;\n}\n.lni-lg {\n  font-size: 1.2em;\n}\n/* absolute units */\n.lni-16 {\n  font-size: 16px;\n}\n.lni-32 {\n  font-size: 32px;\n}\n\n/*------------------------\n  spinning icons\n-------------------------*/\n.lni-is-spinning {\n  animation: lni-spin 1s infinite linear;\n}\n@keyframes lni-spin {\n  0% {\n    transform: rotate(0deg);\n  }\n  100% {\n    transform: rotate(360deg);\n  }\n}\n/*------------------------\n  rotated/flipped icons\n-------------------------*/\n.lni-rotate-90 {\n  transform: rotate(90deg);\n}\n.lni-rotate-180 {\n  transform: rotate(180deg);\n}\n.lni-rotate-270 {\n  transform: rotate(270deg);\n}\n.lni-flip-y {\n  transform: scaleY(-1);\n}\n.lni-flip-x {\n  transform: scaleX(-1);\n}\n/*------------------------\n\ticons\n-------------------------*/\n\n.lni-500px::before {\n  content: \"\\ea03\";\n}\n\n.lni-add-files::before {\n  content: \"\\ea01\";\n}\n\n.lni-adobe::before {\n  content: \"\\ea06\";\n}\n\n.lni-agenda::before {\n  content: \"\\ea02\";\n}\n\n.lni-airbnb::before {\n  content: \"\\ea07\";\n}\n\n.lni-alarm-clock::before {\n  content: \"\\ea08\";\n}\n\n.lni-alarm::before {\n  content: \"\\ea04\";\n}\n\n.lni-amazon-original::before {\n  content: \"\\ea05\";\n}\n\n.lni-amazon-pay::before {\n  content: \"\\ea09\";\n}\n\n.lni-amazon::before {\n  content: \"\\ea0a\";\n}\n\n.lni-ambulance::before {\n  content: \"\\ea0b\";\n}\n\n.lni-amex::before {\n  content: \"\\ea0c\";\n}\n\n.lni-anchor::before {\n  content: \"\\ea0d\";\n}\n\n.lni-android-original::before {\n  content: \"\\ea0e\";\n}\n\n.lni-android::before {\n  content: \"\\ea0f\";\n}\n\n.lni-angellist::before {\n  content: \"\\ea10\";\n}\n\n.lni-angle-double-down::before {\n  content: \"\\ea11\";\n}\n\n.lni-angle-double-left::before {\n  content: \"\\ea12\";\n}\n\n.lni-angle-double-right::before {\n  content: \"\\ea13\";\n}\n\n.lni-angle-double-up::before {\n  content: \"\\ea14\";\n}\n\n.lni-angular::before {\n  content: \"\\ea15\";\n}\n\n.lni-apartment::before {\n  content: \"\\ea16\";\n}\n\n.lni-app-store::before {\n  content: \"\\ea17\";\n}\n\n.lni-apple-music::before {\n  content: \"\\ea18\";\n}\n\n.lni-apple-pay::before {\n  content: \"\\ea19\";\n}\n\n.lni-apple::before {\n  content: \"\\ea1a\";\n}\n\n.lni-archive::before {\n  content: \"\\ea1f\";\n}\n\n.lni-arrow-down-circle::before {\n  content: \"\\ea1b\";\n}\n\n.lni-arrow-down::before {\n  content: \"\\ea1c\";\n}\n\n.lni-arrow-left-circle::before {\n  content: \"\\ea1d\";\n}\n\n.lni-arrow-left::before {\n  content: \"\\ea1e\";\n}\n\n.lni-arrow-right-circle::before {\n  content: \"\\ea20\";\n}\n\n.lni-arrow-right::before {\n  content: \"\\ea21\";\n}\n\n.lni-arrow-top-left::before {\n  content: \"\\ea22\";\n}\n\n.lni-arrow-top-right::before {\n  content: \"\\ea23\";\n}\n\n.lni-arrow-up-circle::before {\n  content: \"\\ea24\";\n}\n\n.lni-arrow-up::before {\n  content: \"\\ea25\";\n}\n\n.lni-arrows-horizontal::before {\n  content: \"\\ea26\";\n}\n\n.lni-arrows-vertical::before {\n  content: \"\\ea27\";\n}\n\n.lni-atlassian::before {\n  content: \"\\ea28\";\n}\n\n.lni-aws::before {\n  content: \"\\ea29\";\n}\n\n.lni-azure::before {\n  content: \"\\ea2a\";\n}\n\n.lni-backward::before {\n  content: \"\\ea2b\";\n}\n\n.lni-baloon::before {\n  content: \"\\ea2c\";\n}\n\n.lni-ban::before {\n  content: \"\\ea2d\";\n}\n\n.lni-bar-chart::before {\n  content: \"\\ea2e\";\n}\n\n.lni-basketball::before {\n  content: \"\\ea2f\";\n}\n\n.lni-behance-original::before {\n  content: \"\\ea30\";\n}\n\n.lni-behance::before {\n  content: \"\\ea31\";\n}\n\n.lni-bi-cycle::before {\n  content: \"\\ea32\";\n}\n\n.lni-bitbucket::before {\n  content: \"\\ea33\";\n}\n\n.lni-bitcoin::before {\n  content: \"\\ea34\";\n}\n\n.lni-blackboard::before {\n  content: \"\\ea35\";\n}\n\n.lni-blogger::before {\n  content: \"\\ea36\";\n}\n\n.lni-bluetooth-original::before {\n  content: \"\\ea37\";\n}\n\n.lni-bluetooth::before {\n  content: \"\\ea38\";\n}\n\n.lni-bold::before {\n  content: \"\\ea39\";\n}\n\n.lni-bolt-alt::before {\n  content: \"\\ea3a\";\n}\n\n.lni-bolt::before {\n  content: \"\\ea40\";\n}\n\n.lni-book::before {\n  content: \"\\ea3b\";\n}\n\n.lni-bookmark-alt::before {\n  content: \"\\ea3c\";\n}\n\n.lni-bookmark::before {\n  content: \"\\ea3d\";\n}\n\n.lni-bootstrap::before {\n  content: \"\\ea3e\";\n}\n\n.lni-bricks::before {\n  content: \"\\ea3f\";\n}\n\n.lni-bridge::before {\n  content: \"\\ea41\";\n}\n\n.lni-briefcase::before {\n  content: \"\\ea42\";\n}\n\n.lni-brush-alt::before {\n  content: \"\\ea43\";\n}\n\n.lni-brush::before {\n  content: \"\\ea44\";\n}\n\n.lni-btc::before {\n  content: \"\\ea45\";\n}\n\n.lni-bubble::before {\n  content: \"\\ea46\";\n}\n\n.lni-bug::before {\n  content: \"\\ea47\";\n}\n\n.lni-bulb::before {\n  content: \"\\ea48\";\n}\n\n.lni-bullhorn::before {\n  content: \"\\ea49\";\n}\n\n.lni-burger::before {\n  content: \"\\ea4a\";\n}\n\n.lni-bus::before {\n  content: \"\\ea4b\";\n}\n\n.lni-cake::before {\n  content: \"\\ea4c\";\n}\n\n.lni-calculator::before {\n  content: \"\\ea4d\";\n}\n\n.lni-calendar::before {\n  content: \"\\ea4e\";\n}\n\n.lni-camera::before {\n  content: \"\\ea4f\";\n}\n\n.lni-candy-cane::before {\n  content: \"\\ea50\";\n}\n\n.lni-candy::before {\n  content: \"\\ea51\";\n}\n\n.lni-capsule::before {\n  content: \"\\ea52\";\n}\n\n.lni-car-alt::before {\n  content: \"\\ea53\";\n}\n\n.lni-car::before {\n  content: \"\\ea54\";\n}\n\n.lni-caravan::before {\n  content: \"\\ea55\";\n}\n\n.lni-cart-full::before {\n  content: \"\\ea56\";\n}\n\n.lni-cart::before {\n  content: \"\\ea57\";\n}\n\n.lni-certificate::before {\n  content: \"\\ea58\";\n}\n\n.lni-check-box::before {\n  content: \"\\ea59\";\n}\n\n.lni-checkmark-circle::before {\n  content: \"\\ea5a\";\n}\n\n.lni-checkmark::before {\n  content: \"\\ea5b\";\n}\n\n.lni-chef-hat::before {\n  content: \"\\ea5c\";\n}\n\n.lni-chevron-down-circle::before {\n  content: \"\\ea5d\";\n}\n\n.lni-chevron-down::before {\n  content: \"\\ea5e\";\n}\n\n.lni-chevron-left-circle::before {\n  content: \"\\ea5f\";\n}\n\n.lni-chevron-left::before {\n  content: \"\\ea60\";\n}\n\n.lni-chevron-right-circle::before {\n  content: \"\\ea61\";\n}\n\n.lni-chevron-right::before {\n  content: \"\\ea62\";\n}\n\n.lni-chevron-up-circle::before {\n  content: \"\\ea63\";\n}\n\n.lni-chevron-up::before {\n  content: \"\\ea64\";\n}\n\n.lni-chrome::before {\n  content: \"\\ea65\";\n}\n\n.lni-chromecast::before {\n  content: \"\\ea66\";\n}\n\n.lni-circle-minus::before {\n  content: \"\\ea67\";\n}\n\n.lni-circle-plus::before {\n  content: \"\\ea68\";\n}\n\n.lni-clipboard::before {\n  content: \"\\ea69\";\n}\n\n.lni-close::before {\n  content: \"\\ea6a\";\n}\n\n.lni-cloud-check::before {\n  content: \"\\ea6b\";\n}\n\n.lni-cloud-download::before {\n  content: \"\\ea6c\";\n}\n\n.lni-cloud-network::before {\n  content: \"\\ea6d\";\n}\n\n.lni-cloud-sync::before {\n  content: \"\\ea6e\";\n}\n\n.lni-cloud-upload::before {\n  content: \"\\ea6f\";\n}\n\n.lni-cloud::before {\n  content: \"\\ea70\";\n}\n\n.lni-cloudflare::before {\n  content: \"\\ea71\";\n}\n\n.lni-cloudy-sun::before {\n  content: \"\\ea72\";\n}\n\n.lni-code-alt::before {\n  content: \"\\ea73\";\n}\n\n.lni-code::before {\n  content: \"\\ea74\";\n}\n\n.lni-codepen::before {\n  content: \"\\ea75\";\n}\n\n.lni-coffee-cup::before {\n  content: \"\\ea76\";\n}\n\n.lni-cog::before {\n  content: \"\\ea77\";\n}\n\n.lni-cogs::before {\n  content: \"\\ea78\";\n}\n\n.lni-coin::before {\n  content: \"\\ea79\";\n}\n\n.lni-comments-alt::before {\n  content: \"\\ea7a\";\n}\n\n.lni-comments-reply::before {\n  content: \"\\ea7b\";\n}\n\n.lni-comments::before {\n  content: \"\\ea7c\";\n}\n\n.lni-compass::before {\n  content: \"\\ea7d\";\n}\n\n.lni-connectdevelop::before {\n  content: \"\\ea7e\";\n}\n\n.lni-construction-hammer::before {\n  content: \"\\ea7f\";\n}\n\n.lni-construction::before {\n  content: \"\\ea80\";\n}\n\n.lni-consulting::before {\n  content: \"\\ea81\";\n}\n\n.lni-control-panel::before {\n  content: \"\\ea82\";\n}\n\n.lni-cool::before {\n  content: \"\\ea83\";\n}\n\n.lni-cpanel::before {\n  content: \"\\ea84\";\n}\n\n.lni-creative-commons::before {\n  content: \"\\ea85\";\n}\n\n.lni-credit-cards::before {\n  content: \"\\ea86\";\n}\n\n.lni-crop::before {\n  content: \"\\ea87\";\n}\n\n.lni-cross-circle::before {\n  content: \"\\ea88\";\n}\n\n.lni-crown::before {\n  content: \"\\ea89\";\n}\n\n.lni-css3::before {\n  content: \"\\ea8a\";\n}\n\n.lni-cup::before {\n  content: \"\\ea8b\";\n}\n\n.lni-customer::before {\n  content: \"\\ea8c\";\n}\n\n.lni-cut::before {\n  content: \"\\ea8d\";\n}\n\n.lni-dashboard::before {\n  content: \"\\ea8e\";\n}\n\n.lni-database::before {\n  content: \"\\ea8f\";\n}\n\n.lni-delivery::before {\n  content: \"\\ea90\";\n}\n\n.lni-dev::before {\n  content: \"\\ea91\";\n}\n\n.lni-diamond-alt::before {\n  content: \"\\ea92\";\n}\n\n.lni-diamond::before {\n  content: \"\\ea93\";\n}\n\n.lni-digitalocean::before {\n  content: \"\\ea94\";\n}\n\n.lni-diners-club::before {\n  content: \"\\ea95\";\n}\n\n.lni-dinner::before {\n  content: \"\\ea96\";\n}\n\n.lni-direction-alt::before {\n  content: \"\\ea97\";\n}\n\n.lni-direction-ltr::before {\n  content: \"\\ea98\";\n}\n\n.lni-direction-rtl::before {\n  content: \"\\ea99\";\n}\n\n.lni-direction::before {\n  content: \"\\ea9a\";\n}\n\n.lni-discord::before {\n  content: \"\\ea9b\";\n}\n\n.lni-discover::before {\n  content: \"\\ea9c\";\n}\n\n.lni-display-alt::before {\n  content: \"\\ea9d\";\n}\n\n.lni-display::before {\n  content: \"\\ea9e\";\n}\n\n.lni-docker::before {\n  content: \"\\ea9f\";\n}\n\n.lni-dollar::before {\n  content: \"\\eaa0\";\n}\n\n.lni-domain::before {\n  content: \"\\eaa1\";\n}\n\n.lni-download::before {\n  content: \"\\eaa2\";\n}\n\n.lni-dribbble::before {\n  content: \"\\eaa3\";\n}\n\n.lni-drop::before {\n  content: \"\\eaa4\";\n}\n\n.lni-dropbox-original::before {\n  content: \"\\eaa5\";\n}\n\n.lni-dropbox::before {\n  content: \"\\eaa6\";\n}\n\n.lni-drupal-original::before {\n  content: \"\\eaa7\";\n}\n\n.lni-drupal::before {\n  content: \"\\eaa8\";\n}\n\n.lni-dumbbell::before {\n  content: \"\\eaa9\";\n}\n\n.lni-edge::before {\n  content: \"\\eaaa\";\n}\n\n.lni-empty-file::before {\n  content: \"\\eaab\";\n}\n\n.lni-enter::before {\n  content: \"\\eaac\";\n}\n\n.lni-envato::before {\n  content: \"\\eaad\";\n}\n\n.lni-envelope::before {\n  content: \"\\eaae\";\n}\n\n.lni-eraser::before {\n  content: \"\\eaaf\";\n}\n\n.lni-euro::before {\n  content: \"\\eab0\";\n}\n\n.lni-exit-down::before {\n  content: \"\\eab1\";\n}\n\n.lni-exit-up::before {\n  content: \"\\eab2\";\n}\n\n.lni-exit::before {\n  content: \"\\eab3\";\n}\n\n.lni-eye::before {\n  content: \"\\eab4\";\n}\n\n.lni-facebook-filled::before {\n  content: \"\\eab5\";\n}\n\n.lni-facebook-messenger::before {\n  content: \"\\eab6\";\n}\n\n.lni-facebook-original::before {\n  content: \"\\eab7\";\n}\n\n.lni-facebook-oval::before {\n  content: \"\\eab8\";\n}\n\n.lni-facebook::before {\n  content: \"\\eab9\";\n}\n\n.lni-figma::before {\n  content: \"\\eaba\";\n}\n\n.lni-files::before {\n  content: \"\\eabb\";\n}\n\n.lni-firefox-original::before {\n  content: \"\\eabc\";\n}\n\n.lni-firefox::before {\n  content: \"\\eabd\";\n}\n\n.lni-fireworks::before {\n  content: \"\\eabe\";\n}\n\n.lni-first-aid::before {\n  content: \"\\eabf\";\n}\n\n.lni-flag-alt::before {\n  content: \"\\eac0\";\n}\n\n.lni-flag::before {\n  content: \"\\eac1\";\n}\n\n.lni-flags::before {\n  content: \"\\eac2\";\n}\n\n.lni-flickr::before {\n  content: \"\\eac3\";\n}\n\n.lni-flower::before {\n  content: \"\\eac4\";\n}\n\n.lni-folder::before {\n  content: \"\\eac5\";\n}\n\n.lni-forward::before {\n  content: \"\\eac6\";\n}\n\n.lni-frame-expand::before {\n  content: \"\\eac7\";\n}\n\n.lni-fresh-juice::before {\n  content: \"\\eac8\";\n}\n\n.lni-friendly::before {\n  content: \"\\eac9\";\n}\n\n.lni-full-screen::before {\n  content: \"\\eaca\";\n}\n\n.lni-funnel::before {\n  content: \"\\eacb\";\n}\n\n.lni-gallery::before {\n  content: \"\\eacc\";\n}\n\n.lni-game::before {\n  content: \"\\eacd\";\n}\n\n.lni-gatsby::before {\n  content: \"\\eace\";\n}\n\n.lni-gift::before {\n  content: \"\\eacf\";\n}\n\n.lni-git::before {\n  content: \"\\ead0\";\n}\n\n.lni-github-original::before {\n  content: \"\\ead1\";\n}\n\n.lni-github::before {\n  content: \"\\ead2\";\n}\n\n.lni-goodreads::before {\n  content: \"\\ead3\";\n}\n\n.lni-google-drive::before {\n  content: \"\\ead4\";\n}\n\n.lni-google-pay::before {\n  content: \"\\ead5\";\n}\n\n.lni-google-wallet::before {\n  content: \"\\ead6\";\n}\n\n.lni-google::before {\n  content: \"\\ead7\";\n}\n\n.lni-graduation::before {\n  content: \"\\ead8\";\n}\n\n.lni-graph::before {\n  content: \"\\ead9\";\n}\n\n.lni-grid-alt::before {\n  content: \"\\eada\";\n}\n\n.lni-grid::before {\n  content: \"\\eadb\";\n}\n\n.lni-grow::before {\n  content: \"\\eadc\";\n}\n\n.lni-hacker-news::before {\n  content: \"\\eadd\";\n}\n\n.lni-hammer::before {\n  content: \"\\eade\";\n}\n\n.lni-hand::before {\n  content: \"\\eadf\";\n}\n\n.lni-handshake::before {\n  content: \"\\eae0\";\n}\n\n.lni-happy::before {\n  content: \"\\eae1\";\n}\n\n.lni-harddrive::before {\n  content: \"\\eae2\";\n}\n\n.lni-headphone-alt::before {\n  content: \"\\eae3\";\n}\n\n.lni-headphone::before {\n  content: \"\\eae4\";\n}\n\n.lni-heart-filled::before {\n  content: \"\\eae5\";\n}\n\n.lni-heart-monitor::before {\n  content: \"\\eae6\";\n}\n\n.lni-heart::before {\n  content: \"\\eae7\";\n}\n\n.lni-helicopter::before {\n  content: \"\\eae8\";\n}\n\n.lni-helmet::before {\n  content: \"\\eae9\";\n}\n\n.lni-help::before {\n  content: \"\\eaea\";\n}\n\n.lni-highlight-alt::before {\n  content: \"\\eaeb\";\n}\n\n.lni-highlight::before {\n  content: \"\\eaec\";\n}\n\n.lni-home::before {\n  content: \"\\eaed\";\n}\n\n.lni-hospital::before {\n  content: \"\\eaee\";\n}\n\n.lni-hourglass::before {\n  content: \"\\eaef\";\n}\n\n.lni-html5::before {\n  content: \"\\eaf0\";\n}\n\n.lni-image::before {\n  content: \"\\eaf1\";\n}\n\n.lni-imdb::before {\n  content: \"\\eaf2\";\n}\n\n.lni-inbox::before {\n  content: \"\\eaf3\";\n}\n\n.lni-indent-decrease::before {\n  content: \"\\eaf4\";\n}\n\n.lni-indent-increase::before {\n  content: \"\\eaf5\";\n}\n\n.lni-infinite::before {\n  content: \"\\eaf6\";\n}\n\n.lni-information::before {\n  content: \"\\eaf7\";\n}\n\n.lni-instagram-filled::before {\n  content: \"\\eaf8\";\n}\n\n.lni-instagram-original::before {\n  content: \"\\eaf9\";\n}\n\n.lni-instagram::before {\n  content: \"\\eafa\";\n}\n\n.lni-invention::before {\n  content: \"\\eafb\";\n}\n\n.lni-invest-monitor::before {\n  content: \"\\eafc\";\n}\n\n.lni-investment::before {\n  content: \"\\eafd\";\n}\n\n.lni-island::before {\n  content: \"\\eafe\";\n}\n\n.lni-italic::before {\n  content: \"\\eaff\";\n}\n\n.lni-java::before {\n  content: \"\\eb00\";\n}\n\n.lni-javascript::before {\n  content: \"\\eb01\";\n}\n\n.lni-jcb::before {\n  content: \"\\eb02\";\n}\n\n.lni-joomla-original::before {\n  content: \"\\eb03\";\n}\n\n.lni-joomla::before {\n  content: \"\\eb04\";\n}\n\n.lni-jsfiddle::before {\n  content: \"\\eb05\";\n}\n\n.lni-juice::before {\n  content: \"\\eb06\";\n}\n\n.lni-key::before {\n  content: \"\\eb07\";\n}\n\n.lni-keyboard::before {\n  content: \"\\eb08\";\n}\n\n.lni-keyword-research::before {\n  content: \"\\eb09\";\n}\n\n.lni-laptop-phone::before {\n  content: \"\\eb0a\";\n}\n\n.lni-laptop::before {\n  content: \"\\eb0b\";\n}\n\n.lni-laravel::before {\n  content: \"\\eb0c\";\n}\n\n.lni-layers::before {\n  content: \"\\eb0d\";\n}\n\n.lni-layout::before {\n  content: \"\\eb0e\";\n}\n\n.lni-leaf::before {\n  content: \"\\eb0f\";\n}\n\n.lni-library::before {\n  content: \"\\eb10\";\n}\n\n.lni-license::before {\n  content: \"\\eb11\";\n}\n\n.lni-lifering::before {\n  content: \"\\eb12\";\n}\n\n.lni-line-dashed::before {\n  content: \"\\eb13\";\n}\n\n.lni-line-dotted::before {\n  content: \"\\eb14\";\n}\n\n.lni-line-double::before {\n  content: \"\\eb15\";\n}\n\n.lni-line-spacing::before {\n  content: \"\\eb16\";\n}\n\n.lni-line::before {\n  content: \"\\eb17\";\n}\n\n.lni-lineicons-alt::before {\n  content: \"\\eb18\";\n}\n\n.lni-lineicons::before {\n  content: \"\\eb19\";\n}\n\n.lni-link::before {\n  content: \"\\eb1a\";\n}\n\n.lni-linkedin-original::before {\n  content: \"\\eb1b\";\n}\n\n.lni-linkedin::before {\n  content: \"\\eb1c\";\n}\n\n.lni-list::before {\n  content: \"\\eb1d\";\n}\n\n.lni-lock-alt::before {\n  content: \"\\eb1e\";\n}\n\n.lni-lock::before {\n  content: \"\\eb1f\";\n}\n\n.lni-magento::before {\n  content: \"\\eb20\";\n}\n\n.lni-magnet::before {\n  content: \"\\eb21\";\n}\n\n.lni-magnifier::before {\n  content: \"\\eb22\";\n}\n\n.lni-mailchimp::before {\n  content: \"\\eb23\";\n}\n\n.lni-map-marker::before {\n  content: \"\\eb24\";\n}\n\n.lni-map::before {\n  content: \"\\eb25\";\n}\n\n.lni-markdown::before {\n  content: \"\\eb26\";\n}\n\n.lni-mashroom::before {\n  content: \"\\eb27\";\n}\n\n.lni-mastercard::before {\n  content: \"\\eb28\";\n}\n\n.lni-medium::before {\n  content: \"\\eb29\";\n}\n\n.lni-menu::before {\n  content: \"\\eb2a\";\n}\n\n.lni-mic::before {\n  content: \"\\eb2b\";\n}\n\n.lni-microphone::before {\n  content: \"\\eb2c\";\n}\n\n.lni-microscope::before {\n  content: \"\\eb2d\";\n}\n\n.lni-microsoft-edge::before {\n  content: \"\\eb2e\";\n}\n\n.lni-microsoft::before {\n  content: \"\\eb2f\";\n}\n\n.lni-minus::before {\n  content: \"\\eb30\";\n}\n\n.lni-mobile::before {\n  content: \"\\eb31\";\n}\n\n.lni-money-location::before {\n  content: \"\\eb32\";\n}\n\n.lni-money-protection::before {\n  content: \"\\eb33\";\n}\n\n.lni-more-alt::before {\n  content: \"\\eb34\";\n}\n\n.lni-more::before {\n  content: \"\\eb35\";\n}\n\n.lni-mouse::before {\n  content: \"\\eb36\";\n}\n\n.lni-move::before {\n  content: \"\\eb37\";\n}\n\n.lni-music::before {\n  content: \"\\eb38\";\n}\n\n.lni-netlify::before {\n  content: \"\\eb39\";\n}\n\n.lni-network::before {\n  content: \"\\eb3a\";\n}\n\n.lni-night::before {\n  content: \"\\eb3b\";\n}\n\n.lni-nodejs-alt::before {\n  content: \"\\eb3c\";\n}\n\n.lni-nodejs::before {\n  content: \"\\eb3d\";\n}\n\n.lni-notepad::before {\n  content: \"\\eb3e\";\n}\n\n.lni-npm::before {\n  content: \"\\eb3f\";\n}\n\n.lni-offer::before {\n  content: \"\\eb40\";\n}\n\n.lni-opera::before {\n  content: \"\\eb41\";\n}\n\n.lni-package::before {\n  content: \"\\eb42\";\n}\n\n.lni-page-break::before {\n  content: \"\\eb43\";\n}\n\n.lni-pagination::before {\n  content: \"\\eb44\";\n}\n\n.lni-paint-bucket::before {\n  content: \"\\eb45\";\n}\n\n.lni-paint-roller::before {\n  content: \"\\eb46\";\n}\n\n.lni-pallet::before {\n  content: \"\\eb47\";\n}\n\n.lni-paperclip::before {\n  content: \"\\eb48\";\n}\n\n.lni-patreon::before {\n  content: \"\\eb49\";\n}\n\n.lni-pause::before {\n  content: \"\\eb4a\";\n}\n\n.lni-paypal-original::before {\n  content: \"\\eb4b\";\n}\n\n.lni-paypal::before {\n  content: \"\\eb4c\";\n}\n\n.lni-pencil-alt::before {\n  content: \"\\eb4d\";\n}\n\n.lni-pencil::before {\n  content: \"\\eb4e\";\n}\n\n.lni-phone-set::before {\n  content: \"\\eb4f\";\n}\n\n.lni-phone::before {\n  content: \"\\eb50\";\n}\n\n.lni-php::before {\n  content: \"\\eb51\";\n}\n\n.lni-pie-chart::before {\n  content: \"\\eb52\";\n}\n\n.lni-pilcrow::before {\n  content: \"\\eb53\";\n}\n\n.lni-pin::before {\n  content: \"\\eb54\";\n}\n\n.lni-pinterest::before {\n  content: \"\\eb55\";\n}\n\n.lni-pizza::before {\n  content: \"\\eb56\";\n}\n\n.lni-plane::before {\n  content: \"\\eb57\";\n}\n\n.lni-play-store::before {\n  content: \"\\eb58\";\n}\n\n.lni-play::before {\n  content: \"\\eb59\";\n}\n\n.lni-playstation::before {\n  content: \"\\eb5a\";\n}\n\n.lni-plug::before {\n  content: \"\\eb5b\";\n}\n\n.lni-plus::before {\n  content: \"\\eb5c\";\n}\n\n.lni-pointer-down::before {\n  content: \"\\eb5d\";\n}\n\n.lni-pointer-left::before {\n  content: \"\\eb5e\";\n}\n\n.lni-pointer-right::before {\n  content: \"\\eb5f\";\n}\n\n.lni-pointer-top::before {\n  content: \"\\eb60\";\n}\n\n.lni-pointer::before {\n  content: \"\\eb61\";\n}\n\n.lni-popup::before {\n  content: \"\\eb62\";\n}\n\n.lni-postcard::before {\n  content: \"\\eb63\";\n}\n\n.lni-pound::before {\n  content: \"\\eb64\";\n}\n\n.lni-power-switch::before {\n  content: \"\\eb65\";\n}\n\n.lni-printer::before {\n  content: \"\\eb66\";\n}\n\n.lni-producthunt::before {\n  content: \"\\eb67\";\n}\n\n.lni-protection::before {\n  content: \"\\eb68\";\n}\n\n.lni-pulse::before {\n  content: \"\\eb69\";\n}\n\n.lni-pyramids::before {\n  content: \"\\eb6a\";\n}\n\n.lni-python::before {\n  content: \"\\eb6b\";\n}\n\n.lni-question-circle::before {\n  content: \"\\eb6c\";\n}\n\n.lni-quora::before {\n  content: \"\\eb6d\";\n}\n\n.lni-quotation::before {\n  content: \"\\eb6e\";\n}\n\n.lni-radio-button::before {\n  content: \"\\eb6f\";\n}\n\n.lni-rain::before {\n  content: \"\\eb70\";\n}\n\n.lni-react::before {\n  content: \"\\eb73\";\n}\n\n.lni-reddit::before {\n  content: \"\\eb71\";\n}\n\n.lni-reload::before {\n  content: \"\\eb72\";\n}\n\n.lni-remove-file::before {\n  content: \"\\eb74\";\n}\n\n.lni-reply::before {\n  content: \"\\eb75\";\n}\n\n.lni-restaurant::before {\n  content: \"\\eb76\";\n}\n\n.lni-revenue::before {\n  content: \"\\eb77\";\n}\n\n.lni-road::before {\n  content: \"\\eb78\";\n}\n\n.lni-rocket::before {\n  content: \"\\eb79\";\n}\n\n.lni-rss-feed::before {\n  content: \"\\eb7a\";\n}\n\n.lni-ruler-alt::before {\n  content: \"\\eb7b\";\n}\n\n.lni-ruler-pencil::before {\n  content: \"\\eb7c\";\n}\n\n.lni-ruler::before {\n  content: \"\\eb7d\";\n}\n\n.lni-rupee::before {\n  content: \"\\eb7e\";\n}\n\n.lni-sad::before {\n  content: \"\\eb7f\";\n}\n\n.lni-save::before {\n  content: \"\\eb80\";\n}\n\n.lni-school-bench-alt::before {\n  content: \"\\eb81\";\n}\n\n.lni-school-bench::before {\n  content: \"\\eb82\";\n}\n\n.lni-scooter::before {\n  content: \"\\eb83\";\n}\n\n.lni-scroll-down::before {\n  content: \"\\eb84\";\n}\n\n.lni-search-alt::before {\n  content: \"\\eb85\";\n}\n\n.lni-search::before {\n  content: \"\\eb86\";\n}\n\n.lni-select::before {\n  content: \"\\eb87\";\n}\n\n.lni-seo::before {\n  content: \"\\eb88\";\n}\n\n.lni-service::before {\n  content: \"\\eb89\";\n}\n\n.lni-share-alt-1::before {\n  content: \"\\eb8a\";\n}\n\n.lni-share-alt::before {\n  content: \"\\eb8b\";\n}\n\n.lni-share::before {\n  content: \"\\eb8c\";\n}\n\n.lni-shield::before {\n  content: \"\\eb8d\";\n}\n\n.lni-shift-left::before {\n  content: \"\\eb8e\";\n}\n\n.lni-shift-right::before {\n  content: \"\\eb8f\";\n}\n\n.lni-ship::before {\n  content: \"\\eb90\";\n}\n\n.lni-shopify::before {\n  content: \"\\eb91\";\n}\n\n.lni-shopping-basket::before {\n  content: \"\\eb92\";\n}\n\n.lni-shortcode::before {\n  content: \"\\eb93\";\n}\n\n.lni-shovel::before {\n  content: \"\\eb94\";\n}\n\n.lni-shuffle::before {\n  content: \"\\eb95\";\n}\n\n.lni-signal::before {\n  content: \"\\eb96\";\n}\n\n.lni-sketch::before {\n  content: \"\\eb97\";\n}\n\n.lni-skipping-rope::before {\n  content: \"\\eb98\";\n}\n\n.lni-skype::before {\n  content: \"\\eb99\";\n}\n\n.lni-slack-line::before {\n  content: \"\\eb9a\";\n}\n\n.lni-slack::before {\n  content: \"\\eb9b\";\n}\n\n.lni-slice::before {\n  content: \"\\eb9c\";\n}\n\n.lni-slideshare::before {\n  content: \"\\eb9d\";\n}\n\n.lni-slim::before {\n  content: \"\\eb9e\";\n}\n\n.lni-smile::before {\n  content: \"\\eb9f\";\n}\n\n.lni-snapchat::before {\n  content: \"\\eba0\";\n}\n\n.lni-sort-alpha-asc::before {\n  content: \"\\eba1\";\n}\n\n.lni-sort-amount-asc::before {\n  content: \"\\eba2\";\n}\n\n.lni-sort-amount-dsc::before {\n  content: \"\\eba3\";\n}\n\n.lni-soundcloud-original::before {\n  content: \"\\eba4\";\n}\n\n.lni-soundcloud::before {\n  content: \"\\eba5\";\n}\n\n.lni-speechless::before {\n  content: \"\\eba6\";\n}\n\n.lni-spellcheck::before {\n  content: \"\\eba7\";\n}\n\n.lni-spinner-arrow::before {\n  content: \"\\eba8\";\n}\n\n.lni-spinner-solid::before {\n  content: \"\\eba9\";\n}\n\n.lni-spinner::before {\n  content: \"\\ebaa\";\n}\n\n.lni-spotify-original::before {\n  content: \"\\ebab\";\n}\n\n.lni-spotify::before {\n  content: \"\\ebac\";\n}\n\n.lni-spray::before {\n  content: \"\\ebad\";\n}\n\n.lni-sprout::before {\n  content: \"\\ebae\";\n}\n\n.lni-squarespace::before {\n  content: \"\\ebaf\";\n}\n\n.lni-stackoverflow::before {\n  content: \"\\ebb0\";\n}\n\n.lni-stamp::before {\n  content: \"\\ebb1\";\n}\n\n.lni-star-empty::before {\n  content: \"\\ebb2\";\n}\n\n.lni-star-filled::before {\n  content: \"\\ebb3\";\n}\n\n.lni-star-half::before {\n  content: \"\\ebb4\";\n}\n\n.lni-star::before {\n  content: \"\\ebb5\";\n}\n\n.lni-stats-down::before {\n  content: \"\\ebb6\";\n}\n\n.lni-stats-up::before {\n  content: \"\\ebb7\";\n}\n\n.lni-steam::before {\n  content: \"\\ebb8\";\n}\n\n.lni-sthethoscope::before {\n  content: \"\\ebb9\";\n}\n\n.lni-stop::before {\n  content: \"\\ebba\";\n}\n\n.lni-strikethrough::before {\n  content: \"\\ebbb\";\n}\n\n.lni-stripe::before {\n  content: \"\\ebbc\";\n}\n\n.lni-stumbleupon::before {\n  content: \"\\ebbd\";\n}\n\n.lni-sun::before {\n  content: \"\\ebbe\";\n}\n\n.lni-support::before {\n  content: \"\\ebbf\";\n}\n\n.lni-surf-board::before {\n  content: \"\\ebc0\";\n}\n\n.lni-suspect::before {\n  content: \"\\ebc1\";\n}\n\n.lni-swift::before {\n  content: \"\\ebc2\";\n}\n\n.lni-syringe::before {\n  content: \"\\ebc3\";\n}\n\n.lni-tab::before {\n  content: \"\\ebc4\";\n}\n\n.lni-tag::before {\n  content: \"\\ebc5\";\n}\n\n.lni-target-customer::before {\n  content: \"\\ebc6\";\n}\n\n.lni-target-revenue::before {\n  content: \"\\ebc7\";\n}\n\n.lni-target::before {\n  content: \"\\ebc8\";\n}\n\n.lni-taxi::before {\n  content: \"\\ebc9\";\n}\n\n.lni-teabag::before {\n  content: \"\\ebca\";\n}\n\n.lni-telegram-original::before {\n  content: \"\\ebcb\";\n}\n\n.lni-telegram::before {\n  content: \"\\ebcc\";\n}\n\n.lni-text-align-center::before {\n  content: \"\\ebcd\";\n}\n\n.lni-text-align-justify::before {\n  content: \"\\ebce\";\n}\n\n.lni-text-align-left::before {\n  content: \"\\ebcf\";\n}\n\n.lni-text-align-right::before {\n  content: \"\\ebd0\";\n}\n\n.lni-text-format-remove::before {\n  content: \"\\ebd4\";\n}\n\n.lni-text-format::before {\n  content: \"\\ebd1\";\n}\n\n.lni-thought::before {\n  content: \"\\ebd2\";\n}\n\n.lni-thumbs-down::before {\n  content: \"\\ebd3\";\n}\n\n.lni-thumbs-up::before {\n  content: \"\\ebd5\";\n}\n\n.lni-thunder-alt::before {\n  content: \"\\ebd6\";\n}\n\n.lni-thunder::before {\n  content: \"\\ebd7\";\n}\n\n.lni-ticket-alt::before {\n  content: \"\\ebd8\";\n}\n\n.lni-ticket::before {\n  content: \"\\ebd9\";\n}\n\n.lni-tiktok::before {\n  content: \"\\ebda\";\n}\n\n.lni-timer::before {\n  content: \"\\ebdb\";\n}\n\n.lni-tounge::before {\n  content: \"\\ebdc\";\n}\n\n.lni-train-alt::before {\n  content: \"\\ebdd\";\n}\n\n.lni-train::before {\n  content: \"\\ebde\";\n}\n\n.lni-trash-can::before {\n  content: \"\\ebdf\";\n}\n\n.lni-travel::before {\n  content: \"\\ebe0\";\n}\n\n.lni-tree::before {\n  content: \"\\ebe1\";\n}\n\n.lni-trees::before {\n  content: \"\\ebe2\";\n}\n\n.lni-trello::before {\n  content: \"\\ebe3\";\n}\n\n.lni-trowel::before {\n  content: \"\\ebe4\";\n}\n\n.lni-tshirt::before {\n  content: \"\\ebe5\";\n}\n\n.lni-tumblr::before {\n  content: \"\\ebe6\";\n}\n\n.lni-twitch::before {\n  content: \"\\ebe7\";\n}\n\n.lni-twitter-filled::before {\n  content: \"\\ebe8\";\n}\n\n.lni-twitter-original::before {\n  content: \"\\ebe9\";\n}\n\n.lni-twitter::before {\n  content: \"\\ebea\";\n}\n\n.lni-ubuntu::before {\n  content: \"\\ebeb\";\n}\n\n.lni-underline::before {\n  content: \"\\ebec\";\n}\n\n.lni-unlink::before {\n  content: \"\\ebed\";\n}\n\n.lni-unlock::before {\n  content: \"\\ebee\";\n}\n\n.lni-unsplash::before {\n  content: \"\\ebef\";\n}\n\n.lni-upload::before {\n  content: \"\\ebf0\";\n}\n\n.lni-user::before {\n  content: \"\\ebf1\";\n}\n\n.lni-users::before {\n  content: \"\\ebf6\";\n}\n\n.lni-ux::before {\n  content: \"\\ebf2\";\n}\n\n.lni-vector::before {\n  content: \"\\ebf3\";\n}\n\n.lni-video::before {\n  content: \"\\ebf4\";\n}\n\n.lni-vimeo::before {\n  content: \"\\ebf5\";\n}\n\n.lni-visa::before {\n  content: \"\\ebf7\";\n}\n\n.lni-vk::before {\n  content: \"\\ebf8\";\n}\n\n.lni-volume-high::before {\n  content: \"\\ebf9\";\n}\n\n.lni-volume-low::before {\n  content: \"\\ebfa\";\n}\n\n.lni-volume-medium::before {\n  content: \"\\ebfb\";\n}\n\n.lni-volume-mute::before {\n  content: \"\\ebfc\";\n}\n\n.lni-volume::before {\n  content: \"\\ebfd\";\n}\n\n.lni-wallet::before {\n  content: \"\\ebfe\";\n}\n\n.lni-warning::before {\n  content: \"\\ebff\";\n}\n\n.lni-website-alt::before {\n  content: \"\\ec00\";\n}\n\n.lni-website::before {\n  content: \"\\ec01\";\n}\n\n.lni-wechat::before {\n  content: \"\\ec02\";\n}\n\n.lni-weight::before {\n  content: \"\\ec03\";\n}\n\n.lni-whatsapp::before {\n  content: \"\\ec04\";\n}\n\n.lni-wheelbarrow::before {\n  content: \"\\ec05\";\n}\n\n.lni-wheelchair::before {\n  content: \"\\ec06\";\n}\n\n.lni-windows::before {\n  content: \"\\ec07\";\n}\n\n.lni-wordpress-filled::before {\n  content: \"\\ec08\";\n}\n\n.lni-wordpress::before {\n  content: \"\\ec09\";\n}\n\n.lni-world-alt::before {\n  content: \"\\ec0a\";\n}\n\n.lni-world::before {\n  content: \"\\ec0c\";\n}\n\n.lni-write::before {\n  content: \"\\ec0b\";\n}\n\n.lni-xbox::before {\n  content: \"\\ec0d\";\n}\n\n.lni-yahoo::before {\n  content: \"\\ec0e\";\n}\n\n.lni-ycombinator::before {\n  content: \"\\ec0f\";\n}\n\n.lni-yen::before {\n  content: \"\\ec10\";\n}\n\n.lni-youtube::before {\n  content: \"\\ec13\";\n}\n\n.lni-zip::before {\n  content: \"\\ec11\";\n}\n\n.lni-zoom-in::before {\n  content: \"\\ec12\";\n}\n\n.lni-zoom-out::before {\n  content: \"\\ec14\";\n}\n"
  },
  {
    "path": "assets/css/syntax.css",
    "content": ".highlight table td { padding: 5px; }\n.highlight table pre { margin: 0; }\n.highlight .gh {\n  color: #999999;\n}\n.highlight .sr {\n  color: #f6aa11;\n}\n.highlight .go {\n  color: #888888;\n}\n.highlight .gp {\n  color: #555555;\n}\n.highlight .gs {\n}\n.highlight .gu {\n  color: #aaaaaa;\n}\n.highlight .nb {\n  color: #f6aa11;\n}\n.highlight .cm {\n  color: #75715e;\n}\n.highlight .cp {\n  color: #75715e;\n}\n.highlight .c1 {\n  color: #75715e;\n}\n.highlight .cs {\n  color: #75715e;\n}\n.highlight .c, .highlight .ch, .highlight .cd, .highlight .cpf {\n  color: #75715e;\n}\n.highlight .err {\n  color: #960050;\n}\n.highlight .gr {\n  color: #960050;\n}\n.highlight .gt {\n  color: #960050;\n}\n.highlight .gd {\n  color: #49483e;\n}\n.highlight .gi {\n  color: #49483e;\n}\n.highlight .ge {\n  color: #49483e;\n}\n.highlight .kc {\n  color: #66d9ef;\n}\n.highlight .kd {\n  color: #66d9ef;\n}\n.highlight .kr {\n  color: #66d9ef;\n}\n.highlight .no {\n  color: #66d9ef;\n}\n.highlight .kt {\n  color: #66d9ef;\n}\n.highlight .mf {\n  color: #ae81ff;\n}\n.highlight .mh {\n  color: #ae81ff;\n}\n.highlight .il {\n  color: #ae81ff;\n}\n.highlight .mi {\n  color: #ae81ff;\n}\n.highlight .mo {\n  color: #ae81ff;\n}\n.highlight .m, .highlight .mb, .highlight .mx {\n  color: #ae81ff;\n}\n.highlight .sc {\n  color: #ae81ff;\n}\n.highlight .se {\n  color: #ae81ff;\n}\n.highlight .ss {\n  color: #ae81ff;\n}\n.highlight .sd {\n  color: #e6db74;\n}\n.highlight .s2 {\n  color: #e6db74;\n}\n.highlight .sb {\n  color: #e6db74;\n}\n.highlight .sh {\n  color: #e6db74;\n}\n.highlight .si {\n  color: #e6db74;\n}\n.highlight .sx {\n  color: #e6db74;\n}\n.highlight .s1 {\n  color: #e6db74;\n}\n.highlight .s, .highlight .sa, .highlight .dl {\n  color: #e6db74;\n}\n.highlight .na {\n  color: #a6e22e;\n}\n.highlight .nc {\n  color: #a6e22e;\n}\n.highlight .nd {\n  color: #a6e22e;\n}\n.highlight .ne {\n  color: #a6e22e;\n}\n.highlight .nf, .highlight .fm {\n  color: #a6e22e;\n}\n.highlight .vc {\n  color: #ffffff;\n  background-color: #272822;\n}\n.highlight .nn {\n  color: #ffffff;\n  background-color: #272822;\n}\n.highlight .nl {\n  color: #ffffff;\n  background-color: #272822;\n}\n.highlight .ni {\n  color: #ffffff;\n  background-color: #272822;\n}\n.highlight .bp {\n  color: #ffffff;\n  background-color: #272822;\n}\n.highlight .vg {\n  color: #ffffff;\n  background-color: #272822;\n}\n.highlight .vi {\n  color: #ffffff;\n  background-color: #272822;\n}\n.highlight .nv, .highlight .vm {\n  color: #ffffff;\n  background-color: #272822;\n}\n.highlight .w {\n  color: #ffffff;\n  background-color: #272822;\n}\n.highlight {\n  color: #ffffff;\n  background-color: #272822;\n}\n.highlight .n, .highlight .py, .highlight .nx {\n  color: #ffffff;\n  background-color: #272822;\n}\n.highlight .ow {\n  color: #f92672;\n}\n.highlight .nt {\n  color: #f92672;\n}\n.highlight .k, .highlight .kv {\n  color: #f92672;\n}\n.highlight .kn {\n  color: #f92672;\n}\n.highlight .kp {\n  color: #f92672;\n}\n.highlight .o {\n  color: #f92672;\n}\n"
  },
  {
    "path": "assets/css/ud-styles.css",
    "content": "/* =======\n\n\tTemplate Name: Play Bootstrap\n\tAuthor: UIdeck\n\tAuthor URI: https://uideck.com/\n\tSupport: https://github.com/uideck/\n\tVersion: 1.0\n\n======== */\n/*===========================\n  COMMON css \n===========================*/\n@import url('https://fonts.googleapis.com/css2?family=Inter:wght@200;300;400;500;600;700;800;900&display=swap');\n:root {\n  --font: 'Inter', sans-serif;\n  --body-color: #637381;\n  --heading-color: #212b36;\n  --primary-color: #3056d3;\n  --white: #ffffff;\n}\n\nbody {\n  font-family: var(--font);\n  font-weight: normal;\n  font-style: normal;\n  color: var(--body-color);\n  overflow-x: hidden;\n}\n\n* {\n  margin: 0;\n  padding: 0;\n  -webkit-box-sizing: border-box;\n  box-sizing: border-box;\n}\n\nimg {\n  max-width: 100%;\n}\n\na,\nbutton,\ninput,\ntextarea {\n  -webkit-transition: all 0.3s ease-out 0s;\n  transition: all 0.3s ease-out 0s;\n}\n\na,\na:focus,\ninput:focus,\ntextarea:focus,\nbutton:focus,\n.navbar-toggler:focus {\n  text-decoration: none;\n  outline: none;\n  -webkit-box-shadow: none;\n  box-shadow: none;\n}\n\na:focus,\na:hover {\n  text-decoration: none;\n}\n\ni,\nspan,\na {\n  display: inline-block;\n}\n\naudio,\ncanvas,\niframe,\nimg,\nsvg,\nvideo {\n  vertical-align: middle;\n}\n\nh1,\nh2,\nh3,\nh4,\nh5,\nh6 {\n  font-weight: 700;\n  color: var(--heading-color);\n  margin: 0px;\n}\n\nh1 {\n  font-size: 48px;\n}\n\nh2 {\n  font-size: 36px;\n}\n\nh3 {\n  font-size: 28px;\n}\n\nh4 {\n  font-size: 22px;\n}\n\nh5 {\n  font-size: 18px;\n}\n\nh6 {\n  font-size: 16px;\n}\n\nul,\nol {\n  margin: 0px;\n  padding: 0px;\n  list-style-type: none;\n}\n\np {\n  font-size: 16px;\n  font-weight: 400;\n  line-height: 26px;\n  color: var(--body-color);\n  margin: 0px;\n}\n\n.bg_cover {\n  background-position: center center;\n  background-size: cover;\n  background-repeat: no-repeat;\n  width: 100%;\n  height: 100%;\n}\n\n/*===== All Button Style =====*/\n.ud-main-btn {\n  display: inline-block;\n  text-align: center;\n  white-space: nowrap;\n  vertical-align: middle;\n  font-weight: 500;\n  font-size: 16px;\n  border-radius: 5px;\n  padding: 15px 25px;\n  border: 1px solid transparent;\n  color: var(--white);\n  cursor: pointer;\n  z-index: 5;\n  -webkit-transition: all 0.4s ease-out 0s;\n  transition: all 0.4s ease-out 0s;\n  background: var(--primary-color);\n}\n\n.ud-main-btn:hover {\n  color: var(--white);\n  background: var(--heading-color);\n}\n\n@media (max-width: 767px) {\n  .container {\n    padding-left: 40px;\n    padding-right: 40px;\n  }\n}\n\n@media only screen and (min-width: 576px) and (max-width: 767px) {\n  .container {\n    padding-left: 20px;\n    padding-right: 20px;\n  }\n}\n\n.back-to-top {\n  width: 40px;\n  height: 40px;\n  line-height: 40px;\n  background: var(--primary-color);\n  -webkit-box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.2);\n  box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.2);\n  text-align: center;\n  -webkit-box-pack: center;\n  -ms-flex-pack: center;\n  justify-content: center;\n  -webkit-box-align: center;\n  -ms-flex-align: center;\n  align-items: center;\n  border-radius: 5px;\n  position: fixed;\n  right: 30px;\n  bottom: 30px;\n  z-index: 99;\n  color: var(--white);\n}\n\n.back-to-top:hover {\n  color: var(--white);\n  background: var(--heading-color);\n}\n\n/* ===== Header CSS ===== */\n.ud-header {\n  position: absolute;\n  top: 0;\n  left: 0;\n  width: 100%;\n  z-index: 99;\n  -webkit-transition: all 0.3s ease-out 0s;\n  transition: all 0.3s ease-out 0s;\n}\n\n.sticky {\n  position: fixed;\n  z-index: 99;\n  background-color: rgba(255, 255, 255, 0.8);\n  -webkit-backdrop-filter: blur(5px);\n  backdrop-filter: blur(5px);\n  -webkit-box-shadow: inset 0 -1px 0 0 rgba(0, 0, 0, 0.1);\n  box-shadow: inset 0 -1px 0 0 rgba(0, 0, 0, 0.1);\n  -webkit-transition: all 0.3s ease-out 0s;\n  transition: all 0.3s ease-out 0s;\n}\n\n.sticky .navbar {\n  padding: 0;\n}\n\n.navbar {\n  padding: 0px 0;\n  border-radius: 5px;\n  position: relative;\n  -webkit-transition: all 0.3s ease-out 0s;\n  transition: all 0.3s ease-out 0s;\n}\n\n.navbar-brand {\n  padding: 0;\n}\n\n@media only screen and (min-width: 768px) and (max-width: 991px),\n  (max-width: 767px) {\n  .navbar-brand {\n    padding: 5px 0px;\n  }\n}\n\n.navbar-brand img {\n  max-width: 160px;\n}\n\n.navbar-toggler {\n  padding: 0;\n}\n\n.navbar-toggler .toggler-icon {\n  width: 30px;\n  height: 2px;\n  background-color: var(--white);\n  display: block;\n  margin: 5px 0;\n  position: relative;\n  -webkit-transition: all 0.3s ease-out 0s;\n  transition: all 0.3s ease-out 0s;\n}\n\n.navbar-toggler.active .toggler-icon:nth-of-type(1) {\n  -webkit-transform: rotate(45deg);\n  transform: rotate(45deg);\n  top: 7px;\n}\n\n.navbar-toggler.active .toggler-icon:nth-of-type(2) {\n  opacity: 0;\n}\n\n.navbar-toggler.active .toggler-icon:nth-of-type(3) {\n  -webkit-transform: rotate(135deg);\n  transform: rotate(135deg);\n  top: -7px;\n}\n\n@media only screen and (min-width: 768px) and (max-width: 991px),\n  (max-width: 767px) {\n  .navbar-collapse {\n    position: absolute;\n    top: 100%;\n    right: 0;\n    max-width: 300px;\n    width: 100%;\n    background-color: var(--white);\n    z-index: 9;\n    -webkit-box-shadow: 0px 15px 20px 0px rgba(0, 0, 0, 0.1);\n    box-shadow: 0px 15px 20px 0px rgba(0, 0, 0, 0.1);\n    padding: 0px;\n    display: none;\n    border-radius: 5px;\n  }\n  .navbar-collapse.show {\n    display: block;\n  }\n}\n\n@media only screen and (min-width: 768px) and (max-width: 991px),\n  (max-width: 767px) {\n  .navbar-nav {\n    padding: 20px 30px;\n  }\n}\n\n.navbar-nav .nav-item {\n  position: relative;\n  padding: 0px 20px;\n}\n\n@media only screen and (min-width: 992px) and (max-width: 1199px) {\n  .navbar-nav .nav-item {\n    padding: 0px 12px;\n  }\n}\n\n@media only screen and (min-width: 768px) and (max-width: 991px),\n  (max-width: 767px) {\n  .navbar-nav .nav-item {\n    padding: 0px;\n  }\n}\n\n.navbar-nav .nav-item > a {\n  font-size: 16px;\n  font-weight: 400;\n  color: var(--white);\n  -webkit-transition: all 0.3s ease-out 0s;\n  transition: all 0.3s ease-out 0s;\n  padding: 25px 8px;\n  position: relative;\n}\n\n@media only screen and (min-width: 768px) and (max-width: 991px),\n  (max-width: 767px) {\n  .navbar-nav .nav-item > a {\n    display: block;\n    padding: 8px 0;\n    color: var(--heading-color);\n  }\n}\n\n.navbar-nav .nav-item > a:hover,\n.navbar-nav .nav-item > a.active {\n  color: var(--white);\n  opacity: 0.5;\n}\n\n@media only screen and (min-width: 768px) and (max-width: 991px),\n  (max-width: 767px) {\n  .navbar-nav .nav-item > a:hover,\n  .navbar-nav .nav-item > a.active {\n    color: var(--primary-color);\n    opacity: 1;\n  }\n}\n\n.navbar-nav .nav-item .ud-submenu {\n  position: absolute;\n  width: 250px;\n  background: var(--white);\n  top: 110%;\n  padding: 20px 30px;\n  -webkit-box-shadow: 0 15px 44px rgba(140, 140, 140, 0.18);\n  box-shadow: 0 15px 44px rgba(140, 140, 140, 0.18);\n  border-radius: 5px;\n  opacity: 0;\n  visibility: hidden;\n  -webkit-transition: all 0.3s ease-out 0s;\n  transition: all 0.3s ease-out 0s;\n}\n\n@media only screen and (min-width: 768px) and (max-width: 991px),\n  (max-width: 767px) {\n  .navbar-nav .nav-item .ud-submenu {\n    position: static;\n    -webkit-box-shadow: none;\n    box-shadow: none;\n    width: 100%;\n    padding: 0px;\n    opacity: 1;\n    visibility: visible;\n    display: none;\n  }\n}\n\n.navbar-nav .nav-item .ud-submenu.show {\n  display: block;\n}\n\n.navbar-nav .nav-item .ud-submenu .ud-submenu-link {\n  padding: 7px 0;\n  color: var(--heading-color);\n  font-size: 14px;\n}\n\n.navbar-nav .nav-item .ud-submenu .ud-submenu-link:hover {\n  color: var(--primary-color);\n}\n\n.navbar-nav .nav-item:hover > a {\n  color: var(--white);\n  opacity: 0.5;\n}\n\n@media only screen and (min-width: 768px) and (max-width: 991px),\n  (max-width: 767px) {\n  .navbar-nav .nav-item:hover > a {\n    color: var(--primary-color);\n    opacity: 1;\n  }\n}\n\n.navbar-nav .nav-item:hover > .ud-submenu {\n  opacity: 1;\n  visibility: visible;\n  top: 100%;\n}\n\n.navbar-nav .nav-item.nav-item-has-children > a {\n  position: relative;\n}\n\n.navbar-nav .nav-item.nav-item-has-children > a::after {\n  content: '';\n  -webkit-box-sizing: border-box;\n  box-sizing: border-box;\n  position: absolute;\n  width: 10px;\n  height: 10px;\n  border-bottom: 2px solid;\n  border-right: 2px solid;\n  -webkit-transform: rotate(45deg) translateY(-50%);\n  transform: rotate(45deg) translateY(-50%);\n  right: -15px;\n  top: 50%;\n  margin-top: -2px;\n}\n\n@media only screen and (min-width: 768px) and (max-width: 991px),\n  (max-width: 767px) {\n  .navbar-nav .nav-item.nav-item-has-children > a::after {\n    right: 5px;\n  }\n}\n\n@media only screen and (min-width: 768px) and (max-width: 991px),\n  (max-width: 767px) {\n  .navbar-btn {\n    position: absolute;\n    top: 50%;\n    right: 50px;\n    -webkit-transform: translateY(-50%);\n    transform: translateY(-50%);\n  }\n}\n\n.navbar-btn .ud-main-btn {\n  padding: 8px 16px;\n  background: transparent;\n}\n\n.navbar-btn .ud-login-btn:hover {\n  opacity: 0.5;\n}\n\n.navbar-btn .ud-white-btn {\n  background: rgba(255, 255, 255, 0.2);\n}\n\n.navbar-btn .ud-white-btn:hover {\n  background: white;\n  color: var(--heading-color);\n}\n\n.sticky .navbar-toggler .toggler-icon {\n  background-color: var(--heading-color);\n}\n\n.sticky .navbar-nav .nav-item:hover > a {\n  color: var(--primary-color);\n  opacity: 1;\n}\n\n.sticky .navbar-nav .nav-item a {\n  color: var(--heading-color);\n}\n\n.sticky .navbar-nav .nav-item a.active,\n.sticky .navbar-nav .nav-item a:hover {\n  color: var(--primary-color);\n  opacity: 1;\n}\n\n.sticky .navbar-btn .ud-main-btn.ud-login-btn {\n  color: var(--heading-color);\n}\n\n.sticky .navbar-btn .ud-main-btn.ud-login-btn:hover {\n  color: var(--primary-color);\n  opacity: 1;\n}\n\n.sticky .navbar-btn .ud-white-btn {\n  background: var(--primary-color);\n  color: var(--white);\n}\n\n.sticky .navbar-btn .ud-white-btn:hover {\n  background: var(--heading-color);\n}\n\n/* ===== Hero CSS ===== */\n.ud-hero {\n  background: var(--primary-color);\n  padding-top: 180px;\n}\n\n@media only screen and (min-width: 768px) and (max-width: 991px) {\n  .ud-hero {\n    padding-top: 160px;\n  }\n}\n\n@media (max-width: 767px) {\n  .ud-hero {\n    padding-top: 130px;\n  }\n}\n\n.ud-hero-content {\n  max-width: 780px;\n  margin: auto;\n  margin-bottom: 30px;\n}\n\n.ud-hero-content .ud-hero-title {\n  color: var(--white);\n  font-weight: 700;\n  font-size: 45px;\n  line-height: 60px;\n  text-align: center;\n  margin-bottom: 30px;\n}\n\n@media only screen and (min-width: 768px) and (max-width: 991px) {\n  .ud-hero-content .ud-hero-title {\n    font-size: 38px;\n    line-height: 50px;\n  }\n}\n\n@media (max-width: 767px) {\n  .ud-hero-content .ud-hero-title {\n    font-size: 26px;\n    line-height: 38px;\n  }\n}\n\n.ud-hero-content .ud-hero-desc {\n  font-weight: normal;\n  font-size: 20px;\n  line-height: 35px;\n  text-align: center;\n  color: var(--white);\n  opacity: 0.8;\n  max-width: 600px;\n  margin: auto;\n  margin-bottom: 30px;\n}\n\n@media (max-width: 767px) {\n  .ud-hero-content .ud-hero-desc {\n    font-size: 16px;\n    line-height: 30px;\n  }\n}\n\n.ud-hero-buttons {\n  display: -webkit-box;\n  display: -ms-flexbox;\n  display: flex;\n  -webkit-box-align: center;\n  -ms-flex-align: center;\n  align-items: center;\n  -webkit-box-pack: center;\n  -ms-flex-pack: center;\n  justify-content: center;\n}\n\n.ud-hero-buttons .ud-main-btn {\n  margin: 8px;\n}\n\n@media (max-width: 767px) {\n  .ud-hero-buttons .ud-main-btn {\n    margin: 5px;\n  }\n}\n\n@media (max-width: 767px) {\n  .ud-hero-buttons .ud-main-btn {\n    padding: 12px 16px;\n  }\n}\n\n.ud-hero-buttons .ud-white-btn {\n  background: var(--white);\n  color: var(--heading-color);\n}\n\n.ud-hero-buttons .ud-white-btn:hover {\n  -webkit-box-shadow: 0px 0px 25px rgba(0, 0, 0, 0.2);\n  box-shadow: 0px 0px 25px rgba(0, 0, 0, 0.2);\n  background: #fefefe;\n  color: var(--primary-color);\n}\n\n.ud-hero-buttons .ud-link-btn:hover {\n  color: var(--white);\n  background: transparent;\n  opacity: 0.5;\n}\n\n.ud-hero-brands-wrapper {\n  text-align: center;\n  margin-bottom: 40px;\n}\n\n.ud-hero-brands-wrapper img {\n  -webkit-transition: all 0.3s;\n  transition: all 0.3s;\n  opacity: 0.5;\n  max-width: 250px;\n}\n\n.ud-hero-brands-wrapper img:hover {\n  opacity: 1;\n}\n\n.ud-hero-image {\n  max-width: 845px;\n  margin: auto;\n  text-align: center;\n  position: relative;\n  z-index: 1;\n}\n\n.ud-hero-image img {\n  max-width: 100%;\n  text-align: center;\n}\n\n.ud-hero-image .shape {\n  position: absolute;\n  z-index: -1;\n}\n\n.ud-hero-image .shape.shape-1 {\n  bottom: 0;\n  left: -30px;\n}\n\n.ud-hero-image .shape.shape-2 {\n  top: -20px;\n  right: -20px;\n}\n\n/* ===== Features CSS ===== */\n.ud-features {\n  padding-top: 120px;\n  padding-bottom: 90px;\n}\n\n@media (max-width: 767px) {\n  .ud-features {\n    padding-top: 80px;\n    padding-bottom: 40px;\n  }\n}\n\n.ud-section-title {\n  max-width: 620px;\n  margin-bottom: 70px;\n}\n\n.ud-section-title span {\n  font-weight: 600;\n  font-size: 18px;\n  color: var(--primary-color);\n  margin-bottom: 10px;\n}\n\n.ud-section-title h2 {\n  font-weight: 700;\n  font-size: 42px;\n  line-height: 55px;\n  text-transform: capitalize;\n  color: var(--heading-color);\n  margin-bottom: 20px;\n}\n\n.ud-section-title p {\n  font-size: 20px;\n  line-height: 30px;\n}\n\n@media (max-width: 767px) {\n  .ud-section-title p {\n    font-size: 16px;\n    line-height: 26px;\n  }\n}\n\n.ud-single-feature {\n  margin-bottom: 40px;\n}\n\n.ud-single-feature:hover .ud-feature-icon::before {\n  -webkit-transform: rotate(45deg);\n  transform: rotate(45deg);\n}\n\n.ud-single-feature .ud-feature-icon {\n  width: 70px;\n  height: 70px;\n  display: -webkit-box;\n  display: -ms-flexbox;\n  display: flex;\n  -webkit-box-align: center;\n  -ms-flex-align: center;\n  align-items: center;\n  -webkit-box-pack: center;\n  -ms-flex-pack: center;\n  justify-content: center;\n  border-radius: 14px;\n  background: var(--primary-color);\n  font-size: 32px;\n  color: var(--white);\n  position: relative;\n  z-index: 1;\n  text-align: center;\n  margin-bottom: 40px;\n}\n\n.ud-single-feature .ud-feature-icon::before {\n  content: '';\n  position: absolute;\n  width: 100%;\n  height: 100%;\n  top: 0;\n  left: 0;\n  border-radius: 14px;\n  background: var(--primary-color);\n  opacity: 0.2;\n  z-index: -1;\n  -webkit-transform: rotate(23deg);\n  transform: rotate(23deg);\n  -webkit-transition: all 0.3s ease-out 0s;\n  transition: all 0.3s ease-out 0s;\n}\n\n.ud-single-feature .ud-feature-title {\n  font-weight: 700;\n  font-size: 20px;\n  line-height: 28px;\n  margin-bottom: 12px;\n}\n\n@media only screen and (min-width: 992px) and (max-width: 1199px) {\n  .ud-single-feature .ud-feature-title {\n    font-size: 18px;\n    line-height: 26px;\n  }\n}\n\n.ud-single-feature .ud-feature-desc {\n  font-size: 16px;\n  line-height: 24px;\n  margin-bottom: 40px;\n}\n\n.ud-single-feature .ud-feature-link {\n  font-weight: 500;\n  color: var(--body-color);\n}\n\n.ud-single-feature .ud-feature-link:hover {\n  color: var(--primary-color);\n}\n\n/* ===== About CSS ===== */\n.ud-about {\n  background: #f3f4fe;\n  padding: 120px 0;\n}\n\n@media (max-width: 767px) {\n  .ud-about {\n    padding: 80px 0;\n  }\n}\n\n.ud-about-wrapper {\n  background: var(--white);\n  border: 1px solid rgba(0, 0, 0, 0.08);\n  display: -webkit-box;\n  display: -ms-flexbox;\n  display: flex;\n  -webkit-box-pack: justify;\n  -ms-flex-pack: justify;\n  justify-content: space-between;\n}\n\n@media only screen and (min-width: 768px) and (max-width: 991px),\n  (max-width: 767px) {\n  .ud-about-wrapper {\n    display: block;\n  }\n}\n\n.ud-about-content-wrapper {\n  padding: 70px;\n}\n\n@media (max-width: 767px) {\n  .ud-about-content-wrapper {\n    padding: 50px 30px;\n  }\n}\n\n@media only screen and (min-width: 576px) and (max-width: 767px) {\n  .ud-about-content-wrapper {\n    padding: 50px;\n  }\n}\n\n.ud-about-content {\n  max-width: 500px;\n}\n\n.ud-about-content .tag {\n  font-weight: 500;\n  font-size: 14px;\n  color: var(--white);\n  background: var(--primary-color);\n  padding: 5px 20px;\n  display: inline-block;\n  margin-bottom: 20px;\n}\n\n.ud-about-content h2 {\n  font-weight: bold;\n  font-size: 36px;\n  line-height: 45px;\n  margin-bottom: 30px;\n}\n\n@media (max-width: 767px) {\n  .ud-about-content h2 {\n    font-size: 26px;\n    line-height: 38px;\n  }\n}\n\n.ud-about-content p {\n  font-size: 16px;\n  line-height: 28px;\n  margin-bottom: 40px;\n}\n\n.ud-about-content .ud-main-btn:hover {\n  background: #2748b4;\n  -webkit-box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.3);\n  box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.3);\n}\n\n@media only screen and (min-width: 768px) and (max-width: 991px),\n  (max-width: 767px) {\n  .ud-about-image {\n    text-align: center;\n  }\n}\n\n/* ===== Pricing CSS ===== */\n.ud-pricing {\n  padding-top: 120px;\n  padding-bottom: 90px;\n}\n\n@media (max-width: 767px) {\n  .ud-pricing {\n    padding-top: 80px;\n    padding-bottom: 40px;\n  }\n}\n\n.ud-single-pricing {\n  margin-bottom: 40px;\n  background: var(--white);\n  border: 2px solid #d4deff;\n  border-radius: 8px;\n  text-align: center;\n  padding: 45px 30px;\n  position: relative;\n}\n\n.ud-single-pricing.active {\n  background: -webkit-gradient(\n    linear,\n    left top,\n    left bottom,\n    from(#3056d3),\n    to(#179bee)\n  );\n  background: linear-gradient(180deg, #3056d3 0%, #179bee 100%);\n  border: none;\n  padding: 55px 30px;\n}\n\n.ud-single-pricing.active .ud-pricing-header h3,\n.ud-single-pricing.active .ud-pricing-header h4 {\n  color: var(--white);\n}\n\n.ud-single-pricing.active .ud-pricing-body li {\n  color: var(--white);\n}\n\n.ud-single-pricing.first-item::after,\n.ud-single-pricing.last-item::after {\n  content: '';\n  position: absolute;\n  width: 55px;\n  height: 55px;\n  z-index: 1;\n}\n\n.ud-single-pricing.first-item::after {\n  background: var(--primary-color);\n  left: -2px;\n  bottom: -2px;\n  border-radius: 0px 55px 0px 8px;\n}\n\n.ud-single-pricing.last-item::after {\n  background: #13c296;\n  top: -2px;\n  right: -2px;\n  border-radius: 0px 8px 0px 55px;\n}\n\n.ud-single-pricing .ud-popular-tag {\n  display: inline-block;\n  padding: 10px 25px;\n  background: var(--white);\n  border-radius: 30px;\n  color: var(--primary-color);\n  margin-bottom: 20px;\n  font-weight: 600;\n}\n\n.ud-single-pricing .ud-pricing-header h3 {\n  font-weight: 500;\n  font-size: 15px;\n  margin-bottom: 8px;\n}\n\n.ud-single-pricing .ud-pricing-header h4 {\n  font-weight: 600;\n  font-size: 26px;\n  color: var(--primary-color);\n  margin-bottom: 40px;\n}\n\n.ud-single-pricing .ud-pricing-body {\n  margin-bottom: 40px;\n}\n\n.ud-single-pricing .ud-pricing-body li {\n  font-weight: 500;\n  font-size: 15px;\n  margin-bottom: 18px;\n}\n\n.ud-single-pricing .ud-main-btn {\n  border-radius: 30px;\n  padding: 15px 40px;\n}\n\n.ud-single-pricing .ud-border-btn {\n  border: 1px solid #d4deff;\n  color: var(--primary-color);\n  background: var(--white);\n}\n\n.ud-single-pricing .ud-border-btn:hover {\n  color: var(--white);\n  border-color: var(--primary-color);\n  background: var(--primary-color);\n}\n\n.ud-single-pricing .ud-white-btn {\n  background: var(--white);\n  color: var(--heading-color);\n}\n\n.ud-single-pricing .ud-white-btn:hover {\n  color: var(--white);\n  background: var(--heading-color);\n}\n\n/* ===== FAQ CSS ===== */\n.ud-faq {\n  padding-top: 120px;\n  padding-bottom: 90px;\n  background: #f3f4fe;\n  position: relative;\n  z-index: 1;\n}\n\n@media (max-width: 767px) {\n  .ud-faq {\n    padding-top: 80px;\n    padding-bottom: 50px;\n  }\n}\n\n.ud-faq .shape {\n  position: absolute;\n  z-index: -1;\n  left: 0;\n  bottom: 0;\n}\n\n.ud-single-faq {\n  background: var(--white);\n  border: 1px solid #f3f4fe;\n  -webkit-box-shadow: 0px 20px 95px rgba(201, 203, 204, 0.3);\n  box-shadow: 0px 20px 95px rgba(201, 203, 204, 0.3);\n  border-radius: 10px;\n  margin-bottom: 30px;\n}\n\n.ud-single-faq .ud-faq-btn {\n  text-align: left;\n  display: -webkit-box;\n  display: -ms-flexbox;\n  display: flex;\n  width: 100%;\n  -webkit-box-align: center;\n  -ms-flex-align: center;\n  align-items: center;\n  border: none;\n  background: transparent;\n  font-weight: 600;\n  font-size: 18px;\n  color: var(--heading-color);\n  opacity: 0.88;\n  padding: 30px;\n}\n\n@media only screen and (min-width: 992px) and (max-width: 1199px),\n  (max-width: 767px) {\n  .ud-single-faq .ud-faq-btn {\n    padding: 15px;\n  }\n}\n\n.ud-single-faq .ud-faq-btn.collapsed span.icon i {\n  -webkit-transform: rotate(0deg);\n  transform: rotate(0deg);\n}\n\n.ud-single-faq .ud-faq-btn span.icon {\n  display: -webkit-box;\n  display: -ms-flexbox;\n  display: flex;\n  -webkit-box-align: center;\n  -ms-flex-align: center;\n  align-items: center;\n  -webkit-box-pack: center;\n  -ms-flex-pack: center;\n  justify-content: center;\n  width: 42px;\n  height: 42px;\n  background: rgba(48, 86, 211, 0.06);\n  border-radius: 10px;\n  color: var(--primary-color);\n  margin-right: 24px;\n}\n\n.ud-single-faq .ud-faq-btn span.icon i {\n  -webkit-transform: rotate(180deg);\n  transform: rotate(180deg);\n  -webkit-transition: all 0.3s;\n  transition: all 0.3s;\n  font-size: 14px;\n  font-weight: 700;\n}\n\n.ud-single-faq .ud-faq-body {\n  padding: 0px 30px 40px 95px;\n}\n\n@media only screen and (min-width: 992px) and (max-width: 1199px),\n  (max-width: 767px) {\n  .ud-single-faq .ud-faq-body {\n    padding: 0px 16px 20px 82px;\n  }\n}\n\n/* ===== Testimonials CSS ===== */\n.ud-testimonials {\n  padding-top: 120px;\n}\n\n@media (max-width: 767px) {\n  .ud-testimonials {\n    padding-top: 80px;\n  }\n}\n\n.ud-single-testimonial {\n  padding: 30px;\n  -webkit-box-shadow: 0px 60px 120px -20px #ebeffd;\n  box-shadow: 0px 60px 120px -20px #ebeffd;\n  background: var(--white);\n  margin-bottom: 50px;\n}\n\n.ud-single-testimonial .ud-testimonial-ratings {\n  margin-bottom: 10px;\n}\n\n.ud-single-testimonial .ud-testimonial-ratings i {\n  color: #fbb040;\n}\n\n.ud-single-testimonial .ud-testimonial-content {\n  margin-bottom: 25px;\n}\n\n.ud-single-testimonial .ud-testimonial-content p {\n  font-size: 16px;\n  line-height: 30px;\n  color: #637381;\n}\n\n.ud-single-testimonial .ud-testimonial-info {\n  display: -webkit-box;\n  display: -ms-flexbox;\n  display: flex;\n  -webkit-box-align: center;\n  -ms-flex-align: center;\n  align-items: center;\n}\n\n.ud-single-testimonial .ud-testimonial-info .ud-testimonial-image {\n  width: 50px;\n  height: 50px;\n  border-radius: 50%;\n  overflow: hidden;\n  margin-right: 20px;\n}\n\n.ud-single-testimonial .ud-testimonial-info .ud-testimonial-meta h4 {\n  font-weight: 600;\n  font-size: 14px;\n}\n\n.ud-single-testimonial .ud-testimonial-info .ud-testimonial-meta p {\n  font-size: 12px;\n  color: #969696;\n}\n\n.ud-brands .ud-title {\n  margin-bottom: 30px;\n}\n\n.ud-brands .ud-title h6 {\n  font-weight: normal;\n  font-size: 12px;\n  color: var(--body-color);\n  display: inline-block;\n  position: relative;\n}\n\n.ud-brands .ud-title h6::after {\n  content: '';\n  position: absolute;\n  width: 30px;\n  height: 1px;\n  background: #afb2b5;\n  right: -40px;\n  top: 50%;\n}\n\n.ud-brands .ud-brands-logo {\n  display: -webkit-box;\n  display: -ms-flexbox;\n  display: flex;\n  -webkit-box-align: center;\n  -ms-flex-align: center;\n  align-items: center;\n  -ms-flex-wrap: wrap;\n  flex-wrap: wrap;\n  margin-right: -40px;\n}\n\n.ud-brands .ud-brands-logo .ud-single-logo {\n  margin-right: 40px;\n  margin-bottom: 20px;\n  max-width: 140px;\n}\n\n.ud-brands .ud-brands-logo .ud-single-logo:hover img {\n  -webkit-filter: none;\n  filter: none;\n}\n\n.ud-brands .ud-brands-logo .ud-single-logo img {\n  -webkit-filter: grayscale(1);\n  filter: grayscale(1);\n  -webkit-transition: all 0.3s ease-out 0s;\n  transition: all 0.3s ease-out 0s;\n}\n\n/* ===== Team CSS ===== */\n.ud-team {\n  padding-top: 120px;\n  padding-bottom: 80px;\n}\n\n@media (max-width: 767px) {\n  .ud-team {\n    padding-top: 80px;\n    padding-bottom: 40px;\n  }\n}\n\n.ud-single-team {\n  margin-bottom: 40px;\n}\n\n.ud-single-team .ud-team-image-wrapper {\n  width: 170px;\n  height: 170px;\n  position: relative;\n  margin: 0px auto 25px;\n}\n\n.ud-single-team .ud-team-image {\n  border-radius: 50%;\n}\n\n.ud-single-team .ud-team-image img {\n  width: 100%;\n  border-radius: 50%;\n}\n\n.ud-single-team .shape {\n  position: absolute;\n  z-index: -1;\n}\n\n.ud-single-team .shape.shape-1 {\n  top: 0;\n  left: 0;\n}\n\n.ud-single-team .shape.shape-2 {\n  bottom: 0;\n  right: 0;\n}\n\n.ud-single-team .ud-team-info {\n  text-align: center;\n  margin-bottom: 20px;\n}\n\n.ud-single-team .ud-team-info h5 {\n  font-weight: 500;\n  font-size: 18px;\n  text-transform: capitalize;\n  margin-bottom: 10px;\n}\n\n.ud-single-team .ud-team-info h6 {\n  font-weight: 500;\n  font-size: 12px;\n  color: var(--body-color);\n}\n\n.ud-single-team .ud-team-socials {\n  display: -webkit-box;\n  display: -ms-flexbox;\n  display: flex;\n  -webkit-box-align: center;\n  -ms-flex-align: center;\n  align-items: center;\n  -webkit-box-pack: center;\n  -ms-flex-pack: center;\n  justify-content: center;\n}\n\n.ud-single-team .ud-team-socials a {\n  width: 32px;\n  height: 32px;\n  display: -webkit-box;\n  display: -ms-flexbox;\n  display: flex;\n  -webkit-box-align: center;\n  -ms-flex-align: center;\n  align-items: center;\n  -webkit-box-pack: center;\n  -ms-flex-pack: center;\n  justify-content: center;\n  margin: 0px 10px;\n  color: #cdced6;\n}\n\n.ud-single-team .ud-team-socials a:hover {\n  color: var(--primary-color);\n}\n\n/* ===== Contact CSS ===== */\n.ud-contact {\n  padding: 120px 0px;\n  position: relative;\n}\n\n@media (max-width: 767px) {\n  .ud-contact {\n    padding: 80px 0;\n  }\n}\n\n.ud-contact::after {\n  content: '';\n  position: absolute;\n  z-index: -1;\n  width: 100%;\n  top: 0;\n  left: 0;\n  height: 50%;\n  background: #f3f4fe;\n}\n\n@media only screen and (min-width: 992px) and (max-width: 1199px) {\n  .ud-contact::after {\n    height: 45%;\n  }\n}\n\n.ud-contact-title {\n  margin-bottom: 150px;\n}\n\n@media only screen and (min-width: 768px) and (max-width: 991px),\n  (max-width: 767px) {\n  .ud-contact-title {\n    margin-bottom: 50px;\n  }\n}\n\n.ud-contact-title span {\n  color: var(--heading-color);\n  font-weight: 600;\n  font-size: 15px;\n  margin-bottom: 20px;\n}\n\n.ud-contact-title h2 {\n  font-weight: 600;\n  font-size: 35px;\n  line-height: 41px;\n}\n\n.ud-contact-info-wrapper {\n  display: -webkit-box;\n  display: -ms-flexbox;\n  display: flex;\n  -webkit-box-pack: justify;\n  -ms-flex-pack: justify;\n  justify-content: space-between;\n  -ms-flex-wrap: wrap;\n  flex-wrap: wrap;\n}\n\n@media only screen and (min-width: 768px) and (max-width: 991px),\n  (max-width: 767px) {\n  .ud-contact-info-wrapper {\n    margin-bottom: 50px;\n  }\n}\n\n.ud-contact-info-wrapper .ud-single-info {\n  display: -webkit-box;\n  display: -ms-flexbox;\n  display: flex;\n  max-width: 100%;\n  width: 330px;\n  margin-bottom: 30px;\n}\n\n.ud-contact-info-wrapper .ud-info-icon {\n  font-size: 32px;\n  color: var(--primary-color);\n  margin-right: 24px;\n}\n\n.ud-contact-info-wrapper .ud-info-meta h5 {\n  font-weight: 600;\n  font-size: 18px;\n  margin-bottom: 15px;\n}\n\n.ud-contact-info-wrapper .ud-info-meta p {\n  font-size: 15px;\n  line-height: 24px;\n}\n\n.ud-contact-form-wrapper {\n  -webkit-box-shadow: 0px 4px 28px rgba(0, 0, 0, 0.05);\n  box-shadow: 0px 4px 28px rgba(0, 0, 0, 0.05);\n  border-radius: 8px;\n  background: var(--white);\n  padding: 60px;\n}\n\n@media (max-width: 767px) {\n  .ud-contact-form-wrapper {\n    padding: 40px 30px;\n  }\n}\n\n@media only screen and (min-width: 1200px) and (max-width: 1399px),\n  only screen and (min-width: 992px) and (max-width: 1199px),\n  only screen and (min-width: 576px) and (max-width: 767px) {\n  .ud-contact-form-wrapper {\n    padding: 50px 40px;\n  }\n}\n\n.ud-contact-form-wrapper .ud-contact-form-title {\n  font-style: normal;\n  font-weight: 600;\n  font-size: 28px;\n  margin-bottom: 30px;\n}\n\n@media (max-width: 767px) {\n  .ud-contact-form-wrapper .ud-contact-form-title {\n    font-size: 24px;\n  }\n}\n\n.ud-contact-form-wrapper .ud-form-group {\n  margin-bottom: 25px;\n}\n\n.ud-contact-form-wrapper .ud-form-group label {\n  display: block;\n  font-weight: normal;\n  font-size: 12px;\n}\n\n.ud-contact-form-wrapper .ud-form-group input,\n.ud-contact-form-wrapper .ud-form-group textarea {\n  display: block;\n  width: 100%;\n  padding: 15px 0;\n  border: none;\n  outline: none;\n  border-bottom: 1px solid #f1f1f1;\n  resize: none;\n}\n\n.ud-contact-form-wrapper .ud-form-group input:focus,\n.ud-contact-form-wrapper .ud-form-group textarea:focus {\n  border-color: var(--primary-color);\n}\n\n/* ===== Footer CSS ===== */\n.ud-footer {\n  background: var(--heading-color);\n  padding-top: 100px;\n  position: relative;\n  z-index: 1;\n  overflow: hidden;\n}\n\n.ud-footer .shape {\n  position: absolute;\n  z-index: -1;\n}\n\n.ud-footer .shape.shape-1 {\n  top: 0;\n  left: 0;\n}\n\n.ud-footer .shape.shape-2 {\n  top: 0;\n  right: 0;\n}\n\n.ud-footer .shape.shape-3 {\n  bottom: 0;\n  right: 0;\n}\n\n.ud-widget {\n  margin-bottom: 50px;\n}\n\n.ud-widget .ud-footer-logo {\n  max-width: 160px;\n  display: block;\n  margin-bottom: 10px;\n}\n\n.ud-widget .ud-footer-logo img {\n  width: 100%;\n}\n\n.ud-widget .ud-widget-desc {\n  font-size: 15px;\n  line-height: 24px;\n  color: #f3f4fe;\n  margin-bottom: 30px;\n  max-width: 260px;\n}\n\n.ud-widget .ud-widget-socials {\n  display: -webkit-box;\n  display: -ms-flexbox;\n  display: flex;\n  -webkit-box-align: center;\n  -ms-flex-align: center;\n  align-items: center;\n}\n\n.ud-widget .ud-widget-socials a {\n  font-size: 16px;\n  color: #dddddd;\n  margin-right: 20px;\n}\n\n.ud-widget .ud-widget-socials a:hover {\n  color: var(--primary-color);\n}\n\n.ud-widget .ud-widget-title {\n  font-weight: 600;\n  font-size: 18px;\n  margin-bottom: 35px;\n  color: var(--white);\n}\n\n.ud-widget .ud-widget-links a {\n  display: inline-block;\n  margin-bottom: 12px;\n  font-size: 15px;\n  line-height: 30px;\n  color: #f3f4fe;\n}\n\n.ud-widget .ud-widget-links a:hover {\n  color: var(--primary-color);\n  padding-left: 10px;\n}\n\n.ud-widget .ud-widget-brands {\n  display: -webkit-box;\n  display: -ms-flexbox;\n  display: flex;\n  -ms-flex-wrap: wrap;\n  flex-wrap: wrap;\n  -webkit-box-pack: justify;\n  -ms-flex-pack: justify;\n  justify-content: space-between;\n}\n\n.ud-widget .ud-widget-brands a {\n  display: block;\n  max-width: 120px;\n  margin-bottom: 20px;\n  margin-right: 20px;\n}\n\n@media only screen and (min-width: 1200px) and (max-width: 1399px) {\n  .ud-widget .ud-widget-brands a {\n    max-width: 100px;\n  }\n}\n\n.ud-footer-bottom {\n  padding: 35px 0;\n  border-top: 1px solid rgba(136, 144, 164, 0.43);\n}\n\n.ud-footer-bottom .ud-footer-bottom-left {\n  display: -webkit-box;\n  display: -ms-flexbox;\n  display: flex;\n  -webkit-box-align: center;\n  -ms-flex-align: center;\n  align-items: center;\n}\n\n@media (max-width: 767px) {\n  .ud-footer-bottom .ud-footer-bottom-left {\n    -webkit-box-pack: center;\n    -ms-flex-pack: center;\n    justify-content: center;\n  }\n}\n\n.ud-footer-bottom .ud-footer-bottom-left a {\n  font-weight: normal;\n  font-size: 15px;\n  color: #f3f4fe;\n  margin-right: 30px;\n  display: inline-block;\n}\n\n@media (max-width: 767px) {\n  .ud-footer-bottom .ud-footer-bottom-left a {\n    margin: 0px 8px 8px;\n  }\n}\n\n.ud-footer-bottom .ud-footer-bottom-left a:hover {\n  color: var(--primary-color);\n}\n\n.ud-footer-bottom .ud-footer-bottom-right {\n  text-align: right;\n  font-weight: normal;\n  font-size: 15px;\n  color: #f3f4fe;\n}\n\n.ud-footer-bottom .ud-footer-bottom-right a {\n  color: var(--primary-color);\n}\n\n.ud-footer-bottom .ud-footer-bottom-right a:hover {\n  text-decoration: underline;\n}\n\n@media (max-width: 767px) {\n  .ud-footer-bottom .ud-footer-bottom-right {\n    text-align: center;\n    margin-top: 10px;\n  }\n}\n\n/* ====== Banner CSS ======= */\n.ud-page-banner {\n  padding-top: 130px;\n  padding-bottom: 80px;\n  background: var(--primary-color);\n  background-image: url('../images/banner/banner-bg.svg');\n  background-position: center;\n  background-repeat: no-repeat;\n  background-size: cover;\n}\n\n.ud-banner-content {\n  text-align: center;\n  max-width: 600px;\n  margin: auto;\n}\n\n.ud-banner-content h1 {\n  color: var(--white);\n  font-size: 38px;\n  font-weight: 600;\n}\n\n/* ====== Login CSS ====== */\n.ud-login {\n  padding-top: 80px;\n  padding-bottom: 80px;\n}\n\n.ud-login-wrapper {\n  max-width: 500px;\n  margin: auto;\n  background: var(--white);\n  text-align: center;\n  padding: 60px;\n  -webkit-box-shadow: 0px 10px 35px rgba(0, 0, 0, 0.05);\n  box-shadow: 0px 10px 35px rgba(0, 0, 0, 0.05);\n}\n\n.ud-login-wrapper .ud-login-logo {\n  margin-bottom: 30px;\n}\n\n.ud-login-form .ud-form-group {\n  margin-bottom: 25px;\n}\n\n.ud-login-form .ud-form-group input {\n  width: 100%;\n  border: 2px solid #dddddd;\n  border-radius: 4px;\n  padding: 12px 24px;\n  background: #fcfdfe;\n  color: var(--body-color);\n}\n\n.ud-login-form .ud-form-group input:focus {\n  border-color: var(--primary-color);\n}\n\n.ud-socials-connect {\n  padding-top: 10px;\n  padding-bottom: 30px;\n}\n\n.ud-socials-connect p {\n  font-size: 16px;\n  color: var(--body-color);\n  margin-bottom: 10px;\n}\n\n.ud-socials-connect ul {\n  display: -webkit-box;\n  display: -ms-flexbox;\n  display: flex;\n  -webkit-box-align: center;\n  -ms-flex-align: center;\n  align-items: center;\n  margin-left: -10px;\n  margin-right: -10px;\n}\n\n.ud-socials-connect ul li {\n  width: 100%;\n}\n\n.ud-socials-connect ul li a {\n  height: 45px;\n  background: var(--primary-color);\n  display: -webkit-box;\n  display: -ms-flexbox;\n  display: flex;\n  -webkit-box-align: center;\n  -ms-flex-align: center;\n  align-items: center;\n  -webkit-box-pack: center;\n  -ms-flex-pack: center;\n  justify-content: center;\n  margin: 10px;\n  border-radius: 6px;\n  color: var(--white);\n  font-size: 20px;\n}\n\n.ud-socials-connect ul li a.facebook {\n  background: #4064ac;\n}\n\n.ud-socials-connect ul li a.facebook:hover {\n  background: #315294;\n}\n\n.ud-socials-connect ul li a.twitter {\n  background: #1c9cea;\n}\n\n.ud-socials-connect ul li a.twitter:hover {\n  background: #0f8bd8;\n}\n\n.ud-socials-connect ul li a.google {\n  background: #d64937;\n}\n\n.ud-socials-connect ul li a.google:hover {\n  background: #c53b29;\n}\n\n.forget-pass {\n  font-size: 16px;\n  color: var(--body-color);\n  margin-bottom: 8px;\n}\n\n.signup-option {\n  color: var(--body-color);\n  font-size: 16px;\n}\n\n.signup-option a {\n  color: var(--primary-color);\n}\n\n/* ====== Blog CSS ====== */\n.ud-blog-grids {\n  padding-top: 120px;\n  padding-bottom: 80px;\n}\n\n.ud-blog-grids.ud-related-articles {\n  padding-top: 100px;\n}\n\n@media (max-width: 767px) {\n  .ud-blog-grids {\n    padding-top: 80px;\n    padding-bottom: 40px;\n  }\n}\n\n.ud-single-blog {\n  margin-bottom: 40px;\n}\n\n.ud-single-blog:hover .ud-blog-image img {\n  -webkit-transform: scale(1.1) rotate(3deg);\n  transform: scale(1.1) rotate(3deg);\n}\n\n.ud-single-blog .ud-blog-image {\n  border-radius: 4px;\n  overflow: hidden;\n  margin-bottom: 30px;\n}\n\n.ud-single-blog .ud-blog-image a {\n  display: block;\n}\n\n.ud-single-blog .ud-blog-image img {\n  width: 100%;\n  -webkit-transition: all 0.3s ease-out 0s;\n  transition: all 0.3s ease-out 0s;\n}\n\n.ud-single-blog .ud-blog-date {\n  display: -webkit-inline-box;\n  display: -ms-inline-flexbox;\n  display: inline-flex;\n  font-size: 12px;\n  font-weight: 600;\n  padding: 8px 16px;\n  background: var(--primary-color);\n  color: var(--white);\n  border-radius: 5px;\n  margin-bottom: 20px;\n}\n\n.ud-single-blog .ud-blog-title {\n  font-weight: 600;\n  font-size: 24px;\n  line-height: 32px;\n  margin-bottom: 15px;\n}\n\n@media only screen and (min-width: 992px) and (max-width: 1199px) {\n  .ud-single-blog .ud-blog-title {\n    font-size: 20px;\n    line-height: 28px;\n  }\n}\n\n.ud-single-blog .ud-blog-title a {\n  color: inherit;\n}\n\n.ud-single-blog .ud-blog-title a:hover {\n  color: var(--primary-color);\n}\n\n.ud-single-blog .ud-blog-desc {\n  font-size: 16px;\n  line-height: 28px;\n}\n\n.ud-related-articles-title {\n  font-weight: 800;\n  font-size: 28px;\n  padding-bottom: 25px;\n  position: relative;\n  margin-bottom: 50px;\n}\n\n.ud-related-articles-title::after {\n  content: '';\n  position: absolute;\n  width: 80px;\n  height: 2px;\n  background: var(--primary-color);\n  left: 0;\n  bottom: 0;\n}\n\n/* ====== Blog Details CSS ====== */\n.ud-blog-details {\n  padding-top: 120px;\n}\n\n@media (max-width: 767px) {\n  .ud-blog-details {\n    padding-top: 80px;\n  }\n}\n\n.ud-blog-details-image {\n  position: relative;\n  border-radius: 5px;\n  overflow: hidden;\n  height: 500px;\n}\n\n@media (max-width: 767px) {\n  .ud-blog-details-image {\n    height: 300px;\n  }\n}\n\n.ud-blog-details-image > img {\n  position: absolute;\n  left: 0;\n  top: 0;\n  width: 100%;\n  height: 100%;\n  -o-object-fit: cover;\n  object-fit: cover;\n  -o-object-position: center center;\n  object-position: center center;\n}\n\n.ud-blog-overlay {\n  position: absolute;\n  top: 0;\n  left: 0;\n  width: 100%;\n  height: 100%;\n  display: -webkit-box;\n  display: -ms-flexbox;\n  display: flex;\n  -webkit-box-align: end;\n  -ms-flex-align: end;\n  align-items: flex-end;\n  background: -webkit-gradient(\n    linear,\n    left top,\n    left bottom,\n    color-stop(75.88%, rgba(48, 86, 211, 0)),\n    color-stop(93.23%, rgba(13, 21, 49, 0.72))\n  );\n  background: linear-gradient(\n    180deg,\n    rgba(48, 86, 211, 0) 75.88%,\n    rgba(13, 21, 49, 0.72) 93.23%\n  );\n  border-radius: 5px;\n  padding: 30px;\n}\n\n.ud-blog-overlay-content {\n  display: -webkit-box;\n  display: -ms-flexbox;\n  display: flex;\n  -webkit-box-align: center;\n  -ms-flex-align: center;\n  align-items: center;\n}\n\n@media (max-width: 767px) {\n  .ud-blog-overlay-content {\n    -webkit-box-orient: vertical;\n    -webkit-box-direction: normal;\n    -ms-flex-direction: column;\n    flex-direction: column;\n    -webkit-box-align: start;\n    -ms-flex-align: start;\n    align-items: flex-start;\n  }\n}\n\n.ud-blog-overlay-content .ud-blog-author {\n  display: -webkit-box;\n  display: -ms-flexbox;\n  display: flex;\n  -webkit-box-align: center;\n  -ms-flex-align: center;\n  align-items: center;\n  margin-right: 40px;\n}\n\n@media (max-width: 767px) {\n  .ud-blog-overlay-content .ud-blog-author {\n    margin-right: 0px;\n    margin-bottom: 20px;\n  }\n}\n\n.ud-blog-overlay-content .ud-blog-author img {\n  width: 40px;\n  height: 40px;\n  border-radius: 50%;\n  overflow: hidden;\n  margin-right: 15px;\n}\n\n.ud-blog-overlay-content .ud-blog-author span {\n  font-weight: 500;\n  font-size: 14px;\n  line-height: 28px;\n  color: #ffffff;\n}\n\n.ud-blog-overlay-content .ud-blog-author a {\n  color: inherit;\n}\n\n.ud-blog-overlay-content .ud-blog-author a:hover {\n  color: var(--primary-color);\n}\n\n.ud-blog-overlay-content .ud-blog-meta {\n  display: -webkit-box;\n  display: -ms-flexbox;\n  display: flex;\n  -webkit-box-align: center;\n  -ms-flex-align: center;\n  align-items: center;\n}\n\n.ud-blog-overlay-content .ud-blog-meta p {\n  display: -webkit-box;\n  display: -ms-flexbox;\n  display: flex;\n  -webkit-box-align: center;\n  -ms-flex-align: center;\n  align-items: center;\n  font-weight: 500;\n  font-size: 14px;\n  line-height: 28px;\n  color: #ffffff;\n  margin-right: 30px;\n}\n\n.ud-blog-overlay-content .ud-blog-meta p:last-child {\n  margin-right: 0px;\n}\n\n.ud-blog-overlay-content .ud-blog-meta p i {\n  font-size: 16px;\n  margin-right: 10px;\n}\n\n.ud-blog-details-content {\n  padding-top: 60px;\n}\n\n@media only screen and (min-width: 1400px) and (max-width: 1920px),\n  only screen and (min-width: 1200px) and (max-width: 1399px) {\n  .ud-blog-details-content {\n    padding-right: 50px;\n  }\n}\n\n.ud-blog-details-title {\n  font-weight: 700;\n  font-size: 35px;\n  line-height: 50px;\n  margin-bottom: 35px;\n}\n\n@media (max-width: 767px) {\n  .ud-blog-details-title {\n    font-size: 26px;\n    line-height: 35px;\n  }\n}\n\n@media only screen and (min-width: 576px) and (max-width: 767px) {\n  .ud-blog-details-title {\n    font-size: 30px;\n    line-height: 40px;\n  }\n}\n\n.ud-blog-details-para {\n  font-size: 16px;\n  line-height: 28px;\n  margin-bottom: 30px;\n}\n\n.ud-blog-details-subtitle {\n  font-weight: 700;\n  font-size: 26px;\n  margin-bottom: 30px;\n}\n\n@media (max-width: 767px) {\n  .ud-blog-details-subtitle {\n    font-size: 22px;\n    margin-bottom: 25px;\n  }\n}\n\n.ud-blog-quote {\n  background-image: url('../images/blog/quote-bg.svg');\n  background-repeat: no-repeat;\n  background-size: cover;\n  padding: 40px;\n  text-align: center;\n  margin-bottom: 40px;\n}\n\n@media (max-width: 767px) {\n  .ud-blog-quote {\n    padding: 30px;\n  }\n}\n\n.ud-blog-quote i {\n  font-size: 40px;\n  font-weight: 700;\n  color: var(--primary-color);\n  line-height: 1;\n  margin-bottom: 20px;\n}\n\n@media (max-width: 767px) {\n  .ud-blog-quote i {\n    margin-bottom: 15px;\n  }\n}\n\n.ud-blog-quote p {\n  font-style: italic;\n  font-weight: 600;\n  font-size: 16px;\n  line-height: 27px;\n  text-align: center;\n  color: var(--heading-color);\n  margin-bottom: 15px;\n}\n\n@media (max-width: 767px) {\n  .ud-blog-quote p {\n    font-size: 14px;\n    line-height: 24px;\n  }\n}\n\n.ud-blog-quote h6 {\n  color: var(--body-color);\n  font-style: italic;\n  font-weight: 500;\n  font-size: 12px;\n  line-height: 20px;\n  text-align: center;\n}\n\n.ud-blog-details-action {\n  display: -webkit-box;\n  display: -ms-flexbox;\n  display: flex;\n  -webkit-box-align: center;\n  -ms-flex-align: center;\n  align-items: center;\n  -webkit-box-pack: justify;\n  -ms-flex-pack: justify;\n  justify-content: space-between;\n}\n\n@media (max-width: 767px) {\n  .ud-blog-details-action {\n    -webkit-box-orient: vertical;\n    -webkit-box-direction: normal;\n    -ms-flex-direction: column;\n    flex-direction: column;\n    -webkit-box-align: start;\n    -ms-flex-align: start;\n    align-items: flex-start;\n  }\n}\n\n.ud-blog-tags {\n  display: -webkit-box;\n  display: -ms-flexbox;\n  display: flex;\n  -webkit-box-align: center;\n  -ms-flex-align: center;\n  align-items: center;\n}\n\n@media (max-width: 767px) {\n  .ud-blog-tags {\n    margin-bottom: 20px;\n  }\n}\n\n.ud-blog-tags li {\n  margin-right: 14px;\n}\n\n.ud-blog-tags li:last-child {\n  margin-right: 0px;\n}\n\n.ud-blog-tags a {\n  padding: 8px 16px;\n  font-size: 12px;\n  font-weight: 500;\n  color: var(--primary-color);\n  background: rgba(48, 86, 211, 0.06);\n  border-radius: 3px;\n}\n\n.ud-blog-tags a:hover {\n  background: var(--primary-color);\n  color: var(--white);\n}\n\n.ud-blog-share {\n  display: -webkit-box;\n  display: -ms-flexbox;\n  display: flex;\n  -webkit-box-align: center;\n  -ms-flex-align: center;\n  align-items: center;\n}\n\n.ud-blog-share h6 {\n  font-weight: 500;\n  font-size: 12px;\n  color: var(--body-color);\n  margin-right: 20px;\n}\n\n.ud-blog-share-links {\n  display: -webkit-box;\n  display: -ms-flexbox;\n  display: flex;\n  -webkit-box-align: center;\n  -ms-flex-align: center;\n  align-items: center;\n}\n\n.ud-blog-share-links li {\n  margin-right: 14px;\n}\n\n.ud-blog-share-links li:last-child {\n  margin-right: 0px;\n}\n\n.ud-blog-share-links a {\n  font-size: 18px;\n  width: 35px;\n  height: 35px;\n  display: -webkit-box;\n  display: -ms-flexbox;\n  display: flex;\n  -webkit-box-align: center;\n  -ms-flex-align: center;\n  align-items: center;\n  -webkit-box-pack: center;\n  -ms-flex-pack: center;\n  justify-content: center;\n  border-radius: 50%;\n  color: var(--white);\n}\n\n.ud-blog-share-links a.facebook {\n  background: #4064ac;\n}\n\n.ud-blog-share-links a.facebook:hover {\n  background: #315294;\n}\n\n.ud-blog-share-links a.twitter {\n  background: #1c9cea;\n}\n\n.ud-blog-share-links a.twitter:hover {\n  background: #0f8bd8;\n}\n\n.ud-blog-share-links a.linkedin {\n  background: #007ab9;\n}\n\n.ud-blog-share-links a.linkedin:hover {\n  background: #03689b;\n}\n\n.ud-blog-sidebar {\n  padding-top: 60px;\n}\n\n.ud-newsletter-box {\n  background: var(--primary-color);\n  padding: 60px 45px;\n  position: relative;\n  z-index: 1;\n  text-align: center;\n  border-radius: 5px;\n  margin-bottom: 50px;\n}\n\n@media only screen and (min-width: 992px) and (max-width: 1199px),\n  (max-width: 767px) {\n  .ud-newsletter-box {\n    padding: 50px 30px;\n  }\n}\n\n@media only screen and (min-width: 576px) and (max-width: 767px) {\n  .ud-newsletter-box {\n    padding: 60px 45px;\n  }\n}\n\n.ud-newsletter-box .shape {\n  position: absolute;\n  z-index: -1;\n}\n\n.ud-newsletter-box .shape.shape-1 {\n  top: 0;\n  right: 0;\n}\n\n.ud-newsletter-box .shape.shape-2 {\n  left: 0;\n  bottom: 0;\n}\n\n.ud-newsletter-box .ud-newsletter-title {\n  font-weight: 600;\n  font-size: 25px;\n  color: var(--white);\n  margin-bottom: 5px;\n}\n\n@media only screen and (min-width: 992px) and (max-width: 1199px) {\n  .ud-newsletter-box .ud-newsletter-title {\n    font-size: 23px;\n  }\n}\n\n.ud-newsletter-box p {\n  font-size: 16px;\n  line-height: 24px;\n  color: var(--white);\n}\n\n.ud-newsletter-box .ud-newsletter-form {\n  margin-top: 30px;\n}\n\n.ud-newsletter-box .ud-newsletter-form input {\n  width: 100%;\n  -webkit-box-shadow: 0px 4px 42px rgba(0, 0, 0, 0.01);\n  box-shadow: 0px 4px 42px rgba(0, 0, 0, 0.01);\n  border-radius: 5px;\n  background: rgba(255, 255, 255, 0.2);\n  color: var(--white);\n  text-align: center;\n  margin-bottom: 15px;\n  border: 2px solid transparent;\n  padding: 12px 20px;\n}\n\n.ud-newsletter-box .ud-newsletter-form input::-webkit-input-placeholder {\n  color: var(--white);\n  opacity: 1;\n}\n\n.ud-newsletter-box .ud-newsletter-form input:-ms-input-placeholder {\n  color: var(--white);\n  opacity: 1;\n}\n\n.ud-newsletter-box .ud-newsletter-form input::-ms-input-placeholder {\n  color: var(--white);\n  opacity: 1;\n}\n\n.ud-newsletter-box .ud-newsletter-form input::placeholder {\n  color: var(--white);\n  opacity: 1;\n}\n\n.ud-newsletter-box .ud-newsletter-form input:focus {\n  border-color: var(--white);\n}\n\n.ud-newsletter-box .ud-newsletter-form .ud-main-btn {\n  background: #13c296;\n  -webkit-box-shadow: 0px 4px 42px rgba(0, 0, 0, 0.01);\n  box-shadow: 0px 4px 42px rgba(0, 0, 0, 0.01);\n  border-radius: 5px;\n  width: 100%;\n  margin-bottom: 24px;\n}\n\n.ud-newsletter-box .ud-newsletter-form .ud-main-btn:hover {\n  background: var(--heading-color);\n}\n\n.ud-newsletter-box .ud-newsletter-form .ud-newsletter-note {\n  font-weight: 500;\n  font-size: 14px;\n  line-height: 22px;\n}\n\n.ud-articles-box {\n  margin-bottom: 50px;\n}\n\n.ud-articles-box .ud-articles-box-title {\n  font-weight: 600;\n  font-size: 28px;\n  padding-bottom: 25px;\n  position: relative;\n  margin-bottom: 20px;\n}\n\n.ud-articles-box .ud-articles-box-title::after {\n  content: '';\n  position: absolute;\n  width: 80px;\n  height: 2px;\n  background: var(--primary-color);\n  left: 0;\n  bottom: 0;\n}\n\n.ud-articles-box .ud-articles-list li {\n  padding: 20px 0;\n  border-bottom: 1px solid #f2f3f8;\n  display: -webkit-box;\n  display: -ms-flexbox;\n  display: flex;\n  -webkit-box-align: center;\n  -ms-flex-align: center;\n  align-items: center;\n}\n\n.ud-articles-box .ud-articles-list li:last-child {\n  padding-bottom: 0px;\n  border-bottom: 0px;\n}\n\n.ud-articles-box .ud-articles-list .ud-article-image {\n  max-width: 80px;\n  width: 100%;\n  height: 80px;\n  border-radius: 50%;\n  overflow: hidden;\n  margin-right: 20px;\n}\n\n@media only screen and (min-width: 992px) and (max-width: 1199px),\n  (max-width: 767px) {\n  .ud-articles-box .ud-articles-list .ud-article-image {\n    max-width: 65px;\n    height: 65px;\n  }\n}\n\n@media only screen and (min-width: 576px) and (max-width: 767px) {\n  .ud-articles-box .ud-articles-list .ud-article-image {\n    max-width: 80px;\n    height: 80px;\n  }\n}\n\n.ud-articles-box .ud-articles-list .ud-article-image img {\n  width: 100%;\n}\n\n.ud-articles-box .ud-articles-list .ud-article-title {\n  font-weight: 500;\n  font-size: 18px;\n  line-height: 22px;\n  margin-bottom: 5px;\n}\n\n@media only screen and (min-width: 992px) and (max-width: 1199px) {\n  .ud-articles-box .ud-articles-list .ud-article-title {\n    font-size: 16px;\n  }\n}\n\n.ud-articles-box .ud-articles-list .ud-article-title a {\n  color: inherit;\n}\n\n.ud-articles-box .ud-articles-list .ud-article-title a:hover {\n  color: var(--primary-color);\n}\n\n.ud-articles-box .ud-articles-list .ud-article-author {\n  font-size: 14px;\n}\n\n.ud-banner-ad {\n  border-radius: 5px;\n  overflow: hidden;\n}\n\n.ud-banner-ad a {\n  display: block;\n}\n\n.ud-banner-ad img {\n  width: 100%;\n}\n\n/* ====== Error 404 CSS ======= */\n.ud-404 {\n  padding-top: 120px;\n  padding-bottom: 120px;\n}\n\n@media (max-width: 767px) {\n  .ud-404 {\n    padding-top: 80px;\n    padding-bottom: 80px;\n  }\n}\n\n.ud-404-wrapper {\n  text-align: center;\n  max-width: 850px;\n  margin: 0px auto;\n  background: var(--white);\n  padding: 100px 60px;\n  -webkit-box-shadow: 0px 0px 25px rgba(0, 0, 0, 0.1);\n  box-shadow: 0px 0px 25px rgba(0, 0, 0, 0.1);\n  border-radius: 10px;\n  position: relative;\n  overflow: hidden;\n  z-index: 1;\n}\n\n@media (max-width: 767px) {\n  .ud-404-wrapper {\n    padding: 50px 30px;\n  }\n}\n\n.ud-404-wrapper .shape {\n  position: absolute;\n  z-index: -1;\n}\n\n.ud-404-wrapper .shape.shape-1 {\n  top: 0;\n  left: 0;\n}\n\n.ud-404-wrapper .shape.shape-2 {\n  right: 0;\n  bottom: 0;\n}\n\n.ud-404-title {\n  font-size: 42px;\n  font-weight: 700;\n  margin-bottom: 30px;\n}\n\n@media only screen and (min-width: 768px) and (max-width: 991px) {\n  .ud-404-title {\n    font-size: 35px;\n  }\n}\n\n@media (max-width: 767px) {\n  .ud-404-title {\n    font-size: 30px;\n  }\n}\n\n.ud-404-subtitle {\n  font-size: 24px;\n  font-weight: 400;\n  margin-bottom: 30px;\n}\n\n@media only screen and (min-width: 768px) and (max-width: 991px) {\n  .ud-404-subtitle {\n    font-size: 22px;\n  }\n}\n\n@media (max-width: 767px) {\n  .ud-404-subtitle {\n    font-size: 18px;\n  }\n}\n\n.ud-404-links {\n  display: -webkit-box;\n  display: -ms-flexbox;\n  display: flex;\n  -webkit-box-align: center;\n  -ms-flex-align: center;\n  align-items: center;\n  -webkit-box-pack: center;\n  -ms-flex-pack: center;\n  justify-content: center;\n  -ms-flex-wrap: wrap;\n  flex-wrap: wrap;\n}\n\n.ud-404-links a {\n  font-size: 16px;\n  font-weight: 500;\n  padding: 12px 24px;\n  color: var(--heading-color);\n  background: rgba(48, 86, 211, 0.06);\n  border-radius: 5px;\n  margin: 5px 10px;\n}\n\n.ud-404-links a:hover {\n  background: var(--heading-color);\n  color: var(--white);\n}\n\n@media (max-width: 767px) {\n  .ud-404-links a {\n    margin: 5px 10px;\n    font-size: 14px;\n    padding: 10px 20px;\n  }\n}\n/*# sourceMappingURL=ud-styles.css.map */\n"
  },
  {
    "path": "assets/js/main.js",
    "content": ";(function () {\r\n  'use strict'\r\n\r\n  // ======= Sticky\r\n  window.onscroll = function () {\r\n    const ud_header = document.querySelector('.ud-header')\r\n    const sticky = ud_header.offsetTop\r\n    // const logo = document.querySelector(\".navbar-brand img\");\r\n\r\n    if (window.pageYOffset > sticky) {\r\n      ud_header.classList.add('sticky')\r\n    } else {\r\n      ud_header.classList.remove('sticky')\r\n    }\r\n\r\n    // === logo change\r\n    const logo = document.querySelector('.navbar-brand')\r\n    if (ud_header.classList.contains('sticky')) {\r\n      logo.classList.add('text-black')\r\n      logo.classList.remove('text-white')\r\n    } else {\r\n      logo.classList.remove('text-black')\r\n      logo.classList.add('text-white')\r\n    }\r\n\r\n    // show or hide the back-top-top button\r\n    const backToTop = document.querySelector('.back-to-top')\r\n    if (\r\n      document.body.scrollTop > 50 ||\r\n      document.documentElement.scrollTop > 50\r\n    ) {\r\n      backToTop.style.display = 'flex'\r\n    } else {\r\n      backToTop.style.display = 'none'\r\n    }\r\n  }\r\n\r\n  //===== close navbar-collapse when a  clicked\r\n  let navbarToggler = document.querySelector('.navbar-toggler')\r\n  const navbarCollapse = document.querySelector('.navbar-collapse')\r\n\r\n  document.querySelectorAll('.ud-menu-scroll').forEach((e) =>\r\n    e.addEventListener('click', () => {\r\n      navbarToggler.classList.remove('active')\r\n      navbarCollapse.classList.remove('show')\r\n    }),\r\n  )\r\n  navbarToggler.addEventListener('click', function () {\r\n    navbarToggler.classList.toggle('active')\r\n    navbarCollapse.classList.toggle('show')\r\n  })\r\n\r\n  // ===== submenu\r\n  const submenuButton = document.querySelectorAll('.nav-item-has-children')\r\n  submenuButton.forEach((elem) => {\r\n    elem.querySelector('a').addEventListener('click', () => {\r\n      elem.querySelector('.ud-submenu').classList.toggle('show')\r\n    })\r\n  })\r\n\r\n  // ===== wow js\r\n  new WOW().init()\r\n\r\n  // ====== scroll top js\r\n  function scrollTo(element, to = 0, duration = 500) {\r\n    const start = element.scrollTop\r\n    const change = to - start\r\n    const increment = 20\r\n    let currentTime = 0\r\n\r\n    const animateScroll = () => {\r\n      currentTime += increment\r\n\r\n      const val = Math.easeInOutQuad(currentTime, start, change, duration)\r\n\r\n      element.scrollTop = val\r\n\r\n      if (currentTime < duration) {\r\n        setTimeout(animateScroll, increment)\r\n      }\r\n    }\r\n\r\n    animateScroll()\r\n  }\r\n\r\n  Math.easeInOutQuad = function (t, b, c, d) {\r\n    t /= d / 2\r\n    if (t < 1) return (c / 2) * t * t + b\r\n    t--\r\n    return (-c / 2) * (t * (t - 2) - 1) + b\r\n  }\r\n\r\n  document.querySelector('.back-to-top').onclick = () => {\r\n    scrollTo(document.documentElement)\r\n  }\r\n})()\r\n"
  },
  {
    "path": "assets/scss/_404.scss",
    "content": "/* ====== Error 404 CSS ======= */\n\n.ud-404 {\n  padding-top: 120px;\n  padding-bottom: 120px;\n\n  @media #{$xs} {\n    padding-top: 80px;\n    padding-bottom: 80px;\n  }\n}\n\n.ud-404-wrapper {\n  text-align: center;\n  max-width: 850px;\n  margin: 0px auto;\n  background: var(--white);\n  padding: 100px 60px;\n  box-shadow: 0px 0px 25px rgba(0, 0, 0, 0.1);\n  border-radius: 10px;\n  position: relative;\n  overflow: hidden;\n  z-index: 1;\n\n  @media #{$xs} {\n    padding: 50px 30px;\n  }\n\n  .shape {\n    position: absolute;\n    z-index: -1;\n\n    &.shape-1 {\n      top: 0;\n      left: 0;\n    }\n\n    &.shape-2 {\n      right: 0;\n      bottom: 0;\n    }\n  }\n}\n\n.ud-404-title {\n  font-size: 42px;\n  font-weight: 700;\n  margin-bottom: 30px;\n\n  @media #{$md} {\n    font-size: 35px;\n  }\n\n  @media #{$xs} {\n    font-size: 30px;\n  }\n}\n\n.ud-404-subtitle {\n  font-size: 24px;\n  font-weight: 400;\n  margin-bottom: 30px;\n\n  @media #{$md} {\n    font-size: 22px;\n  }\n\n  @media #{$xs} {\n    font-size: 18px;\n  }\n}\n\n.ud-404-links {\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  flex-wrap: wrap;\n\n  a {\n    font-size: 16px;\n    font-weight: 500;\n    padding: 12px 24px;\n    color: var(--heading-color);\n    background: rgba(48, 86, 211, 0.06);\n    border-radius: 5px;\n    margin: 5px 10px;\n\n    &:hover {\n      background: var(--heading-color);\n      color: var(--white);\n    }\n\n    @media #{$xs} {\n      margin: 5px 10px;\n      font-size: 14px;\n      padding: 10px 20px;\n    }\n  }\n}\n"
  },
  {
    "path": "assets/scss/_about.scss",
    "content": "/* ===== About CSS ===== */\n\n.ud-about {\n  background: #f3f4fe;\n  padding: 120px 0;\n\n  @media #{$xs} {\n    padding: 80px 0;\n  }\n}\n\n.ud-about-wrapper {\n  background: var(--white);\n  border: 1px solid rgba(0, 0, 0, 0.08);\n  display: flex;\n  justify-content: space-between;\n\n  @media #{$md, $xs} {\n    display: block;\n  }\n}\n\n.ud-about-content-wrapper {\n  padding: 70px;\n\n  @media #{$xs} {\n    padding: 50px 30px;\n  }\n\n  @media #{$sm} {\n    padding: 50px;\n  }\n}\n\n.ud-about-content {\n  max-width: 500px;\n\n  .tag {\n    font-weight: 500;\n    font-size: 14px;\n    color: var(--white);\n    background: var(--primary-color);\n    padding: 5px 20px;\n    display: inline-block;\n    margin-bottom: 20px;\n  }\n\n  h2 {\n    font-weight: bold;\n    font-size: 36px;\n    line-height: 45px;\n    margin-bottom: 30px;\n\n    @media #{$xs} {\n      font-size: 26px;\n      line-height: 38px;\n    }\n  }\n\n  p {\n    font-size: 16px;\n    line-height: 28px;\n    margin-bottom: 40px;\n  }\n\n  .ud-main-btn {\n    &:hover {\n      background: #2748b4;\n      box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.3);\n    }\n  }\n}\n\n.ud-about-image {\n  @media #{$md, $xs} {\n    text-align: center;\n  }\n}\n"
  },
  {
    "path": "assets/scss/_banner.scss",
    "content": "/* ====== Banner CSS ======= */\n.ud-page-banner {\n  padding-top: 130px;\n  padding-bottom: 80px;\n  background: var(--primary-color);\n  background-image: url(\"../images/banner/banner-bg.svg\");\n  background-position: center;\n  background-repeat: no-repeat;\n  background-size: cover;\n}\n\n.ud-banner-content {\n  text-align: center;\n  max-width: 600px;\n  margin: auto;\n\n  h1 {\n    color: var(--white);\n    font-size: 38px;\n    font-weight: 600;\n  }\n}\n"
  },
  {
    "path": "assets/scss/_blog-details.scss",
    "content": "/* ====== Blog Details CSS ====== */\n\n.ud-blog-details {\n  padding-top: 120px;\n\n  @media #{$xs} {\n    padding-top: 80px;\n  }\n}\n\n.ud-blog-details-image {\n  position: relative;\n  border-radius: 5px;\n  overflow: hidden;\n  height: 500px;\n\n  @media #{$xs} {\n    height: 300px;\n  }\n\n  & > img {\n    position: absolute;\n    left: 0;\n    top: 0;\n    width: 100%;\n    height: 100%;\n    object-fit: cover;\n    object-position: center center;\n  }\n}\n\n.ud-blog-overlay {\n  position: absolute;\n  top: 0;\n  left: 0;\n  width: 100%;\n  height: 100%;\n  display: flex;\n  align-items: flex-end;\n  background: linear-gradient(\n    180deg,\n    rgba(48, 86, 211, 0) 75.88%,\n    rgba(13, 21, 49, 0.72) 93.23%\n  );\n  border-radius: 5px;\n  padding: 30px;\n}\n\n.ud-blog-overlay-content {\n  display: flex;\n  align-items: center;\n\n  @media #{$xs} {\n    flex-direction: column;\n    align-items: flex-start;\n  }\n\n  .ud-blog-author {\n    display: flex;\n    align-items: center;\n    margin-right: 40px;\n\n    @media #{$xs} {\n      margin-right: 0px;\n      margin-bottom: 20px;\n    }\n\n    img {\n      width: 40px;\n      height: 40px;\n      border-radius: 50%;\n      overflow: hidden;\n      margin-right: 15px;\n    }\n\n    span {\n      font-weight: 500;\n      font-size: 14px;\n      line-height: 28px;\n      color: #ffffff;\n    }\n\n    a {\n      color: inherit;\n\n      &:hover {\n        color: var(--primary-color);\n      }\n    }\n  }\n\n  .ud-blog-meta {\n    display: flex;\n    align-items: center;\n\n    p {\n      display: flex;\n      align-items: center;\n\n      font-weight: 500;\n      font-size: 14px;\n      line-height: 28px;\n      color: #ffffff;\n      margin-right: 30px;\n\n      &:last-child {\n        margin-right: 0px;\n      }\n\n      i {\n        font-size: 16px;\n        margin-right: 10px;\n      }\n    }\n  }\n}\n\n.ud-blog-details-content {\n  padding-top: 60px;\n\n  @media #{$desktop, $laptop} {\n    padding-right: 50px;\n  }\n}\n\n.ud-blog-details-title {\n  font-weight: 700;\n  font-size: 35px;\n  line-height: 50px;\n  margin-bottom: 35px;\n\n  @media #{$xs} {\n    font-size: 26px;\n    line-height: 35px;\n  }\n\n  @media #{$sm} {\n    font-size: 30px;\n    line-height: 40px;\n  }\n}\n\n.ud-blog-details-para {\n  font-size: 16px;\n  line-height: 28px;\n  margin-bottom: 30px;\n}\n\n.ud-blog-details-subtitle {\n  font-weight: 700;\n  font-size: 26px;\n  margin-bottom: 30px;\n\n  @media #{$xs} {\n    font-size: 22px;\n    margin-bottom: 25px;\n  }\n}\n\n.ud-blog-quote {\n  background-image: url(\"../images/blog/quote-bg.svg\");\n  background-repeat: no-repeat;\n  background-size: cover;\n  padding: 40px;\n  text-align: center;\n  margin-bottom: 40px;\n\n  @media #{$xs} {\n    padding: 30px;\n  }\n\n  i {\n    font-size: 40px;\n    font-weight: 700;\n    color: var(--primary-color);\n    line-height: 1;\n    margin-bottom: 20px;\n\n    @media #{$xs} {\n      margin-bottom: 15px;\n    }\n  }\n\n  p {\n    font-style: italic;\n    font-weight: 600;\n    font-size: 16px;\n    line-height: 27px;\n    text-align: center;\n    color: var(--heading-color);\n    margin-bottom: 15px;\n\n    @media #{$xs} {\n      font-size: 14px;\n      line-height: 24px;\n    }\n  }\n\n  h6 {\n    color: var(--body-color);\n    font-style: italic;\n    font-weight: 500;\n    font-size: 12px;\n    line-height: 20px;\n    text-align: center;\n  }\n}\n\n.ud-blog-details-action {\n  display: flex;\n  align-items: center;\n  justify-content: space-between;\n\n  @media #{$xs} {\n    flex-direction: column;\n    align-items: flex-start;\n  }\n}\n\n.ud-blog-tags {\n  display: flex;\n  align-items: center;\n\n  @media #{$xs} {\n    margin-bottom: 20px;\n  }\n\n  li {\n    margin-right: 14px;\n\n    &:last-child {\n      margin-right: 0px;\n    }\n  }\n\n  a {\n    padding: 8px 16px;\n    font-size: 12px;\n    font-weight: 500;\n\n    color: var(--primary-color);\n    background: rgba(48, 86, 211, 0.06);\n    border-radius: 3px;\n\n    &:hover {\n      background: var(--primary-color);\n      color: var(--white);\n    }\n  }\n}\n\n.ud-blog-share {\n  display: flex;\n  align-items: center;\n\n  h6 {\n    font-weight: 500;\n    font-size: 12px;\n    color: var(--body-color);\n    margin-right: 20px;\n  }\n}\n\n.ud-blog-share-links {\n  display: flex;\n  align-items: center;\n\n  li {\n    margin-right: 14px;\n\n    &:last-child {\n      margin-right: 0px;\n    }\n  }\n\n  a {\n    font-size: 18px;\n    width: 35px;\n    height: 35px;\n    display: flex;\n    align-items: center;\n    justify-content: center;\n    border-radius: 50%;\n    color: var(--white);\n\n    &.facebook {\n      background: #4064ac;\n\n      &:hover {\n        background: #315294;\n      }\n    }\n\n    &.twitter {\n      background: #1c9cea;\n\n      &:hover {\n        background: #0f8bd8;\n      }\n    }\n\n    &.linkedin {\n      background: #007ab9;\n\n      &:hover {\n        background: #03689b;\n      }\n    }\n  }\n}\n\n.ud-blog-sidebar {\n  padding-top: 60px;\n}\n\n.ud-newsletter-box {\n  background: var(--primary-color);\n  padding: 60px 45px;\n  position: relative;\n  z-index: 1;\n  text-align: center;\n  border-radius: 5px;\n  margin-bottom: 50px;\n\n  @media #{$lg, $xs} {\n    padding: 50px 30px;\n  }\n\n  @media #{$sm} {\n    padding: 60px 45px;\n  }\n\n  .shape {\n    position: absolute;\n    z-index: -1;\n\n    &.shape-1 {\n      top: 0;\n      right: 0;\n    }\n\n    &.shape-2 {\n      left: 0;\n      bottom: 0;\n    }\n  }\n\n  .ud-newsletter-title {\n    font-weight: 600;\n    font-size: 25px;\n    color: var(--white);\n    margin-bottom: 5px;\n\n    @media #{$lg } {\n      font-size: 23px;\n    }\n  }\n\n  p {\n    font-size: 16px;\n    line-height: 24px;\n    color: var(--white);\n  }\n\n  .ud-newsletter-form {\n    margin-top: 30px;\n\n    input {\n      width: 100%;\n      box-shadow: 0px 4px 42px rgba(0, 0, 0, 0.01);\n      border-radius: 5px;\n      background: rgba(255, 255, 255, 0.2);\n      color: var(--white);\n      text-align: center;\n      margin-bottom: 15px;\n      border: 2px solid transparent;\n      padding: 12px 20px;\n\n      &::placeholder {\n        color: var(--white);\n        opacity: 1;\n      }\n\n      &:focus {\n        border-color: var(--white);\n      }\n    }\n\n    .ud-main-btn {\n      background: #13c296;\n      box-shadow: 0px 4px 42px rgba(0, 0, 0, 0.01);\n      border-radius: 5px;\n      width: 100%;\n      margin-bottom: 24px;\n\n      &:hover {\n        background: var(--heading-color);\n      }\n    }\n\n    .ud-newsletter-note {\n      font-weight: 500;\n      font-size: 14px;\n      line-height: 22px;\n    }\n  }\n}\n\n.ud-articles-box {\n  margin-bottom: 50px;\n\n  .ud-articles-box-title {\n    font-weight: 600;\n    font-size: 28px;\n    padding-bottom: 25px;\n    position: relative;\n    margin-bottom: 20px;\n\n    &::after {\n      content: \"\";\n      position: absolute;\n      width: 80px;\n      height: 2px;\n      background: var(--primary-color);\n      left: 0;\n      bottom: 0;\n    }\n  }\n\n  .ud-articles-list {\n    li {\n      padding: 20px 0;\n      border-bottom: 1px solid #f2f3f8;\n      display: flex;\n      align-items: center;\n\n      &:last-child {\n        padding-bottom: 0px;\n        border-bottom: 0px;\n      }\n    }\n\n    .ud-article-image {\n      max-width: 80px;\n      width: 100%;\n      height: 80px;\n      border-radius: 50%;\n      overflow: hidden;\n      margin-right: 20px;\n\n      @media #{$lg, $xs} {\n        max-width: 65px;\n        height: 65px;\n      }\n\n      @media #{$sm} {\n        max-width: 80px;\n        height: 80px;\n      }\n\n      img {\n        width: 100%;\n      }\n    }\n\n    .ud-article-title {\n      font-weight: 500;\n      font-size: 18px;\n      line-height: 22px;\n      margin-bottom: 5px;\n\n      @media #{$lg} {\n        font-size: 16px;\n      }\n\n      a {\n        color: inherit;\n\n        &:hover {\n          color: var(--primary-color);\n        }\n      }\n    }\n\n    .ud-article-author {\n      font-size: 14px;\n    }\n  }\n}\n\n.ud-banner-ad {\n  border-radius: 20px;\n  overflow: hidden;\n\n  a {\n    display: block;\n  }\n\n  img {\n    width: 80%;\n    padding: 10px;\n  }\n}\n"
  },
  {
    "path": "assets/scss/_blog.scss",
    "content": "/* ====== Blog CSS ====== */\n\n.ud-blog-grids {\n  padding-top: 120px;\n  padding-bottom: 80px;\n\n  &.ud-related-articles {\n    padding-top: 100px;\n  }\n\n  @media #{$xs} {\n    padding-top: 80px;\n    padding-bottom: 40px;\n  }\n}\n\n.ud-single-blog {\n  margin-bottom: 40px;\n\n  &:hover {\n    .ud-blog-image {\n      img {\n        @include transform(scale(1.1) rotate(3deg));\n      }\n    }\n  }\n\n  .ud-blog-image {\n    border-radius: 4px;\n    overflow: hidden;\n    margin-bottom: 30px;\n\n    a {\n      display: block;\n    }\n\n    img {\n      width: 100%;\n      @include transition(0.3s);\n    }\n  }\n\n  .ud-blog-date {\n    display: inline-flex;\n    font-size: 12px;\n\n    font-weight: 600;\n    padding: 8px 16px;\n    background: var(--primary-color);\n    color: var(--white);\n    border-radius: 5px;\n    margin-bottom: 20px;\n  }\n\n  .ud-blog-title {\n    font-weight: 600;\n    font-size: 24px;\n    line-height: 32px;\n    margin-bottom: 15px;\n\n    @media #{$lg} {\n      font-size: 20px;\n      line-height: 28px;\n    }\n\n    a {\n      color: inherit;\n\n      &:hover {\n        color: var(--primary-color);\n      }\n    }\n  }\n\n  .ud-blog-desc {\n    font-size: 16px;\n    line-height: 28px;\n  }\n}\n\n.ud-related-articles-title {\n  font-weight: 800;\n  font-size: 28px;\n  padding-bottom: 25px;\n  position: relative;\n  margin-bottom: 50px;\n\n  &::after {\n    content: \"\";\n    position: absolute;\n    width: 80px;\n    height: 2px;\n    background: var(--primary-color);\n    left: 0;\n    bottom: 0;\n  }\n}\n"
  },
  {
    "path": "assets/scss/_common.scss",
    "content": "/*===========================\r\n  COMMON css \r\n===========================*/\r\n@import url(\"https://fonts.googleapis.com/css2?family=Inter:wght@200;300;400;500;600;700;800;900&display=swap\");\r\n\r\n:root {\r\n  --font: \"Inter\", sans-serif;\r\n  --body-color: #637381;\r\n  --heading-color: #212b36;\r\n  --primary-color: #3056d3;\r\n  --white: #ffffff;\r\n}\r\n\r\nbody {\r\n  font-family: var(--font);\r\n  font-weight: normal;\r\n  font-style: normal;\r\n  color: var(--body-color);\r\n  overflow-x: hidden;\r\n}\r\n\r\n* {\r\n  margin: 0;\r\n  padding: 0;\r\n  @include box-sizing(border-box);\r\n}\r\n\r\nimg {\r\n  max-width: 100%;\r\n}\r\n\r\na,\r\nbutton,\r\ninput,\r\ntextarea {\r\n  @include transition(0.3s);\r\n}\r\n\r\na,\r\na:focus,\r\ninput:focus,\r\ntextarea:focus,\r\nbutton:focus,\r\n.navbar-toggler:focus {\r\n  text-decoration: none;\r\n  outline: none;\r\n  box-shadow: none;\r\n}\r\n\r\na:focus,\r\na:hover {\r\n  text-decoration: none;\r\n}\r\n\r\ni,\r\nspan,\r\na {\r\n  display: inline-block;\r\n}\r\n\r\naudio,\r\ncanvas,\r\niframe,\r\nimg,\r\nsvg,\r\nvideo {\r\n  vertical-align: middle;\r\n}\r\n\r\nh1,\r\nh2,\r\nh3,\r\nh4,\r\nh5,\r\nh6 {\r\n  font-weight: 700;\r\n  color: var(--heading-color);\r\n  margin: 0px;\r\n}\r\n\r\nh1 {\r\n  font-size: 48px;\r\n}\r\nh2 {\r\n  font-size: 36px;\r\n}\r\nh3 {\r\n  font-size: 28px;\r\n}\r\nh4 {\r\n  font-size: 22px;\r\n}\r\nh5 {\r\n  font-size: 18px;\r\n}\r\nh6 {\r\n  font-size: 16px;\r\n}\r\n\r\nul,\r\nol {\r\n  margin: 0px;\r\n  padding: 0px;\r\n  list-style-type: none;\r\n}\r\n\r\np {\r\n  font-size: 16px;\r\n  font-weight: 400;\r\n  line-height: 26px;\r\n  color: var(--body-color);\r\n  margin: 0px;\r\n}\r\n\r\n.bg_cover {\r\n  background-position: center center;\r\n  background-size: cover;\r\n  background-repeat: no-repeat;\r\n  width: 100%;\r\n  height: 100%;\r\n}\r\n\r\n/*===== All Button Style =====*/\r\n\r\n.ud-main-btn {\r\n  display: inline-block;\r\n  text-align: center;\r\n  white-space: nowrap;\r\n  vertical-align: middle;\r\n\r\n  font-weight: 500;\r\n  font-size: 16px;\r\n  border-radius: 5px;\r\n  padding: 15px 25px;\r\n  border: 1px solid transparent;\r\n  color: var(--white);\r\n  cursor: pointer;\r\n  z-index: 5;\r\n  @include transition(0.4s);\r\n  background: var(--primary-color);\r\n\r\n  &:hover {\r\n    color: var(--white);\r\n    background: var(--heading-color);\r\n  }\r\n}\r\n\r\n.container {\r\n  @media #{$xs} {\r\n    padding-left: 40px;\r\n    padding-right: 40px;\r\n  }\r\n  @media #{$sm} {\r\n    padding-left: 20px;\r\n    padding-right: 20px;\r\n  }\r\n}\r\n\r\n.back-to-top {\r\n  width: 40px;\r\n  height: 40px;\r\n  line-height: 40px;\r\n  background: var(--primary-color);\r\n  box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.2);\r\n  text-align: center;\r\n  justify-content: center;\r\n  align-items: center;\r\n  border-radius: 5px;\r\n  position: fixed;\r\n  right: 30px;\r\n  bottom: 30px;\r\n  z-index: 99;\r\n  color: var(--white);\r\n\r\n  &:hover {\r\n    color: var(--white);\r\n    background: var(--heading-color);\r\n  }\r\n}\r\n"
  },
  {
    "path": "assets/scss/_contact.scss",
    "content": "/* ===== Contact CSS ===== */\n.ud-contact {\n  padding: 120px 0px;\n  position: relative;\n\n  @media #{$xs} {\n    padding: 80px 0;\n  }\n\n  &::after {\n    content: \"\";\n    position: absolute;\n    z-index: -1;\n    width: 100%;\n    top: 0;\n    left: 0;\n    height: 50%;\n    background: #f3f4fe;\n\n    @media #{$lg} {\n      height: 45%;\n    }\n  }\n}\n\n.ud-contact-title {\n  margin-bottom: 150px;\n\n  @media #{$md, $xs} {\n    margin-bottom: 50px;\n  }\n\n  span {\n    color: var(--heading-color);\n    font-weight: 600;\n    font-size: 15px;\n    margin-bottom: 20px;\n  }\n\n  h2 {\n    font-weight: 600;\n    font-size: 35px;\n    line-height: 41px;\n  }\n}\n\n.ud-contact-info-wrapper {\n  display: flex;\n  justify-content: space-between;\n  flex-wrap: wrap;\n\n  @media #{$md, $xs} {\n    margin-bottom: 50px;\n  }\n\n  .ud-single-info {\n    display: flex;\n    max-width: 100%;\n    width: 330px;\n    margin-bottom: 30px;\n  }\n\n  .ud-info-icon {\n    font-size: 32px;\n    color: var(--primary-color);\n    margin-right: 24px;\n  }\n\n  .ud-info-meta {\n    h5 {\n      font-weight: 600;\n      font-size: 18px;\n      margin-bottom: 15px;\n    }\n\n    p {\n      font-size: 15px;\n      line-height: 24px;\n    }\n  }\n}\n\n.ud-contact-form-wrapper {\n  box-shadow: 0px 4px 28px rgba(0, 0, 0, 0.05);\n  border-radius: 8px;\n  background: var(--white);\n  padding: 60px;\n\n  @media #{$xs} {\n    padding: 40px 30px;\n  }\n\n  @media #{$laptop, $lg, $sm} {\n    padding: 50px 40px;\n  }\n\n  .ud-contact-form-title {\n    font-style: normal;\n    font-weight: 600;\n    font-size: 28px;\n    margin-bottom: 30px;\n\n    @media #{$xs} {\n      font-size: 24px;\n    }\n  }\n\n  .ud-form-group {\n    margin-bottom: 25px;\n\n    label {\n      display: block;\n      font-weight: normal;\n      font-size: 12px;\n    }\n\n    input,\n    textarea {\n      display: block;\n      width: 100%;\n      padding: 15px 0;\n      border: none;\n      outline: none;\n      border-bottom: 1px solid #f1f1f1;\n      resize: none;\n\n      &:focus {\n        border-color: var(--primary-color);\n      }\n    }\n  }\n}\n"
  },
  {
    "path": "assets/scss/_default.scss",
    "content": "/* ======================\n    DEFAULT CSS\n========================= */\n\n// Margin-top\n@for $i from 1 through 45 {\n  .mt-#{5 * $i} {\n    margin-top: 5px * $i;\n  }\n}\n\n// Margin-bottom\n@for $i from 1 through 45 {\n  .mb-#{5 * $i} {\n    margin-bottom: 5px * $i;\n  }\n}\n\n// Padding-top\n@for $i from 1 through 45 {\n  .pt-#{5 * $i} {\n    padding-top: 5px * $i;\n  }\n}\n\n// Padding-bottom\n@for $i from 1 through 45 {\n  .pb-#{5 * $i} {\n    padding-bottom: 5px * $i;\n  }\n}\n"
  },
  {
    "path": "assets/scss/_faq.scss",
    "content": "/* ===== FAQ CSS ===== */\n\n.ud-faq {\n  padding-top: 120px;\n  padding-bottom: 90px;\n  background: #f3f4fe;\n  position: relative;\n  z-index: 1;\n\n  @media #{$xs } {\n    padding-top: 80px;\n    padding-bottom: 50px;\n  }\n\n  .shape {\n    position: absolute;\n    z-index: -1;\n    left: 0;\n    bottom: 0;\n  }\n}\n\n.ud-single-faq {\n  background: var(--white);\n  border: 1px solid #f3f4fe;\n  box-shadow: 0px 20px 95px rgba(201, 203, 204, 0.3);\n  border-radius: 10px;\n  margin-bottom: 30px;\n\n  .ud-faq-btn {\n    text-align: left;\n    display: flex;\n    width: 100%;\n    align-items: center;\n    border: none;\n    background: transparent;\n\n    font-weight: 600;\n    font-size: 18px;\n    color: var(--heading-color);\n    opacity: 0.88;\n    padding: 30px;\n\n    @media #{$lg, $xs} {\n      padding: 15px;\n    }\n\n    &.collapsed {\n      span.icon i {\n        @include transform(rotate(0deg));\n      }\n    }\n\n    span.icon {\n      display: flex;\n      align-items: center;\n      justify-content: center;\n      width: 42px;\n      height: 42px;\n      background: rgba(48, 86, 211, 0.06);\n      border-radius: 10px;\n      color: var(--primary-color);\n      margin-right: 24px;\n\n      i {\n        @include transform(rotate(180deg));\n        transition: all 0.3s;\n        font-size: 14px;\n        font-weight: 700;\n      }\n    }\n  }\n\n  .ud-faq-body {\n    padding: 0px 30px 40px 95px;\n\n    @media #{$lg, $xs} {\n      padding: 0px 16px 20px 82px;\n    }\n  }\n}\n"
  },
  {
    "path": "assets/scss/_features.scss",
    "content": "/* ===== Features CSS ===== */\n\n.ud-features {\n  padding-top: 120px;\n  padding-bottom: 90px;\n\n  @media #{$xs} {\n    padding-top: 80px;\n    padding-bottom: 40px;\n  }\n}\n\n.ud-section-title {\n  max-width: 620px;\n  margin-bottom: 70px;\n\n  span {\n    font-weight: 600;\n    font-size: 18px;\n    color: var(--primary-color);\n    margin-bottom: 10px;\n  }\n\n  h2 {\n    font-weight: 700;\n    font-size: 42px;\n    line-height: 55px;\n    text-transform: capitalize;\n    color: var(--heading-color);\n    margin-bottom: 20px;\n  }\n\n  p {\n    font-size: 20px;\n    line-height: 30px;\n\n    @media #{$xs} {\n      font-size: 16px;\n      line-height: 26px;\n    }\n  }\n}\n\n.ud-single-feature {\n  margin-bottom: 40px;\n\n  &:hover {\n    .ud-feature-icon::before {\n      @include transform(rotate(45deg));\n    }\n  }\n\n  .ud-feature-icon {\n    width: 70px;\n    height: 70px;\n    display: flex;\n    align-items: center;\n    justify-content: center;\n    border-radius: 14px;\n    background: var(--primary-color);\n    font-size: 32px;\n    color: var(--white);\n    position: relative;\n    z-index: 1;\n    text-align: center;\n    margin-bottom: 40px;\n\n    &::before {\n      content: \"\";\n      position: absolute;\n      width: 100%;\n      height: 100%;\n      top: 0;\n      left: 0;\n      border-radius: 14px;\n      background: var(--primary-color);\n      opacity: 0.2;\n      z-index: -1;\n      @include transform(rotate(23deg));\n      @include transition(0.3s);\n    }\n  }\n\n  .ud-feature-title {\n    font-weight: 700;\n    font-size: 20px;\n    line-height: 28px;\n    margin-bottom: 12px;\n\n    @media #{$lg} {\n      font-size: 18px;\n      line-height: 26px;\n    }\n  }\n\n  .ud-feature-desc {\n    font-size: 16px;\n    line-height: 24px;\n    margin-bottom: 40px;\n  }\n\n  .ud-feature-link {\n    font-weight: 500;\n    color: var(--body-color);\n\n    &:hover {\n      color: var(--primary-color);\n    }\n  }\n}\n"
  },
  {
    "path": "assets/scss/_footer.scss",
    "content": "/* ===== Footer CSS ===== */\n\n.ud-footer {\n  background: var(--heading-color);\n  padding-top: 100px;\n  position: relative;\n  z-index: 1;\n  overflow: hidden;\n\n  .shape {\n    position: absolute;\n    z-index: -1;\n\n    &.shape-1 {\n      top: 0;\n      left: 0;\n    }\n\n    &.shape-2 {\n      top: 0;\n      right: 0;\n    }\n\n    &.shape-3 {\n      bottom: 0;\n      right: 0;\n    }\n  }\n}\n\n.ud-widget {\n  margin-bottom: 50px;\n\n  .ud-footer-logo {\n    max-width: 160px;\n    display: block;\n    margin-bottom: 10px;\n\n    img {\n      width: 100%;\n    }\n  }\n\n  .ud-widget-desc {\n    font-size: 15px;\n    line-height: 24px;\n    color: #f3f4fe;\n    margin-bottom: 30px;\n    max-width: 260px;\n  }\n\n  .ud-widget-socials {\n    display: flex;\n    align-items: center;\n\n    a {\n      font-size: 16px;\n      color: #dddddd;\n      margin-right: 20px;\n\n      &:hover {\n        color: var(--primary-color);\n      }\n    }\n  }\n\n  .ud-widget-title {\n    font-weight: 600;\n    font-size: 18px;\n    margin-bottom: 35px;\n    color: var(--white);\n  }\n\n  .ud-widget-links {\n    a {\n      display: inline-block;\n      margin-bottom: 12px;\n      font-size: 15px;\n      line-height: 30px;\n      color: #f3f4fe;\n\n      &:hover {\n        color: var(--primary-color);\n        padding-left: 10px;\n      }\n    }\n  }\n\n  .ud-widget-brands {\n    display: flex;\n    flex-wrap: wrap;\n    justify-content: space-between;\n\n    a {\n      display: block;\n      max-width: 120px;\n      margin-bottom: 20px;\n      margin-right: 20px;\n\n      @media #{$laptop} {\n        max-width: 100px;\n      }\n    }\n  }\n}\n\n.ud-footer-bottom {\n  padding: 35px 0;\n  border-top: 1px solid rgba(136, 144, 164, 0.43);\n\n  .ud-footer-bottom-left {\n    display: flex;\n    align-items: center;\n\n    @media #{$xs} {\n      justify-content: center;\n    }\n\n    a {\n      font-weight: normal;\n      font-size: 15px;\n      color: #f3f4fe;\n      margin-right: 30px;\n      display: inline-block;\n\n      @media #{$xs} {\n        margin: 0px 8px 8px;\n      }\n\n      &:hover {\n        color: var(--primary-color);\n      }\n    }\n  }\n\n  .ud-footer-bottom-right {\n    text-align: right;\n    font-weight: normal;\n    font-size: 15px;\n    color: #f3f4fe;\n\n    a {\n      color: var(--primary-color);\n\n      &:hover {\n        text-decoration: underline;\n      }\n    }\n\n    @media #{$xs} {\n      text-align: center;\n      margin-top: 10px;\n    }\n  }\n}\n"
  },
  {
    "path": "assets/scss/_header.scss",
    "content": "/* ===== Header CSS ===== */\r\n.ud-header {\r\n  position: absolute;\r\n  top: 0;\r\n  left: 0;\r\n  width: 100%;\r\n  z-index: 99;\r\n  @include transition(0.3s);\r\n}\r\n\r\n.sticky {\r\n  position: fixed;\r\n  z-index: 99;\r\n  background-color: rgba(255, 255, 255, 0.8);\r\n  backdrop-filter: blur(5px);\r\n  @include box-shadow(inset 0 -1px 0 0 rgba(0, 0, 0, 0.1));\r\n  @include transition(0.3s);\r\n\r\n  & .navbar {\r\n    padding: 0;\r\n  }\r\n}\r\n\r\n.navbar {\r\n  padding: 0px 0;\r\n  border-radius: 5px;\r\n  position: relative;\r\n  @include transition(0.3s);\r\n}\r\n\r\n.navbar-brand {\r\n  padding: 0;\r\n\r\n  @media #{$md, $xs} {\r\n    padding: 5px 0px;\r\n  }\r\n\r\n  img {\r\n    max-width: 160px;\r\n  }\r\n}\r\n\r\n.navbar-toggler {\r\n  padding: 0;\r\n\r\n  & .toggler-icon {\r\n    width: 30px;\r\n    height: 2px;\r\n    background-color: var(--white);\r\n    display: block;\r\n    margin: 5px 0;\r\n    position: relative;\r\n    @include transition(0.3s);\r\n  }\r\n\r\n  &.active {\r\n    & .toggler-icon {\r\n      &:nth-of-type(1) {\r\n        @include transform(rotate(45deg));\r\n        top: 7px;\r\n      }\r\n\r\n      &:nth-of-type(2) {\r\n        opacity: 0;\r\n      }\r\n\r\n      &:nth-of-type(3) {\r\n        @include transform(rotate(135deg));\r\n        top: -7px;\r\n      }\r\n    }\r\n  }\r\n}\r\n\r\n.navbar-collapse {\r\n  @media #{$md, $xs} {\r\n    position: absolute;\r\n    top: 100%;\r\n    right: 0;\r\n    max-width: 300px;\r\n    width: 100%;\r\n    background-color: var(--white);\r\n    z-index: 9;\r\n    @include box-shadow(0px 15px 20px 0px rgba(0, 0, 0, 0.1));\r\n    padding: 0px;\r\n    display: none;\r\n    border-radius: 5px;\r\n\r\n    &.show {\r\n      display: block;\r\n    }\r\n  }\r\n}\r\n\r\n.navbar-nav {\r\n  @media #{$md, $xs} {\r\n    padding: 20px 30px;\r\n  }\r\n\r\n  & .nav-item {\r\n    position: relative;\r\n    padding: 0px 20px;\r\n\r\n    @media #{$lg} {\r\n      padding: 0px 12px;\r\n    }\r\n\r\n    @media #{$md, $xs} {\r\n      padding: 0px;\r\n    }\r\n\r\n    & > a {\r\n      font-size: 16px;\r\n      font-weight: 400;\r\n      color: var(--white);\r\n      @include transition(0.3s);\r\n      padding: 25px 8px;\r\n      position: relative;\r\n\r\n      @media #{$md, $xs} {\r\n        display: block;\r\n        padding: 8px 0;\r\n        color: var(--heading-color);\r\n      }\r\n\r\n      &:hover,\r\n      &.active {\r\n        color: var(--white);\r\n        opacity: 0.5;\r\n\r\n        @media #{$md, $xs} {\r\n          color: var(--primary-color);\r\n          opacity: 1;\r\n        }\r\n      }\r\n    }\r\n\r\n    .ud-submenu {\r\n      position: absolute;\r\n      width: 250px;\r\n      background: var(--white);\r\n      top: 110%;\r\n      padding: 20px 30px;\r\n      box-shadow: 0 15px 44px rgba(140, 140, 140, 0.18);\r\n      border-radius: 5px;\r\n      opacity: 0;\r\n      visibility: hidden;\r\n      @include transition(0.3s);\r\n\r\n      @media #{$md, $xs} {\r\n        position: static;\r\n        box-shadow: none;\r\n        width: 100%;\r\n        padding: 0px;\r\n        opacity: 1;\r\n        visibility: visible;\r\n        display: none;\r\n      }\r\n\r\n      &.show {\r\n        display: block;\r\n      }\r\n\r\n      .ud-submenu-link {\r\n        padding: 7px 0;\r\n        color: var(--heading-color);\r\n        font-size: 14px;\r\n\r\n        &:hover {\r\n          color: var(--primary-color);\r\n        }\r\n      }\r\n    }\r\n\r\n    &:hover {\r\n      & > a {\r\n        color: var(--white);\r\n        opacity: 0.5;\r\n\r\n        @media #{$md, $xs} {\r\n          color: var(--primary-color);\r\n          opacity: 1;\r\n        }\r\n      }\r\n\r\n      & > .ud-submenu {\r\n        opacity: 1;\r\n        visibility: visible;\r\n        top: 100%;\r\n      }\r\n    }\r\n\r\n    &.nav-item-has-children {\r\n      & > a {\r\n        position: relative;\r\n\r\n        &::after {\r\n          content: \"\";\r\n          box-sizing: border-box;\r\n          position: absolute;\r\n          width: 10px;\r\n          height: 10px;\r\n          border-bottom: 2px solid;\r\n          border-right: 2px solid;\r\n          transform: rotate(45deg) translateY(-50%);\r\n          right: -15px;\r\n          top: 50%;\r\n          margin-top: -2px;\r\n\r\n          @media #{$md, $xs} {\r\n            right: 5px;\r\n          }\r\n        }\r\n      }\r\n    }\r\n  }\r\n}\r\n\r\n.navbar-btn {\r\n  @media #{$md, $xs} {\r\n    position: absolute;\r\n    top: 50%;\r\n    right: 50px;\r\n    @include transform(translateY(-50%));\r\n  }\r\n\r\n  .ud-main-btn {\r\n    padding: 8px 16px;\r\n    background: transparent;\r\n  }\r\n\r\n  .ud-login-btn {\r\n    &:hover {\r\n      opacity: 0.5;\r\n    }\r\n  }\r\n\r\n  .ud-white-btn {\r\n    background: rgba(255, 255, 255, 0.2);\r\n\r\n    &:hover {\r\n      background: rgba(255, 255, 255, 1);\r\n      color: var(--heading-color);\r\n    }\r\n  }\r\n}\r\n\r\n.sticky {\r\n  & .navbar-toggler {\r\n    & .toggler-icon {\r\n      background-color: var(--heading-color);\r\n    }\r\n  }\r\n\r\n  & .navbar-nav {\r\n    & .nav-item {\r\n      &:hover {\r\n        & > a {\r\n          color: var(--primary-color);\r\n          opacity: 1;\r\n        }\r\n      }\r\n\r\n      & a {\r\n        color: var(--heading-color);\r\n\r\n        &.active,\r\n        &:hover {\r\n          color: var(--primary-color);\r\n          opacity: 1;\r\n        }\r\n      }\r\n    }\r\n  }\r\n\r\n  .navbar-btn {\r\n    .ud-main-btn {\r\n      &.ud-login-btn {\r\n        color: var(--heading-color);\r\n\r\n        &:hover {\r\n          color: var(--primary-color);\r\n          opacity: 1;\r\n        }\r\n      }\r\n    }\r\n\r\n    .ud-white-btn {\r\n      background: var(--primary-color);\r\n      color: var(--white);\r\n\r\n      &:hover {\r\n        background: var(--heading-color);\r\n      }\r\n    }\r\n  }\r\n}\r\n"
  },
  {
    "path": "assets/scss/_hero.scss",
    "content": "/* ===== Hero CSS ===== */\n\n.ud-hero {\n  background: var(--primary-color);\n  padding-top: 180px;\n\n  @media #{$md} {\n    padding-top: 160px;\n  }\n\n  @media #{$xs} {\n    padding-top: 130px;\n  }\n}\n\n.ud-hero-content {\n  max-width: 780px;\n  margin: auto;\n  margin-bottom: 30px;\n\n  .ud-hero-title {\n    color: var(--white);\n    font-weight: 700;\n    font-size: 45px;\n    line-height: 60px;\n    text-align: center;\n    margin-bottom: 30px;\n\n    @media #{$md} {\n      font-size: 38px;\n      line-height: 50px;\n    }\n\n    @media #{$xs} {\n      font-size: 26px;\n      line-height: 38px;\n    }\n  }\n\n  .ud-hero-desc {\n    font-weight: normal;\n    font-size: 20px;\n    line-height: 35px;\n    text-align: center;\n    color: var(--white);\n    opacity: 0.8;\n    max-width: 600px;\n    margin: auto;\n    margin-bottom: 30px;\n\n    @media #{$xs} {\n      font-size: 16px;\n      line-height: 30px;\n    }\n  }\n}\n\n.ud-hero-buttons {\n  display: flex;\n  align-items: center;\n  justify-content: center;\n\n  .ud-main-btn {\n    margin: 8px;\n\n    @media #{$xs} {\n      margin: 5px;\n    }\n  }\n\n  .ud-main-btn {\n    @media #{$xs} {\n      padding: 12px 16px;\n    }\n  }\n\n  .ud-white-btn {\n    background: var(--white);\n    color: var(--heading-color);\n\n    &:hover {\n      box-shadow: 0px 0px 25px rgba(0, 0, 0, 0.2);\n      background: #fefefe;\n      color: var(--primary-color);\n    }\n  }\n\n  .ud-link-btn {\n    &:hover {\n      color: var(--white);\n      background: transparent;\n      opacity: 0.5;\n    }\n  }\n}\n\n.ud-hero-brands-wrapper {\n  text-align: center;\n  margin-bottom: 40px;\n\n  img {\n    transition: all 0.3s;\n    opacity: 0.5;\n    max-width: 250px;\n\n    &:hover {\n      opacity: 1;\n    }\n  }\n}\n\n.ud-hero-image {\n  max-width: 845px;\n  margin: auto;\n  text-align: center;\n  position: relative;\n  z-index: 1;\n\n  img {\n    max-width: 100%;\n    text-align: center;\n  }\n\n  .shape {\n    position: absolute;\n    z-index: -1;\n\n    &.shape-1 {\n      bottom: 0;\n      left: -30px;\n    }\n\n    &.shape-2 {\n      top: -20px;\n      right: -20px;\n    }\n  }\n}\n"
  },
  {
    "path": "assets/scss/_login.scss",
    "content": "/* ====== Login CSS ====== */\n.ud-login {\n  padding-top: 80px;\n  padding-bottom: 80px;\n}\n\n.ud-login-wrapper {\n  max-width: 500px;\n  margin: auto;\n  background: var(--white);\n  text-align: center;\n  padding: 60px;\n  box-shadow: 0px 10px 35px rgba(0, 0, 0, 0.05);\n\n  .ud-login-logo {\n    margin-bottom: 30px;\n  }\n}\n\n.ud-login-form {\n  .ud-form-group {\n    margin-bottom: 25px;\n\n    input {\n      width: 100%;\n      border: 2px solid #dddddd;\n      border-radius: 4px;\n      padding: 12px 24px;\n      background: #fcfdfe;\n      color: var(--body-color);\n\n      &:focus {\n        border-color: var(--primary-color);\n      }\n    }\n  }\n}\n\n.ud-socials-connect {\n  padding-top: 10px;\n  padding-bottom: 30px;\n\n  p {\n    font-size: 16px;\n    color: var(--body-color);\n    margin-bottom: 10px;\n  }\n\n  ul {\n    display: flex;\n    align-items: center;\n    margin-left: -10px;\n    margin-right: -10px;\n\n    li {\n      width: 100%;\n\n      a {\n        height: 45px;\n        background: var(--primary-color);\n        display: flex;\n        align-items: center;\n        justify-content: center;\n        margin: 10px;\n        border-radius: 6px;\n        color: var(--white);\n        font-size: 20px;\n\n        &.facebook {\n          background: #4064ac;\n\n          &:hover {\n            background: #315294;\n          }\n        }\n\n        &.twitter {\n          background: #1c9cea;\n\n          &:hover {\n            background: #0f8bd8;\n          }\n        }\n\n        &.google {\n          background: #d64937;\n\n          &:hover {\n            background: #c53b29;\n          }\n        }\n      }\n    }\n  }\n}\n\n.forget-pass {\n  font-size: 16px;\n  color: var(--body-color);\n  margin-bottom: 8px;\n}\n\n.signup-option {\n  color: var(--body-color);\n  font-size: 16px;\n\n  a {\n    color: var(--primary-color);\n  }\n}\n"
  },
  {
    "path": "assets/scss/_mixin.scss",
    "content": "@mixin transition($time) {\r\n\t-webkit-transition: all $time ease-out 0s;\r\n\t-moz-transition: all $time ease-out 0s;\r\n\t-ms-transition: all $time ease-out 0s;\r\n\t-o-transition: all $time ease-out 0s;\r\n\ttransition: all $time ease-out 0s;\r\n}\r\n\r\n\r\n@mixin transform($value) {\r\n  -webkit-transform: $value;\r\n     -moz-transform: $value;\r\n      -ms-transform: $value;\r\n       -o-transform: $value;\r\n          transform: $value;\r\n}\r\n\r\n@mixin user-select($value) {\r\n  -webkit-user-select: $value;\r\n     -moz-user-select: $value;\r\n      -ms-user-select: $value;\r\n          user-select: $value;\r\n}\r\n\r\n\r\n@mixin box-sizing($value) {\r\n  -webkit-box-sizing: $value;\r\n     -moz-box-sizing: $value;\r\n          box-sizing: $value;\r\n}\r\n\r\n\r\n@mixin animation($value) {\r\n  -webkit-animation: $value;\r\n     -moz-animation: $value;\r\n       -o-animation: $value;\r\n          animation: $value;\r\n}\r\n\r\n\r\n@mixin animation-delay($value) {\r\n  -webkit-animation-delay: $value;\r\n     -moz-animation-delay: $value;\r\n       -o-animation-delay: $value;\r\n          animation-delay: $value;\r\n}\r\n\r\n\r\n\r\n@mixin box-shadow($value) {\r\n  -webkit-box-shadow: $value;\r\n     -moz-box-shadow: $value;\r\n          box-shadow: $value;\r\n}\r\n\r\n\r\n// Placeholder Mixins\r\n@mixin placeholder {\r\n    &::placeholder { @content; }\r\n    &::-moz-placeholder { @content; }\r\n    &::-moz-placeholder { @content; }\r\n    &::-webkit-input-placeholder { @content; }\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n"
  },
  {
    "path": "assets/scss/_pricing.scss",
    "content": "/* ===== Pricing CSS ===== */\n\n.ud-pricing {\n  padding-top: 120px;\n  padding-bottom: 90px;\n\n  @media #{$xs} {\n    padding-top: 80px;\n    padding-bottom: 40px;\n  }\n}\n\n.ud-single-pricing {\n  margin-bottom: 40px;\n  background: var(--white);\n  border: 2px solid #d4deff;\n  border-radius: 8px;\n  text-align: center;\n  padding: 45px 30px;\n  position: relative;\n\n  &.active {\n    background: linear-gradient(180deg, #3056d3 0%, #179bee 100%);\n    border: none;\n    padding: 55px 30px;\n\n    .ud-pricing-header {\n      h3,\n      h4 {\n        color: var(--white);\n      }\n    }\n    .ud-pricing-body {\n      li {\n        color: var(--white);\n      }\n    }\n  }\n\n  &.first-item::after,\n  &.last-item::after {\n    content: \"\";\n    position: absolute;\n    width: 55px;\n    height: 55px;\n    z-index: 1;\n  }\n\n  &.first-item::after {\n    background: var(--primary-color);\n    left: -2px;\n    bottom: -2px;\n    border-radius: 0px 55px 0px 8px;\n  }\n\n  &.last-item::after {\n    background: #13c296;\n    top: -2px;\n    right: -2px;\n    border-radius: 0px 8px 0px 55px;\n  }\n\n  .ud-popular-tag {\n    display: inline-block;\n    padding: 10px 25px;\n    background: var(--white);\n    border-radius: 30px;\n    color: var(--primary-color);\n    margin-bottom: 20px;\n    font-weight: 600;\n  }\n\n  .ud-pricing-header {\n    h3 {\n      font-weight: 500;\n      font-size: 15px;\n      margin-bottom: 8px;\n    }\n    h4 {\n      font-weight: 600;\n      font-size: 26px;\n      color: var(--primary-color);\n      margin-bottom: 40px;\n    }\n  }\n\n  .ud-pricing-body {\n    margin-bottom: 40px;\n\n    li {\n      font-weight: 500;\n      font-size: 15px;\n      margin-bottom: 18px;\n    }\n  }\n\n  .ud-main-btn {\n    border-radius: 30px;\n    padding: 15px 40px;\n  }\n\n  .ud-border-btn {\n    border: 1px solid #d4deff;\n    color: var(--primary-color);\n    background: var(--white);\n\n    &:hover {\n      color: var(--white);\n      border-color: var(--primary-color);\n      background: var(--primary-color);\n    }\n  }\n  .ud-white-btn {\n    background: var(--white);\n    color: var(--heading-color);\n\n    &:hover {\n      color: var(--white);\n      background: var(--heading-color);\n    }\n  }\n}\n"
  },
  {
    "path": "assets/scss/_team.scss",
    "content": "/* ===== Team CSS ===== */\n.ud-team {\n  padding-top: 120px;\n  padding-bottom: 80px;\n\n  @media #{$xs} {\n    padding-top: 80px;\n    padding-bottom: 40px;\n  }\n}\n\n.ud-single-team {\n  margin-bottom: 40px;\n\n  .ud-team-image-wrapper {\n    width: 170px;\n    height: 170px;\n    position: relative;\n    margin: 0px auto 25px;\n  }\n  .ud-team-image {\n    border-radius: 50%;\n\n    img {\n      width: 100%;\n      border-radius: 50%;\n    }\n  }\n\n  .shape {\n    position: absolute;\n    z-index: -1;\n\n    &.shape-1 {\n      top: 0;\n      left: 0;\n    }\n    &.shape-2 {\n      bottom: 0;\n      right: 0;\n    }\n  }\n\n  .ud-team-info {\n    text-align: center;\n    margin-bottom: 20px;\n\n    h5 {\n      font-weight: 500;\n      font-size: 18px;\n      text-transform: capitalize;\n      margin-bottom: 10px;\n    }\n\n    h6 {\n      font-weight: 500;\n      font-size: 12px;\n      color: var(--body-color);\n    }\n  }\n\n  .ud-team-socials {\n    display: flex;\n    align-items: center;\n    justify-content: center;\n\n    a {\n      width: 32px;\n      height: 32px;\n      display: flex;\n      align-items: center;\n      justify-content: center;\n      margin: 0px 10px;\n      color: #cdced6;\n\n      &:hover {\n        color: var(--primary-color);\n      }\n    }\n  }\n}\n"
  },
  {
    "path": "assets/scss/_testimonials.scss",
    "content": "/* ===== Testimonials CSS ===== */\n.ud-testimonials {\n  padding-top: 120px;\n\n  @media #{$xs} {\n    padding-top: 80px;\n  }\n}\n\n.ud-single-testimonial {\n  padding: 30px;\n  box-shadow: 0px 60px 120px -20px #ebeffd;\n  background: var(--white);\n  margin-bottom: 50px;\n\n  .ud-testimonial-ratings {\n    margin-bottom: 10px;\n\n    i {\n      color: #fbb040;\n    }\n  }\n\n  .ud-testimonial-content {\n    margin-bottom: 25px;\n\n    p {\n      font-size: 16px;\n      line-height: 30px;\n      color: #637381;\n    }\n  }\n\n  .ud-testimonial-info {\n    display: flex;\n    align-items: center;\n\n    .ud-testimonial-image {\n      width: 50px;\n      height: 50px;\n      border-radius: 50%;\n      overflow: hidden;\n      margin-right: 20px;\n    }\n\n    .ud-testimonial-meta {\n      h4 {\n        font-weight: 600;\n        font-size: 14px;\n      }\n\n      p {\n        font-size: 12px;\n        color: #969696;\n      }\n    }\n  }\n}\n\n.ud-brands {\n  .ud-title {\n    margin-bottom: 30px;\n\n    h6 {\n      font-weight: normal;\n      font-size: 12px;\n      color: var(--body-color);\n      display: inline-block;\n      position: relative;\n\n      &::after {\n        content: \"\";\n        position: absolute;\n        width: 30px;\n        height: 1px;\n        background: #afb2b5;\n        right: -40px;\n        top: 50%;\n      }\n    }\n  }\n\n  .ud-brands-logo {\n    display: flex;\n    align-items: center;\n    flex-wrap: wrap;\n    margin-right: -40px;\n\n    .ud-single-logo {\n      margin-right: 40px;\n      margin-bottom: 20px;\n      max-width: 140px;\n\n      &:hover {\n        img {\n          filter: none;\n        }\n      }\n\n      img {\n        filter: grayscale(1);\n        @include transition(0.3s);\n      }\n    }\n  }\n}"
  },
  {
    "path": "assets/scss/_variables.scss",
    "content": "// Responsive Variables\r\n$xl-desktop: \"only screen and (min-width: 1921px)\";\r\n$desktop: \"only screen and (min-width: 1400px) and (max-width: 1920px)\";\r\n$laptop: \"only screen and (min-width: 1200px) and (max-width: 1399px)\";\r\n$lg: \"only screen and (min-width: 992px) and (max-width: 1199px)\";\r\n$md: \"only screen and (min-width: 768px) and (max-width: 991px)\";\r\n$xs: \"(max-width: 767px)\";\r\n$sm: \"only screen and (min-width: 576px) and (max-width: 767px)\";\r\n"
  },
  {
    "path": "assets/scss/ud-styles.scss",
    "content": "/* =======\r\n\r\n\tTemplate Name: Play Bootstrap\r\n\tAuthor: UIdeck\r\n\tAuthor URI: https://uideck.com/\r\n\tSupport: https://github.com/uideck/\r\n\tVersion: 1.0\r\n\r\n======== */\r\n\r\n@import \"variables\";\r\n@import \"mixin\";\r\n@import \"common\";\r\n@import \"header\";\r\n@import \"hero\";\r\n@import \"features\";\r\n@import \"about\";\r\n@import \"pricing\";\r\n@import \"faq\";\r\n@import \"testimonials\";\r\n@import \"team\";\r\n@import \"contact\";\r\n@import \"footer\";\r\n@import \"banner\";\r\n@import \"login\";\r\n@import \"blog\";\r\n@import \"blog-details\";\r\n@import \"404\";\r\n// @import \"default\";\r\n"
  },
  {
    "path": "blog-details.html",
    "content": "<!-- =========\n\n\tTemplate Name: Play\n\tAuthor: UIdeck\n\tAuthor URI: https://uideck.com/\n\tSupport: https://uideck.com/support/\n\tVersion: 1.1\n\n========== -->\n\n<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"UTF-8\" />\n    <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n    <title>Play | Open source Project by UIdeck</title>\n\n    <!--====== Favicon Icon ======-->\n    <link\n      rel=\"shortcut icon\"\n      href=\"assets/images/favicon.svg\"\n      type=\"image/svg\"\n    />\n\n    <!-- ===== All CSS files ===== -->\n    <link rel=\"stylesheet\" href=\"assets/css/bootstrap.min.css\" />\n    <link rel=\"stylesheet\" href=\"assets/css/animate.css\" />\n    <link rel=\"stylesheet\" href=\"assets/css/lineicons.css\" />\n    <link rel=\"stylesheet\" href=\"assets/css/ud-styles.css\" />\n  </head>\n  <body>\n    <!-- ====== Header Start ====== -->\n    <header class=\"ud-header\">\n      <div class=\"container\">\n        <div class=\"row\">\n          <div class=\"col-lg-12\">\n            <nav class=\"navbar navbar-expand-lg\">\n              <a class=\"navbar-brand\" href=\"index.html\">\n                <img src=\"assets/images/logo/logo.svg\" alt=\"Logo\" />\n              </a>\n              <button class=\"navbar-toggler\">\n                <span class=\"toggler-icon\"> </span>\n                <span class=\"toggler-icon\"> </span>\n                <span class=\"toggler-icon\"> </span>\n              </button>\n\n              <div class=\"navbar-collapse\">\n                <ul id=\"nav\" class=\"navbar-nav mx-auto\">\n                  <li class=\"nav-item\">\n                    <a class=\"ud-menu-scroll\" href=\"#home\">Home</a>\n                  </li>\n\n                  <li class=\"nav-item\">\n                    <a class=\"ud-menu-scroll\" href=\"#about\">About</a>\n                  </li>\n                  <li class=\"nav-item\">\n                    <a class=\"ud-menu-scroll\" href=\"#pricing\">Pricing</a>\n                  </li>\n                  <li class=\"nav-item\">\n                    <a class=\"ud-menu-scroll\" href=\"#team\">Team</a>\n                  </li>\n                  <li class=\"nav-item\">\n                    <a class=\"ud-menu-scroll\" href=\"#contact\">Contact</a>\n                  </li>\n                  <li class=\"nav-item nav-item-has-children\">\n                    <a href=\"javascript:void(0)\"> Pages </a>\n                    <ul class=\"ud-submenu\">\n                      <li class=\"ud-submenu-item\">\n                        <a href=\"about.html\" class=\"ud-submenu-link\">\n                          About Page\n                        </a>\n                      </li>\n                      <li class=\"ud-submenu-item\">\n                        <a href=\"pricing.html\" class=\"ud-submenu-link\">\n                          Pricing Page\n                        </a>\n                      </li>\n                      <li class=\"ud-submenu-item\">\n                        <a href=\"contact.html\" class=\"ud-submenu-link\">\n                          Contact Page\n                        </a>\n                      </li>\n                      <li class=\"ud-submenu-item\">\n                        <a href=\"blog.html\" class=\"ud-submenu-link\">\n                          Blog Grid Page\n                        </a>\n                      </li>\n                      <li class=\"ud-submenu-item\">\n                        <a href=\"blog-details.html\" class=\"ud-submenu-link\">\n                          Blog Details Page\n                        </a>\n                      </li>\n                      <li class=\"ud-submenu-item\">\n                        <a href=\"login.html\" class=\"ud-submenu-link\">\n                          Sign In Page\n                        </a>\n                      </li>\n                      <li class=\"ud-submenu-item\">\n                        <a href=\"404.html\" class=\"ud-submenu-link\">404 Page</a>\n                      </li>\n                    </ul>\n                  </li>\n                </ul>\n              </div>\n\n              <div class=\"navbar-btn d-none d-sm-inline-block\">\n                <a href=\"login.html\" class=\"ud-main-btn ud-login-btn\">\n                  Sign In\n                </a>\n                <a class=\"ud-main-btn ud-white-btn\" href=\"javascript:void(0)\">\n                  Sign Up\n                </a>\n              </div>\n            </nav>\n          </div>\n        </div>\n      </div>\n    </header>\n    <!-- ====== Header End ====== -->\n\n    <!-- ====== Banner Start ====== -->\n    <section class=\"ud-page-banner\">\n      <div class=\"container\">\n        <div class=\"row\">\n          <div class=\"col-lg-12\">\n            <div class=\"ud-banner-content\">\n              <h1>Blog Page</h1>\n            </div>\n          </div>\n        </div>\n      </div>\n    </section>\n    <!-- ====== Banner End ====== -->\n\n    <!-- ====== Blog Details Start ====== -->\n    <section class=\"ud-blog-details\">\n      <div class=\"container\">\n        <div class=\"row\">\n          <div class=\"col-lg-12\">\n            <div class=\"ud-blog-details-image\">\n              <img\n                src=\"assets/images/blog/blog-details-01.jpg\"\n                alt=\"blog details\"\n              />\n              <div class=\"ud-blog-overlay\">\n                <div class=\"ud-blog-overlay-content\">\n                  <div class=\"ud-blog-author\">\n                    <img src=\"assets/images/blog/author-01.png\" alt=\"author\" />\n                    <span>\n                      By <a href=\"javascript:void(0)\"> Samuyl Joshi </a>\n                    </span>\n                  </div>\n\n                  <div class=\"ud-blog-meta\">\n                    <p class=\"date\">\n                      <i class=\"lni lni-calendar\"></i> <span>12 Jan 2024</span>\n                    </p>\n                    <p class=\"comment\">\n                      <i class=\"lni lni-comments\"></i> <span>50</span>\n                    </p>\n                    <p class=\"view\">\n                      <i class=\"lni lni-eye\"></i> <span>35</span>\n                    </p>\n                  </div>\n                </div>\n              </div>\n            </div>\n          </div>\n\n          <div class=\"col-lg-8\">\n            <div class=\"ud-blog-details-content\">\n              <h2 class=\"ud-blog-details-title\">\n                Facing a challenge is kind of a turn-on for an easy rider\n              </h2>\n              <p class=\"ud-blog-details-para\">\n                There’s a time and place for everything… including asking for\n                reviews. For instance: you should not asking for a review on\n                your checkout page. The sole purpose of this page is to guide\n                your customer to complete their purchase, and this means that\n                the page should be as minimalist and pared-down possible. You\n                don’t want to have any unnecessary elements or Call To Actions.\n              </p>\n              <p class=\"ud-blog-details-para\">\n                There’s a time and place for everything… including asking for\n                reviews. For instance: you should not asking for a review on\n                your checkout page. The sole purpose of this page is to guide\n                your customer to complete their purchase, and this means that\n                the page should be as minimalist and pared-down possible. You\n                don’t want to have any unnecessary elements or Call To Actions.\n              </p>\n              <h3 class=\"ud-blog-details-subtitle\">Sea no quidam vulputate</h3>\n              <p class=\"ud-blog-details-para\">\n                At quo cetero fastidii. Usu ex ornatus corpora sententiae,\n                vocibus deleniti ut nec. Ut enim eripuit eligendi est, in\n                iracundia signiferumque quo. Sed virtute suavitate suscipiantur\n                ea, dolor this can eloquentiam ei pro. Suas adversarium\n                interpretaris eu sit, eum viris impedit ne. Erant appareat\n                corrumpit ei vel.\n              </p>\n\n              <div class=\"ud-blog-quote\">\n                <i class=\"lni lni-quotation\"></i>\n                <p>\n                  A spring of truth shall flow from it: like a new star it shall\n                  scatter the darkness of ignorance, and cause a light\n                  heretofore unknown to shine amongst men.\n                </p>\n                <h6>“Andrio Domeco”</h6>\n              </div>\n              <h3 class=\"ud-blog-details-subtitle\">\n                What is it with your ideas?\n              </h3>\n              <p class=\"ud-blog-details-para\">\n                At quo cetero fastidii. Usu ex ornatus corpora sententiae,\n                vocibus deleniti ut nec. Ut enim eripuit eligendi est, in\n                iracundia signiferumque quo. Sed virtute suavitate suscipiantur\n                ea, dolor this can eloquentiam ei pro. Suas adversarium\n                interpretaris eu sit, eum viris impedit ne. Erant appareat\n                corrumpit ei vel.\n              </p>\n              <p class=\"ud-blog-details-para\">\n                At quo cetero fastidii. Usu ex ornatus corpora sententiae,\n                vocibus deleniti ut nec. Ut enim eripuit eligendi est, in\n                iracundia signiferumque quo. Sed virtute suavitate suscipiantur\n                ea, dolor this can eloquentiam ei pro. Suas adversarium\n                interpretaris eu sit, eum viris impedit ne. Erant appareat\n                corrumpit ei vel.\n              </p>\n\n              <div class=\"ud-blog-details-action\">\n                <ul class=\"ud-blog-tags\">\n                  <li>\n                    <a href=\"javascript:void(0)\">Design</a>\n                  </li>\n                  <li>\n                    <a href=\"javascript:void(0)\">Development</a>\n                  </li>\n                  <li>\n                    <a href=\"javascript:void(0)\">Info</a>\n                  </li>\n                </ul>\n                <div class=\"ud-blog-share\">\n                  <h6>Share This Post</h6>\n                  <ul class=\"ud-blog-share-links\">\n                    <li>\n                      <a href=\"javascript:void(0)\" class=\"facebook\">\n                        <i class=\"lni lni-facebook-filled\"></i>\n                      </a>\n                    </li>\n                    <li>\n                      <a href=\"javascript:void(0)\" class=\"twitter\">\n                        <i class=\"lni lni-twitter-filled\"></i>\n                      </a>\n                    </li>\n                    <li>\n                      <a href=\"javascript:void(0)\" class=\"linkedin\">\n                        <i class=\"lni lni-linkedin-original\"></i>\n                      </a>\n                    </li>\n                  </ul>\n                </div>\n              </div>\n            </div>\n          </div>\n          <div class=\"col-lg-4\">\n            <div class=\"ud-blog-sidebar\">\n              <div class=\"ud-newsletter-box\">\n                <img\n                  src=\"assets/images/blog/dotted-shape.svg\"\n                  alt=\"shape\"\n                  class=\"shape shape-1\"\n                />\n                <img\n                  src=\"assets/images/blog/dotted-shape.svg\"\n                  alt=\"shape\"\n                  class=\"shape shape-2\"\n                />\n                <h3 class=\"ud-newsletter-title\">Join our newsletter!</h3>\n                <p>Enter your email to receive our latest newsletter.</p>\n                <form class=\"ud-newsletter-form\">\n                  <input\n                    type=\"email\"\n                    name=\"email\"\n                    placeholder=\"Your Email address\"\n                  />\n                  <button class=\"ud-main-btn\">Subscribe Now</button>\n                  <p class=\"ud-newsletter-note\">Don't worry, we don't spam</p>\n                </form>\n              </div>\n\n              <div class=\"ud-articles-box\">\n                <h3 class=\"ud-articles-box-title\">Popular Articles</h3>\n                <ul class=\"ud-articles-list\">\n                  <li>\n                    <div class=\"ud-article-image\">\n                      <img\n                        src=\"assets/images/blog/article-author-01.png\"\n                        alt=\"author\"\n                      />\n                    </div>\n                    <div class=\"ud-article-content\">\n                      <h5 class=\"ud-article-title\">\n                        <a href=\"javascript:void(0)\">\n                          The 8 best landing page builders, reviewed\n                        </a>\n                      </h5>\n                      <p class=\"ud-article-author\">Martin Fedous</p>\n                    </div>\n                  </li>\n                  <li>\n                    <div class=\"ud-article-image\">\n                      <img\n                        src=\"assets/images/blog/article-author-02.png\"\n                        alt=\"author\"\n                      />\n                    </div>\n                    <div class=\"ud-article-content\">\n                      <h5 class=\"ud-article-title\">\n                        <a href=\"javascript:void(0)\">\n                          Create engaging online courses your student…\n                        </a>\n                      </h5>\n                      <p class=\"ud-article-author\">Glomiya Lucy</p>\n                    </div>\n                  </li>\n                  <li>\n                    <div class=\"ud-article-image\">\n                      <img\n                        src=\"assets/images/blog/article-author-03.png\"\n                        alt=\"author\"\n                      />\n                    </div>\n                    <div class=\"ud-article-content\">\n                      <h5 class=\"ud-article-title\">\n                        <a href=\"javascript:void(0)\">\n                          The ultimate formula for launching online course\n                        </a>\n                      </h5>\n                      <p class=\"ud-article-author\">Andrio jeson</p>\n                    </div>\n                  </li>\n                  <li>\n                    <div class=\"ud-article-image\">\n                      <img\n                        src=\"assets/images/blog/article-author-04.png\"\n                        alt=\"author\"\n                      />\n                    </div>\n                    <div class=\"ud-article-content\">\n                      <h5 class=\"ud-article-title\">\n                        <a href=\"javascript:void(0)\">\n                          50 Best web design tips & tricks that will help you\n                        </a>\n                      </h5>\n                      <p class=\"ud-article-author\">Samoyel Dayno</p>\n                    </div>\n                  </li>\n                </ul>\n              </div>\n\n              <div class=\"ud-banner-ad\">\n                <a href=\"javascript:void(0)\">\n                  <img\n                    src=\"assets/images/blog/bannder-ad.png\"\n                    alt=\"ad banner\"\n                  />\n                </a>\n              </div>\n            </div>\n          </div>\n        </div>\n      </div>\n    </section>\n    <!-- ====== Blog Details End ====== -->\n\n    <!-- ====== Blog Start ====== -->\n    <section class=\"ud-blog-grids ud-related-articles\">\n      <div class=\"container\">\n        <div class=\"row col-lg-12\">\n          <div class=\"ud-related-title\">\n            <h2 class=\"ud-related-articles-title\">Related Articles</h2>\n          </div>\n        </div>\n        <div class=\"row\">\n          <div class=\"col-lg-4 col-md-6\">\n            <div class=\"ud-single-blog\">\n              <div class=\"ud-blog-image\">\n                <a href=\"blog-details.html\">\n                  <img src=\"assets/images/blog/blog-01.jpg\" alt=\"blog\" />\n                </a>\n              </div>\n              <div class=\"ud-blog-content\">\n                <span class=\"ud-blog-date\">Dec 22, 2023</span>\n                <h3 class=\"ud-blog-title\">\n                  <a href=\"blog-details.html\">\n                    Meet AutoManage, the best AI management tools\n                  </a>\n                </h3>\n                <p class=\"ud-blog-desc\">\n                  Lorem Ipsum is simply dummy text of the printing and\n                  typesetting industry.\n                </p>\n              </div>\n            </div>\n          </div>\n          <div class=\"col-lg-4 col-md-6\">\n            <div class=\"ud-single-blog\">\n              <div class=\"ud-blog-image\">\n                <a href=\"blog-details.html\">\n                  <img src=\"assets/images/blog/blog-02.jpg\" alt=\"blog\" />\n                </a>\n              </div>\n              <div class=\"ud-blog-content\">\n                <span class=\"ud-blog-date\">Dec 22, 2023</span>\n                <h3 class=\"ud-blog-title\">\n                  <a href=\"blog-details.html\">\n                    How to earn more money as a wellness coach\n                  </a>\n                </h3>\n                <p class=\"ud-blog-desc\">\n                  Lorem Ipsum is simply dummy text of the printing and\n                  typesetting industry.\n                </p>\n              </div>\n            </div>\n          </div>\n          <div class=\"col-lg-4 col-md-6\">\n            <div class=\"ud-single-blog\">\n              <div class=\"ud-blog-image\">\n                <a href=\"blog-details.html\">\n                  <img src=\"assets/images/blog/blog-03.jpg\" alt=\"blog\" />\n                </a>\n              </div>\n              <div class=\"ud-blog-content\">\n                <span class=\"ud-blog-date\">Dec 22, 2023</span>\n                <h3 class=\"ud-blog-title\">\n                  <a href=\"blog-details.html\">\n                    The no-fuss guide to upselling and cross selling\n                  </a>\n                </h3>\n                <p class=\"ud-blog-desc\">\n                  Lorem Ipsum is simply dummy text of the printing and\n                  typesetting industry.\n                </p>\n              </div>\n            </div>\n          </div>\n        </div>\n      </div>\n    </section>\n    <!-- ====== Blog End ====== -->\n\n    <!-- ====== Footer Start ====== -->\n    <footer class=\"ud-footer wow fadeInUp\" data-wow-delay=\".15s\">\n      <div class=\"shape shape-1\">\n        <img src=\"assets/images/footer/shape-1.svg\" alt=\"shape\" />\n      </div>\n      <div class=\"shape shape-2\">\n        <img src=\"assets/images/footer/shape-2.svg\" alt=\"shape\" />\n      </div>\n      <div class=\"shape shape-3\">\n        <img src=\"assets/images/footer/shape-3.svg\" alt=\"shape\" />\n      </div>\n      <div class=\"ud-footer-widgets\">\n        <div class=\"container\">\n          <div class=\"row\">\n            <div class=\"col-xl-3 col-lg-4 col-md-6\">\n              <div class=\"ud-widget\">\n                <a href=\"index.html\" class=\"ud-footer-logo\">\n                  <img src=\"assets/images/logo/logo.svg\" alt=\"logo\" />\n                </a>\n                <p class=\"ud-widget-desc\">\n                  We create digital experiences for brands and companies by\n                  using technology.\n                </p>\n                <ul class=\"ud-widget-socials\">\n                  <li>\n                    <a href=\"https://twitter.com/MusharofChy\">\n                      <i class=\"lni lni-facebook-filled\"></i>\n                    </a>\n                  </li>\n                  <li>\n                    <a href=\"https://twitter.com/MusharofChy\">\n                      <i class=\"lni lni-twitter-filled\"></i>\n                    </a>\n                  </li>\n                  <li>\n                    <a href=\"https://twitter.com/MusharofChy\">\n                      <i class=\"lni lni-instagram-filled\"></i>\n                    </a>\n                  </li>\n                  <li>\n                    <a href=\"https://twitter.com/MusharofChy\">\n                      <i class=\"lni lni-linkedin-original\"></i>\n                    </a>\n                  </li>\n                </ul>\n              </div>\n            </div>\n\n            <div class=\"col-xl-2 col-lg-2 col-md-6 col-sm-6\">\n              <div class=\"ud-widget\">\n                <h5 class=\"ud-widget-title\">About Us</h5>\n                <ul class=\"ud-widget-links\">\n                  <li>\n                    <a href=\"javascript:void(0)\">Home</a>\n                  </li>\n                  <li>\n                    <a href=\"javascript:void(0)\">Features</a>\n                  </li>\n                  <li>\n                    <a href=\"javascript:void(0)\">About</a>\n                  </li>\n                  <li>\n                    <a href=\"javascript:void(0)\">Testimonial</a>\n                  </li>\n                </ul>\n              </div>\n            </div>\n            <div class=\"col-xl-2 col-lg-3 col-md-6 col-sm-6\">\n              <div class=\"ud-widget\">\n                <h5 class=\"ud-widget-title\">Features</h5>\n                <ul class=\"ud-widget-links\">\n                  <li>\n                    <a href=\"javascript:void(0)\">How it works</a>\n                  </li>\n                  <li>\n                    <a href=\"javascript:void(0)\">Privacy policy</a>\n                  </li>\n                  <li>\n                    <a href=\"javascript:void(0)\">Terms of service</a>\n                  </li>\n                  <li>\n                    <a href=\"javascript:void(0)\">Refund policy</a>\n                  </li>\n                </ul>\n              </div>\n            </div>\n            <div class=\"col-xl-2 col-lg-3 col-md-6 col-sm-6\">\n              <div class=\"ud-widget\">\n                <h5 class=\"ud-widget-title\">Our Products</h5>\n                <ul class=\"ud-widget-links\">\n                  <li>\n                    <a\n                      href=\"https://lineicons.com/\"\n                      rel=\"nofollow noopner\"\n                      target=\"_blank\"\n                      >Lineicons\n                    </a>\n                  </li>\n                  <li>\n                    <a\n                      href=\"https://ecommercehtml.com/\"\n                      rel=\"nofollow noopner\"\n                      target=\"_blank\"\n                      >Ecommerce HTML</a\n                    >\n                  </li>\n                  <li>\n                    <a\n                      href=\"https://ayroui.com/\"\n                      rel=\"nofollow noopner\"\n                      target=\"_blank\"\n                      >Ayro UI</a\n                    >\n                  </li>\n                  <li>\n                    <a\n                      href=\"https://graygrids.com/\"\n                      rel=\"nofollow noopner\"\n                      target=\"_blank\"\n                      >Plain Admin</a\n                    >\n                  </li>\n                </ul>\n              </div>\n            </div>\n            <div class=\"col-xl-3 col-lg-6 col-md-8 col-sm-10\">\n              <div class=\"ud-widget\">\n                <h5 class=\"ud-widget-title\">Partners</h5>\n                <ul class=\"ud-widget-brands\">\n                  <li>\n                    <a\n                      href=\"https://ayroui.com/\"\n                      rel=\"nofollow noopner\"\n                      target=\"_blank\"\n                    >\n                      <img\n                        src=\"assets/images/footer/brands/ayroui.svg\"\n                        alt=\"ayroui\"\n                      />\n                    </a>\n                  </li>\n                  <li>\n                    <a\n                      href=\"https://ecommercehtml.com/\"\n                      rel=\"nofollow noopner\"\n                      target=\"_blank\"\n                    >\n                      <img\n                        src=\"assets/images/footer/brands/ecommerce-html.svg\"\n                        alt=\"ecommerce-html\"\n                      />\n                    </a>\n                  </li>\n                  <li>\n                    <a\n                      href=\"https://graygrids.com/\"\n                      rel=\"nofollow noopner\"\n                      target=\"_blank\"\n                    >\n                      <img\n                        src=\"assets/images/footer/brands/graygrids.svg\"\n                        alt=\"graygrids\"\n                      />\n                    </a>\n                  </li>\n                  <li>\n                    <a\n                      href=\"https://lineicons.com/\"\n                      rel=\"nofollow noopner\"\n                      target=\"_blank\"\n                    >\n                      <img\n                        src=\"assets/images/footer/brands/lineicons.svg\"\n                        alt=\"lineicons\"\n                      />\n                    </a>\n                  </li>\n                  <li>\n                    <a\n                      href=\"https://uideck.com/\"\n                      rel=\"nofollow noopner\"\n                      target=\"_blank\"\n                    >\n                      <img\n                        src=\"assets/images/footer/brands/uideck.svg\"\n                        alt=\"uideck\"\n                      />\n                    </a>\n                  </li>\n                  <li>\n                    <a\n                      href=\"https://tailwindtemplates.co/\"\n                      rel=\"nofollow noopner\"\n                      target=\"_blank\"\n                    >\n                      <img\n                        src=\"assets/images/footer/brands/tailwindtemplates.svg\"\n                        alt=\"tailwindtemplates\"\n                      />\n                    </a>\n                  </li>\n                </ul>\n              </div>\n            </div>\n          </div>\n        </div>\n      </div>\n      <div class=\"ud-footer-bottom\">\n        <div class=\"container\">\n          <div class=\"row\">\n            <div class=\"col-md-8\">\n              <ul class=\"ud-footer-bottom-left\">\n                <li>\n                  <a href=\"javascript:void(0)\">Privacy policy</a>\n                </li>\n                <li>\n                  <a href=\"javascript:void(0)\">Support policy</a>\n                </li>\n                <li>\n                  <a href=\"javascript:void(0)\">Terms of service</a>\n                </li>\n              </ul>\n            </div>\n            <div class=\"col-md-4\">\n              <p class=\"ud-footer-bottom-right\">\n                Designed and Developed by\n                <a href=\"https://uideck.com\" rel=\"nofollow\">UIdeck</a>\n              </p>\n            </div>\n          </div>\n        </div>\n      </div>\n    </footer>\n    <!-- ====== Footer End ====== -->\n\n    <!-- ====== Back To Top Start ====== -->\n    <a href=\"javascript:void(0)\" class=\"back-to-top\">\n      <i class=\"lni lni-chevron-up\"> </i>\n    </a>\n    <!-- ====== Back To Top End ====== -->\n\n    <!-- ====== All Javascript Files ====== -->\n    <script src=\"assets/js/bootstrap.bundle.min.js\"></script>\n    <script src=\"assets/js/wow.min.js\"></script>\n    <script src=\"assets/js/main.js\"></script>\n  </body>\n</html>\n"
  },
  {
    "path": "google-cloud-ace-resources.md",
    "content": "---\nlayout: resources\ntitle: Google Cloud Associate Cloud Engineer - Resources\nresources:\n  - title: Download PDF - Slides\n    description: Download the slides and have them ready.\n    url: 'https://github.com/in28minutes/course-material/raw/main/09-google-certified-associate-cloud-engineer/CoursePresentation-GoogleCertifiedAssociateCloudEngineer.pdf'\n  - title: Download Code Examples\n    description: Download and have this ready. We will use the code examples during the course.\n    url: 'https://github.com/in28minutes/course-material/raw/main/09-google-certified-associate-cloud-engineer/course-downloads.zip'\n  - title: LinkedIn Newsletter\n    description: Read in28minutes Newsletter. Published on LinkedIn.\n    icon: lni-linkedin\n    url: 'https://www.linkedin.com/newsletters/6978624731038023681/'\n---"
  },
  {
    "path": "google-cloud-cdl-resources.md",
    "content": "---\nlayout: resources\ntitle: Google Cloud Digital Leader - Resources\nresources:\n  - title: Download PDF - Slides\n    description: Download the slides and have them ready.\n    url: 'https://github.com/in28minutes/course-material/raw/main/15-google-cloud-digital-leader/Course-Presentation-GoogleCloudDigitalLeader.pdf'\n  - title: Download Code Examples\n    description: Download and have this ready. We will use the code examples during the course.\n    url: 'https://github.com/in28minutes/course-material/raw/main/15-google-cloud-digital-leader/downloads.zip'\n  - title: LinkedIn Newsletter\n    description: Read in28minutes Newsletter. Published on LinkedIn.\n    icon: lni-linkedin\n    url: 'https://www.linkedin.com/newsletters/6978624731038023681/'\n---"
  },
  {
    "path": "index.md",
    "content": "---\nlayout: home\n\n# Header\nheader:\n  title: 1 Million Learners - Cloud, DevOps and Microservices\n  description: 7 Amazing Roadmaps - ZERO to EXPERT\n  image:\n  main_button:\n    title: Start learning\n    url: https://www.in28minutes.com/roadmaps\n  secondary_button:\n    title: Watch on YouTube\n    url: https://www.youtube.com/user/rithustutorials/videos\n\n# Features\nfeatures:\n  title: Take your first step into Cloud and DevOps\n  description: Join 1 MILLION learners\n  items:\n    - title: Cloud Roadmaps\n      description: Get started with AWS, Azure and Google Cloud\n      icon: lni-layout\n    - title: DevOps Roadmaps\n      description: Get started with Docker, Kubernetes and Terraform\n      icon: lni-layout\n    - title: Spring Boot Roadmaps\n      description: Learn Java, Spring Boot, Microservices and Full Stack development\n      icon: lni-layout\n    - title: Hands-on courses designed for absolute beginners\n      description: 50+ Course with almost 250,000+ reviews\n      icon: lni-layout\n\n# About\nabout:\n  title: YOUR FIRST STEP into Programming, Cloud & DevOps\n  description: Ranga Karanam, the founder of in28minutes, has 2 decades of experience with technology - architecture, design, and programming.  We are helping learners take their first steps into modern cloud native technology and gain expertise on AWS, Azure, Google Cloud, Docker, Kubernetes amongst others.\n\n# FAQ\nfaq:\n  title: FAQ\n  description: There are many variations of passages of Lorem Ipsum available but the majority have suffered alteration in some form.\n  items:\n    - title: How to use UIdeck?\n      description: Lorem Ipsum is simply dummy text of the printing and\n        typesetting industry. Lorem Ipsum has been the industry's\n        standard dummy text ever since the 1500s, when an unknown\n        printer took a galley of type and scrambled it to make a\n        type specimen book.\n    - title: How to use UIdeck?\n      description: Lorem Ipsum is simply dummy text of the printing and\n        typesetting industry. Lorem Ipsum has been the industry's\n        standard dummy text ever since the 1500s, when an unknown\n        printer took a galley of type and scrambled it to make a\n        type specimen book.\n    - title: How to use UIdeck?\n      description: Lorem Ipsum is simply dummy text of the printing and\n        typesetting industry. Lorem Ipsum has been the industry's\n        standard dummy text ever since the 1500s, when an unknown\n        printer took a galley of type and scrambled it to make a\n        type specimen book.\n    - title: How to use UIdeck?\n      description: Lorem Ipsum is simply dummy text of the printing and\n        typesetting industry. Lorem Ipsum has been the industry's\n        standard dummy text ever since the 1500s, when an unknown\n        printer took a galley of type and scrambled it to make a\n        type specimen book.\n\n# Testimonials\ntestimonials:\n  title: What our students say\n  description: Lots of love from our learners\n  items:\n    - name: Learner - AZ-900 Microsoft Azure Fundamentals in a Weekend\n      comment: Get certified quickly without even looking for other resources. Just watch videos for 2 days and appeared for the exam and cleared the exam.\n    - name: Learner - AWS Certified Cloud Practitioner - AWS Certification\n      comment: Awesome course to get started with AWS. I have started with ZERO AWS knowledge and now I am familiar and confident to talk in AWS terminology. THANK YOU Ranga !!!!\n    - name: Learner -  Master Microservices with Spring Boot and Spring Cloud\n      comment: My respect and admiration for you as a teacher cannot be expressed in words. You did amazing job with full of responsibility. Thank you for the gift I felt I climbed several ladder as a programmer when I completed you great course. Thank you countless time!!\n---\n"
  }
]