Spring Boot
Spring Boot
Spring Boot
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 {
3. Hospital.java
package com.example.project;
public Hospital() {
}
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();
}
}
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();
}
/**
* 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);
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);
}
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;
}
return hospitalRepository.findOne(id);
}
// }
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
}
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
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;
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;
4. Results.java
package com.example.project;
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 {
if (newsList.getStatusCode() == HttpStatus.OK) {
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);
}