Skip to content

Commit

Permalink
Updated CustomError ref
Browse files Browse the repository at this point in the history
  • Loading branch information
sainik73 committed Feb 5, 2021
1 parent a8f7723 commit 37cc4ee
Show file tree
Hide file tree
Showing 5 changed files with 271 additions and 66 deletions.
126 changes: 114 additions & 12 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.1</version>
<version>2.4.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example.openapi</groupId>
Expand All @@ -23,6 +23,10 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
Expand All @@ -49,25 +53,25 @@
<version>1.18.16</version>
</dependency>

<!-- https://mvnrepository.com/artifact/io.swagger.core.v3/swagger-annotations -->
<dependency>
<groupId>io.swagger</groupId>
<groupId>io.swagger.core.v3</groupId>
<artifactId>swagger-annotations</artifactId>
<version>1.5.21</version>
<version>2.1.6</version>
</dependency>

<!-- https://mvnrepository.com/artifact/io.swagger.core.v3/swagger-models -->
<dependency>
<groupId>io.swagger</groupId>
<groupId>io.swagger.core.v3</groupId>
<artifactId>swagger-models</artifactId>
<version>1.6.0</version>
<version>2.1.6</version>
</dependency>

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.10.3</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
</dependencies>

<build>
Expand All @@ -76,10 +80,29 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!--<plugin>
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<version>5.0.0</version>
<executions>
<execution>
<goals>
<goal>generate</goal>
</goals>
<configuration>
<inputSpec>${project.basedir}/src/main/resources/students-api.yaml</inputSpec>
<generatorName>java</generatorName>
<configOptions>
<sourceFolder>src/gen/java/main</sourceFolder>
</configOptions>
</configuration>
</execution>
</executions>
</plugin>-->
<plugin>
<groupId>io.swagger.codegen.v3</groupId>
<artifactId>swagger-codegen-maven-plugin</artifactId>
<version>3.0.18</version>
<version>3.0.24</version>
<executions>
<execution>
<goals>
Expand All @@ -89,16 +112,95 @@
<inputSpec>${project.basedir}/src/main/resources/students-api.yaml</inputSpec>
<language>spring</language>
<output>${project.build.directory}/generated-sources/</output>
<generateApiDocumentation>false</generateApiDocumentation>
<generateModelDocumentation>false</generateModelDocumentation>
<generateApiTests>false</generateApiTests>
<generateModelTests>false</generateModelTests>
<generateSupportingFiles>false</generateSupportingFiles>
<apiPackage>com.example.openapi</apiPackage>
<modelPackage>com.example.openapi.model</modelPackage>
<apiPackage>${project.groupId}</apiPackage>
<modelPackage>${project.groupId}.model</modelPackage>
<configOptions>
<interfaceOnly>true</interfaceOnly>
<useBeanValidation>true</useBeanValidation>
<enable303>true</enable303>
<dateLibrary>java8</dateLibrary>
<hideGenerationTimestamp>true</hideGenerationTimestamp>
</configOptions>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.1.0</version>
<executions>
<execution>
<id>copy-resources</id>
<!-- here is the phase where you need to copy resources -->
<phase>package</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>${project.basedir}/target/custom-build-dir</outputDirectory>
<resources>
<resource>
<directory>src/main/docker</directory>
<filtering>true</filtering>
</resource>
<resource>
<directory>target</directory>
<includes>
<include>**/*.jar</include>
</includes>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>io.fabric8</groupId>
<artifactId>docker-maven-plugin</artifactId>
<version>0.34.0</version>
<executions>
<execution>
<id>start</id>
<phase>pre-integration-test</phase>
<goals>
<goal>build</goal>
<goal>start</goal>
</goals>
</execution>
<execution>
<id>stop</id>
<phase>post-integration-test</phase>
<goals>
<goal>stop</goal>
</goals>
</execution>
</executions>
<configuration>
<dockerHost>http://localhost:2375</dockerHost>
<images>
<image>
<name>docker.io/sainik73/students-api:1.0.0</name>
<build>
<dockerFile>${project.basedir}/target/custom-build-dir/dockerfile</dockerFile >
</build>
<run>
<ports>
<port>8180:8080</port>
</ports>
<!--<wait>
<url>http://localhost:8180/info/ping</url>
<time>5000</time>
</wait>-->
</run>
</image>
</images>
</configuration>
</plugin>
</plugins>
</build>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,84 +2,129 @@


import com.example.openapi.StudentsApi;
import com.example.openapi.StudentsByAgeApi;
import com.example.openapi.model.Student;
import com.example.openapi.model.Students;
import com.example.openapi.students.exception.StudentNotFoundException;
import com.example.openapi.students.service.StudentsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RestController;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Objects;
import java.util.*;
import java.util.function.Predicate;

/**
* This is the REST controller class for the Students API
*/
@RestController
@Slf4j
public class StudentsApiController implements StudentsApi , StudentsByAgeApi {
@Validated
public class StudentsApiController implements StudentsApi {
@Autowired
private StudentsService studentsService;

private final Predicate<List<Student>> zeroSizePredicate =
studentsList -> (studentsList.size() == 0);


/**
* This method implements default get endpoint
* for ping
*/
@RequestMapping(value = "/info/ping",
produces = { "application/text" },
method = RequestMethod.GET)
public ResponseEntity<String> ping() {
return new ResponseEntity<>("OK",HttpStatus.OK);
}


@Override
public ResponseEntity<Void> studentsPost(Student body) {
public ResponseEntity<Void> createStudent(@Valid Student body) {
//validate request and call DB to create resource
Student s = studentsService.create(body.getStudentid(), body.getName(), body.getAge());
log.debug("Successfully Created the student: {}",s.getStudentid());
return new ResponseEntity<>(HttpStatus.CREATED);
}

@Override
public ResponseEntity<Void> studentsPut(Student body) {
public ResponseEntity<Void> updateStudent(@Valid Student body) {
//validate request and call DB to create resource
Student s = studentsService.update(body.getStudentid(), body.getName(), body.getAge());
log.debug("Successfully Updated the student: {}",s.getStudentid());
return new ResponseEntity<>(HttpStatus.OK);
}

@Override
public ResponseEntity<Student> studentsStudentIdGet(Integer studentId) {
public ResponseEntity<Student> findStudentById(Integer studentId) {
//call DB to get resource by studentId
Student s = studentsService.getById(studentId);
Predicate<Student> nonNullPredicate = Objects::nonNull;
ResponseEntity<Student> responseEntity = null;
ResponseEntity<Student> responseEntity;
if (nonNullPredicate.test(s)) {
log.debug("Got Students by Id: {}, Name:{} ", new Object[]{s.getStudentid(), s.getName()});
log.debug("Got Students by Id: {}, Name:{} ", s.getStudentid(), s.getName());
responseEntity = new ResponseEntity<>(s, HttpStatus.OK);
}else{
log.debug("Student not found by Id: {}", studentId);
responseEntity = new ResponseEntity<>(HttpStatus.NOT_FOUND);
log.debug("No Student found using Id: {}", studentId);
throw new StudentNotFoundException("Id", studentId);
}

return responseEntity;
}

@Override
public ResponseEntity<Students> studentsGet(String studentName) {
public ResponseEntity<Students> findStudentsByName(@NotNull @Valid String studentName) {
//call DB to get resources by studentName
List<Student> studentsList = studentsService.getByName(studentName);
log.debug("Got Students by Name: {}, List Size:{} ", new Object[]{studentName,studentsList.size()});
if(zeroSizePredicate.test(studentsList)) {
throw new StudentNotFoundException("Name", studentName);
}
log.debug("Got Students by Name: {}, List Size:{} ", studentName,studentsList.size());
Students students = new Students();
students.addAll(studentsList);
return new ResponseEntity<>(students, HttpStatus.OK);
}

@Override
public ResponseEntity<Students> findAllStudents() {
//call DB to get all resources
List<Student> studentsList = studentsService.getAll();
if(zeroSizePredicate.test(studentsList)) {
throw new StudentNotFoundException();
}
log.debug("Got Students List Size:{} ", studentsList.size());
Students students = new Students();
students.addAll(studentsList);
return new ResponseEntity<>(students, HttpStatus.OK);
}

@Override
public ResponseEntity<Students> studentsByAgeGet(@NotNull @Valid Integer studentAge) {
public ResponseEntity<Students> findStudentsByAge(@NotNull @Valid Integer studentAge) {
//call DB to get resources by studentAge
List<Student> studentsList = studentsService.getByAge(studentAge);
log.debug("Got Students by Age: {}, List Size:{} ", new Object[]{studentAge,studentsList.size()});

if(zeroSizePredicate.test(studentsList)) {
throw new StudentNotFoundException("Age", studentAge);
}
log.debug("Got Students by Age: {}, List Size:{} ", studentAge,studentsList.size());
Students students = new Students();
students.addAll(studentsList);
return new ResponseEntity<>(students, HttpStatus.OK);
}

@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException.class)
public Map<String, String> handleMethodArgumentNotValid(MethodArgumentNotValidException ex) {
Map<String, String> errors = new HashMap<>();

ex.getBindingResult().getFieldErrors().forEach(error ->
errors.put(error.getField(), error.getDefaultMessage()));

return errors;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,7 @@ public com.example.openapi.model.Student update(int id, String name, int age){

public com.example.openapi.model.Student getById(Integer studentId){
Optional<Student> s = studentsRepository.findById(studentId);
if (s.isPresent()) {
return convertToJSON(s.get());
}
return null;
return s.map(this::convertToJSON).orElse(null);
}

public List<com.example.openapi.model.Student> getByName(String studentName){
Expand All @@ -58,9 +55,18 @@ public List<com.example.openapi.model.Student> getByAge(Integer studentAge) {
return jsonStudent;
}

public List<com.example.openapi.model.Student> getAll() {
List<Student> studentsList = studentsRepository.findAll();
List<com.example.openapi.model.Student> jsonStudent = new ArrayList<>();
for (Student student : studentsList) {
jsonStudent.add(convertToJSON(student));
}
return jsonStudent;
}

/**
* Method to convert the DB model object to json model
* @param student
* @param student Object of Student
* @return com.example.openapi.model.Student
*/
private com.example.openapi.model.Student convertToJSON(Student student) {
Expand Down
Loading

0 comments on commit 37cc4ee

Please sign in to comment.