Friday 20 September 2019

Setting up the application to work with RestTemplate


Step 1: Create new maven project ‘springInMemoryApp’.

Step 2: Update pom.xml with maven dependencies.

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>springInMemoryApp</groupId>
  <artifactId>springInMemoryApp</artifactId>
  <version>1</version>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.6.RELEASE</version>
  </parent>

  <name>springbootApp</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
  </dependencies>
</project>

Step 3: Create a package ‘com.sample.app.model’ and define Employee class like below.


Employee.java
package com.sample.app.model;

public class Employee {

  private int id;
  private String firstName;
  private String lastName;

  public Employee() {
  }

  public Employee(int id, String firstName, String lastName) {
    this.id = id;
    this.firstName = firstName;
    this.lastName = lastName;
  }

  public int getId() {
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }

  public String getFirstName() {
    return firstName;
  }

  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }

  public String getLastName() {
    return lastName;
  }

  public void setLastName(String lastName) {
    this.lastName = lastName;
  }

  @Override
  public String toString() {
    return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + "]";
  }

}

Step 4: Create a package ‘com.sample.app.util’ and define EmployeeUtil.java.

EmployeeUtil.java
package com.sample.app.util;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import com.sample.app.model.Employee;

public class EmployeeUtil {

  private static int idCounter = 1;

  private static final Map<Integer, Employee> employeesRepo = new HashMap<>();

  private static Employee buildEmployee(String firstName, String lastName) {
    Employee emp = new Employee();
    emp.setId(idCounter);
    emp.setFirstName(firstName);
    emp.setLastName(lastName);

    idCounter++;

    return emp;
  }

  static {
    Employee emp1 = buildEmployee("Deepak", "Moud");
    Employee emp2 = buildEmployee("Srinivasa Rao", "Gumma");
    Employee emp3 = buildEmployee("Purna Chandra", "Rao");
    Employee emp4 = buildEmployee("Madhavi Latha", "Gumma");
    Employee emp5 = buildEmployee("Raghava", "Reddy");

    employeesRepo.put(emp1.getId(), emp1);
    employeesRepo.put(emp2.getId(), emp2);
    employeesRepo.put(emp3.getId(), emp3);
    employeesRepo.put(emp4.getId(), emp4);
    employeesRepo.put(emp5.getId(), emp5);

  }

  public static Collection<Employee> all() {
    return employeesRepo.values();
  }

  public static Employee byId(int id) {
    return employeesRepo.get(id);
  }

  public static Employee create(String firstName, String lastName) {
    Employee emp = buildEmployee(firstName, lastName);
    employeesRepo.put(emp.getId(), emp);
    return emp;
  }

  public static Employee create(Employee emp) {
    return create(emp.getFirstName(), emp.getLastName());
  }

  public static Employee delete(int id) {
    return employeesRepo.remove(id);
  }

  public static Employee updateById(int id, Employee emp) {
    emp.setId(id);
    return employeesRepo.put(id, emp);
  }
}

Step 5: Create com.sample.app.controller package and define EmployeeController like below.


EmployeeController.java
package com.sample.app.controller;

import java.util.Collection;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.sample.app.model.Employee;
import com.sample.app.util.EmployeeUtil;

@RestController
@RequestMapping("api/v1/")
public class EmployeeController {

  @RequestMapping(value = "employees", method = RequestMethod.GET)
  public ResponseEntity<Collection<Employee>> all() {
    return ResponseEntity.ok(EmployeeUtil.all());
  }

  @RequestMapping(value = "employees", method = RequestMethod.POST)
  public ResponseEntity<Employee> create(@RequestBody Employee emp) {
    return new ResponseEntity<>(EmployeeUtil.create(emp), HttpStatus.CREATED);

  }

  @RequestMapping(value = "employees/{id}", method = RequestMethod.GET)
  public ResponseEntity<Employee> byId(@PathVariable int id) {
    Employee emp = EmployeeUtil.byId(id);

    if (emp == null) {
      return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }

    return ResponseEntity.ok(emp);

  }

  @RequestMapping(value = "employees/{id}", method = RequestMethod.DELETE)
  public ResponseEntity<Employee> deleteById(@PathVariable int id) {
    Employee emp = EmployeeUtil.byId(id);

    if (emp == null) {
      return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }

    return ResponseEntity.ok(EmployeeUtil.delete(id));
  }

  @RequestMapping(value = "employees/{id}", method = RequestMethod.PUT)
  public ResponseEntity<Employee> updateById(@PathVariable int id, @RequestBody Employee emp) {

    Employee currentEmp = EmployeeUtil.byId(id);

    if (currentEmp == null) {
      return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }

    return ResponseEntity.ok(EmployeeUtil.updateById(id, emp));
  }

}

Step 6: Define App.java like below.


App.java
package com.sample.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {
  public static void main(String[] args) {
    SpringApplication.run(App.class, args);
  }
}


Total project structure looks like below.

Run App.java.

Open the url ‘http://localhost:8080/api/v1/employees’ in browser, you will get below response.

[{"id":1,"firstName":"Deepak","lastName":"Moud"},{"id":2,"firstName":"Srinivasa Rao","lastName":"Gumma"},{"id":3,"firstName":"Purna Chandra","lastName":"Rao"},{"id":4,"firstName":"Madhavi Latha","lastName":"Gumma"},{"id":5,"firstName":"Raghava","lastName":"Reddy"}]

You can download the complete working application from this link.


Previous                                                    Next                                                    Home

No comments:

Post a Comment