kandi background
Explore Kits

springBoot | springboot 框架与其它组件结合如 jpa、mybatis、websocket、security、shiro、cache等 | Security Framework library

 by   527515025 Java Version: Current License: No License

 by   527515025 Java Version: Current License: No License

Download this library from

kandi X-RAY | springBoot Summary

springBoot is a Java library typically used in Security, Security Framework, Spring Boot, JPA applications. springBoot has no bugs and it has medium support. However springBoot has 1 vulnerabilities and it build file is not available. You can download it from GitHub.
springboot 框架与其它组件结合如 jpa、mybatis、websocket、security、shiro、cache等
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • springBoot has a medium active ecosystem.
  • It has 5395 star(s) with 2739 fork(s). There are 346 watchers for this library.
  • It had no major release in the last 12 months.
  • There are 32 open issues and 5 have been closed. On average issues are closed in 1 days. There are 38 open pull requests and 0 closed requests.
  • It has a neutral sentiment in the developer community.
  • The latest version of springBoot is current.
springBoot Support
Best in #Security Framework
Average in #Security Framework
springBoot Support
Best in #Security Framework
Average in #Security Framework

quality kandi Quality

  • springBoot has 0 bugs and 0 code smells.
springBoot Quality
Best in #Security Framework
Average in #Security Framework
springBoot Quality
Best in #Security Framework
Average in #Security Framework

securitySecurity

  • springBoot has 1 vulnerability issues reported (1 critical, 0 high, 0 medium, 0 low).
  • springBoot code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.
springBoot Security
Best in #Security Framework
Average in #Security Framework
springBoot Security
Best in #Security Framework
Average in #Security Framework

license License

  • springBoot does not have a standard license declared.
  • Check the repository for any license declaration and review the terms closely.
  • Without a license, all rights are reserved, and you cannot use the library in your applications.
springBoot License
Best in #Security Framework
Average in #Security Framework
springBoot License
Best in #Security Framework
Average in #Security Framework

buildReuse

  • springBoot releases are not available. You will need to build from source code and install.
  • springBoot has no build file. You will be need to create the build yourself to build the component from source.
springBoot Reuse
Best in #Security Framework
Average in #Security Framework
springBoot Reuse
Best in #Security Framework
Average in #Security Framework
Top functions reviewed by kandi - BETA

kandi has reviewed springBoot and discovered the below as its top functions. This is intended to give you an instant insight into springBoot implemented functionality, and help decide if they suit your requirements.

  • Do security check?
  • Search list query .
  • Sets the Quartz session validation job .
  • Get the Quartz properties .
  • Get the authorization info
  • To graph DTO
  • Bean cache manager .
  • Encodes a password .
  • Checks access to the given authentication method .
  • Gets parameter map .

springBoot Key Features

springboot 框架与其它组件结合如 jpa、mybatis、websocket、security、shiro、cache等

Java @Override equals(): When this.getClass() != o.getClass() fails but shouldn't

copy iconCopydownload iconDownload
if ( !(this instanceof MyClass && o instanceof MyClass) )
{
   return false;
}
-----------------------
@Override
public boolean equals(Object o) {
    if (this == o) {
        return true;
    }
    if (!(o instanceof MyClass)) {
        return false;
    }
    MyClass other = (MyClass) o;
    return id != null && id.equals(other.getId());
}


@Override
public int hashCode() {
    return getClass().hashCode();
}
-----------------------
 public boolean equals(Object obj) {
   if (obj == null) { return false; }
   if (obj == this) { return true; }
   if (obj.getClass() != getClass()) {
     return false;
   }
   
   ... do the actual comparison here
 }
-----------------------
if ( o == null || this.getClass() != o.getClass() )
if ( o == null || !this.getClass().equals( o.getClass() ) )
final public class MyClass extends MySuperClass
{
  ...
  @Override
  public boolean equals( Object o )
  {
    if ( this == o )
    {
      return true;
    }
    if ( o == null || !this.getClass().equals( o.getClass() ) )
    {
      return false;
    }
    if ( !super.equals( o ) )
    {
      return false;
    }
    MyClass that = ( MyClass ) o;
    return this.var1.equals( that.var1 ) && this.var2.equals( that.var2 );
  }
  ...
}
-----------------------
if ( o == null || this.getClass() != o.getClass() )
if ( o == null || !this.getClass().equals( o.getClass() ) )
final public class MyClass extends MySuperClass
{
  ...
  @Override
  public boolean equals( Object o )
  {
    if ( this == o )
    {
      return true;
    }
    if ( o == null || !this.getClass().equals( o.getClass() ) )
    {
      return false;
    }
    if ( !super.equals( o ) )
    {
      return false;
    }
    MyClass that = ( MyClass ) o;
    return this.var1.equals( that.var1 ) && this.var2.equals( that.var2 );
  }
  ...
}
-----------------------
if ( o == null || this.getClass() != o.getClass() )
if ( o == null || !this.getClass().equals( o.getClass() ) )
final public class MyClass extends MySuperClass
{
  ...
  @Override
  public boolean equals( Object o )
  {
    if ( this == o )
    {
      return true;
    }
    if ( o == null || !this.getClass().equals( o.getClass() ) )
    {
      return false;
    }
    if ( !super.equals( o ) )
    {
      return false;
    }
    MyClass that = ( MyClass ) o;
    return this.var1.equals( that.var1 ) && this.var2.equals( that.var2 );
  }
  ...
}

Springboot 2.6.0 / Spring fox 3 - Failed to start bean 'documentationPluginsBootstrapper'

copy iconCopydownload iconDownload
@SpringBootApplication
@EnableSwagger2
public class Application {
-----------------------
// build.gradle
implementation "org.springdoc:springdoc-openapi-ui:1.6.4"
@SpringBootApplication
@OpenAPIDefinition
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}
-----------------------
// build.gradle
implementation "org.springdoc:springdoc-openapi-ui:1.6.4"
@SpringBootApplication
@OpenAPIDefinition
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}
-----------------------
@Bean
public WebMvcEndpointHandlerMapping webEndpointServletHandlerMapping(WebEndpointsSupplier webEndpointsSupplier, ServletEndpointsSupplier servletEndpointsSupplier, ControllerEndpointsSupplier controllerEndpointsSupplier, EndpointMediaTypes endpointMediaTypes, CorsEndpointProperties corsProperties, WebEndpointProperties webEndpointProperties, Environment environment) {
        List<ExposableEndpoint<?>> allEndpoints = new ArrayList();
        Collection<ExposableWebEndpoint> webEndpoints = webEndpointsSupplier.getEndpoints();
        allEndpoints.addAll(webEndpoints);
        allEndpoints.addAll(servletEndpointsSupplier.getEndpoints());
        allEndpoints.addAll(controllerEndpointsSupplier.getEndpoints());
        String basePath = webEndpointProperties.getBasePath();
        EndpointMapping endpointMapping = new EndpointMapping(basePath);
        boolean shouldRegisterLinksMapping = this.shouldRegisterLinksMapping(webEndpointProperties, environment, basePath);
        return new WebMvcEndpointHandlerMapping(endpointMapping, webEndpoints, endpointMediaTypes, corsProperties.toCorsConfiguration(), new EndpointLinksResolver(allEndpoints, basePath), shouldRegisterLinksMapping, null);
    }


private boolean shouldRegisterLinksMapping(WebEndpointProperties webEndpointProperties, Environment environment, String basePath) {
        return webEndpointProperties.getDiscovery().isEnabled() && (StringUtils.hasText(basePath) || ManagementPortType.get(environment).equals(ManagementPortType.DIFFERENT));
    }
-----------------------
@EnableSwagger2
@SpringBootApplication
@EnableSwagger2
public class Application {}
-----------------------
@EnableWebMvc
@SpringBootApplication
public class MyApp {
    public static void main(String[] args) {
        SpringApplication.run(MyApp.class);
    }
}
-----------------------
@Bean
    public WebMvcRequestHandlerProvider webMvcRequestHandlerProvider(Optional<ServletContext> servletContext, HandlerMethodResolver methodResolver, List<RequestMappingInfoHandlerMapping> handlerMappings) {
        handlerMappings = handlerMappings.stream().filter(rh -> rh.getClass().getName().contains("RequestMapping")).toList();
        return new WebMvcRequestHandlerProvider(servletContext, methodResolver, handlerMappings);
    }

How to add basepath in OpenApi so that it is autogenerated with maven?

copy iconCopydownload iconDownload
@RequestMapping("${project.name.base-path:/my-path}")

Springboot: Better handling of error messages

copy iconCopydownload iconDownload
{
      "Error": {
        "Code": "401",
        "Message": "Unauthorized",
        "Target": null,
        "InnerError": {
          "Code": "System.UnauthorizedAccessException",
          "Message": "Exception occured in AppAssertedAuth Handler",
          "Target": "MoveNext"
        }
      }

}
public enum ErrorCodeEnum {

    USER_NOT_SIGNED_IN(HttpStatus.BAD_REQUEST, "UserNotSignedIn"),
    FILE_SIZE_EXCEEDED(HttpStatus.PAYLOAD_TOO_LARGE, "FileSizeExceeded"),
    FILE_TYPE(HttpStatus.UNSUPPORTED_MEDIA_TYPE, "FileType"),
    SERVICE_UNAVAILABLE(HttpStatus.SERVICE_UNAVAILABLE, "ServiceUnavailable"),
    SERVICE_TEMPORARY_UNAVAILABLE(HttpStatus.SERVICE_UNAVAILABLE, "ServiceTemporaryUnavailable"),
    ORDER_NOT_FOUND(HttpStatus.NOT_FOUND, "OrderNotFound"),
    UNAUTHORIZED(HttpStatus.UNAUTHORIZED, "Unauthorized"),
    UNEXPECTED_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "UnexpectedError"),
    HEADER_MISSING(HttpStatus.BAD_REQUEST, "HeaderMissing"),
public class ErrorResponse {

    @JsonIgnore
    private String timestamp;
    private String error;
    private String message;
    private String code;
    @JsonIgnore
    private Integer status;
    @JsonIgnore
    private String path;
    @JsonAlias("error_description")
    private String errorDescription;
    //Create constructer as per your requirements 
    @ControllerAdvice
    public class GlobalExceptionHandler {
    
        private final MessageSource messageSource;
    
        public GlobalExceptionHandler(MessageSource messageSource) {
            this.messageSource = messageSource;
        }
        @ExceptionHandler(MissingRequestHeaderException.class)
        public ResponseEntity<ErrorResponse> handleMissingHeader(ResponseStatusException ex) {
            Sentry.captureException(ex);
            return ResponseEntity.badRequest().body(new ErrorResponse(ex.getMessage(), ex));
        }
        
        @ExceptionHandler(MissingServletRequestParameterException.class)
        public ResponseEntity<ErrorResponse> handleMissingParameterException(Exception ex) {
            log.error("Exception: Class {}|{}", ex.getClass().getCanonicalName(), ex.getMessage(), ex);
            return ResponseEntity.badRequest().body(new ErrorResponse(ex.getMessage(), ErrorCodeEnum.PARAMETER_MISSING));
        }
    
        @ExceptionHandler(MethodArgumentNotValidException.class)
        public ResponseEntity<ErrorResponse>  handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
            final var errors = e.getAllErrors();

            return ResponseEntity.badRequest().body(new ErrorMessage(/* error message based errors */);
        }

        @ExceptionHandler(CustomWebClientException.class)
        public ResponseEntity<ErrorResponse> handleSalesAssistantException(CustomWebClientException ex) {
            log.error(
                    "CustomWebClientException from WebClient - Status {}, Body {}",
                    ex.getErrorCodeEnum().getHttpStatus(),
                    ex);
            Sentry.captureException(ex);
            String errorMessage = getTranslatedMessage(ex.getErrorCodeEnum(), ex.getMessage());
    
            return new ResponseEntity<>(
                    new ErrorResponse(errorMessage, ex), ex.getErrorCodeEnum().getHttpStatus());
        }
    
        private String getTranslatedMessage(ErrorCodeEnum errorCodeEnum, String defaultMessage) {
            return messageSource.getMessage(
                    errorCodeEnum.getErrorCode(), null, defaultMessage, LocaleContextHolder.getLocale());
        }
  }

/*  class CustomWebClientException extends WebClientException {
        private final ErrorCodeEnum errorCodeEnum;
        private ErrorResponse errorResponse;
    
        public CustomWebClientException(ErrorCodeEnum errorCodeEnum, ErrorResponse errorResponse) {
            super(errorResponse.getMessage());
            this.errorCodeEnum = errorCodeEnum;
            this.errorResponse = errorResponse;
        }
    } */
-----------------------
{
      "Error": {
        "Code": "401",
        "Message": "Unauthorized",
        "Target": null,
        "InnerError": {
          "Code": "System.UnauthorizedAccessException",
          "Message": "Exception occured in AppAssertedAuth Handler",
          "Target": "MoveNext"
        }
      }

}
public enum ErrorCodeEnum {

    USER_NOT_SIGNED_IN(HttpStatus.BAD_REQUEST, "UserNotSignedIn"),
    FILE_SIZE_EXCEEDED(HttpStatus.PAYLOAD_TOO_LARGE, "FileSizeExceeded"),
    FILE_TYPE(HttpStatus.UNSUPPORTED_MEDIA_TYPE, "FileType"),
    SERVICE_UNAVAILABLE(HttpStatus.SERVICE_UNAVAILABLE, "ServiceUnavailable"),
    SERVICE_TEMPORARY_UNAVAILABLE(HttpStatus.SERVICE_UNAVAILABLE, "ServiceTemporaryUnavailable"),
    ORDER_NOT_FOUND(HttpStatus.NOT_FOUND, "OrderNotFound"),
    UNAUTHORIZED(HttpStatus.UNAUTHORIZED, "Unauthorized"),
    UNEXPECTED_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "UnexpectedError"),
    HEADER_MISSING(HttpStatus.BAD_REQUEST, "HeaderMissing"),
public class ErrorResponse {

    @JsonIgnore
    private String timestamp;
    private String error;
    private String message;
    private String code;
    @JsonIgnore
    private Integer status;
    @JsonIgnore
    private String path;
    @JsonAlias("error_description")
    private String errorDescription;
    //Create constructer as per your requirements 
    @ControllerAdvice
    public class GlobalExceptionHandler {
    
        private final MessageSource messageSource;
    
        public GlobalExceptionHandler(MessageSource messageSource) {
            this.messageSource = messageSource;
        }
        @ExceptionHandler(MissingRequestHeaderException.class)
        public ResponseEntity<ErrorResponse> handleMissingHeader(ResponseStatusException ex) {
            Sentry.captureException(ex);
            return ResponseEntity.badRequest().body(new ErrorResponse(ex.getMessage(), ex));
        }
        
        @ExceptionHandler(MissingServletRequestParameterException.class)
        public ResponseEntity<ErrorResponse> handleMissingParameterException(Exception ex) {
            log.error("Exception: Class {}|{}", ex.getClass().getCanonicalName(), ex.getMessage(), ex);
            return ResponseEntity.badRequest().body(new ErrorResponse(ex.getMessage(), ErrorCodeEnum.PARAMETER_MISSING));
        }
    
        @ExceptionHandler(MethodArgumentNotValidException.class)
        public ResponseEntity<ErrorResponse>  handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
            final var errors = e.getAllErrors();

            return ResponseEntity.badRequest().body(new ErrorMessage(/* error message based errors */);
        }

        @ExceptionHandler(CustomWebClientException.class)
        public ResponseEntity<ErrorResponse> handleSalesAssistantException(CustomWebClientException ex) {
            log.error(
                    "CustomWebClientException from WebClient - Status {}, Body {}",
                    ex.getErrorCodeEnum().getHttpStatus(),
                    ex);
            Sentry.captureException(ex);
            String errorMessage = getTranslatedMessage(ex.getErrorCodeEnum(), ex.getMessage());
    
            return new ResponseEntity<>(
                    new ErrorResponse(errorMessage, ex), ex.getErrorCodeEnum().getHttpStatus());
        }
    
        private String getTranslatedMessage(ErrorCodeEnum errorCodeEnum, String defaultMessage) {
            return messageSource.getMessage(
                    errorCodeEnum.getErrorCode(), null, defaultMessage, LocaleContextHolder.getLocale());
        }
  }

/*  class CustomWebClientException extends WebClientException {
        private final ErrorCodeEnum errorCodeEnum;
        private ErrorResponse errorResponse;
    
        public CustomWebClientException(ErrorCodeEnum errorCodeEnum, ErrorResponse errorResponse) {
            super(errorResponse.getMessage());
            this.errorCodeEnum = errorCodeEnum;
            this.errorResponse = errorResponse;
        }
    } */
-----------------------
{
      "Error": {
        "Code": "401",
        "Message": "Unauthorized",
        "Target": null,
        "InnerError": {
          "Code": "System.UnauthorizedAccessException",
          "Message": "Exception occured in AppAssertedAuth Handler",
          "Target": "MoveNext"
        }
      }

}
public enum ErrorCodeEnum {

    USER_NOT_SIGNED_IN(HttpStatus.BAD_REQUEST, "UserNotSignedIn"),
    FILE_SIZE_EXCEEDED(HttpStatus.PAYLOAD_TOO_LARGE, "FileSizeExceeded"),
    FILE_TYPE(HttpStatus.UNSUPPORTED_MEDIA_TYPE, "FileType"),
    SERVICE_UNAVAILABLE(HttpStatus.SERVICE_UNAVAILABLE, "ServiceUnavailable"),
    SERVICE_TEMPORARY_UNAVAILABLE(HttpStatus.SERVICE_UNAVAILABLE, "ServiceTemporaryUnavailable"),
    ORDER_NOT_FOUND(HttpStatus.NOT_FOUND, "OrderNotFound"),
    UNAUTHORIZED(HttpStatus.UNAUTHORIZED, "Unauthorized"),
    UNEXPECTED_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "UnexpectedError"),
    HEADER_MISSING(HttpStatus.BAD_REQUEST, "HeaderMissing"),
public class ErrorResponse {

    @JsonIgnore
    private String timestamp;
    private String error;
    private String message;
    private String code;
    @JsonIgnore
    private Integer status;
    @JsonIgnore
    private String path;
    @JsonAlias("error_description")
    private String errorDescription;
    //Create constructer as per your requirements 
    @ControllerAdvice
    public class GlobalExceptionHandler {
    
        private final MessageSource messageSource;
    
        public GlobalExceptionHandler(MessageSource messageSource) {
            this.messageSource = messageSource;
        }
        @ExceptionHandler(MissingRequestHeaderException.class)
        public ResponseEntity<ErrorResponse> handleMissingHeader(ResponseStatusException ex) {
            Sentry.captureException(ex);
            return ResponseEntity.badRequest().body(new ErrorResponse(ex.getMessage(), ex));
        }
        
        @ExceptionHandler(MissingServletRequestParameterException.class)
        public ResponseEntity<ErrorResponse> handleMissingParameterException(Exception ex) {
            log.error("Exception: Class {}|{}", ex.getClass().getCanonicalName(), ex.getMessage(), ex);
            return ResponseEntity.badRequest().body(new ErrorResponse(ex.getMessage(), ErrorCodeEnum.PARAMETER_MISSING));
        }
    
        @ExceptionHandler(MethodArgumentNotValidException.class)
        public ResponseEntity<ErrorResponse>  handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
            final var errors = e.getAllErrors();

            return ResponseEntity.badRequest().body(new ErrorMessage(/* error message based errors */);
        }

        @ExceptionHandler(CustomWebClientException.class)
        public ResponseEntity<ErrorResponse> handleSalesAssistantException(CustomWebClientException ex) {
            log.error(
                    "CustomWebClientException from WebClient - Status {}, Body {}",
                    ex.getErrorCodeEnum().getHttpStatus(),
                    ex);
            Sentry.captureException(ex);
            String errorMessage = getTranslatedMessage(ex.getErrorCodeEnum(), ex.getMessage());
    
            return new ResponseEntity<>(
                    new ErrorResponse(errorMessage, ex), ex.getErrorCodeEnum().getHttpStatus());
        }
    
        private String getTranslatedMessage(ErrorCodeEnum errorCodeEnum, String defaultMessage) {
            return messageSource.getMessage(
                    errorCodeEnum.getErrorCode(), null, defaultMessage, LocaleContextHolder.getLocale());
        }
  }

/*  class CustomWebClientException extends WebClientException {
        private final ErrorCodeEnum errorCodeEnum;
        private ErrorResponse errorResponse;
    
        public CustomWebClientException(ErrorCodeEnum errorCodeEnum, ErrorResponse errorResponse) {
            super(errorResponse.getMessage());
            this.errorCodeEnum = errorCodeEnum;
            this.errorResponse = errorResponse;
        }
    } */
-----------------------
{
      "Error": {
        "Code": "401",
        "Message": "Unauthorized",
        "Target": null,
        "InnerError": {
          "Code": "System.UnauthorizedAccessException",
          "Message": "Exception occured in AppAssertedAuth Handler",
          "Target": "MoveNext"
        }
      }

}
public enum ErrorCodeEnum {

    USER_NOT_SIGNED_IN(HttpStatus.BAD_REQUEST, "UserNotSignedIn"),
    FILE_SIZE_EXCEEDED(HttpStatus.PAYLOAD_TOO_LARGE, "FileSizeExceeded"),
    FILE_TYPE(HttpStatus.UNSUPPORTED_MEDIA_TYPE, "FileType"),
    SERVICE_UNAVAILABLE(HttpStatus.SERVICE_UNAVAILABLE, "ServiceUnavailable"),
    SERVICE_TEMPORARY_UNAVAILABLE(HttpStatus.SERVICE_UNAVAILABLE, "ServiceTemporaryUnavailable"),
    ORDER_NOT_FOUND(HttpStatus.NOT_FOUND, "OrderNotFound"),
    UNAUTHORIZED(HttpStatus.UNAUTHORIZED, "Unauthorized"),
    UNEXPECTED_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "UnexpectedError"),
    HEADER_MISSING(HttpStatus.BAD_REQUEST, "HeaderMissing"),
public class ErrorResponse {

    @JsonIgnore
    private String timestamp;
    private String error;
    private String message;
    private String code;
    @JsonIgnore
    private Integer status;
    @JsonIgnore
    private String path;
    @JsonAlias("error_description")
    private String errorDescription;
    //Create constructer as per your requirements 
    @ControllerAdvice
    public class GlobalExceptionHandler {
    
        private final MessageSource messageSource;
    
        public GlobalExceptionHandler(MessageSource messageSource) {
            this.messageSource = messageSource;
        }
        @ExceptionHandler(MissingRequestHeaderException.class)
        public ResponseEntity<ErrorResponse> handleMissingHeader(ResponseStatusException ex) {
            Sentry.captureException(ex);
            return ResponseEntity.badRequest().body(new ErrorResponse(ex.getMessage(), ex));
        }
        
        @ExceptionHandler(MissingServletRequestParameterException.class)
        public ResponseEntity<ErrorResponse> handleMissingParameterException(Exception ex) {
            log.error("Exception: Class {}|{}", ex.getClass().getCanonicalName(), ex.getMessage(), ex);
            return ResponseEntity.badRequest().body(new ErrorResponse(ex.getMessage(), ErrorCodeEnum.PARAMETER_MISSING));
        }
    
        @ExceptionHandler(MethodArgumentNotValidException.class)
        public ResponseEntity<ErrorResponse>  handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
            final var errors = e.getAllErrors();

            return ResponseEntity.badRequest().body(new ErrorMessage(/* error message based errors */);
        }

        @ExceptionHandler(CustomWebClientException.class)
        public ResponseEntity<ErrorResponse> handleSalesAssistantException(CustomWebClientException ex) {
            log.error(
                    "CustomWebClientException from WebClient - Status {}, Body {}",
                    ex.getErrorCodeEnum().getHttpStatus(),
                    ex);
            Sentry.captureException(ex);
            String errorMessage = getTranslatedMessage(ex.getErrorCodeEnum(), ex.getMessage());
    
            return new ResponseEntity<>(
                    new ErrorResponse(errorMessage, ex), ex.getErrorCodeEnum().getHttpStatus());
        }
    
        private String getTranslatedMessage(ErrorCodeEnum errorCodeEnum, String defaultMessage) {
            return messageSource.getMessage(
                    errorCodeEnum.getErrorCode(), null, defaultMessage, LocaleContextHolder.getLocale());
        }
  }

/*  class CustomWebClientException extends WebClientException {
        private final ErrorCodeEnum errorCodeEnum;
        private ErrorResponse errorResponse;
    
        public CustomWebClientException(ErrorCodeEnum errorCodeEnum, ErrorResponse errorResponse) {
            super(errorResponse.getMessage());
            this.errorCodeEnum = errorCodeEnum;
            this.errorResponse = errorResponse;
        }
    } */
-----------------------
@ExceptionHandler(ConstraintViolationException.class)
protected ResponseEntity<Object> handleConstraintViolation(ConstraintViolationException e, WebRequest request){
   return Optional.ofNullable(e).map(ConstraintViolationException::getConstraintViolations).map(this::createException).orElseGet(this::generateGenericError);
}
private ErrorBody createException(FieldError fieldError) {
    return ErrorBody.builder()
            .code(fieldError.getCode())
            .message(fieldError.getDefaultMessage())
            .field(fieldError.getField())
            .value(fieldError.getRejectedValue())
            .build();
}
-----------------------
@ExceptionHandler(ConstraintViolationException.class)
protected ResponseEntity<Object> handleConstraintViolation(ConstraintViolationException e, WebRequest request){
   return Optional.ofNullable(e).map(ConstraintViolationException::getConstraintViolations).map(this::createException).orElseGet(this::generateGenericError);
}
private ErrorBody createException(FieldError fieldError) {
    return ErrorBody.builder()
            .code(fieldError.getCode())
            .message(fieldError.getDefaultMessage())
            .field(fieldError.getField())
            .value(fieldError.getRejectedValue())
            .build();
}
-----------------------
@InitBinder
void initBinder(WebDataBinder binder) {
    if (binder.getTarget() == null) {
        return;
    }
    final var validator1 = // your validator1 instance

    //check if specific validator is eligible to validate request and its body
    if (validator1.supports(binget.getTarget().getClass()) {
        binder.setValidator(validator);
    }
}
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseBody
ErrorMessage handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
    final var errors = e.getAllErrors()

    return new ErrorMessage(/* populate your error message based on given errors */);
}
@Override
public void validate(Object target, Errors errors) {
    final var credentials = (Credentials) target;

    //reject username field with given c000 code if it's null
    if (isNull(credentials.getUsername())) {
        errors.rejectValue("username", "c000", "username cannot be null");
        return;
    }

    if (credentials.getUsername().trim().isEmpty()) {
        errors.rejectValue("username", "c001", "username cannot be empty");
        return;
    }

    if (credentials.getUsername().length() > 256) {
        errors.rejectValue("username", "c002", "username cannot be longer than 256 characters");
        return;
    }
}

-----------------------
@InitBinder
void initBinder(WebDataBinder binder) {
    if (binder.getTarget() == null) {
        return;
    }
    final var validator1 = // your validator1 instance

    //check if specific validator is eligible to validate request and its body
    if (validator1.supports(binget.getTarget().getClass()) {
        binder.setValidator(validator);
    }
}
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseBody
ErrorMessage handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
    final var errors = e.getAllErrors()

    return new ErrorMessage(/* populate your error message based on given errors */);
}
@Override
public void validate(Object target, Errors errors) {
    final var credentials = (Credentials) target;

    //reject username field with given c000 code if it's null
    if (isNull(credentials.getUsername())) {
        errors.rejectValue("username", "c000", "username cannot be null");
        return;
    }

    if (credentials.getUsername().trim().isEmpty()) {
        errors.rejectValue("username", "c001", "username cannot be empty");
        return;
    }

    if (credentials.getUsername().length() > 256) {
        errors.rejectValue("username", "c002", "username cannot be longer than 256 characters");
        return;
    }
}

-----------------------
@InitBinder
void initBinder(WebDataBinder binder) {
    if (binder.getTarget() == null) {
        return;
    }
    final var validator1 = // your validator1 instance

    //check if specific validator is eligible to validate request and its body
    if (validator1.supports(binget.getTarget().getClass()) {
        binder.setValidator(validator);
    }
}
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseBody
ErrorMessage handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
    final var errors = e.getAllErrors()

    return new ErrorMessage(/* populate your error message based on given errors */);
}
@Override
public void validate(Object target, Errors errors) {
    final var credentials = (Credentials) target;

    //reject username field with given c000 code if it's null
    if (isNull(credentials.getUsername())) {
        errors.rejectValue("username", "c000", "username cannot be null");
        return;
    }

    if (credentials.getUsername().trim().isEmpty()) {
        errors.rejectValue("username", "c001", "username cannot be empty");
        return;
    }

    if (credentials.getUsername().length() > 256) {
        errors.rejectValue("username", "c002", "username cannot be longer than 256 characters");
        return;
    }
}

-----------------------
@ExceptionHandler(MethodArgumentNotValidException.class)
   public ResponseEntity<ErrorMessage> handleArgumentNotValidException(MethodArgumentNotValidException ex, Locale locale) {
      BindingResult result = ex.getBindingResult();
      List<String> errorMessages = result.getAllErrors()
              .stream()
              .map(err-> messageSource.getMessage(err, locale))
              .collect(Collectors.toList());
      return new ResponseEntity<>(new ErrorMessage(errorMessages), HttpStatus.BAD_REQUEST);
}
NotNull.obj.greeting=Please, provide a valid greeting message.
Size.obj.greeting=Greeting message  must contain between {2} and {1} characters.
NotNull.obj.greeting=Por favor, proporcione un mensaje de saludo válido.
Size.obj.greeting=El mensaje de bienvenida debe contener entre {2} y {1} caracteres.
curl -X POST -H "Content-Type: application/json" -H "Accept-Language: es-MX" -d '{
  "description": "employee info"
}' http://localhost:8080/api/employee
-----------------------
@ExceptionHandler(MethodArgumentNotValidException.class)
   public ResponseEntity<ErrorMessage> handleArgumentNotValidException(MethodArgumentNotValidException ex, Locale locale) {
      BindingResult result = ex.getBindingResult();
      List<String> errorMessages = result.getAllErrors()
              .stream()
              .map(err-> messageSource.getMessage(err, locale))
              .collect(Collectors.toList());
      return new ResponseEntity<>(new ErrorMessage(errorMessages), HttpStatus.BAD_REQUEST);
}
NotNull.obj.greeting=Please, provide a valid greeting message.
Size.obj.greeting=Greeting message  must contain between {2} and {1} characters.
NotNull.obj.greeting=Por favor, proporcione un mensaje de saludo válido.
Size.obj.greeting=El mensaje de bienvenida debe contener entre {2} y {1} caracteres.
curl -X POST -H "Content-Type: application/json" -H "Accept-Language: es-MX" -d '{
  "description": "employee info"
}' http://localhost:8080/api/employee
-----------------------
@ExceptionHandler(MethodArgumentNotValidException.class)
   public ResponseEntity<ErrorMessage> handleArgumentNotValidException(MethodArgumentNotValidException ex, Locale locale) {
      BindingResult result = ex.getBindingResult();
      List<String> errorMessages = result.getAllErrors()
              .stream()
              .map(err-> messageSource.getMessage(err, locale))
              .collect(Collectors.toList());
      return new ResponseEntity<>(new ErrorMessage(errorMessages), HttpStatus.BAD_REQUEST);
}
NotNull.obj.greeting=Please, provide a valid greeting message.
Size.obj.greeting=Greeting message  must contain between {2} and {1} characters.
NotNull.obj.greeting=Por favor, proporcione un mensaje de saludo válido.
Size.obj.greeting=El mensaje de bienvenida debe contener entre {2} y {1} caracteres.
curl -X POST -H "Content-Type: application/json" -H "Accept-Language: es-MX" -d '{
  "description": "employee info"
}' http://localhost:8080/api/employee
-----------------------
@ExceptionHandler(MethodArgumentNotValidException.class)
   public ResponseEntity<ErrorMessage> handleArgumentNotValidException(MethodArgumentNotValidException ex, Locale locale) {
      BindingResult result = ex.getBindingResult();
      List<String> errorMessages = result.getAllErrors()
              .stream()
              .map(err-> messageSource.getMessage(err, locale))
              .collect(Collectors.toList());
      return new ResponseEntity<>(new ErrorMessage(errorMessages), HttpStatus.BAD_REQUEST);
}
NotNull.obj.greeting=Please, provide a valid greeting message.
Size.obj.greeting=Greeting message  must contain between {2} and {1} characters.
NotNull.obj.greeting=Por favor, proporcione un mensaje de saludo válido.
Size.obj.greeting=El mensaje de bienvenida debe contener entre {2} y {1} caracteres.
curl -X POST -H "Content-Type: application/json" -H "Accept-Language: es-MX" -d '{
  "description": "employee info"
}' http://localhost:8080/api/employee
-----------------------
@Bean
public Validator validatorFactory (MessageSource messageSource) {
    LocalValidatorFactoryBean validator =  new LocalValidatorFactoryBean();
    validator.setValidationMessageSource(messageSource);
    return validator;
}

@Bean
public MessageSource messageSource() {
    ReloadableResourceBundleMessageSource bean = new ReloadableResourceBundleMessageSource();
    bean.addBasenames("classpath:org.hibernate.validator.ValidationMessages", "classpath:validation_errors"); // validation_errors.properties is my resource bundle
    bean.setDefaultEncoding("UTF-8");
    return bean;
}
javax.validation.constraints.NotNull.message = Not null please!
javax.validation.constraints.NotBlank.message = Not empty please!
org.hibernate.validator.constraints.Length.message = String length between {min} and {max} please!
@ResponseBody
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
List<ErrorMessage> methodArgumentNotValidHandler(MethodArgumentNotValidException e) {
    return e.getBindingResult().getAllErrors().stream()
            .filter(objectError -> objectError.contains(ConstraintViolation.class))
            .map(objectError -> objectError.unwrap(ConstraintViolation.class))
            .map(ConstraintViolation::getMessage)
            .map(message -> new ErrorMessage("VE-400", message))
            .collect(Collectors.toList());
}
-----------------------
@Bean
public Validator validatorFactory (MessageSource messageSource) {
    LocalValidatorFactoryBean validator =  new LocalValidatorFactoryBean();
    validator.setValidationMessageSource(messageSource);
    return validator;
}

@Bean
public MessageSource messageSource() {
    ReloadableResourceBundleMessageSource bean = new ReloadableResourceBundleMessageSource();
    bean.addBasenames("classpath:org.hibernate.validator.ValidationMessages", "classpath:validation_errors"); // validation_errors.properties is my resource bundle
    bean.setDefaultEncoding("UTF-8");
    return bean;
}
javax.validation.constraints.NotNull.message = Not null please!
javax.validation.constraints.NotBlank.message = Not empty please!
org.hibernate.validator.constraints.Length.message = String length between {min} and {max} please!
@ResponseBody
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
List<ErrorMessage> methodArgumentNotValidHandler(MethodArgumentNotValidException e) {
    return e.getBindingResult().getAllErrors().stream()
            .filter(objectError -> objectError.contains(ConstraintViolation.class))
            .map(objectError -> objectError.unwrap(ConstraintViolation.class))
            .map(ConstraintViolation::getMessage)
            .map(message -> new ErrorMessage("VE-400", message))
            .collect(Collectors.toList());
}
-----------------------
@Bean
public Validator validatorFactory (MessageSource messageSource) {
    LocalValidatorFactoryBean validator =  new LocalValidatorFactoryBean();
    validator.setValidationMessageSource(messageSource);
    return validator;
}

@Bean
public MessageSource messageSource() {
    ReloadableResourceBundleMessageSource bean = new ReloadableResourceBundleMessageSource();
    bean.addBasenames("classpath:org.hibernate.validator.ValidationMessages", "classpath:validation_errors"); // validation_errors.properties is my resource bundle
    bean.setDefaultEncoding("UTF-8");
    return bean;
}
javax.validation.constraints.NotNull.message = Not null please!
javax.validation.constraints.NotBlank.message = Not empty please!
org.hibernate.validator.constraints.Length.message = String length between {min} and {max} please!
@ResponseBody
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
List<ErrorMessage> methodArgumentNotValidHandler(MethodArgumentNotValidException e) {
    return e.getBindingResult().getAllErrors().stream()
            .filter(objectError -> objectError.contains(ConstraintViolation.class))
            .map(objectError -> objectError.unwrap(ConstraintViolation.class))
            .map(ConstraintViolation::getMessage)
            .map(message -> new ErrorMessage("VE-400", message))
            .collect(Collectors.toList());
}

How to manage OAuth flow in mobile application with server

copy iconCopydownload iconDownload
curl --location --request POST 'http://localhost:8080/auth/realms/testrealm/protocol/openid-connect/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'grant_type=authorization_code' \
--data-urlencode 'client_id=confidentialclient' \
--data-urlencode 'client_secret=<CLIENT_SECRET_VALUE>' \
--data-urlencode 'code=<AUTHORIZATION_CODE_VALUE>' \
--data-urlencode 'redirect_uri=http://localhost:8080/callback' \
--data-urlencode 'code_verifier=<CODE_VERIFIER_PKCE>'
curl --location --request POST 'http://localhost:8080/auth/realms/testrealm/protocol/openid-connect/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'grant_type=authorization_code' \
--data-urlencode 'client_id=publiclcient' \
--data-urlencode 'code=<AUTHORIZATION_CODE_VALUE>' \
--data-urlencode 'redirect_uri=http://localhost:8080/callback' \
--data-urlencode 'code_verifier=<CODE_VERIFIER_PKCE>'

-----------------------
curl --location --request POST 'http://localhost:8080/auth/realms/testrealm/protocol/openid-connect/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'grant_type=authorization_code' \
--data-urlencode 'client_id=confidentialclient' \
--data-urlencode 'client_secret=<CLIENT_SECRET_VALUE>' \
--data-urlencode 'code=<AUTHORIZATION_CODE_VALUE>' \
--data-urlencode 'redirect_uri=http://localhost:8080/callback' \
--data-urlencode 'code_verifier=<CODE_VERIFIER_PKCE>'
curl --location --request POST 'http://localhost:8080/auth/realms/testrealm/protocol/openid-connect/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'grant_type=authorization_code' \
--data-urlencode 'client_id=publiclcient' \
--data-urlencode 'code=<AUTHORIZATION_CODE_VALUE>' \
--data-urlencode 'redirect_uri=http://localhost:8080/callback' \
--data-urlencode 'code_verifier=<CODE_VERIFIER_PKCE>'

Could not set unknown property 'mainClassName' for extension 'springBoot' of type org.springframework.boot.gradle.dsl.SpringBootExtension

copy iconCopydownload iconDownload
springBoot {
    mainClass = 'com.mir3.service.contactfileparser.Main'
}
/**
 * Returns the fully-qualified name of the application's main class.
 * @return the fully-qualified name of the application's main class
 * @since 2.4.0
 */
public Property<String> getMainClass() {
    return this.mainClass;
}
-----------------------
springBoot {
    mainClass = 'com.mir3.service.contactfileparser.Main'
}
/**
 * Returns the fully-qualified name of the application's main class.
 * @return the fully-qualified name of the application's main class
 * @since 2.4.0
 */
public Property<String> getMainClass() {
    return this.mainClass;
}

Cosmos DB Container Name with EL not resolving in SpringBootTest

copy iconCopydownload iconDownload
@ContextConfiguration(classes = {TestContextConfig.class, MyClass1.class, MyClass2.class})

Java Predicate implementation can't access global final variable

copy iconCopydownload iconDownload
private final TestService service;
private final Predicate<User> userPredicate;

@AutoWired
public MyService(TestService service) {
  this.service = service;
  this.userPredicate = user -> service.isValidUser(user);
}

Spring boot applicaiton unable to find SQLite jdbc driver class

copy iconCopydownload iconDownload
package com.mehul.SQLiteDemo.dialect;

import java.sql.Types;

import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.function.SQLFunctionTemplate;
import org.hibernate.dialect.function.StandardSQLFunction;
import org.hibernate.dialect.function.VarArgsSQLFunction;
import org.hibernate.type.StringType;

public class SQLDialect extends Dialect {
    public SQLDialect() {
        registerColumnType(Types.BIT, "integer");
        registerColumnType(Types.TINYINT, "tinyint");
        registerColumnType(Types.SMALLINT, "smallint");
        registerColumnType(Types.INTEGER, "integer");
        registerColumnType(Types.BIGINT, "bigint");
        registerColumnType(Types.FLOAT, "float");
        registerColumnType(Types.REAL, "real");
        registerColumnType(Types.DOUBLE, "double");
        registerColumnType(Types.NUMERIC, "numeric");
        registerColumnType(Types.DECIMAL, "decimal");
        registerColumnType(Types.CHAR, "char");
        registerColumnType(Types.VARCHAR, "varchar");
        registerColumnType(Types.LONGVARCHAR, "longvarchar");
        registerColumnType(Types.DATE, "date");
        registerColumnType(Types.TIME, "time");
        registerColumnType(Types.TIMESTAMP, "timestamp");
        registerColumnType(Types.BINARY, "blob");
        registerColumnType(Types.VARBINARY, "blob");
        registerColumnType(Types.LONGVARBINARY, "blob");
        // registerColumnType(Types.NULL, "null");
        registerColumnType(Types.BLOB, "blob");
        registerColumnType(Types.CLOB, "clob");
        registerColumnType(Types.BOOLEAN, "integer");

        registerFunction("concat", new VarArgsSQLFunction(StringType.INSTANCE, "", "||", ""));
        registerFunction("mod", new SQLFunctionTemplate(StringType.INSTANCE, "?1 % ?2"));
        registerFunction("substr", new StandardSQLFunction("substr", StringType.INSTANCE));
        registerFunction("substring", new StandardSQLFunction("substr", StringType.INSTANCE));
    }

    public boolean supportsIdentityColumns() {
        return true;
    }

    public boolean hasDataTypeInIdentityColumn() {
        return false; // As specify in NHibernate dialect
    }

    public String getIdentityColumnString() {
        // return "integer primary key autoincrement";
        return "integer";
    }

    public String getIdentitySelectString() {
        return "select last_insert_rowid()";
    }

    public boolean supportsLimit() {
        return true;
    }

    protected String getLimitString(String query, boolean hasOffset) {
        return new StringBuffer(query.length() + 20).append(query).append(hasOffset ? " limit ? offset ?" : " limit ?")
                .toString();
    }

    public boolean supportsTemporaryTables() {
        return true;
    }

    public String getCreateTemporaryTableString() {
        return "create temporary table if not exists";
    }

    public boolean dropTemporaryTableAfterUse() {
        return false;
    }

    public boolean supportsCurrentTimestampSelection() {
        return true;
    }

    public boolean isCurrentTimestampSelectStringCallable() {
        return false;
    }

    public String getCurrentTimestampSelectString() {
        return "select current_timestamp";
    }

    public boolean supportsUnionAll() {
        return true;
    }

    public boolean hasAlterTable() {
        return false; // As specify in NHibernate dialect
    }

    public boolean dropConstraints() {
        return false;
    }

    public String getAddColumnString() {
        return "add column";
    }

    public String getForUpdateString() {
        return "";
    }

    public boolean supportsOuterJoinForUpdate() {
        return false;
    }

    public String getDropForeignKeyString() {
        throw new UnsupportedOperationException("No drop foreign key syntax supported by SQLiteDialect");
    }

    public String getAddForeignKeyConstraintString(String constraintName, String[] foreignKey, String referencedTable,
            String[] primaryKey, boolean referencesPrimaryKey) {
        throw new UnsupportedOperationException("No add foreign key syntax supported by SQLiteDialect");
    }

    public String getAddPrimaryKeyConstraintString(String constraintName) {
        throw new UnsupportedOperationException("No add primary key syntax supported by SQLiteDialect");
    }

    public boolean supportsIfExistsBeforeTableName() {
        return true;
    }

    public boolean supportsCascadeDelete() {
        return false;
    }
}
-----------------------
import java.sql.Types;
import org.hibernate.dialect.Dialect;

public class SQLiteDialect extends Dialect {
 public SQLiteDialect() {
  super();
  registerColumnType(Types.BIT, "integer");
  registerColumnType(Types.TINYINT, "tinyint");
  registerColumnType(Types.SMALLINT, "smallint");
  registerColumnType(Types.INTEGER, "integer");
  registerColumnType(Types.BIGINT, "bigint");
  registerColumnType(Types.FLOAT, "float");
  registerColumnType(Types.REAL, "real");
  registerColumnType(Types.DOUBLE, "double");
  registerColumnType(Types.NUMERIC, "numeric");
  registerColumnType(Types.DECIMAL, "decimal");
  registerColumnType(Types.CHAR, "char");
  registerColumnType(Types.VARCHAR, "varchar");
  .
  .
  .
 }
}
    <dependency>
        <groupId>com.github.gwenn</groupId>
        <artifactId>sqlite-dialect</artifactId>
        <version>0.1.2</version>
    </dependency>
hibernate.dialect=org.sqlite.hibernate.dialect.SQLiteDialect

-----------------------
import java.sql.Types;
import org.hibernate.dialect.Dialect;

public class SQLiteDialect extends Dialect {
 public SQLiteDialect() {
  super();
  registerColumnType(Types.BIT, "integer");
  registerColumnType(Types.TINYINT, "tinyint");
  registerColumnType(Types.SMALLINT, "smallint");
  registerColumnType(Types.INTEGER, "integer");
  registerColumnType(Types.BIGINT, "bigint");
  registerColumnType(Types.FLOAT, "float");
  registerColumnType(Types.REAL, "real");
  registerColumnType(Types.DOUBLE, "double");
  registerColumnType(Types.NUMERIC, "numeric");
  registerColumnType(Types.DECIMAL, "decimal");
  registerColumnType(Types.CHAR, "char");
  registerColumnType(Types.VARCHAR, "varchar");
  .
  .
  .
 }
}
    <dependency>
        <groupId>com.github.gwenn</groupId>
        <artifactId>sqlite-dialect</artifactId>
        <version>0.1.2</version>
    </dependency>
hibernate.dialect=org.sqlite.hibernate.dialect.SQLiteDialect

-----------------------
import java.sql.Types;
import org.hibernate.dialect.Dialect;

public class SQLiteDialect extends Dialect {
 public SQLiteDialect() {
  super();
  registerColumnType(Types.BIT, "integer");
  registerColumnType(Types.TINYINT, "tinyint");
  registerColumnType(Types.SMALLINT, "smallint");
  registerColumnType(Types.INTEGER, "integer");
  registerColumnType(Types.BIGINT, "bigint");
  registerColumnType(Types.FLOAT, "float");
  registerColumnType(Types.REAL, "real");
  registerColumnType(Types.DOUBLE, "double");
  registerColumnType(Types.NUMERIC, "numeric");
  registerColumnType(Types.DECIMAL, "decimal");
  registerColumnType(Types.CHAR, "char");
  registerColumnType(Types.VARCHAR, "varchar");
  .
  .
  .
 }
}
    <dependency>
        <groupId>com.github.gwenn</groupId>
        <artifactId>sqlite-dialect</artifactId>
        <version>0.1.2</version>
    </dependency>
hibernate.dialect=org.sqlite.hibernate.dialect.SQLiteDialect

-----------------------
<hibernate.version>5.1.0.Final</hibernate.version>

The spring boot project cannot access static files

copy iconCopydownload iconDownload
   <link href="/spring-demo/static/js/chunk-vendors.365b8cfb.js" rel="preload" as="script">

Community Discussions

Trending Discussions on springBoot
  • Java @Override equals(): When this.getClass() != o.getClass() fails but shouldn't
  • Springboot 2.6.0 / Spring fox 3 - Failed to start bean 'documentationPluginsBootstrapper'
  • How to add basepath in OpenApi so that it is autogenerated with maven?
  • Auth0 error : Authorization server not configured with default connection
  • Springboot: Better handling of error messages
  • How to manage OAuth flow in mobile application with server
  • Could not set unknown property 'mainClassName' for extension 'springBoot' of type org.springframework.boot.gradle.dsl.SpringBootExtension
  • Cosmos DB Container Name with EL not resolving in SpringBootTest
  • Java Predicate implementation can't access global final variable
  • Spring boot applicaiton unable to find SQLite jdbc driver class
Trending Discussions on springBoot

QUESTION

Java @Override equals(): When this.getClass() != o.getClass() fails but shouldn't

Asked 2022-Apr-17 at 12:25

I have this @Override for equals() in my MyClass class:

public class MyClass extends MySuperClass
{
  ...
  @Override
  public boolean equals( Object o )
  {
    if ( this == o )
    {
      return true;
    }
    if ( o == null || this.getClass() != o.getClass() )
    {
      return false;
    }
    if ( !super.equals( o ) )
    {
      return false;
    }
    MyClass that = ( MyClass ) o;
    return this.var1.equals( that.var1 ) && this.var2.equals( that.var2 );
  }
  ...
}

Pretty standard. Matter of fact, it follows Java best practices.
Later in life I have this in another sub-package class (my controller class):

...
package com.a.b.api.controllers;
...
import com.a.b.jpa.models.MyClass;
...
MyClass myObject1 = new MyClass( var1, var2 );
MyClass myObject2 = this.myClassRepository.getById( 1 ); // SpringBoot/Jpa/Hibernate

if ( myObject2.equals( myObject1 ) )
{
   ...do something...
}
...
this.myClassRepository.save( myObject1 );
...

My problem is that the .equals() is always failing here:

if ( o == null || this.getClass() != o.getClass() )

because java says that this.getClass() and o.getClass() are NOT equal. When I debug the code (in Intellij IDEA 2022.1 UE) I see this:

this.getClass() = MyClass@13706

but

o.getClass = com.a.b.jpa.models.MyClass@8f7462

But they are the same class! Almost every Java book, tutorial, blog, Intellij IDEA, etc. demonstrates the .equals() this way. I have tried this in Ubuntu 20.04.4 LTS java-14-openjdk-amd64 and java-17-openjdk-amd64 with the same results.

What am I doing wrong?

ANSWER

Answered 2022-Apr-14 at 15:31

myObject2 is an instance of a proxy class, generated at runtime by Hibernate using Byte Buddy. The generated proxy intercepts all method invocations, that's why getClass() returns different results.

As an alternative to getClass(), using instanceof might be another approach:

if ( !(this instanceof MyClass && o instanceof MyClass) )
{
   return false;
}

However keep in mind that instanceof has its drawbacks. It violates the symmetry principle.

You shouldn't compare these objects in the first place, since a new object should be different from a Hibernate managed one that has a persistent state.

Source https://stackoverflow.com/questions/71873676

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

Vulnerabilities

No vulnerabilities reported

Install springBoot

You can download it from GitHub.
You can use springBoot like any standard Java library. Please include the the jar files in your classpath. You can also use any IDE and you can run and debug the springBoot component as you would do with any other Java program. Best practice is to use a build tool that supports dependency management such as Maven or Gradle. For Maven installation, please refer maven.apache.org. For Gradle installation, please refer gradle.org .

Support

For any new features, suggestions and bugs create an issue on GitHub. If you have any questions check and ask questions on community page Stack Overflow .

DOWNLOAD this Library from

Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

Share this Page

share link
Consider Popular Security Framework Libraries
Compare Security Framework Libraries with Highest Support
Compare Security Framework Libraries with Highest Quality
Compare Security Framework Libraries with Permissive License
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

  • © 2022 Open Weaver Inc.