Spring Boot - API Cantabile_FP Hands-On Solutions.
Course Id:- 55962
Please use these below hands-On Solutions Education Purpose Only. Learn the Technology.
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.AuthenticationManagerBuilder;
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.WebSecurityConfigurerAdapter;
@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
Reference URL:- spring - java.lang.AssertionError: Status expected:<200> but was:<404> with test cases failing - Stack Overflow
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.AuthenticationManagerBuilder;
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.WebSecurityConfigurerAdapter;
@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}").buildAndExpand(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
Reference URL:- Consume a public api for ny times – BytesofGigabytes
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.AuthenticationManagerBuilder;
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.WebSecurityConfigurerAdapter;
@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);
}
}
Please give fresco play hands for reactjs- interlace your interface
ReplyDeleteHlo
ReplyDeleteCould you please provide the hands on for mini project spring boot fersco play(63089)
Please upload course id-63089 which is hands-on
ReplyDeleteHello
ReplyDeleteCould you please provide the hands on for mini project spring boot fresco play(63089)
Web Technologies : Mini-Project - Spring hands-on_E2_FP(70997) - Please give solution for this
ReplyDeleteCould u please help with 63431 handson
ReplyDeleteBuild a Full Stack API - Try-it-Out can you please provide this answer once again iam getting errors
ReplyDeletei am unable to consume rest API becuse news.java and newsService showing errors .can u help me what to do with those errors
ReplyDeleteBuild a REST API code is not working
ReplyDeleteSpring Boot Build a REST API
ReplyDelete--- Full Stack
1) change import package name to :
package com.example.project;
2) just refer and take code from here :-
https://stackoverflow.com/questions/61862563/java-lang-assertionerror-status-expected200-but-was404-with-test-cases-fa
hi , getting error in the 1) Build A REST API APP ,.
ReplyDelete