0% found this document useful (0 votes)
59 views

Spring Boot

The document describes the code for building a REST API application in Spring Boot. It includes code for a HospitalController and HospitalService to manage hospital data, Spring Security configuration for basic authentication, and consuming a REST API using RestTemplate. Code snippets are provided for the key classes used, including Hospital.java for the data model and SpringSecurityConfig.java for security configuration. The document also outlines steps for building a full stack API and trying it out.

Uploaded by

Sankha
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
59 views

Spring Boot

The document describes the code for building a REST API application in Spring Boot. It includes code for a HospitalController and HospitalService to manage hospital data, Spring Security configuration for basic authentication, and consuming a REST API using RestTemplate. Code snippets are provided for the key classes used, including Hospital.java for the data model and SpringSecurityConfig.java for security configuration. The document also outlines steps for building a full stack API and trying it out.

Uploaded by

Sankha
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 13

Spring Boot - API Cantabile_FP Hands-On Solutions.

Course Id:- 55962

1. Build A REST API APP , 2.Spring Boot DATABASE Integration (Same)

1. HospitalControl.java

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.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
Exception {
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();
}
}

2.HospitalService.java

package com.example.project;

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

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();
}

3. Hospital.java

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;
}

}
3. Spring Boot Security

1. SpringSecurityConfig.java

package com.example.project;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import
org.springframework.security.config.annotation.authentication.builders.Authenticati
onManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import
org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import
org.springframework.security.config.annotation.web.configuration.WebSecurityConfigu
rerAdapter;

@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
");
}
}

2. AuthenticationEntryPoint.java

package com.example.project;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.AuthenticationException;
import
org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint;
import org.springframework.stereotype.Component;

@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();
}
}

4. Spring Boot Consume Rest API

package com.example.project;

import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
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.web.client.RestTemplate;

@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;
}

5. Build a Full Stack API - Try-it-Out

1. AuthenticationEntryPoint.java

package com.example.project;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.AuthenticationException;
import
org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint;
import org.springframework.stereotype.Component;

@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();
}

2..SpringSecurityConfig.java

package com.example.project;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import
org.springframework.security.config.annotation.authentication.builders.Authenticati
onManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import
org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import
org.springframework.security.config.annotation.web.configuration.WebSecurityConfigu
rerAdapter;

@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
");
}
}

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}").buildAndExp
and(sevedUser.getId()).toUri();
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.demo.Hospital;

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.demo.Hospital;

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);

6) Consume Public APIs - Try-it-Out


1. AuthenticationEntryPoint.java

package com.example.project;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.AuthenticationException;
import
org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint;
import org.springframework.stereotype.Component;

@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();
}

2. News.Java

package com.example.project;
import com.example.project.Results;

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;
}

3. NewsController.java

package com.example.project;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class NewsController {

@Autowired
NewsService newsService;

@RequestMapping(value = "/news/topstories", method = RequestMethod.GET)


public News getNews() throws Exception {
return newsService.getTopStories();
}

4. Results.java

package com.example.project;

public class Results{

private String title;

public String getTitle() {


return title;
}
public void setTitle(String title) {
this.title = title;
}
}

5.SpringSecurityConfig.java

package com.example.project;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import
org.springframework.security.config.annotation.authentication.builders.Authenticati
onManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import
org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import
org.springframework.security.config.annotation.web.configuration.WebSecurityConfigu
rerAdapter;

@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
");
}
}

6. NewsService.java

package com.example.project;

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);
}

You might also like