Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

finished guided project #1

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions usermodel-exceptions-initial/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.2.8.RELEASE</version>
<version>2.2.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.lambdaschool</groupId>
Expand All @@ -15,7 +15,7 @@
<description>Demo project for Spring Boot</description>

<properties>
<java.version>14</java.version>
<java.version>11</java.version>
</properties>

<dependencies>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.lambdaschool.usermodel.config;


import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class SwaggerWebMVC implements WebMvcConfigurer {

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package com.lambdaschool.usermodel.exceptions;

import com.lambdaschool.usermodel.services.HelperFunctions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.WebRequest;

import java.util.LinkedHashMap;
import java.util.Map;


@Component
public class CustomErrorDetails extends DefaultErrorAttributes {

@Autowired
HelperFunctions helperFunctions;

@Override
public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {

Map<String, Object> errorAttributes = super.getErrorAttributes(webRequest, includeStackTrace);

Map<String, Object> errorDetails = new LinkedHashMap<>();
errorDetails.put("title", errorAttributes.get("error"));
errorDetails.put("status", errorAttributes.get("status"));
errorDetails.put("detail", errorAttributes.get("message"));
errorDetails.put("timestamp", errorAttributes.get("timestamp"));
errorDetails.put("developerMessage", "path " + errorAttributes.get("path"));

errorDetails.put("errors", helperFunctions.getConstraintViolations(this.getError(webRequest)));

return errorDetails;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.lambdaschool.usermodel.exceptions;



public class ResourceNotFoundException extends RuntimeException {

public ResourceNotFoundException(String message) {
super("Error from application " + message);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package com.lambdaschool.usermodel.handlers;

import com.lambdaschool.usermodel.exceptions.ResourceNotFoundException;
import com.lambdaschool.usermodel.models.ErrorDetail;
import com.lambdaschool.usermodel.services.HelperFunctions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import java.util.Date;


@Order(Ordered.HIGHEST_PRECEDENCE)
@RestControllerAdvice
public class RestExceptionHandler extends ResponseEntityExceptionHandler {

@Autowired
HelperFunctions helperFunctions;

public RestExceptionHandler() {
super();
}

@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<?> handleResourceNotFoundException(ResourceNotFoundException rnfe){
ErrorDetail errorDetail = new ErrorDetail();
errorDetail.setTimestamp(new Date());
errorDetail.setStatus(HttpStatus.NOT_FOUND.value());
errorDetail.setTitle("Resource not Found");
errorDetail.setDetail(rnfe.getMessage());
errorDetail.setDeveloperMessage(rnfe.getClass().getName());

errorDetail.setErrors(helperFunctions.getConstraintViolations(rnfe));

return new ResponseEntity<>(errorDetail, null, HttpStatus.NOT_FOUND);
}
@Override
protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body, HttpHeaders headers, HttpStatus status, WebRequest request) {

ErrorDetail errDetail = new ErrorDetail();
errDetail.setTimestamp(new Date());
errDetail.setStatus(status.value());
errDetail.setTitle("Rest Internal Exception");
errDetail.setDetail(ex.getMessage());
errDetail.setDeveloperMessage(ex.getClass().getName());

errDetail.setErrors(helperFunctions.getConstraintViolations(ex));
return new ResponseEntity<>(errDetail, null, status);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package com.lambdaschool.usermodel.models;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ErrorDetail {

private String title;
private int status;
private String detail;
private Date timestamp;
private String developerMessage;

private List<ValidationError> errors = new ArrayList<>();

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

public int getStatus() {
return status;
}

public void setStatus(int status) {
this.status = status;
}

public String getDetail() {
return detail;
}

public void setDetail(String detail) {
this.detail = detail;
}

public Date getTimestamp() {
return timestamp;
}

public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}

public String getDeveloperMessage() {
return developerMessage;
}

public void setDeveloperMessage(String developerMessage) {
this.developerMessage = developerMessage;
}

public List<ValidationError> getErrors() {
return errors;
}

public void setErrors(List<ValidationError> errors) {
this.errors = errors;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.Email;
import javax.validation.constraints.Size;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
Expand Down Expand Up @@ -44,6 +45,7 @@ public class User
*/
@Column(nullable = false)
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
@Size(min = 4, max = 30)
private String password;

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.lambdaschool.usermodel.models;

public class ValidationError {

private String code;
private String message;

public String getCode() {
return code;
}

public void setCode(String code) {
this.code = code;
}

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.lambdaschool.usermodel.services;

import com.lambdaschool.usermodel.models.ValidationError;

import java.util.List;

public interface HelperFunctions {

List<ValidationError> getConstraintViolations(Throwable cause);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package com.lambdaschool.usermodel.services;

import com.lambdaschool.usermodel.models.ValidationError;
import org.springframework.stereotype.Service;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.ArrayList;
import java.util.List;

@Service(value = "helperFunctions")
public class HelperFunctionsImpl implements HelperFunctions {

@Override
public List<ValidationError> getConstraintViolations(Throwable cause) {

while ((cause) != null && !(cause instanceof ConstraintViolationException)){

cause = cause.getCause();
}
List<ValidationError> listVE = new ArrayList<>();

if (cause != null){
ConstraintViolationException ex= (ConstraintViolationException) cause;
for(ConstraintViolation cv : ex.getConstraintViolations()){
ValidationError newVe = new ValidationError();

newVe.setCode(cv.getInvalidValue().toString());
newVe.setMessage(cv.getMessage());
listVE.add(newVe);
}
}

return listVE;
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.lambdaschool.usermodel.services;

import com.lambdaschool.usermodel.exceptions.ResourceNotFoundException;
import com.lambdaschool.usermodel.models.Role;
import com.lambdaschool.usermodel.repository.RoleRepository;
import com.lambdaschool.usermodel.repository.UserRepository;
Expand All @@ -8,7 +9,7 @@
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityExistsException;
import javax.persistence.EntityNotFoundException;

import java.util.ArrayList;
import java.util.List;

Expand Down Expand Up @@ -57,7 +58,7 @@ public List<Role> findAll()
public Role findRoleById(long id)
{
return rolerepos.findById(id)
.orElseThrow(() -> new EntityNotFoundException("Role id " + id + " not found!"));
.orElseThrow(() -> new ResourceNotFoundException("Role id " + id + " not found!"));
}

@Override
Expand All @@ -70,7 +71,7 @@ public Role findByName(String name)
return rr;
} else
{
throw new EntityNotFoundException(name);
throw new ResourceNotFoundException(name);
}
}

Expand Down Expand Up @@ -101,7 +102,7 @@ public Role update(long id,
{
if (role.getName() == null)
{
throw new EntityNotFoundException("No role name found to update!");
throw new ResourceNotFoundException("No role name found to update!");
}

if (role.getUsers()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.lambdaschool.usermodel.services;

import com.lambdaschool.usermodel.exceptions.ResourceNotFoundException;
import com.lambdaschool.usermodel.models.Role;
import com.lambdaschool.usermodel.models.User;
import com.lambdaschool.usermodel.models.UserRoles;
Expand All @@ -9,7 +10,7 @@
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityNotFoundException;

import java.util.ArrayList;
import java.util.List;

Expand All @@ -34,10 +35,10 @@ public class UserServiceImpl
private RoleService roleService;

public User findUserById(long id) throws
EntityNotFoundException
ResourceNotFoundException
{
return userrepos.findById(id)
.orElseThrow(() -> new EntityNotFoundException("User id " + id + " not found!"));
.orElseThrow(() -> new ResourceNotFoundException("User id " + id + " not found!"));
}

@Override
Expand Down Expand Up @@ -65,7 +66,7 @@ public List<User> findAll()
public void delete(long id)
{
userrepos.findById(id)
.orElseThrow(() -> new EntityNotFoundException("User id " + id + " not found!"));
.orElseThrow(() -> new ResourceNotFoundException("User id " + id + " not found!"));
userrepos.deleteById(id);
}

Expand All @@ -75,7 +76,7 @@ public User findByName(String name)
User uu = userrepos.findByUsername(name.toLowerCase());
if (uu == null)
{
throw new EntityNotFoundException("User name " + name + " not found!");
throw new ResourceNotFoundException("User name " + name + " not found!");
}
return uu;
}
Expand All @@ -89,7 +90,7 @@ public User save(User user)
if (user.getUserid() != 0)
{
userrepos.findById(user.getUserid())
.orElseThrow(() -> new EntityNotFoundException("User id " + user.getUserid() + " not found!"));
.orElseThrow(() -> new ResourceNotFoundException("User id " + user.getUserid() + " not found!"));
newUser.setUserid(user.getUserid());
}

Expand Down
Loading