Spring Boot Hospital List
Spring Boot Hospital List
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.
<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>
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;
}
}
package com.example.project;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
public interface HospitalRepository extends CrudRepository<Hospital,Integer>{
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
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;
}
}
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")
;
}
}
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
</dependency>
@SpringBootApplication
public class RestBooksApi {
static RestTemplate restTemplate;
public RestBooksApi(){
restTemplate = new RestTemplate();
}
/**
* 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);
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);
}
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;
return hospitalRepository.findOne(id);
}
// }
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class Hospital {
@Id
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
Create a spring boot project to consume a public api for ny times, which displays the current stories.
2)Add Json as well as spring boot starter web dependency which is shown
below
<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>
return title;
this.title = title;
return results;
this.results = results;
return section;
}
public void setSection(String section) {
this.section = section;
return 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
headers.setContentType(MediaType.APPLICATION_JSON);
if (newsList.getStatusCode() == HttpStatus.OK) {
jsonArray = jsonObject.getJSONArray("results");
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
@Autowired
NewsService newsService;
@GetMapping("/api/news/topstories")
return newsService.getTopStories();