Skip to content

Commit 5de4fb1

Browse files
committed
use messageContainer for success and error message and exception
1 parent ac977c8 commit 5de4fb1

File tree

15 files changed

+126
-78
lines changed

15 files changed

+126
-78
lines changed

src/main/java/ir/bigz/springbootreal/commons/generallog/AppLogAspect.java

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,14 @@
11
package ir.bigz.springbootreal.commons.generallog;
22

3-
import com.fasterxml.jackson.databind.ObjectMapper;
43
import ir.bigz.springbootreal.commons.util.Utils;
54
import ir.bigz.springbootreal.exception.AppException;
65
import ir.bigz.springbootreal.exception.HttpExceptionModel;
76
import org.aspectj.lang.JoinPoint;
8-
import org.aspectj.lang.Signature;
97
import org.aspectj.lang.annotation.*;
108
import org.slf4j.Logger;
119
import org.slf4j.LoggerFactory;
12-
import org.springframework.beans.factory.annotation.Autowired;
1310
import org.springframework.http.ResponseEntity;
1411
import org.springframework.stereotype.Component;
15-
import org.springframework.web.context.request.RequestContextHolder;
16-
import org.springframework.web.context.request.ServletRequestAttributes;
1712

1813
import javax.servlet.http.HttpServletRequest;
1914
import java.util.Arrays;
@@ -56,15 +51,15 @@ public void afterReturningResponseOfControllerMethod(JoinPoint joinPoint, Object
5651
public void logAfterThrowException(JoinPoint joinPoint, AppException exception){
5752
String methodName = joinPoint.getSignature().getName();
5853
LOG.info("exception method: {} | errorCode: {} | message: {}",
59-
methodName, exception.getHttpErrorCode(), exception.getDetail());
54+
methodName, exception.getSampleExceptionType().getErrorCode(), exception.getDetail());
6055
}
6156

6257
@AfterReturning(value = "execution(* ir.bigz.springbootreal.exception.validation.ErrorController.*(..))", returning = "object")
6358
public void logAfterThrowValidationException(JoinPoint joinPoint, Object object){
6459
HttpExceptionModel httpExceptionModel = (HttpExceptionModel) ((ResponseEntity) object).getBody();
6560
LOG.info("validation exception path: {} | errorCode: {} | errors: {}",
6661
httpExceptionModel.getValidationError().getPath(),
67-
httpExceptionModel.getHttpErrorCode(),
62+
httpExceptionModel.getErrorCode(),
6863
httpExceptionModel.getValidationError().getErrors());
6964
}
7065
}

src/main/java/ir/bigz/springbootreal/commons/util/Utils.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import ir.bigz.springbootreal.dto.SqlOperation;
55
import ir.bigz.springbootreal.dto.ValueCondition;
66
import ir.bigz.springbootreal.exception.AppException;
7-
import ir.bigz.springbootreal.exception.HttpErrorCode;
7+
import ir.bigz.springbootreal.exception.SampleExceptionType;
88
import org.javatuples.Quartet;
99
import org.springframework.data.domain.Sort;
1010

@@ -53,7 +53,7 @@ public static boolean isNotNull(String s) {
5353
}
5454

5555
public static boolean isNull(String s) {
56-
return s == null || s.equals("") || s.toLowerCase().equals("null");
56+
return s == null || s.equals("") || s.equalsIgnoreCase("null");
5757
}
5858

5959
public static boolean isNotNull(Object obj) {
@@ -121,7 +121,7 @@ public static List<Sort.Order> getSortOrderFromPagedQuery(PagedQuery pagedQuery,
121121
orders.add(order);
122122
}catch (Exception e){
123123
throw AppException.newInstance(
124-
HttpErrorCode.CREATE_QUERY_ERROR, String.format("field %s ordering is wrong", orderParam)
124+
SampleExceptionType.CREATE_QUERY_ERROR, String.format("field %s ordering is wrong", orderParam)
125125
);
126126
}
127127
}

src/main/java/ir/bigz/springbootreal/controller/AbstractController.java

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -27,22 +27,20 @@ protected HttpServletRequest request() {
2727

2828
protected PagedQuery getPagedQuery() {
2929
return new PagedQuery(request().getParameterMap().entrySet().stream()
30-
.collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()[0])));
30+
.collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue()[0])));
3131
}
3232

3333
protected PagedQuery getPagedQuery(Map<String, String> extraParams) {
3434
var params = request().getParameterMap().entrySet().stream()
35-
.collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()[0]));
35+
.collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue()[0]));
3636
if (extraParams != null)
3737
params.putAll(extraParams);
3838
return new PagedQuery(params);
3939
}
4040

4141
protected Map<String, String> getQueryString() {
42-
Map<String, String> result = new HashMap<>();
43-
result.putAll(request().getParameterMap().entrySet().stream()
44-
.collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()[0])));
45-
return result;
42+
return new HashMap<>(request().getParameterMap().entrySet().stream()
43+
.collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue()[0])));
4644
}
4745

4846
protected Map<String, String> getUnlimitedSizeParam() {
@@ -60,16 +58,16 @@ protected ResponseEntity<?> getSuccessMessage(MessageSource messageSource, Messa
6058
messageContainer.getMessages().get(0).getMessageParams(), Objects.nonNull(locale) ? locale : Locale.getDefault()));
6159
}
6260

63-
protected ResponseEntity<?> getErrorMessage(MessageSource messageSource, ExceptionType exceptionType, Object[] messageParams) {
61+
protected ResponseEntity<?> getErrorMessage(MessageSource messageSource, ExceptionType exceptionType, Locale locale, Object[] messageParams) {
6462
return ResponseEntity.status(exceptionType.getHttpStatus())
6563
.headers(httpHeaders -> httpHeaders.set("Content-Type", MediaType.APPLICATION_JSON_VALUE + "; charset=utf-8"))
66-
.body(getErrorModelResponse(exceptionType, messageSource, messageParams));
64+
.body(getErrorModelResponse(exceptionType, messageSource, locale, messageParams));
6765
}
6866

69-
private HttpExceptionModel getErrorModelResponse(ExceptionType exceptionType, MessageSource messageSource, Object... messageParams) {
67+
private HttpExceptionModel getErrorModelResponse(ExceptionType exceptionType, MessageSource messageSource, Locale locale, Object... messageParams) {
7068
return HttpExceptionModel.builder()
7169
.errorCode(exceptionType.getErrorCode())
72-
.message(messageSource.getMessage(exceptionType.getReasonMessage(), messageParams, Locale.getDefault()))
70+
.message(messageSource.getMessage(exceptionType.getReasonMessage(), messageParams, Objects.nonNull(locale) ? locale : Locale.getDefault()))
7371
.timestamp(Utils.getTimestampNow().toString())
7472
.build();
7573
}

src/main/java/ir/bigz/springbootreal/controller/SampleController.java

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
package ir.bigz.springbootreal.controller;
22

33
import ir.bigz.springbootreal.dto.PageResult;
4+
import ir.bigz.springbootreal.exception.SampleExceptionType;
45
import ir.bigz.springbootreal.messages.MessageContainer;
6+
import ir.bigz.springbootreal.service.MessageService;
57
import ir.bigz.springbootreal.service.UserService;
68
import ir.bigz.springbootreal.viewmodel.UserModel;
79
import ir.bigz.springbootreal.viewmodel.search.UserSearchDto;
@@ -23,33 +25,38 @@
2325
@RestController
2426
@CrossOrigin
2527
@RequestMapping("/api")
26-
public class SampleController extends AbstractController{
28+
public class SampleController extends AbstractController {
2729

2830
final UserService userService;
2931

32+
final MessageService messageService;
33+
3034
final MessageSource source;
3135

3236
@Autowired
3337
@Qualifier("loadErrorMessageSource")
3438
ReloadableResourceBundleMessageSource loadMessageSource;
3539

36-
public SampleController(UserService userService, MessageSource source) {
40+
public SampleController(UserService userService, MessageService messageService, MessageSource source) {
3741
this.userService = userService;
42+
this.messageService = messageService;
3843
this.source = source;
3944
}
4045

4146
@GetMapping("/v1/geterror")
4247
public ResponseEntity<?> getErrorMessage(
4348
@RequestHeader(name = "Accept-Language", required = false) final Locale locale) {
44-
return ResponseEntity.ok(loadMessageSource.getMessage("Exception", new Object[0], locale));
49+
MessageContainer messageContainer = messageService.getErrorMessage("internal_error");
50+
return getErrorMessage(loadMessageSource,
51+
SampleExceptionType.of(messageContainer.getErrorMessages().get(0).getMessageKey()),
52+
locale, messageContainer.getErrorMessages().get(0).getMessageParams());
4553
}
4654

4755
@GetMapping("/v1/welcome")
4856
public ResponseEntity<?> getLocaleMessage(
4957
@RequestHeader(name = "Accept-Language", required = false) final Locale locale,
5058
@RequestParam(name = "username", defaultValue = "Java Geek", required = false) final String username) {
51-
MessageContainer messageContainer = MessageContainer.create();
52-
messageContainer.add("welcome.message", new Object[]{username});
59+
MessageContainer messageContainer = messageService.getNormalMessage("welcome.message", username);
5360
return getSuccessMessage(source, messageContainer, locale);
5461
}
5562

@@ -80,7 +87,7 @@ public ResponseEntity<?> updateUser(@RequestBody UserModel userModel, @PathVaria
8087
@ResponseStatus(HttpStatus.ACCEPTED)
8188
public ResponseEntity<?> deleteUser(@PathVariable("id") long userId) {
8289
String result = userService.deleteUser(userId);
83-
if(result.equals("Success")){
90+
if (result.equals("Success")) {
8491
return ResponseEntity.ok(result);
8592
}
8693
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(result);

src/main/java/ir/bigz/springbootreal/dal/DaoRepositoryImpl.java

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import ir.bigz.springbootreal.dto.PageResult;
44
import ir.bigz.springbootreal.dto.PagedQuery;
55
import ir.bigz.springbootreal.exception.AppException;
6-
import ir.bigz.springbootreal.exception.HttpErrorCode;
6+
import ir.bigz.springbootreal.exception.SampleExceptionType;
77
import org.hibernate.Session;
88
import org.hibernate.jpa.QueryHints;
99
import org.springframework.data.domain.Page;
@@ -37,7 +37,7 @@ public abstract class DaoRepositoryImpl<T, K extends Serializable> implements Da
3737

3838
protected CriteriaBuilder criteriaBuilder;
3939

40-
private static int maxPageSize = 1000;
40+
private static final int maxPageSize = 1000;
4141

4242
@SuppressWarnings("unchecked")
4343
protected DaoRepositoryImpl() {
@@ -100,7 +100,7 @@ public <S extends T> void delete(S entity) {
100100
@Override
101101
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
102102
public void deleteById(K id) {
103-
entityManager.remove(findById(id).get());
103+
findById(id).ifPresent(t -> entityManager.remove(t));
104104
}
105105

106106
@Override
@@ -170,10 +170,10 @@ public PageResult<T> pageCreateQuery(String nativeQuery, PagedQuery pagedQuery,
170170
if (orderField.length > 1 && orderField[1].equalsIgnoreCase(PagedQuery.ORDER_DESC)) {
171171
order = PagedQuery.ORDER_DESC;
172172
}
173-
orderString.append(orderColumn + " " + order);
173+
orderString.append(orderColumn).append(" ").append(order);
174174
}catch (Exception e){
175175
throw AppException.newInstance(
176-
HttpErrorCode.CREATE_QUERY_ERROR, String.format("field %s ordering is wrong", orderParam)
176+
SampleExceptionType.CREATE_QUERY_ERROR, String.format("field %s ordering is wrong", orderParam)
177177
);
178178
}
179179
}
@@ -323,13 +323,10 @@ protected Long totalCountOfSearch(String queryString, Map<String, Object> parame
323323
protected List<Order> orderByClauseBuilder(Root<T> root, Sort sort){
324324

325325
List<Order> orders = new ArrayList<>();
326-
Iterator<Sort.Order> iterator = sort.iterator();
327-
while(iterator.hasNext()){
328-
Sort.Order order = iterator.next();
329-
if(order.getDirection() == Sort.Direction.ASC){
326+
for (Sort.Order order : sort) {
327+
if (order.getDirection() == Sort.Direction.ASC) {
330328
orders.add(criteriaBuilder.asc(root.get(order.getProperty())));
331-
}
332-
else{
329+
} else {
333330
orders.add(criteriaBuilder.desc(root.get(order.getProperty())));
334331
}
335332
}

src/main/java/ir/bigz/springbootreal/exception/AppException.java

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@
55

66
public class AppException extends ResponseStatusException{
77

8-
private HttpErrorCode httpErrorCode;
9-
private String detail;
8+
private final SampleExceptionType sampleExceptionType;
9+
private final String detail;
1010

1111

1212
static public AppException newInstance(HttpStatus status) {
@@ -21,27 +21,27 @@ static public AppException newInstance(HttpStatus status, String message, Throwa
2121
return new AppException(status, message, cause, null, null);
2222
}
2323

24-
static public AppException newInstance(HttpStatus status, String message, Throwable cause, HttpErrorCode errorCode) {
25-
return new AppException(status, message, cause, errorCode, null);
24+
static public AppException newInstance(HttpStatus status, String message, Throwable cause, SampleExceptionType exceptionType) {
25+
return new AppException(status, message, cause, exceptionType, null);
2626
}
2727

28-
static public AppException newInstance(HttpErrorCode errorCode, String message, Throwable cause) {
29-
return new AppException(errorCode.getHttpStatus(), message, cause, errorCode, null);
28+
static public AppException newInstance(SampleExceptionType exceptionType, String message, Throwable cause) {
29+
return new AppException(exceptionType.getHttpStatus(), message, cause, exceptionType, null);
3030
}
3131

32-
static public AppException newInstance(HttpErrorCode errorCode, String detail) {
33-
return new AppException(errorCode.getHttpStatus(), null, null, errorCode, detail);
32+
static public AppException newInstance(SampleExceptionType exceptionType, String detail) {
33+
return new AppException(exceptionType.getHttpStatus(), null, null, exceptionType, detail);
3434
}
3535

3636

37-
public AppException(HttpStatus httpStatus, String message, Throwable cause, HttpErrorCode errorCode, String detail){
37+
public AppException(HttpStatus httpStatus, String message, Throwable cause, SampleExceptionType exceptionType, String detail){
3838
super(httpStatus, message, cause);
39-
this.httpErrorCode = errorCode;
39+
this.sampleExceptionType = exceptionType;
4040
this.detail = detail;
4141
}
4242

43-
public HttpErrorCode getHttpErrorCode() {
44-
return httpErrorCode;
43+
public SampleExceptionType getSampleExceptionType() {
44+
return sampleExceptionType;
4545
}
4646

4747
public String getDetail() {

src/main/java/ir/bigz/springbootreal/exception/HttpExceptionHandler.java

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
package ir.bigz.springbootreal.exception;
22

3-
import org.springframework.http.HttpStatus;
43
import org.springframework.http.ResponseEntity;
54
import org.springframework.web.bind.annotation.ControllerAdvice;
65
import org.springframework.web.bind.annotation.ExceptionHandler;
@@ -15,13 +14,16 @@ public class HttpExceptionHandler {
1514

1615
@ExceptionHandler(value = {AppException.class})
1716
public ResponseEntity<Object> handleApiRequestException(AppException e){
18-
UUID uuid = UUID.randomUUID();
19-
20-
HttpExceptionModel apiException = new HttpExceptionModel(uuid.toString(),
21-
e.getHttpErrorCode().getErrorCode(), e.getDetail(),
22-
timeLog(), null);
2317

24-
return new ResponseEntity<>(apiException, e.getHttpErrorCode().getHttpStatus());
18+
UUID uuid = UUID.randomUUID();
19+
HttpExceptionModel apiException = new HttpExceptionModel(
20+
uuid.toString(),
21+
e.getSampleExceptionType().getErrorCode(),
22+
e.getDetail(),
23+
timeLog(),
24+
null);
25+
26+
return new ResponseEntity<>(apiException, e.getSampleExceptionType().getHttpStatus());
2527
}
2628

2729
private String timeLog(){

src/main/java/ir/bigz/springbootreal/exception/HttpErrorCode.java renamed to src/main/java/ir/bigz/springbootreal/exception/SampleExceptionType.java

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,21 +2,33 @@
22

33
import org.springframework.http.HttpStatus;
44

5-
public enum HttpErrorCode implements ExceptionType{
5+
import java.util.Arrays;
6+
import java.util.Objects;
7+
8+
public enum SampleExceptionType implements ExceptionType {
69

710
INVALID_ENTITY_FOR_INSERT (10700, "invalid_entity_for_insert", HttpStatus.BAD_REQUEST),
811
INTERNAL_ERROR (10701, "internal_server_error", HttpStatus.INTERNAL_SERVER_ERROR),
912
USER_NOT_FOUND (10702, "user_not_found", HttpStatus.NOT_FOUND),
1013
INVALID_ENTITY_FOR_UPDATE (10703, "invalid_entity_for_update", HttpStatus.BAD_REQUEST),
1114
VALIDATION_ERROR (10704, "validation_error", HttpStatus.BAD_REQUEST),
12-
CREATE_QUERY_ERROR (10705, "create_query_error", HttpStatus.BAD_REQUEST);
15+
CREATE_QUERY_ERROR (10705, "create_query_error", HttpStatus.BAD_REQUEST),
16+
UNKNOWN_ERROR (99999, "unknown_error", HttpStatus.INTERNAL_SERVER_ERROR);
1317

1418
private final CustomExceptionType customExceptionType;
1519

16-
HttpErrorCode(int errorCode, String reasonMessage, HttpStatus httpStatus) {
20+
SampleExceptionType(int errorCode, String reasonMessage, HttpStatus httpStatus) {
1721
this.customExceptionType = new CustomExceptionType(httpStatus, errorCode, reasonMessage);
1822
}
1923

24+
public static CustomExceptionType of(String reasonMessage){
25+
return Arrays.stream(SampleExceptionType.values())
26+
.filter(exceptionType -> Objects.equals(exceptionType.getReasonMessage(), reasonMessage))
27+
.findFirst()
28+
.orElse(UNKNOWN_ERROR)
29+
.getCustomExceptionType();
30+
}
31+
2032
@Override
2133
public HttpStatus getHttpStatus() {
2234
return this.customExceptionType.httpStatus;

src/main/java/ir/bigz/springbootreal/exception/validation/ErrorController.java

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
package ir.bigz.springbootreal.exception.validation;
22

3-
import ir.bigz.springbootreal.exception.HttpErrorCode;
3+
import ir.bigz.springbootreal.exception.SampleExceptionType;
44
import ir.bigz.springbootreal.exception.HttpExceptionModel;
55
import org.springframework.http.HttpHeaders;
66
import org.springframework.http.HttpStatus;
77
import org.springframework.http.ResponseEntity;
8+
import org.springframework.lang.NonNullApi;
89
import org.springframework.validation.FieldError;
910
import org.springframework.web.bind.MethodArgumentNotValidException;
1011
import org.springframework.web.bind.annotation.RestControllerAdvice;
@@ -33,10 +34,10 @@ protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotV
3334
errors.put(fieldName, errorMessage);
3435
});
3536

36-
return ResponseEntity.status(HttpErrorCode.VALIDATION_ERROR.getHttpStatus())
37+
return ResponseEntity.status(SampleExceptionType.VALIDATION_ERROR.getHttpStatus())
3738
.body(HttpExceptionModel.builder()
38-
.errorCode(HttpErrorCode.VALIDATION_ERROR.getErrorCode())
39-
.message(HttpErrorCode.VALIDATION_ERROR.getReasonMessage())
39+
.errorCode(SampleExceptionType.VALIDATION_ERROR.getErrorCode())
40+
.message(SampleExceptionType.VALIDATION_ERROR.getReasonMessage())
4041
.timestamp(timeLog())
4142
.validationError(ValidationErrorResponseModel.builder()
4243
.errors(errors)
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
package ir.bigz.springbootreal.service;
2+
3+
import ir.bigz.springbootreal.messages.MessageContainer;
4+
5+
public interface MessageService {
6+
7+
MessageContainer getErrorMessage(String messageReason, String... params);
8+
MessageContainer getNormalMessage(String messageReason, String... params);
9+
}

0 commit comments

Comments
 (0)