You are on page 1of 25

Spring Boot Hospital List

Problem: Build a REST API to get a list of hospitals

Hospital.java file

package com.example.project;

public class Hospital {
    private int id;
    private String name;
    private String city;
    private double rating;
    
    public Hospital() {
      
    }
    
    public Hospital(int id, String name, String city, double rating) {
      this.id= id;
      this.name= name;
      this.city= city;
      this.rating=rating;
    }
    
  public int getId() {
    return id;
  }
  public void setId(int id) {
    this.id = id;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public String getCity() {
    return city;
  }
  public void setCity(String city) {
    this.city = city;
  }
  public double getRating() {
    return rating;
  }
  public void setRating(double rating) {
    this.rating = rating;
  }

  }

Hospitalcontroller.java file

package com.example.project;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
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.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/test/")

public class HospitalController {

  @Autowired
  private HospitalService hospitalService;
@RequestMapping(value = "/hospitals/{id}", method = RequestMethod.GET)
public @ResponseBody Hospital getHospital(@PathVariable("id") int id) throws Exc
eption{
       Hospital hospital = this.hospitalService.getHospital(id);
       return hospital;
}  

@RequestMapping(value = "/hospitals" , method = RequestMethod.GET)
public @ResponseBody List<Hospital> getAllHospitals() throws Exception{
       return this.hospitalService.getAllHospitals();
}

HospitalService.java

package com.example.project;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class HospitalService {
  
  
  
  private List<Hospital> hospitalList=new ArrayList<>(Arrays.asList(
      new Hospital(1001, "Apollo Hospital", "Chennai", 3.8),
      new Hospital(1002,"Global Hospital","Chennai", 3.5),
      new Hospital(1003,"VCare Hospital","Bangalore", 3)));

public List<Hospital> getAllHospitals(){
  List<Hospital> hospitalList= new ArrayList<Hospital>();
  return hospitalList;
}

public Hospital getHospital(int id){
  return hospitalList.stream().filter(c->c.getId()==(id)).findFirst().get();
}

}
SpringBootApplication.java file

package com.example.project;

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

@SpringBootApplication
public class SpringBoot2Application {

  public static void main(String[] args) {
    SpringApplication.run(SpringBoot2Application.class, args);
  }
}
Spring Boot Database Integration:

Prob: Create a Spring Boot Project, and integrate it with Spring DataJPA using an embedded H2
database.

Step-1: Add Dependency

<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
<dependency>
      <groupId>com.h2database</groupId>
      <artifactId>h2</artifactId>
      <scope>runtime</scope>
    </dependency>

Step-2: integration of App with Spring Data JPA

package com.example.project;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Hospital {
    @Id
    private int id;
    private String name;
    private String city;
    private double rating;
   public Hospital() {
    }
    public Hospital(int id, String name, String city, double rating) {
      this.id= id;
      this.name= name;
      this.city= city;
      this.rating=rating;
    }
  public int getId() {
    return id;
  }
  public void setId(int id) {
    this.id = id;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public String getCity() {
    return city;
  }
  public void setCity(String city) {
    this.city = city;
  }
  public double getRating() {
    return rating;
  }
  public void setRating(double rating) {
    this.rating = rating;
  }
  }

Step-3: Creating HospitalRepository Class

package com.example.project;

import java.util.List;

import org.springframework.data.repository.CrudRepository;

public interface HospitalRepository extends CrudRepository<Hospital,Integer>{
  

Step-4: Edit application.properties file

spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driverClassName=org.h2.Driver
spring.jpa.hibernate.ddl-auto = update
spring.jpa.show-sql=true
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

Step-5: Edit Service file

package com.example.project;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class HospitalService {
@Autowired
private HospitalRepository hospitalRepository;
public List<Hospital> getAllHospitals(){
  List<Hospital> hospitalList= new ArrayList<Hospital>();
  hospitalRepository.findAll().forEach(hospitalList::add);
  return hospitalList;
}
}

Building a Basic Authentication

Prob:3: Spring Security

Step: 1
You need to configure Security dependency in your pom.xml.

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>

Step 2:
Create a 'AuthenticationEntryPoint' class.

@Component
public class AuthenticationEntryPoint extends BasicAuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authEx)
throws IOException, ServletException {
response.addHeader("LoginUser", "Basic " +getRealmName());
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
PrintWriter writer = response.getWriter();
writer.println("HTTP Status 401 - " + authEx.getMessage());
}
@Override
public void afterPropertiesSet() throws Exception {
setRealmName("springboot");
super.afterPropertiesSet();
}
}

Step 3:
Add a 'SpringSecurityConfig' config class to configure authorization.

@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private AuthenticationEntryPoint authEntryPoint;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests()
.anyRequest().authenticated()
.and().httpBasic()
.authenticationEntryPoint(authEntryPoint);
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws
Exception {
auth.inMemoryAuthentication().withUser("username").password("password").roles("USER")
;
}
}

Building REST Service Consumer


Let's try to build a REST service client to consume a simple Google books API.
Step: 1
Let's add an additional dependency to the pom.xml that we used for building REST
services.
This is used for retrieving response entity as a JSON object.

<dependency>

<groupId>org.json</groupId>

<artifactId>json</artifactId>
</dependency>

Step 2: Build a Consumer class.

@SpringBootApplication
public class RestBooksApi {
static RestTemplate restTemplate;

public RestBooksApi(){
restTemplate = new RestTemplate();
}

public static void main(String[] args) {


SpringApplication.run(RestBooksApi.class, args);
try {
JSONObject books=getEntity();
System.out.println(books);
}
catch(Exception e) {
e.printStackTrace();
}
}

/**
* get entity
* @throws JSONException
*/
public static JSONObject getEntity() throws Exception{
JSONObject books = new JSONObject();
String getUrl = "https://www.googleapis.com/books/v1/volumes?
q=isbn:0747532699";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);

HttpEntity<String> entity = new HttpEntity<String>(headers);


ResponseEntity<Map> bookList = restTemplate.exchange(getUrl,
HttpMethod.GET, entity, Map.class);
if (bookList.getStatusCode() == HttpStatus.OK) {
books = new JSONObject(bookList.getBody());
}
return books;
}

Prob: Spring Boot Build a REST API


Build a hospital service which will display the following details:-
Id
Name
City
Rating
-use the id parameter to retrieve data for a specific hospital

-retrieve data for all hospitals

-add new hospitals

-update data for an existing hospital

Delete an existing hospital


HospitalController.java
package com.example.project;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
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.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/test/")
public class HospitalController {

@Autowired
private HospitalService hospitalService;

@GetMapping("hospitals/{id}")
public @ResponseBody Hospital getHospital(@PathVariable("id") int id) throws Exception {
return hospitalService.getHospital(id);

@GetMapping("hospitals/")
public @ResponseBody List<Hospital> getAllHospitals() throws Exception {
return hospitalService.getAllHospitals();

@PostMapping("hospitals/")
public ResponseEntity<String> addHospital(@RequestBody Hospital hospital ) {
hospitalService.addHospital(hospital);
//URI
location=ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(sevedUser.getId()).to
Uri();
return new ResponseEntity<>(HttpStatus.OK);
}

public ResponseEntity<String> updateHospital(@RequestBody Hospital hospital) {


hospitalService.updateHospital(hospital);

return ResponseEntity.ok("ok");
}
@DeleteMapping("hospitals/")
public ResponseEntity<String> deleteHospital(@RequestBody Hospital hospital) {
hospitalService.deleteHospital(hospital);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}

}
HospitalService.java
package com.example.project;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class HospitalService {

@Autowired
private HospitalRepository hospitalRepository;

public List<Hospital> getAllHospitals(){


List<Hospital> hos = new ArrayList<Hospital>();
hospitalRepository.findAll().forEach(hos1 -> hos.add(hos1));
return hos;
}

public Hospital getHospital(int id){

return hospitalRepository.findOne(id);
}

public void addHospital(Hospital hospital){


hospitalRepository.save(hospital);
}

public void updateHospital(Hospital hos){


//if(hospitalRepository.findById(hos.getId()).isPresent())
// {
// Hospital hospital=hospitalRepository.findById(hos.getId()).get();
// hospital.setName(hos.getName());
// hospital.setCity(hos.getCity());
// hospital.setRating(hos.getRating());
hospitalRepository.save(hos);

// }

public void deleteHospital(Hospital hospital) {


hospitalRepository.delete(hospital);
}
}
Hospital.java
package com.example.project;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Hospital {

@Id

public int getId() {


return id;
}
public Hospital() {
super();
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public Hospital(int id, String name, String city, double rating) {
super();
this.id = id;
this.name = name;
this.city = city;
this.rating = rating;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public double getRating() {
return rating;
}
public void setRating(double rating) {
this.rating = rating;
}
private int id;
private String name;
private String city;
private double rating;
}
HospitalRepository.java

package com.example.project;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface HospitalRepository extends JpaRepository<Hospital,Integer>{

}
application.properties
server.port=8080
spring.jpa.show-sql=true
spring.h2.console.enabled=true
spring.datasource.platform=h2
spring.datasource.url=jdbc:h2:mem:testdb

data.sql

insert into hospital values(1,'John','bihar',22);

Prob: Spring Boot Consume Rest API

Create a spring boot project to consume a public api for ny times, which displays the current stories.

Consume a public api for ny times


Please follow the following steps to know how to consume a public api for ny
times.
1)First create a simple maven project

2)Add Json as well as spring boot starter web dependency which is shown
below

Spring Boot starter dependency

<dependency>
<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>

Json dependency

<dependency>

<groupId>org.json</groupId>

<artifactId>json</artifactId>

<version>20180130</version>

</dependency>

3) Create a Results class with title field which is shown below

public class Results{


private String title;

public String getTitle() {

return title;

public void setTitle(String title) {

this.title = title;

4)Create a News class with following fields which is shown below

public class News {


private String section;

private Results[] results;

private String title;

public Results[] getResults() {

return results;

public void setResults(Results[] results) {

this.results = results;

public String getSection() {

return section;

}
public void setSection(String section) {

this.section = section;

public String getTitle() {

return title;

public void setTitle(String title) {

this.title = title;

}
5)Please create News service which is shown below

import java.util.ArrayList;

import java.util.List;

import java.util.Map;

import org.json.JSONArray;

import org.json.JSONObject;

import org.springframework.http.HttpEntity;

import org.springframework.http.HttpHeaders;

import org.springframework.http.HttpMethod;

import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;

import org.springframework.http.ResponseEntity;

import org.springframework.stereotype.Service;

import org.springframework.web.client.RestTemplate;

@Service

public class NewsService {

private String apiKey = "gIIWu7P82GBslJAd0MUSbKMrOaqHjWOo";

private RestTemplate restTemplate = new RestTemplate();

private JSONObject jsonObject;

private JSONArray jsonArray;

private Results[] resultsArray;

private News news=new News();

public News getTopStories() throws Exception {


List<News> topNewsStories = new ArrayList<>();

String Url = "https://api.nytimes.com/svc/topstories/v2/home.json?api-key=" +


apiKey;

HttpHeaders headers = new HttpHeaders();

headers.setContentType(MediaType.APPLICATION_JSON);

HttpEntity entity = new HttpEntity(headers);

ResponseEntity<Map> newsList = restTemplate.exchange(Url, HttpMethod.GET,


entity, Map.class);

if (newsList.getStatusCode() == HttpStatus.OK) {

jsonObject = new JSONObject(newsList.getBody());

jsonArray = jsonObject.getJSONArray("results");

resultsArray = new Results[jsonArray.length()];

for(int i=0; i<jsonArray.length(); i++) {


news.setTitle(jsonArray.getJSONObject(i).get("title").toString());

news.setSection(jsonArray.getJSONObject(i).get("section").toString());

resultsArray[i]=new Results();

resultsArray[i].setTitle(jsonArray.getJSONObject(i).get("title").toString());

news.setResults(resultsArray);

topNewsStories.add(news);

return topNewsStories.get(0);

}
6)Please create a News controller which is shown below

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.RestController;

@RestController

public class NewsController {

@Autowired

NewsService newsService;
@GetMapping("/api/news/topstories")

public News getTopNews() throws Exception {

return newsService.getTopStories();

7)Please run you spring boot application

You might also like