Spring Boot - API Cantabile Hands-on Solutions | TCS Fresco Play

0

Spring Boot - API Cantabile Hands-on Solutions  |  TCS Fresco Play


Spring Boot - API Cantabile Fresco Play MCQs Answers

Disclaimer: The primary purpose of providing this solution is to assist and support anyone who are unable to complete these courses due to a technical issue or a lack of expertise. This website's information or data are solely for the purpose of knowledge and education.

Make an effort to understand these solutions and apply them to your Hands-On difficulties. (It is not advisable that copy and paste these solutions).

Course Path: Microservices/CONSTRUCTION/Spring Boot - API Cantabile

Suggestion: Just Copy whole code from below and replace with existing code on hacker-rank.


1.Spring Boot Rest API

Buid a Rest API


File Name-HospitalController.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();

    }

}


File Name-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();

}

}


File Name- 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;

  }

  }



2.Spring Boot - Database Integration


(Same as the answer of First Question - Spring Boot Rest API)


3.Welcome to Spring Boot - Handson - Security


File Name-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");

  }

}


File Name-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.Welcome to Spring Boot - Handson - Consume API

File Name-RestBooksApi.java

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.Spring Boot -Consume Rest API

File Name-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 {
    }
  @Override
    public void afterPropertiesSet() throws Exception {
    }
}

File Name-Hospital.java

package com.example.project;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "HOSPITAL")
public class Hospital {
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  @Column(name = "ID")
  private Integer id;
  @Column(name = "NAME")
  private String name;
  @Column(name = "CITY")
  private String city;
  @Column(name = "RATING")
  private Double rating;
  public Hospital(Integer id, String name, String city, Double rating) {
    super();
    this.id = id;
    this.name = name;
    this.city = city;
    this.rating = rating;
  }
  public Hospital() {
  }
  public Integer getId() {
    return id;
  }
  public void setId(Integer 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;
  }
  @Override
  public String toString() {
    return "Hospital [id=" + id + ", name=" + name + ", city=" + city + ", rating=" + rating + "]";
  }
}

File NAME- 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 {
  Hospital test1= new Hospital();
  if(id==1000){
  test1.setId(id);
  test1.setName("Apollo Hospital");
  test1.setRating(3.8);
  test1.setCity("Chennai");
  }
  if(id==1001){
    test1.setId(id);
  test1.setName("Global Hospitals");
  test1.setRating(3.8);
  test1.setCity("Goa");
  }
  return test1;
 //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);
}
}

File Name – HospitalRepository.java

package com.example.project;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface HospitalRepository extends CrudRepository<Hospital, Integer> {
  public Hospital findHospitalById(Integer id);
  @Override
  public List<Hospital> findAll();
}

File NAME-HospitalService.java

package com.example.project;
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() {
    return hospitalRepository.findAll();
  }
  public Hospital getHospital(int id) {
    return (hospitalRepository.findHospitalById(id));
  }
  public void addHospital(Hospital hospital) {
  }
  public void updateHospital(Hospital hospital) {
  }
  public void deleteHospital(Hospital hospital) {
  }
}

File Name – SpringBoot3Application.java

package com.example.project;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration;
@SpringBootApplication(exclude = { SecurityAutoConfiguration.class })
public class SpringBoot3Application {
  public static void main(String[] args) {
    SpringApplication.run(SpringBoot3Application.class, args);
  }
}

File Name-SpringSecurityConfig.java

package com.example.project;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
}

File Name- 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


6.Consume Public APIs - Try-it-Out

Welcome to
Spring Boot - Handson - Consume API 1

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

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

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

File Name – 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);
}
}

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

File Name – 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;
  }
}




If you have any queries, please feel free to ask on the comment section.

If you want MCQs and Hands-On solutions for any courses, Please feel free to ask on the comment section too.

Post a Comment

0Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !