spring-boot | Spring Boot helps you to create Spring | Application Framework library

 by   spring-projects Java Version: 3.0.3 License: Apache-2.0

kandi X-RAY | spring-boot Summary

spring-boot is a Java library typically used in Server, Application Framework, Spring Boot, Spring applications. spring-boot has no bugs, it has no vulnerabilities, it has build file available, it has a Permissive License and it has high support. You can download it from GitHub, Maven.
Spring Boot helps you to create Spring-powered, production-grade applications and services with absolute minimum fuss. It takes an opinionated view of the Spring platform so that new and existing users can quickly get to the bits they need. You can use Spring Boot to create stand-alone Java applications that can be started using java -jar or more traditional WAR deployments. We also provide a command-line tool that runs Spring scripts.
    Support
      Quality
        Security
          License
            Reuse
            Support
              Quality
                Security
                  License
                    Reuse

                      kandi-support Support

                        summary
                        spring-boot has a highly active ecosystem.
                        summary
                        It has 66355 star(s) with 38299 fork(s). There are 3381 watchers for this library.
                        summary
                        There were 10 major release(s) in the last 6 months.
                        summary
                        There are 590 open issues and 28255 have been closed. On average issues are closed in 81 days. There are 42 open pull requests and 0 closed requests.
                        summary
                        It has a positive sentiment in the developer community.
                        summary
                        The latest version of spring-boot is 3.0.3
                        spring-boot Support
                          Best in #Application Framework
                            Average in #Application Framework
                            spring-boot Support
                              Best in #Application Framework
                                Average in #Application Framework

                                  kandi-Quality Quality

                                    summary
                                    spring-boot has 0 bugs and 0 code smells.
                                    spring-boot Quality
                                      Best in #Application Framework
                                        Average in #Application Framework
                                        spring-boot Quality
                                          Best in #Application Framework
                                            Average in #Application Framework

                                              kandi-Security Security

                                                summary
                                                spring-boot has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
                                                summary
                                                spring-boot code analysis shows 0 unresolved vulnerabilities.
                                                summary
                                                There are 0 security hotspots that need review.
                                                spring-boot Security
                                                  Best in #Application Framework
                                                    Average in #Application Framework
                                                    spring-boot Security
                                                      Best in #Application Framework
                                                        Average in #Application Framework

                                                          kandi-License License

                                                            summary
                                                            spring-boot is licensed under the Apache-2.0 License. This license is Permissive.
                                                            summary
                                                            Permissive licenses have the least restrictions, and you can use them in most projects.
                                                            spring-boot License
                                                              Best in #Application Framework
                                                                Average in #Application Framework
                                                                spring-boot License
                                                                  Best in #Application Framework
                                                                    Average in #Application Framework

                                                                      kandi-Reuse Reuse

                                                                        summary
                                                                        spring-boot releases are available to install and integrate.
                                                                        summary
                                                                        Deployable package is available in Maven.
                                                                        summary
                                                                        Build file is available. You can build the component from source.
                                                                        summary
                                                                        Installation instructions, examples and code snippets are available.
                                                                        summary
                                                                        It has 364554 lines of code, 39322 functions and 6514 files.
                                                                        summary
                                                                        It has low code complexity. Code complexity directly impacts maintainability of the code.
                                                                        spring-boot Reuse
                                                                          Best in #Application Framework
                                                                            Average in #Application Framework
                                                                            spring-boot Reuse
                                                                              Best in #Application Framework
                                                                                Average in #Application Framework
                                                                                  Top functions reviewed by kandi - BETA
                                                                                  kandi has reviewed spring-boot and discovered the below as its top functions. This is intended to give you an instant insight into spring-boot implemented functionality, and help decide if they suit your requirements.
                                                                                  • Generate the URI for the project .
                                                                                    • Reads a literal .
                                                                                      • Gets the matching beans for the given conditions .
                                                                                        • Parse a string value .
                                                                                          • Appends a string to the output .
                                                                                            • Tokenize a JSON string .
                                                                                              • Compiles given sources .
                                                                                                • Gets the urls from a jar file .
                                                                                                  • Writes a mojo to an output file .
                                                                                                    • Determines whether two elements are equals to the same element .
                                                                                                      Get all kandi verified functions for this library.
                                                                                                      Get all kandi verified functions for this library.

                                                                                                      spring-boot Key Features

                                                                                                      Provide a radically faster and widely accessible getting started experience for all Spring development.
                                                                                                      Be opinionated, but get out of the way quickly as requirements start to diverge from the defaults.
                                                                                                      Provide a range of non-functional features common to large classes of projects (for example, embedded servers, security, metrics, health checks, externalized configuration).
                                                                                                      Absolutely no code generation and no requirement for XML configuration.

                                                                                                      spring-boot Examples and Code Snippets

                                                                                                      No Code Snippets are available at this moment for spring-boot.
                                                                                                      Community Discussions

                                                                                                      Trending Discussions on spring-boot

                                                                                                      EmbeddedKafka failing since Spring Boot 2.6.X : AccessDeniedException: ..\AppData\Local\Temp\spring.kafka*
                                                                                                      chevron right
                                                                                                      Springboot 2.6.0 / Spring fox 3 - Failed to start bean 'documentationPluginsBootstrapper'
                                                                                                      chevron right
                                                                                                      IntelliJ - Invalid source release: 17
                                                                                                      chevron right
                                                                                                      Spring Cloud Gateway; Spring MVC found on classpath, which is incompatible with Spring Cloud Gateway Issue
                                                                                                      chevron right
                                                                                                      Added corsConfigurationSource and still an error "has been blocked by CORS policy"
                                                                                                      chevron right
                                                                                                      Spring Boot 2.6 and Angular in static Resources
                                                                                                      chevron right
                                                                                                      org.junit.platform.commons.JUnitException: TestEngine with ID 'junit-jupiter' failed to discover tests
                                                                                                      chevron right
                                                                                                      Prometheus cannot scrape from spring-boot application over HTTPS
                                                                                                      chevron right
                                                                                                      Kotlin Spring Boot bean validation not working
                                                                                                      chevron right
                                                                                                      Spring boot 2.6.0 Error creating bean with name 'webSecurityConfig'
                                                                                                      chevron right

                                                                                                      QUESTION

                                                                                                      EmbeddedKafka failing since Spring Boot 2.6.X : AccessDeniedException: ..\AppData\Local\Temp\spring.kafka*
                                                                                                      Asked 2022-Mar-25 at 12:39

                                                                                                      e: this has been fixed through Spring Boot 2.6.5 (see https://github.com/spring-projects/spring-boot/issues/30243)

                                                                                                      Since upgrading to Spring Boot 2.6.X (in my case: 2.6.1), I have multiple projects that now have failing unit-tests on Windows that cannot start EmbeddedKafka, that do run with Linux

                                                                                                      There is multiple errors, but this is the first one thrown

                                                                                                      ...
                                                                                                        .   ____          _            __ _ _
                                                                                                       /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
                                                                                                      ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
                                                                                                       \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
                                                                                                        '  |____| .__|_| |_|_| |_\__, | / / / /
                                                                                                       =========|_|==============|___/=/_/_/_/
                                                                                                       :: Spring Boot ::                (v2.6.1)
                                                                                                      
                                                                                                      2021-12-09 16:15:00.300  INFO 13864 --- [           main] k.utils.Log4jControllerRegistration$     : Registered kafka:type=kafka.Log4jController MBean
                                                                                                      2021-12-09 16:15:00.420  INFO 13864 --- [           main] o.a.zookeeper.server.ZooKeeperServer     : 
                                                                                                      2021-12-09 16:15:00.420  INFO 13864 --- [           main] o.a.zookeeper.server.ZooKeeperServer     :   ______                  _                                          
                                                                                                      2021-12-09 16:15:00.420  INFO 13864 --- [           main] o.a.zookeeper.server.ZooKeeperServer     :  |___  /                 | |                                         
                                                                                                      2021-12-09 16:15:00.420  INFO 13864 --- [           main] o.a.zookeeper.server.ZooKeeperServer     :     / /    ___     ___   | | __   ___    ___   _ __     ___   _ __   
                                                                                                      2021-12-09 16:15:00.420  INFO 13864 --- [           main] o.a.zookeeper.server.ZooKeeperServer     :    / /    / _ \   / _ \  | |/ /  / _ \  / _ \ | '_ \   / _ \ | '__|
                                                                                                      2021-12-09 16:15:00.420  INFO 13864 --- [           main] o.a.zookeeper.server.ZooKeeperServer     :   / /__  | (_) | | (_) | |   <  |  __/ |  __/ | |_) | |  __/ | |    
                                                                                                      2021-12-09 16:15:00.420  INFO 13864 --- [           main] o.a.zookeeper.server.ZooKeeperServer     :  /_____|  \___/   \___/  |_|\_\  \___|  \___| | .__/   \___| |_|
                                                                                                      2021-12-09 16:15:00.420  INFO 13864 --- [           main] o.a.zookeeper.server.ZooKeeperServer     :                                               | |                     
                                                                                                      2021-12-09 16:15:00.420  INFO 13864 --- [           main] o.a.zookeeper.server.ZooKeeperServer     :                                               |_|                     
                                                                                                      2021-12-09 16:15:00.420  INFO 13864 --- [           main] o.a.zookeeper.server.ZooKeeperServer     : 
                                                                                                      2021-12-09 16:15:00.422  INFO 13864 --- [           main] o.a.zookeeper.server.ZooKeeperServer     : Server environment:zookeeper.version=3.6.3--6401e4ad2087061bc6b9f80dec2d69f2e3c8660a, built on 04/08/2021 16:35 GMT
                                                                                                      2021-12-09 16:15:00.422  INFO 13864 --- [           main] o.a.zookeeper.server.ZooKeeperServer     : Server environment:host.name=host.docker.internal
                                                                                                      2021-12-09 16:15:00.422  INFO 13864 --- [           main] o.a.zookeeper.server.ZooKeeperServer     : Server environment:java.version=11.0.11
                                                                                                      2021-12-09 16:15:00.422  INFO 13864 --- [           main] o.a.zookeeper.server.ZooKeeperServer     : Server environment:java.vendor=AdoptOpenJDK
                                                                                                      ...
                                                                                                      2021-12-09 16:15:01.015  INFO 13864 --- [nelReaper-Fetch] lientQuotaManager$ThrottledChannelReaper : [ThrottledChannelReaper-Fetch]: Starting
                                                                                                      2021-12-09 16:15:01.015  INFO 13864 --- [lReaper-Produce] lientQuotaManager$ThrottledChannelReaper : [ThrottledChannelReaper-Produce]: Starting
                                                                                                      2021-12-09 16:15:01.016  INFO 13864 --- [lReaper-Request] lientQuotaManager$ThrottledChannelReaper : [ThrottledChannelReaper-Request]: Starting
                                                                                                      2021-12-09 16:15:01.017  INFO 13864 --- [trollerMutation] lientQuotaManager$ThrottledChannelReaper : [ThrottledChannelReaper-ControllerMutation]: Starting
                                                                                                      2021-12-09 16:15:01.037  INFO 13864 --- [           main] kafka.log.LogManager                     : Loading logs from log dirs ArraySeq(C:\Users\ddrop\AppData\Local\Temp\spring.kafka.bf8e2b62-a1f2-4092-b292-a15e35bd31ad18378079390566696446)
                                                                                                      2021-12-09 16:15:01.040  INFO 13864 --- [           main] kafka.log.LogManager                     : Attempting recovery for all logs in C:\Users\ddrop\AppData\Local\Temp\spring.kafka.bf8e2b62-a1f2-4092-b292-a15e35bd31ad18378079390566696446 since no clean shutdown file was found
                                                                                                      2021-12-09 16:15:01.043  INFO 13864 --- [           main] kafka.log.LogManager                     : Loaded 0 logs in 6ms.
                                                                                                      2021-12-09 16:15:01.043  INFO 13864 --- [           main] kafka.log.LogManager                     : Starting log cleanup with a period of 300000 ms.
                                                                                                      2021-12-09 16:15:01.045  INFO 13864 --- [           main] kafka.log.LogManager                     : Starting log flusher with a default period of 9223372036854775807 ms.
                                                                                                      2021-12-09 16:15:01.052  INFO 13864 --- [           main] kafka.log.LogCleaner                     : Starting the log cleaner
                                                                                                      2021-12-09 16:15:01.059  INFO 13864 --- [leaner-thread-0] kafka.log.LogCleaner                     : [kafka-log-cleaner-thread-0]: Starting
                                                                                                      2021-12-09 16:15:01.224  INFO 13864 --- [name=forwarding] k.s.BrokerToControllerRequestThread      : [BrokerToControllerChannelManager broker=0 name=forwarding]: Starting
                                                                                                      2021-12-09 16:15:01.325  INFO 13864 --- [           main] kafka.network.ConnectionQuotas           : Updated connection-accept-rate max connection creation rate to 2147483647
                                                                                                      2021-12-09 16:15:01.327  INFO 13864 --- [           main] kafka.network.Acceptor                   : Awaiting socket connections on localhost:63919.
                                                                                                      2021-12-09 16:15:01.345  INFO 13864 --- [           main] kafka.network.SocketServer               : [SocketServer listenerType=ZK_BROKER, nodeId=0] Created data-plane acceptor and processors for endpoint : ListenerName(PLAINTEXT)
                                                                                                      2021-12-09 16:15:01.350  INFO 13864 --- [0 name=alterIsr] k.s.BrokerToControllerRequestThread      : [BrokerToControllerChannelManager broker=0 name=alterIsr]: Starting
                                                                                                      2021-12-09 16:15:01.364  INFO 13864 --- [eaper-0-Produce] perationPurgatory$ExpiredOperationReaper : [ExpirationReaper-0-Produce]: Starting
                                                                                                      2021-12-09 16:15:01.364  INFO 13864 --- [nReaper-0-Fetch] perationPurgatory$ExpiredOperationReaper : [ExpirationReaper-0-Fetch]: Starting
                                                                                                      2021-12-09 16:15:01.365  INFO 13864 --- [0-DeleteRecords] perationPurgatory$ExpiredOperationReaper : [ExpirationReaper-0-DeleteRecords]: Starting
                                                                                                      2021-12-09 16:15:01.365  INFO 13864 --- [r-0-ElectLeader] perationPurgatory$ExpiredOperationReaper : [ExpirationReaper-0-ElectLeader]: Starting
                                                                                                      2021-12-09 16:15:01.374  INFO 13864 --- [rFailureHandler] k.s.ReplicaManager$LogDirFailureHandler  : [LogDirFailureHandler]: Starting
                                                                                                      2021-12-09 16:15:01.390  INFO 13864 --- [           main] kafka.zk.KafkaZkClient                   : Creating /brokers/ids/0 (is it secure? false)
                                                                                                      2021-12-09 16:15:01.400  INFO 13864 --- [           main] kafka.zk.KafkaZkClient                   : Stat of the created znode at /brokers/ids/0 is: 25,25,1639062901396,1639062901396,1,0,0,72059919267528704,204,0,25
                                                                                                      
                                                                                                      2021-12-09 16:15:01.400  INFO 13864 --- [           main] kafka.zk.KafkaZkClient                   : Registered broker 0 at path /brokers/ids/0 with addresses: PLAINTEXT://localhost:63919, czxid (broker epoch): 25
                                                                                                      2021-12-09 16:15:01.410 ERROR 13864 --- [           main] kafka.server.BrokerMetadataCheckpoint    : Failed to write meta.properties due to
                                                                                                      
                                                                                                      java.nio.file.AccessDeniedException: C:\Users\ddrop\AppData\Local\Temp\spring.kafka.bf8e2b62-a1f2-4092-b292-a15e35bd31ad18378079390566696446
                                                                                                          at java.base/sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:89) ~[na:na]
                                                                                                          at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:103) ~[na:na]
                                                                                                          at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:108) ~[na:na]
                                                                                                      
                                                                                                      package com.example.demo;
                                                                                                      
                                                                                                      import org.junit.jupiter.api.Test;
                                                                                                      import org.springframework.boot.test.context.SpringBootTest;
                                                                                                      import org.springframework.kafka.test.context.EmbeddedKafka;
                                                                                                      
                                                                                                      @SpringBootTest
                                                                                                      @EmbeddedKafka
                                                                                                      class ApplicationTest {
                                                                                                      
                                                                                                          @Test
                                                                                                          void run() {
                                                                                                              int i = 1 + 1; // just a line of code to set a debug-point
                                                                                                          }
                                                                                                      }
                                                                                                      

                                                                                                      I do not have this error when pinning kafka.version to 2.8.1 in pom.xml's properties.

                                                                                                      It seems like the cause is in Kafka itself, but I have a hard time figuring out if it is spring-kafka intitializing Kafka via EmbeddedKafka incorrectly or if Kafka itself is the culrit here.

                                                                                                      Anyone has an idea? Am I missing a test-parameter to set?

                                                                                                      ANSWER

                                                                                                      Answered 2021-Dec-09 at 15:51

                                                                                                      Known bug on the Apache Kafka side. Nothing to do from Spring perspective. See more info here: https://github.com/spring-projects/spring-kafka/discussions/2027. And here: https://issues.apache.org/jira/browse/KAFKA-13391

                                                                                                      You need to wait until Apache Kafka 3.0.1 or don't use embedded Kafka and just rely on the Testcontainers, for example, or fully external Apache Kafka broker.

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

                                                                                                      QUESTION

                                                                                                      Springboot 2.6.0 / Spring fox 3 - Failed to start bean 'documentationPluginsBootstrapper'
                                                                                                      Asked 2022-Mar-25 at 06:14

                                                                                                      I'm trying to initiate a Springboot project using Open Jdk 15, Springboot 2.6.0, Springfox 3. We are working on a project that replaced Netty as the webserver and used Jetty instead because we do not need a non-blocking environment.

                                                                                                      In the code we depend primarily on Reactor API (Flux, Mono), so we can not remove org.springframework.boot:spring-boot-starter-webflux dependencies.

                                                                                                      I replicated the problem that we have in a new project.: https://github.com/jvacaq/spring-fox.

                                                                                                      I figured out that these lines in our build.gradle file are the origin of the problem.

                                                                                                      compile("org.springframework.boot:spring-boot-starter-web") {
                                                                                                         exclude module: "spring-boot-starter-tomcat"
                                                                                                      }
                                                                                                      compile("org.springframework.boot:spring-boot-starter-jetty")
                                                                                                      

                                                                                                      Here is the build.gradle file:

                                                                                                      plugins {
                                                                                                          id 'org.springframework.boot' version '2.6.0'
                                                                                                          id 'io.spring.dependency-management' version '1.0.11.RELEASE'
                                                                                                          id 'java'
                                                                                                      }
                                                                                                      
                                                                                                      group = 'com.example'
                                                                                                      version = '0.0.1-SNAPSHOT'
                                                                                                      sourceCompatibility = '11'
                                                                                                      
                                                                                                      repositories {
                                                                                                          mavenCentral()
                                                                                                      }
                                                                                                      
                                                                                                      dependencies {
                                                                                                          compile("org.springframework.boot:spring-boot-starter-web") {
                                                                                                              exclude module: "spring-boot-starter-tomcat"
                                                                                                          }
                                                                                                          compile("org.springframework.boot:spring-boot-starter-jetty")
                                                                                                          implementation 'org.springframework.boot:spring-boot-starter-webflux'
                                                                                                          testImplementation 'org.springframework.boot:spring-boot-starter-test'
                                                                                                          testImplementation 'io.projectreactor:reactor-test'
                                                                                                          implementation "io.springfox:springfox-boot-starter:3.0.0"
                                                                                                      }
                                                                                                      
                                                                                                      test {
                                                                                                          useJUnitPlatform()
                                                                                                      }
                                                                                                      
                                                                                                      

                                                                                                      I issued the command gradle clean bootrun. The result is this error:

                                                                                                       gradle clean bootrun                                                                                                                                                                                                               
                                                                                                      
                                                                                                      > Task :bootRun FAILED
                                                                                                      
                                                                                                        .   ____          _            __ _ _
                                                                                                       /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
                                                                                                      ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
                                                                                                       \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
                                                                                                        '  |____| .__|_| |_|_| |_\__, | / / / /
                                                                                                       =========|_|==============|___/=/_/_/_/
                                                                                                       :: Spring Boot ::                (v2.6.0)
                                                                                                      
                                                                                                      2021-11-19 09:41:06.665  INFO 16666 --- [           main] c.e.springfox.SpringFoxApplication       : Starting SpringFoxApplication using Java 15.0.2 on advance-Inspiron-5379 with PID 16666 (/home/advance/projects/spring-fox/build/classes/java/main started by advance in /home/advance/projects/spring-fox)
                                                                                                      2021-11-19 09:41:06.666  INFO 16666 --- [           main] c.e.springfox.SpringFoxApplication       : No active profile set, falling back to default profiles: default
                                                                                                      2021-11-19 09:41:07.294  INFO 16666 --- [           main] org.eclipse.jetty.util.log               : Logging initialized @1132ms to org.eclipse.jetty.util.log.Slf4jLog
                                                                                                      2021-11-19 09:41:07.396  INFO 16666 --- [           main] o.s.b.w.e.j.JettyServletWebServerFactory : Server initialized with port: 8080
                                                                                                      2021-11-19 09:41:07.398  INFO 16666 --- [           main] org.eclipse.jetty.server.Server          : jetty-9.4.44.v20210927; built: 2021-09-27T23:02:44.612Z; git: 8da83308eeca865e495e53ef315a249d63ba9332; jvm 15.0.2+7-27
                                                                                                      2021-11-19 09:41:07.417  INFO 16666 --- [           main] o.e.j.s.h.ContextHandler.application     : Initializing Spring embedded WebApplicationContext
                                                                                                      2021-11-19 09:41:07.417  INFO 16666 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 713 ms
                                                                                                      2021-11-19 09:41:07.474  INFO 16666 --- [           main] org.eclipse.jetty.server.session         : DefaultSessionIdManager workerName=node0
                                                                                                      2021-11-19 09:41:07.474  INFO 16666 --- [           main] org.eclipse.jetty.server.session         : No SessionScavenger set, using defaults
                                                                                                      2021-11-19 09:41:07.475  INFO 16666 --- [           main] org.eclipse.jetty.server.session         : node0 Scavenging every 660000ms
                                                                                                      2021-11-19 09:41:07.480  INFO 16666 --- [           main] o.e.jetty.server.handler.ContextHandler  : Started o.s.b.w.e.j.JettyEmbeddedWebAppContext@6aa3bfc{application,/,[file:///tmp/jetty-docbase.8080.2024342829220941812/, jar:file:/home/advance/.gradle/caches/modules-2/files-2.1/io.springfox/springfox-swagger-ui/3.0.0/1e665fbe22148f7c36fa8a08e515a0047cd4390b/springfox-swagger-ui-3.0.0.jar!/META-INF/resources],AVAILABLE}
                                                                                                      2021-11-19 09:41:07.480  INFO 16666 --- [           main] org.eclipse.jetty.server.Server          : Started @1318ms
                                                                                                      2021-11-19 09:41:07.920  INFO 16666 --- [           main] o.e.j.s.h.ContextHandler.application     : Initializing Spring DispatcherServlet 'dispatcherServlet'
                                                                                                      2021-11-19 09:41:07.920  INFO 16666 --- [           main] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
                                                                                                      2021-11-19 09:41:07.921  INFO 16666 --- [           main] o.s.web.servlet.DispatcherServlet        : Completed initialization in 1 ms
                                                                                                      2021-11-19 09:41:07.931  INFO 16666 --- [           main] o.e.jetty.server.AbstractConnector       : Started ServerConnector@2643d762{HTTP/1.1, (http/1.1)}{0.0.0.0:8080}
                                                                                                      2021-11-19 09:41:07.932  INFO 16666 --- [           main] o.s.b.web.embedded.jetty.JettyWebServer  : Jetty started on port(s) 8080 (http/1.1) with context path '/'
                                                                                                      2021-11-19 09:41:07.934  WARN 16666 --- [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException: Cannot invoke "org.springframework.web.servlet.mvc.condition.PatternsRequestCondition.getPatterns()" because "this.condition" is null
                                                                                                      2021-11-19 09:41:07.949  INFO 16666 --- [           main] o.e.jetty.server.AbstractConnector       : Stopped ServerConnector@2643d762{HTTP/1.1, (http/1.1)}{0.0.0.0:8080}
                                                                                                      2021-11-19 09:41:07.950  INFO 16666 --- [           main] org.eclipse.jetty.server.session         : node0 Stopped scavenging
                                                                                                      2021-11-19 09:41:07.951  INFO 16666 --- [           main] o.e.j.s.h.ContextHandler.application     : Destroying Spring FrameworkServlet 'dispatcherServlet'
                                                                                                      2021-11-19 09:41:07.951  INFO 16666 --- [           main] o.e.jetty.server.handler.ContextHandler  : Stopped o.s.b.w.e.j.JettyEmbeddedWebAppContext@6aa3bfc{application,/,[file:///tmp/jetty-docbase.8080.2024342829220941812/, jar:file:/home/advance/.gradle/caches/modules-2/files-2.1/io.springfox/springfox-swagger-ui/3.0.0/1e665fbe22148f7c36fa8a08e515a0047cd4390b/springfox-swagger-ui-3.0.0.jar!/META-INF/resources],STOPPED}
                                                                                                      2021-11-19 09:41:07.958  INFO 16666 --- [           main] ConditionEvaluationReportLoggingListener : 
                                                                                                      
                                                                                                      Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
                                                                                                      2021-11-19 09:41:07.970 ERROR 16666 --- [           main] o.s.boot.SpringApplication               : Application run failed
                                                                                                      
                                                                                                      org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException: Cannot invoke "org.springframework.web.servlet.mvc.condition.PatternsRequestCondition.getPatterns()" because "this.condition" is null
                                                                                                              at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:181) ~[spring-context-5.3.13.jar:5.3.13]
                                                                                                              at org.springframework.context.support.DefaultLifecycleProcessor.access$200(DefaultLifecycleProcessor.java:54) ~[spring-context-5.3.13.jar:5.3.13]
                                                                                                              at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:356) ~[spring-context-5.3.13.jar:5.3.13]
                                                                                                              at java.base/java.lang.Iterable.forEach(Iterable.java:75) ~[na:na]
                                                                                                              at org.springframework.context.support.DefaultLifecycleProcessor.startBeans(DefaultLifecycleProcessor.java:155) ~[spring-context-5.3.13.jar:5.3.13]
                                                                                                              at org.springframework.context.support.DefaultLifecycleProcessor.onRefresh(DefaultLifecycleProcessor.java:123) ~[spring-context-5.3.13.jar:5.3.13]
                                                                                                              at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:935) ~[spring-context-5.3.13.jar:5.3.13]
                                                                                                              at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:586) ~[spring-context-5.3.13.jar:5.3.13]
                                                                                                              at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145) ~[spring-boot-2.6.0.jar:2.6.0]
                                                                                                              at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:730) ~[spring-boot-2.6.0.jar:2.6.0]
                                                                                                              at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:412) ~[spring-boot-2.6.0.jar:2.6.0]
                                                                                                              at org.springframework.boot.SpringApplication.run(SpringApplication.java:302) ~[spring-boot-2.6.0.jar:2.6.0]
                                                                                                              at org.springframework.boot.SpringApplication.run(SpringApplication.java:1301) ~[spring-boot-2.6.0.jar:2.6.0]
                                                                                                              at org.springframework.boot.SpringApplication.run(SpringApplication.java:1290) ~[spring-boot-2.6.0.jar:2.6.0]
                                                                                                              at com.example.springfox.SpringFoxApplication.main(SpringFoxApplication.java:10) ~[main/:na]
                                                                                                      Caused by: java.lang.NullPointerException: Cannot invoke "org.springframework.web.servlet.mvc.condition.PatternsRequestCondition.getPatterns()" because "this.condition" is null
                                                                                                              at springfox.documentation.spring.web.WebMvcPatternsRequestConditionWrapper.getPatterns(WebMvcPatternsRequestConditionWrapper.java:56) ~[springfox-spring-webmvc-3.0.0.jar:3.0.0]
                                                                                                              at springfox.documentation.RequestHandler.sortedPaths(RequestHandler.java:113) ~[springfox-core-3.0.0.jar:3.0.0]
                                                                                                              at springfox.documentation.spi.service.contexts.Orderings.lambda$byPatternsCondition$3(Orderings.java:89) ~[springfox-spi-3.0.0.jar:3.0.0]
                                                                                                              at java.base/java.util.Comparator.lambda$comparing$77a9974f$1(Comparator.java:469) ~[na:na]
                                                                                                              at java.base/java.util.TimSort.countRunAndMakeAscending(TimSort.java:355) ~[na:na]
                                                                                                              at java.base/java.util.TimSort.sort(TimSort.java:220) ~[na:na]
                                                                                                              at java.base/java.util.Arrays.sort(Arrays.java:1306) ~[na:na]
                                                                                                              at java.base/java.util.ArrayList.sort(ArrayList.java:1721) ~[na:na]
                                                                                                              at java.base/java.util.stream.SortedOps$RefSortingSink.end(SortedOps.java:392) ~[na:na]
                                                                                                              at java.base/java.util.stream.Sink$ChainedReference.end(Sink.java:258) ~[na:na]
                                                                                                              at java.base/java.util.stream.Sink$ChainedReference.end(Sink.java:258) ~[na:na]
                                                                                                              at java.base/java.util.stream.Sink$ChainedReference.end(Sink.java:258) ~[na:na]
                                                                                                              at java.base/java.util.stream.Sink$ChainedReference.end(Sink.java:258) ~[na:na]
                                                                                                              at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:485) ~[na:na]
                                                                                                              at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474) ~[na:na]
                                                                                                              at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913) ~[na:na]
                                                                                                              at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[na:na]
                                                                                                              at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:578) ~[na:na]
                                                                                                              at springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider.requestHandlers(WebMvcRequestHandlerProvider.java:81) ~[springfox-spring-webmvc-3.0.0.jar:3.0.0]
                                                                                                              at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195) ~[na:na]
                                                                                                              at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1625) ~[na:na]
                                                                                                              at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484) ~[na:na]
                                                                                                              at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474) ~[na:na]
                                                                                                              at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913) ~[na:na]
                                                                                                              at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[na:na]
                                                                                                              at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:578) ~[na:na]
                                                                                                              at springfox.documentation.spring.web.plugins.AbstractDocumentationPluginsBootstrapper.withDefaults(AbstractDocumentationPluginsBootstrapper.java:107) ~[springfox-spring-web-3.0.0.jar:3.0.0]
                                                                                                              at springfox.documentation.spring.web.plugins.AbstractDocumentationPluginsBootstrapper.buildContext(AbstractDocumentationPluginsBootstrapper.java:91) ~[springfox-spring-web-3.0.0.jar:3.0.0]
                                                                                                              at springfox.documentation.spring.web.plugins.AbstractDocumentationPluginsBootstrapper.bootstrapDocumentationPlugins(AbstractDocumentationPluginsBootstrapper.java:82) ~[springfox-spring-web-3.0.0.jar:3.0.0]
                                                                                                              at springfox.documentation.spring.web.plugins.DocumentationPluginsBootstrapper.start(DocumentationPluginsBootstrapper.java:100) ~[springfox-spring-web-3.0.0.jar:3.0.0]
                                                                                                              at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:178) ~[spring-context-5.3.13.jar:5.3.13]
                                                                                                              ... 14 common frames omitted
                                                                                                      
                                                                                                      
                                                                                                      FAILURE: Build failed with an exception.
                                                                                                      
                                                                                                      * What went wrong:
                                                                                                      Execution failed for task ':bootRun'.
                                                                                                      > Process 'command '/home/advance/.sdkman/candidates/java/15.0.2-open/bin/java'' finished with non-zero exit value 1
                                                                                                      
                                                                                                      * Try:
                                                                                                      Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
                                                                                                      
                                                                                                      * Get more help at https://help.gradle.org
                                                                                                      
                                                                                                      Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
                                                                                                      Use '--warning-mode all' to show the individual deprecation warnings.
                                                                                                      See https://docs.gradle.org/6.9.1/userguide/command_line_interface.html#sec:command_line_warnings
                                                                                                      
                                                                                                      BUILD FAILED in 2s
                                                                                                      5 actionable tasks: 5 executed
                                                                                                      

                                                                                                      Does anyone have an idea how to solve it?

                                                                                                      ANSWER

                                                                                                      Answered 2022-Feb-08 at 12:36

                                                                                                      This problem's caused by a bug in Springfox. It's making an assumption about how Spring MVC is set up that doesn't always hold true. Specifically, it's assuming that MVC's path matching will use the Ant-based path matcher and not the PathPattern-based matcher. PathPattern-based matching has been an option for some time now and is the default as of Spring Boot 2.6.

                                                                                                      As described in Spring Boot 2.6's release notes, you can restore the configuration that Springfox assumes will be used by setting spring.mvc.pathmatch.matching-strategy to ant-path-matcher in your application.properties file. Note that this will only work if you are not using Spring Boot's Actuator. The Actuator always uses PathPattern-based parsing, irrespective of the configured matching-strategy. A change to Springfox will be required if you want to use it with the Actuator in Spring Boot 2.6 and later.

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

                                                                                                      QUESTION

                                                                                                      IntelliJ - Invalid source release: 17
                                                                                                      Asked 2022-Mar-17 at 13:46

                                                                                                      I've created a new Java project in IntelliJ with Gradle that uses Java 17. When running my app it has the error Cause: error: invalid source release: 17.

                                                                                                      My Settings

                                                                                                      I've installed openjdk-17 through IntelliJ and set it as my Project SDK.

                                                                                                      The Project language level has been set to 17 - Sealed types, always-strict floating-point semantics.

                                                                                                      In Modules -> Sources I've set the Language level to Project default (17 - Sealed types, always strict floating-point semantics).

                                                                                                      In Modules -> Dependencies I've set the Module SDK to Project SDK openjdk-17.

                                                                                                      In Settings -> Build, Execution, Deployment -> Compiler -> Java Compiler I've set the Project bytecode version to 17.

                                                                                                      Gradle

                                                                                                      plugins {
                                                                                                          id 'org.springframework.boot' version '2.5.6'
                                                                                                          id 'io.spring.dependency-management' version '1.0.11.RELEASE'
                                                                                                          id 'java'
                                                                                                      }
                                                                                                      
                                                                                                      group = 'com.app'
                                                                                                      version = '0.0.1-SNAPSHOT'
                                                                                                      sourceCompatibility = '17'
                                                                                                      
                                                                                                      repositories {
                                                                                                          mavenCentral()
                                                                                                      }
                                                                                                      
                                                                                                      dependencies {
                                                                                                          implementation 'org.springframework.boot:spring-boot-starter-web'
                                                                                                          implementation 'org.springframework.boot:spring-boot-starter-websocket'
                                                                                                          testImplementation 'org.springframework.boot:spring-boot-starter-test'
                                                                                                          implementation 'com.fasterxml.jackson.core:jackson-core:2.13.0'
                                                                                                          implementation 'com.fasterxml.jackson.core:jackson-databind:2.13.0'
                                                                                                      }
                                                                                                      
                                                                                                      test {
                                                                                                          useJUnitPlatform()
                                                                                                      }
                                                                                                      

                                                                                                      I've looked at all of the answers here but I can't seem to fix this. I must be missing something but I can't find it. I've not had any problems using Java 8 or 11.

                                                                                                      How do I resolve this?

                                                                                                      ANSWER

                                                                                                      Answered 2021-Oct-24 at 14:23

                                                                                                      The message typically entails that your JAVA_HOME environment variable points to a different Java version.

                                                                                                      Here are the steps to follow:

                                                                                                      • Close IntelliJ IDEA
                                                                                                      • Open a terminal window and check your JAVA_HOME variable value:
                                                                                                        • *nix system: echo $JAVA_HOME
                                                                                                        • Windows system: echo %JAVA_HOME%
                                                                                                      • The JAVA_HOME path should be pointing to a different path, then set it to the openjdk-17 path:
                                                                                                        • *nix system: export JAVA_HOME=/path/to/openjdk-17
                                                                                                        • Windows system: set JAVA_HOME=path\to\openjdk-17
                                                                                                      • Open your project again in IntelliJ IDEA
                                                                                                      • Make sure to set both source and target compatibility versions (not only the sourceCompatibility)

                                                                                                      You should be able to build your project.

                                                                                                      EDIT: Gradle Toolchain

                                                                                                      You may need also to instruct Gradle to use a different JVM than the one it uses itself by setting the Java plugin toolchain to your target version:

                                                                                                      // build.gradle
                                                                                                      java {
                                                                                                          toolchain {
                                                                                                              languageVersion = JavaLanguageVersion.of(17)
                                                                                                          }
                                                                                                      }
                                                                                                      

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

                                                                                                      QUESTION

                                                                                                      Spring Cloud Gateway; Spring MVC found on classpath, which is incompatible with Spring Cloud Gateway Issue
                                                                                                      Asked 2022-Mar-16 at 07:16

                                                                                                      I got this below error when run the API-GATEWAY, I tried so many ways but I couldn't solve this issue.

                                                                                                      Description:

                                                                                                      Spring MVC found on classpath, which is incompatible with Spring Cloud Gateway.

                                                                                                      Action:

                                                                                                      Please set spring.main.web-application-type=reactive or remove spring-boot-starter-web dependency.

                                                                                                      Main Class

                                                                                                      package com.sample.apigateway;
                                                                                                      
                                                                                                      import org.springframework.boot.SpringApplication;
                                                                                                      import org.springframework.boot.autoconfigure.SpringBootApplication;
                                                                                                      import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
                                                                                                      
                                                                                                      @SpringBootApplication
                                                                                                      @EnableEurekaClient
                                                                                                      public class ApiGatewayApplication {
                                                                                                      
                                                                                                          public static void main(String[] args) {
                                                                                                              SpringApplication.run(ApiGatewayApplication.class, args);
                                                                                                          }
                                                                                                      
                                                                                                      }
                                                                                                      

                                                                                                      application.yml

                                                                                                      spring:
                                                                                                        application:
                                                                                                          name: GATEWAY-SERVICE
                                                                                                      
                                                                                                        cloud:
                                                                                                          gateway:
                                                                                                            routes:
                                                                                                              - id: USER-SERVICE
                                                                                                                uri: lb://USER-SERVICE
                                                                                                                predicates:
                                                                                                                  - Path=/users/**
                                                                                                              - id: DEPARTMENT-SERVICE
                                                                                                                uri: lb://DEPARTMENT-SERVICE
                                                                                                                predicates:
                                                                                                                  - Path=/departments/**
                                                                                                      
                                                                                                      eureka:
                                                                                                        client:
                                                                                                          register-with-eureka: true
                                                                                                          fetch-registry: true
                                                                                                          service-url:
                                                                                                            defaultZone: http://localhost:8761/eureka/
                                                                                                      
                                                                                                        instance:
                                                                                                          hostname: localhost
                                                                                                      
                                                                                                      server:
                                                                                                        port: 9191
                                                                                                      

                                                                                                      pom.xml

                                                                                                      
                                                                                                      
                                                                                                          4.0.0
                                                                                                          
                                                                                                              org.springframework.boot
                                                                                                              spring-boot-starter-parent
                                                                                                              2.5.3
                                                                                                               
                                                                                                          
                                                                                                          com.sample.apigateway
                                                                                                          apigateway
                                                                                                          0.0.1-SNAPSHOT
                                                                                                          apigateway
                                                                                                          Demo project for Spring Boot
                                                                                                          
                                                                                                              11
                                                                                                              2020.0.3
                                                                                                          
                                                                                                          
                                                                                                              
                                                                                                                  org.springframework.boot
                                                                                                                  spring-boot-starter-actuator
                                                                                                              
                                                                                                              
                                                                                                                  org.springframework.boot
                                                                                                                  spring-boot-starter-webflux
                                                                                                              
                                                                                                              
                                                                                                                  io.springfox
                                                                                                                  springfox-boot-starter
                                                                                                                  3.0.0
                                                                                                              
                                                                                                              
                                                                                                                  org.springframework.cloud
                                                                                                                  spring-cloud-starter-gateway
                                                                                                              
                                                                                                              
                                                                                                                  org.springframework.cloud
                                                                                                                  spring-cloud-starter-netflix-eureka-client
                                                                                                              
                                                                                                              
                                                                                                                  org.springframework.cloud
                                                                                                                  spring-cloud-starter-netflix-eureka-server
                                                                                                              
                                                                                                      
                                                                                                              
                                                                                                                  org.springframework.boot
                                                                                                                  spring-boot-starter-test
                                                                                                                  test
                                                                                                              
                                                                                                          
                                                                                                          
                                                                                                              
                                                                                                                  
                                                                                                                      org.springframework.cloud
                                                                                                                      spring-cloud-dependencies
                                                                                                                      ${spring-cloud.version}
                                                                                                                      pom
                                                                                                                      import
                                                                                                                  
                                                                                                              
                                                                                                          
                                                                                                      
                                                                                                          
                                                                                                              
                                                                                                                  
                                                                                                                      org.springframework.boot
                                                                                                                      spring-boot-maven-plugin
                                                                                                                  
                                                                                                              
                                                                                                          
                                                                                                      
                                                                                                      
                                                                                                      

                                                                                                      Full Error Message

                                                                                                      2021-07-30 23:12:02.420  WARN 19032 --- [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.cloud.gateway.config.GatewayClassPathWarningAutoConfiguration$SpringMvcFoundOnClasspathConfiguration': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.cloud.gateway.config.GatewayClassPathWarningAutoConfiguration$SpringMvcFoundOnClasspathConfiguration]: Constructor threw exception; nested exception is org.springframework.cloud.gateway.support.MvcFoundOnClasspathException
                                                                                                      2021-07-30 23:12:02.423  INFO 19032 --- [           main] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
                                                                                                      2021-07-30 23:12:02.441  INFO 19032 --- [           main] ConditionEvaluationReportLoggingListener : 
                                                                                                      
                                                                                                      Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
                                                                                                      2021-07-30 23:12:02.454 ERROR 19032 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 
                                                                                                      
                                                                                                      ***************************
                                                                                                      APPLICATION FAILED TO START
                                                                                                      ***************************
                                                                                                      
                                                                                                      Description:
                                                                                                      
                                                                                                      Spring MVC found on classpath, which is incompatible with Spring Cloud Gateway.
                                                                                                      
                                                                                                      Action:
                                                                                                      
                                                                                                      Please set spring.main.web-application-type=reactive or remove spring-boot-starter-web dependency.
                                                                                                      
                                                                                                      
                                                                                                      Process finished with exit code 1
                                                                                                      

                                                                                                      ANSWER

                                                                                                      Answered 2021-Aug-01 at 06:17

                                                                                                      Please note that Spring Cloud Gateway is not compatible with Spring MVC (spring-boot-starter-web). This is outlined in section "How to include Spring Cloud Gateway in the official reference documentation":

                                                                                                      Spring Cloud Gateway is built on Spring Boot 2.x, Spring WebFlux, and Project Reactor. As a consequence, many of the familiar synchronous libraries (Spring Data and Spring Security, for example) and patterns you know may not apply when you use Spring Cloud Gateway.

                                                                                                      Additionally, it is stated that:

                                                                                                      Spring Cloud Gateway requires the Netty runtime provided by Spring Boot and Spring Webflux. It does not work in a traditional Servlet Container or when built as a WAR.

                                                                                                      As already suggested by the error message, you would need to remove the dependency on spring-boot-starter-web. You can list all your direct and transitive dependencies with the following command:

                                                                                                      mvn dependency:tree
                                                                                                      

                                                                                                      This will reveal that spring-cloud-starter-netflix-eureka-server depends on spring-boot-starter-web. Once you remove the following lines from your pom.xml, your application should start up:

                                                                                                      
                                                                                                          org.springframework.cloud
                                                                                                          spring-cloud-starter-netflix-eureka-server
                                                                                                      
                                                                                                      

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

                                                                                                      QUESTION

                                                                                                      Added corsConfigurationSource and still an error "has been blocked by CORS policy"
                                                                                                      Asked 2022-Mar-02 at 19:19

                                                                                                      I'm trying to connect Spring Security to my project. Created the Security Config class

                                                                                                      @Configuration
                                                                                                      @EnableWebSecurity
                                                                                                      public class SecurityConfig extends WebSecurityConfigurerAdapter {
                                                                                                      
                                                                                                          private final JwtTokenProvider jwtTokenProvider;
                                                                                                      
                                                                                                          @Bean
                                                                                                          @Override
                                                                                                          public AuthenticationManager authenticationManagerBean() throws Exception {
                                                                                                              return super.authenticationManagerBean();
                                                                                                          }
                                                                                                          
                                                                                                          public SecurityConfig(JwtTokenProvider jwtTokenProvider) {
                                                                                                              this.jwtTokenProvider = jwtTokenProvider;
                                                                                                          }
                                                                                                      
                                                                                                          @Override
                                                                                                          protected void configure(HttpSecurity http) throws Exception {
                                                                                                              http
                                                                                                                      .httpBasic().disable()
                                                                                                                      .cors().and().csrf().disable()
                                                                                                                      .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                                                                                                                      .and()
                                                                                                                      .authorizeRequests()
                                                                                                                      .antMatchers("/auth/api/v1/user/register").permitAll()
                                                                                                                      .antMatchers("/auth/api/v1/admin/*").hasRole("ADMIN")
                                                                                                                      .anyRequest().authenticated()
                                                                                                                      .and()
                                                                                                                      .apply(new JwtConfigurer(jwtTokenProvider));
                                                                                                          }
                                                                                                      }
                                                                                                      

                                                                                                      I am sending a request from the browser for registration

                                                                                                      http://localhost:15001/auth/api/v1/user/register
                                                                                                      

                                                                                                      and I get an answer:

                                                                                                      Access to XMLHttpRequest at 'http://localhost:15001/auth/api/v1/user/register' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
                                                                                                      

                                                                                                      According to the Spring documentation, I add the corsConfigurationSource method:

                                                                                                      @Configuration
                                                                                                      @EnableWebSecurity
                                                                                                      public class SecurityConfig extends WebSecurityConfigurerAdapter {
                                                                                                      
                                                                                                          private final JwtTokenProvider jwtTokenProvider;
                                                                                                      
                                                                                                          @Bean
                                                                                                          @Override
                                                                                                          public AuthenticationManager authenticationManagerBean() throws Exception {
                                                                                                              return super.authenticationManagerBean();
                                                                                                          }
                                                                                                          
                                                                                                          public SecurityConfig(JwtTokenProvider jwtTokenProvider) {
                                                                                                              this.jwtTokenProvider = jwtTokenProvider;
                                                                                                          }
                                                                                                      
                                                                                                          @Bean
                                                                                                          CorsConfigurationSource corsConfigurationSource() {
                                                                                                              CorsConfiguration configuration = new CorsConfiguration();
                                                                                                              configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
                                                                                                              configuration.setAllowedMethods(Arrays.asList("GET","POST"));
                                                                                                              UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
                                                                                                              source.registerCorsConfiguration("/**", configuration);
                                                                                                              return source;
                                                                                                          }
                                                                                                      
                                                                                                          @Override
                                                                                                          protected void configure(HttpSecurity http) throws Exception {
                                                                                                              http
                                                                                                                      .httpBasic().disable()
                                                                                                                      .cors().and().csrf().disable()
                                                                                                                      .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                                                                                                                      .and()
                                                                                                                      .authorizeRequests()
                                                                                                                      .antMatchers("/auth/api/v1/user/register").permitAll()
                                                                                                                      .antMatchers("/auth/api/v1/admin/**").hasRole("ADMIN")
                                                                                                                      .anyRequest().authenticated()
                                                                                                                      .and()
                                                                                                                      .apply(new JwtConfigurer(jwtTokenProvider));
                                                                                                          }
                                                                                                      }
                                                                                                      

                                                                                                      I am sending a request from the browser for registration

                                                                                                      http://localhost:15001/auth/api/v1/user/register
                                                                                                      

                                                                                                      and I still get the same error

                                                                                                      Access to XMLHttpRequest at 'http://localhost:15001/auth/api/v1/user/register' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
                                                                                                      

                                                                                                      Why didn't the error disappear?

                                                                                                      I know there is another way to add on the controller

                                                                                                      @CrossOrigin(origins="http://localhost:4200″)
                                                                                                      

                                                                                                      You can also add to the header. but I want to figure out why this method doesn't work.

                                                                                                      pom.xml

                                                                                                      
                                                                                                        org.springframework.boot
                                                                                                        spring-boot-starter-parent
                                                                                                        2.4.12
                                                                                                          
                                                                                                      
                                                                                                      
                                                                                                      
                                                                                                        
                                                                                                          org.springframework.boot
                                                                                                          spring-boot-starter
                                                                                                        
                                                                                                      
                                                                                                        
                                                                                                          org.springframework.boot
                                                                                                          spring-boot-starter-security
                                                                                                        
                                                                                                      
                                                                                                        
                                                                                                          org.springframework.boot
                                                                                                          spring-boot-starter-test
                                                                                                          test
                                                                                                        
                                                                                                      
                                                                                                        
                                                                                                          org.springframework.boot
                                                                                                          spring-boot-starter-web
                                                                                                        
                                                                                                        
                                                                                                          org.springframework.boot
                                                                                                          spring-boot-starter-data-jpa
                                                                                                        
                                                                                                      
                                                                                                        
                                                                                                          com.auth0
                                                                                                          java-jwt
                                                                                                          ${jwt.version}
                                                                                                        
                                                                                                        
                                                                                                          org.postgresql
                                                                                                          postgresql
                                                                                                          ${postgres.version}
                                                                                                        
                                                                                                      
                                                                                                        
                                                                                                          org.springframework.boot
                                                                                                          spring-boot-configuration-processor
                                                                                                          true
                                                                                                        
                                                                                                      
                                                                                                      

                                                                                                      Here is the code where I form the answer

                                                                                                      final UserDto userDto = userToUserDtoConverter.convert(optionalUser.get());
                                                                                                      if (password.equals(UserUtils.encryptText(optionalAuth.get().getPassword()))) {
                                                                                                        final HttpHeaders responseHeaders = new HttpHeaders();
                                                                                                        final String token = jwtTokenProvider.createToken(optionalAuth.get().getName());
                                                                                                        return confirmUserRegister(userDto, "Пользователь авторизован",
                                                                                                          HttpStatus.OK, responseHeaders);
                                                                                                      }
                                                                                                      
                                                                                                      protected ResponseEntity> confirmUserRegister(
                                                                                                          UserDto userDto, String message, HttpStatus httpStatus, HttpHeaders responseHeaders) {
                                                                                                        final DataResponse response = new DataResponse<>();
                                                                                                        response.setStatus(StatusType.SUCCESSFUL);
                                                                                                        response.setData(userDto);
                                                                                                        response.addMessage(httpStatus.value(), message);
                                                                                                        return new ResponseEntity<>(response, responseHeaders, httpStatus);
                                                                                                      }
                                                                                                      

                                                                                                      Here is the link to the project enter link description here

                                                                                                      The project is still very raw. And this is a copy of the project, so you can edit as you like

                                                                                                      ANSWER

                                                                                                      Answered 2022-Mar-02 at 19:19

                                                                                                      If this is a local environment, you don't need to configure Spring, instead you modify angular configuration.

                                                                                                      Create a file proxy.conf.json in your project's src/ folder.

                                                                                                      Add the following content to the new proxy file:

                                                                                                      {
                                                                                                        "/api": {
                                                                                                          "target": "http://localhost:3000",
                                                                                                          "secure": false
                                                                                                        }
                                                                                                      }
                                                                                                      

                                                                                                      In the CLI configuration file, angular.json, add the proxyConfig option to the serve target:

                                                                                                      ...
                                                                                                      
                                                                                                      "architect": {
                                                                                                        "serve": {
                                                                                                          "builder": "@angular-devkit/build-angular:dev-server",
                                                                                                          "options": {
                                                                                                            "browserTarget": "your-application-name:build",
                                                                                                            "proxyConfig": "src/proxy.conf.json"
                                                                                                          },
                                                                                                      ...
                                                                                                      

                                                                                                      To run the development server with this proxy configuration, call ng serve.

                                                                                                      More details are here. The trouble with configuring Spring CORS is that:

                                                                                                      • you are trying to solve a development environment specific problem
                                                                                                      • this may leak CORS configuration into production setup where they aren't required unless you do actually want CORS set up.

                                                                                                      Now, what to do in production ?

                                                                                                      It actually depends on how you bundle your code.

                                                                                                      If your UI + Java code is going to be in same deployable, WAR or JAR, you don't need to configure CORS because they will be deployed on same domain (https://apps.example.com) or on same context root (https://apps.example.com/app).

                                                                                                      You do need to configure CORS when your UI and java code is not on same domain or you want apps deployed on other domains (https://apps.example.**com**) to access your APIs from their page.

                                                                                                      Please note in Spring, when you set

                                                                                                      configuration.setAllowCredentials(true);
                                                                                                      

                                                                                                      Spring does not accepts:

                                                                                                      configuration.setAllowedOrigins(Arrays.asList("*"));
                                                                                                      

                                                                                                      You are required to configure required origins one by one like this:

                                                                                                      configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
                                                                                                      

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

                                                                                                      QUESTION

                                                                                                      Spring Boot 2.6 and Angular in static Resources
                                                                                                      Asked 2022-Mar-02 at 08:15

                                                                                                      My question is very similar to this question that has already been asked and answered but is not 100% up-to-date.

                                                                                                      We used the solution from Chris Gaskill for quite some time and it suited us perfectly because we wanted to redirect requests that contain more than one path segment (i.e. /foo/bar)

                                                                                                      From Spring Boot 2.4 on, Boot uses the PathPatternParser instead of the AntPathMatcher, wherein the former does not support ** at the start of a pattern anymore (see docs).

                                                                                                      Is there some other solution to get the same behavior? What do you use to redirect all requests, that did not match anything else, to the index.html of the Angular app?

                                                                                                      This is the code of the controller that forwards the requests.

                                                                                                      @Controller
                                                                                                      class SpaRoutingController {
                                                                                                      
                                                                                                        @GetMapping("/**/{path:[^\\.]*}", headers = "X-Requested-With!=XMLHttpRequest")
                                                                                                        fun forward(): String? {
                                                                                                            return "forward:/"
                                                                                                        }
                                                                                                      }
                                                                                                      

                                                                                                      ANSWER

                                                                                                      Answered 2022-Feb-23 at 15:02

                                                                                                      Have you tried to implement redirection on Angular side? In my application I've solved this like:

                                                                                                      const routes: Routes = [
                                                                                                        {path: '', redirectTo: '/myProjects', pathMatch: 'full'},
                                                                                                        //...
                                                                                                        {path: '**', redirectTo: ''}
                                                                                                      }
                                                                                                      
                                                                                                      @NgModule({
                                                                                                        imports: [
                                                                                                          RouterModule.forRoot(routes, {useHash: true})
                                                                                                        ],
                                                                                                        exports: [
                                                                                                          RouterModule
                                                                                                        ],
                                                                                                        declarations: []
                                                                                                      })
                                                                                                      export class MyRoutingModule {
                                                                                                      }
                                                                                                      

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

                                                                                                      QUESTION

                                                                                                      org.junit.platform.commons.JUnitException: TestEngine with ID 'junit-jupiter' failed to discover tests
                                                                                                      Asked 2022-Feb-16 at 06:28

                                                                                                      I wan to implement a Junit 5 test into Gradle project. I tried this:

                                                                                                      Gradle configuration:

                                                                                                      plugins {
                                                                                                          id 'org.springframework.boot' version '2.5.5'
                                                                                                          id 'io.spring.dependency-management' version '1.0.11.RELEASE'
                                                                                                          id 'java'
                                                                                                      }
                                                                                                      
                                                                                                      group = 'test'
                                                                                                      version = '0.0.1'
                                                                                                      sourceCompatibility = '17'
                                                                                                      
                                                                                                      repositories {
                                                                                                          mavenCentral()
                                                                                                      }
                                                                                                      
                                                                                                      ext {
                                                                                                          set('springCloudVersion', "2020.0.4")
                                                                                                      }
                                                                                                      
                                                                                                      dependencies {
                                                                                                          ...............
                                                                                                          testImplementation 'org.springframework.boot:spring-boot-starter-test'
                                                                                                          testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.2'
                                                                                                          testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.2'
                                                                                                      }
                                                                                                      
                                                                                                      dependencyManagement {
                                                                                                          imports {
                                                                                                              mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
                                                                                                          }
                                                                                                      }
                                                                                                      
                                                                                                      test {
                                                                                                          useJUnitPlatform()
                                                                                                      }
                                                                                                      

                                                                                                      Junit test:

                                                                                                      import org.junit.jupiter.api.DisplayName;
                                                                                                      import org.junit.jupiter.api.Test;
                                                                                                      import org.junit.jupiter.api.Timeout;
                                                                                                      
                                                                                                      import java.util.concurrent.TimeUnit;
                                                                                                      
                                                                                                      public class GeneratePdf {
                                                                                                      
                                                                                                          @DisplayName("Test MessageService.get()")
                                                                                                          @Test
                                                                                                          @Timeout(value = 60, unit = TimeUnit.SECONDS)
                                                                                                          public void generatePdfFileTes() throws InterruptedException
                                                                                                          {
                                                                                                              System.out.println("test!");
                                                                                                          }
                                                                                                      
                                                                                                      }
                                                                                                      

                                                                                                      When I run the code I get error:

                                                                                                      Internal Error occurred.
                                                                                                      org.junit.platform.commons.JUnitException: TestEngine with ID 'junit-jupiter' failed to discover tests
                                                                                                          at org.junit.platform.launcher.core.EngineDiscoveryOrchestrator.discoverEngineRoot(EngineDiscoveryOrchestrator.java:160)
                                                                                                          at org.junit.platform.launcher.core.EngineDiscoveryOrchestrator.discoverSafely(EngineDiscoveryOrchestrator.java:134)
                                                                                                          at org.junit.platform.launcher.core.EngineDiscoveryOrchestrator.discover(EngineDiscoveryOrchestrator.java:108)
                                                                                                          at org.junit.platform.launcher.core.EngineDiscoveryOrchestrator.discover(EngineDiscoveryOrchestrator.java:80)
                                                                                                          at org.junit.platform.launcher.core.DefaultLauncher.discover(DefaultLauncher.java:110)
                                                                                                          at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:86)
                                                                                                          at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:86)
                                                                                                          at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:53)
                                                                                                          at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:71)
                                                                                                          at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)
                                                                                                          at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)
                                                                                                          at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
                                                                                                          at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
                                                                                                          at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
                                                                                                      Caused by: org.junit.platform.commons.JUnitException: MethodSelector [className = 'org.merchant.poc.GeneratePdf', methodName = 'generatePdfFileTes', methodParameterTypes = ''] resolution failed
                                                                                                          at org.junit.platform.launcher.listeners.discovery.AbortOnFailureLauncherDiscoveryListener.selectorProcessed(AbortOnFailureLauncherDiscoveryListener.java:39)
                                                                                                          at org.junit.platform.engine.support.discovery.EngineDiscoveryRequestResolution.resolveCompletely(EngineDiscoveryRequestResolution.java:102)
                                                                                                          at org.junit.platform.engine.support.discovery.EngineDiscoveryRequestResolution.run(EngineDiscoveryRequestResolution.java:82)
                                                                                                          at org.junit.platform.engine.support.discovery.EngineDiscoveryRequestResolver.resolve(EngineDiscoveryRequestResolver.java:113)
                                                                                                          at org.junit.jupiter.engine.discovery.DiscoverySelectorResolver.resolveSelectors(DiscoverySelectorResolver.java:46)
                                                                                                          at org.junit.jupiter.engine.JupiterTestEngine.discover(JupiterTestEngine.java:69)
                                                                                                          at org.junit.platform.launcher.core.EngineDiscoveryOrchestrator.discoverEngineRoot(EngineDiscoveryOrchestrator.java:152)
                                                                                                          ... 13 more
                                                                                                      Caused by: org.junit.platform.commons.PreconditionViolationException: Could not load class with name: org.merchant.poc.GeneratePdf
                                                                                                          at org.junit.platform.engine.discovery.MethodSelector.lambda$lazyLoadJavaClass$0(MethodSelector.java:157)
                                                                                                          at org.junit.platform.commons.function.Try$Failure.getOrThrow(Try.java:335)
                                                                                                          at org.junit.platform.engine.discovery.MethodSelector.lazyLoadJavaClass(MethodSelector.java:156)
                                                                                                          at org.junit.platform.engine.discovery.MethodSelector.getJavaClass(MethodSelector.java:135)
                                                                                                          at org.junit.jupiter.engine.discovery.MethodSelectorResolver.resolve(MethodSelectorResolver.java:73)
                                                                                                          at org.junit.platform.engine.support.discovery.EngineDiscoveryRequestResolution.lambda$resolve$2(EngineDiscoveryRequestResolution.java:146)
                                                                                                          at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197)
                                                                                                          at java.base/java.util.ArrayList$ArrayListSpliterator.tryAdvance(ArrayList.java:1602)
                                                                                                          at java.base/java.util.stream.ReferencePipeline.forEachWithCancel(ReferencePipeline.java:129)
                                                                                                          at java.base/java.util.stream.AbstractPipeline.copyIntoWithCancel(AbstractPipeline.java:527)
                                                                                                          at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:513)
                                                                                                          at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:499)
                                                                                                          at java.base/java.util.stream.FindOps$FindOp.evaluateSequential(FindOps.java:150)
                                                                                                          at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
                                                                                                          at java.base/java.util.stream.ReferencePipeline.findFirst(ReferencePipeline.java:647)
                                                                                                          at org.junit.platform.engine.support.discovery.EngineDiscoveryRequestResolution.resolve(EngineDiscoveryRequestResolution.java:185)
                                                                                                          at org.junit.platform.engine.support.discovery.EngineDiscoveryRequestResolution.resolve(EngineDiscoveryRequestResolution.java:125)
                                                                                                          at org.junit.platform.engine.support.discovery.EngineDiscoveryRequestResolution.resolveCompletely(EngineDiscoveryRequestResolution.java:91)
                                                                                                          ... 18 more
                                                                                                      Caused by: java.lang.ClassNotFoundException: org.merchant.poc.GeneratePdf
                                                                                                          at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
                                                                                                          at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
                                                                                                          at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:520)
                                                                                                          at org.junit.platform.commons.util.ReflectionUtils.lambda$tryToLoadClass$9(ReflectionUtils.java:829)
                                                                                                          at org.junit.platform.commons.function.Try.lambda$call$0(Try.java:57)
                                                                                                          at org.junit.platform.commons.function.Try.of(Try.java:93)
                                                                                                          at org.junit.platform.commons.function.Try.call(Try.java:57)
                                                                                                          at org.junit.platform.commons.util.ReflectionUtils.tryToLoadClass(ReflectionUtils.java:792)
                                                                                                          at org.junit.platform.commons.util.ReflectionUtils.tryToLoadClass(ReflectionUtils.java:748)
                                                                                                          ... 34 more
                                                                                                      

                                                                                                      Do you know how this issue can be fixed?

                                                                                                      EDIT:

                                                                                                      import org.junit.jupiter.api.Test;
                                                                                                      
                                                                                                      public class InvoiceTests {
                                                                                                      
                                                                                                          @Test
                                                                                                          public void generateTest()
                                                                                                          {
                                                                                                              System.out.println("test!");
                                                                                                          }
                                                                                                      
                                                                                                      }
                                                                                                      

                                                                                                      I tried this but again it's not working.

                                                                                                      ANSWER

                                                                                                      Answered 2021-Dec-22 at 21:35

                                                                                                      GeneratePdf does not match the default name pattern for test classes. The default pattern is Test*|*Test|*Tests.

                                                                                                      You can change it in your Gradle file with

                                                                                                      test {
                                                                                                        useJUnitPlatform()
                                                                                                        include '**/*Pdf'
                                                                                                      }
                                                                                                      

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

                                                                                                      QUESTION

                                                                                                      Prometheus cannot scrape from spring-boot application over HTTPS
                                                                                                      Asked 2022-Feb-11 at 19:34

                                                                                                      I'm deploying a spring-boot application and prometheus container through docker, and have exposed the spring-boot /actuator/prometheus endpoint successfully. However, when I enable prometheus debug logs, I can see it fails to scrape the metrics:

                                                                                                      ts=2022-02-02T03:54:46.210Z
                                                                                                      caller=scrape.go:1292
                                                                                                      level=debug
                                                                                                      component="scrape manager"
                                                                                                      scrape_pool=spring-actuator
                                                                                                      target=https://127.0.0.1:8443/actuator/prometheus/
                                                                                                      msg="Scrape failed"
                                                                                                      err="Get \"https://127.0.0.1:8443/actuator/prometheus/\": dial tcp 127.0.0.1:8443: connect: connection refused"
                                                                                                      

                                                                                                      I'm thinking it's something to do with how I've set up my spring-boot HTTPS. I am generating a self-signed certificate during the building of my spring-boot application, using the command:

                                                                                                      keytool
                                                                                                        -genkey
                                                                                                        -alias 
                                                                                                        -dname 
                                                                                                        -keyalg RSA
                                                                                                        -keysize 4096
                                                                                                        -storetype PKCS12
                                                                                                        -keystore 
                                                                                                        -validity 3650
                                                                                                        -storepass 
                                                                                                      

                                                                                                      I then export the cert to a .pem file, and extract the .crt and .key:

                                                                                                      openssl pkcs12 -in cert.p12 -out cert.pem -nodes -passin pass:
                                                                                                      

                                                                                                      This is mounted through a shared volume to my prometheus container, which has a --web.config.file containing:

                                                                                                      tls_server_config:
                                                                                                        cert_file: /path/to/cert.crt
                                                                                                        key_file: /path/to/cert.key
                                                                                                      

                                                                                                      And for good measure I added insecure_skip_verify: true to the prometheus.yml config:

                                                                                                      - job_name: 'spring-actuator'
                                                                                                      metrics_path: '/actuator/prometheus/'
                                                                                                      scrape_interval: 60s
                                                                                                      scheme: https
                                                                                                      static_configs:
                                                                                                        - targets: [ '127.0.0.1:8443' ]
                                                                                                      tls_config:
                                                                                                        insecure_skip_verify: true
                                                                                                      

                                                                                                      ANSWER

                                                                                                      Answered 2022-Feb-07 at 22:37

                                                                                                      Ok, I think I found my problem. I made two changes:

                                                                                                      First, I moved the contents of the web.config.file into the prometheus.yml file under the 'spring-actuator'. Then I changed the target to use the hostname for my backend container, rather than 127.0.0.1.

                                                                                                      The end result was a single prometheus.yml file:

                                                                                                      - job_name: 'spring-actuator'
                                                                                                      metrics_path: '/actuator/prometheus/'
                                                                                                      scrape_interval: 60s
                                                                                                      scheme: https
                                                                                                      static_configs:
                                                                                                        - targets: [ 'backend:8443' ]
                                                                                                      tls_config:
                                                                                                        cert_file: /path/to/cert.crt
                                                                                                        key_file: /path/to/cert.key
                                                                                                        insecure_skip_verify: true
                                                                                                      

                                                                                                      So just some silly mistakes, not caused by the certs from what I can see. :)

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

                                                                                                      QUESTION

                                                                                                      Kotlin Spring Boot bean validation not working
                                                                                                      Asked 2022-Feb-02 at 07:44

                                                                                                      I have quite a few projects that is slowly being migrated from Java to Kotlin, but I'm facing a problem when changing from Java POJO to Kotlin data classes. Bean validation stops working in REST controllers. I have created a very simple project directly from https://start.spring.io to demonstrate the failure.

                                                                                                      @SpringBootApplication
                                                                                                      class RestValidationApplication
                                                                                                      
                                                                                                      fun main(args: Array) {
                                                                                                          runApplication(*args)
                                                                                                      }
                                                                                                      
                                                                                                      @RestController
                                                                                                      class Controller {
                                                                                                      
                                                                                                          @PostMapping
                                                                                                          fun test(@Valid @RequestBody request: Test) {
                                                                                                              println(request)
                                                                                                          }
                                                                                                      }
                                                                                                      
                                                                                                      data class Test(@field:NotNull val id: String)
                                                                                                      

                                                                                                      and gradle:

                                                                                                      import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
                                                                                                      
                                                                                                      plugins {
                                                                                                          id("org.springframework.boot") version "2.6.1"
                                                                                                          id("io.spring.dependency-management") version "1.0.11.RELEASE"
                                                                                                          kotlin("jvm") version "1.6.0"
                                                                                                          kotlin("plugin.spring") version "1.6.0"
                                                                                                      }
                                                                                                      
                                                                                                      group = "com.example"
                                                                                                      version = "0.0.1-SNAPSHOT"
                                                                                                      java.sourceCompatibility = JavaVersion.VERSION_17
                                                                                                      
                                                                                                      repositories {
                                                                                                          mavenCentral()
                                                                                                      }
                                                                                                      
                                                                                                      dependencies {
                                                                                                          implementation("org.springframework.boot:spring-boot-starter-validation")
                                                                                                          implementation("org.springframework.boot:spring-boot-starter-web")
                                                                                                          implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
                                                                                                          implementation("org.jetbrains.kotlin:kotlin-reflect")
                                                                                                          implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
                                                                                                          testImplementation("org.springframework.boot:spring-boot-starter-test")
                                                                                                      }
                                                                                                      
                                                                                                      tasks.withType {
                                                                                                          kotlinOptions {
                                                                                                              freeCompilerArgs = listOf("-Xjsr305=strict")
                                                                                                              jvmTarget = "17"
                                                                                                          }
                                                                                                      } 
                                                                                                      

                                                                                                      Sending a request does not trigger the bean validation, but it throws a HttpMessageNotReadableException because id is NULL.

                                                                                                      curl -X POST http://localhost:8080 -H "Content-Type: application/json" -d "{}"
                                                                                                      

                                                                                                      I have tried both @Valid and @Validated and using @get:NotNull on the attributes, but nothing works. I see many others have the same problem and using a Java class from a Kotlin REST controller works. Also changing to a non data class makes validation works. Anyone know if it's possible to get bean validation working with Kotlin data classes?

                                                                                                      ANSWER

                                                                                                      Answered 2021-Dec-16 at 07:38

                                                                                                      I think you are just missing @Validated annotation on top of your controller class.

                                                                                                      import org.springframework.boot.autoconfigure.SpringBootApplication
                                                                                                      import org.springframework.boot.runApplication
                                                                                                      import org.springframework.http.HttpHeaders
                                                                                                      import org.springframework.http.HttpStatus
                                                                                                      import org.springframework.http.ResponseEntity
                                                                                                      import org.springframework.validation.FieldError
                                                                                                      import org.springframework.validation.annotation.Validated
                                                                                                      import org.springframework.web.bind.MethodArgumentNotValidException
                                                                                                      import org.springframework.web.bind.annotation.*
                                                                                                      import org.springframework.web.context.request.WebRequest
                                                                                                      import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler
                                                                                                      import java.time.LocalDateTime
                                                                                                      import javax.validation.Valid
                                                                                                      import javax.validation.constraints.NotEmpty
                                                                                                      
                                                                                                      
                                                                                                      @SpringBootApplication
                                                                                                      class BootValidationApplication
                                                                                                      
                                                                                                      fun main(args: Array) {
                                                                                                          runApplication(*args)
                                                                                                      }
                                                                                                      
                                                                                                      @RestController
                                                                                                      @RequestMapping("/api/v1")
                                                                                                      @Validated
                                                                                                      class CustomerController {
                                                                                                          @PostMapping("/customer")
                                                                                                          fun createCustomer(@Valid @RequestBody customer: Customer): ResponseEntity {
                                                                                                              return ResponseEntity.ok(customer)
                                                                                                          }
                                                                                                      }
                                                                                                      
                                                                                                      
                                                                                                      @ControllerAdvice
                                                                                                      class CustomerExceptionHandler : ResponseEntityExceptionHandler() {
                                                                                                      
                                                                                                          override fun handleMethodArgumentNotValid(
                                                                                                              ex: MethodArgumentNotValidException,
                                                                                                              headers: HttpHeaders,
                                                                                                              status: HttpStatus,
                                                                                                              request: WebRequest
                                                                                                          ): ResponseEntity {
                                                                                                      
                                                                                                              val fieldErrors: List = ex.fieldErrors
                                                                                                              val errorMapping = fieldErrors.associate { it.field to it.defaultMessage }
                                                                                                      
                                                                                                              val errorDetails = ErrorDetails(
                                                                                                                  timestamp = LocalDateTime.now(),
                                                                                                                  message = "Validation Failed",
                                                                                                                  details = errorMapping
                                                                                                              )
                                                                                                              return ResponseEntity(errorDetails, HttpStatus.BAD_REQUEST)
                                                                                                          }
                                                                                                      }
                                                                                                      
                                                                                                      data class Customer(
                                                                                                          @field:NotEmpty(message = "Mandatory field: Name is missing in Request Body") val name: String
                                                                                                      )
                                                                                                      
                                                                                                      data class ErrorDetails(val timestamp: LocalDateTime, val message: String, val details: Map)
                                                                                                      

                                                                                                      The output should look something like this

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

                                                                                                      QUESTION

                                                                                                      Spring boot 2.6.0 Error creating bean with name 'webSecurityConfig'
                                                                                                      Asked 2022-Jan-23 at 12:51

                                                                                                      I am unable to update my spring boot app to 2.6.0 from 2.5.7. It throws the following error.

                                                                                                      2021-12-07T08:40:22,311 ERROR [restartedMain] o.s.b.SpringApplication.reportFailure:819|| Application run failed org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'webSecurityConfig': 
                                                                                                      The requested bean is currently in creation: Is there an unresolvable circular reference?
                                                                                                          at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.beforeSingletonCreation(DefaultSingletonBeanRegistry.java:355)
                                                                                                          at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:227)
                                                                                                      

                                                                                                      From the spring-boot 2.6.0 release notes, it is clear that circular references are disabled. And it can be enabled back with the property spring.main.allow-circular-references = true. But I would like to fix the circular reference in the first place. Can anyone help me troubleshoot this issue? Please find the WebSecurityConfig class below,

                                                                                                      @Configuration
                                                                                                      @EnableWebSecurity
                                                                                                      @SuppressWarnings({"PMD.SignatureDeclareThrowsException"})
                                                                                                      public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
                                                                                                          private final UserDetailsService userDetailsService;
                                                                                                      
                                                                                                          public WebSecurityConfig(final UserDetailsService userDetailsService) {
                                                                                                              this.userDetailsService = userDetailsService;
                                                                                                          }
                                                                                                      
                                                                                                          @Bean
                                                                                                          public BCryptPasswordEncoder bcryptPasswordEncoder() {
                                                                                                              return new BCryptPasswordEncoder();
                                                                                                          }
                                                                                                      
                                                                                                          @Override
                                                                                                          protected void configure(final HttpSecurity http) throws Exception {
                                                                                                              http
                                                                                                                      .authorizeRequests()
                                                                                                                          .antMatchers("/resources/**", "/registration", "/css/**", "/js/**", "/h2-console/*").permitAll()
                                                                                                                          .anyRequest().authenticated().and()
                                                                                                                      .formLogin()
                                                                                                                          .loginPage("/login").permitAll().and()
                                                                                                                      .headers()
                                                                                                                          .frameOptions().sameOrigin().and()
                                                                                                                      .logout()
                                                                                                                          .permitAll().and()
                                                                                                                      .requiresChannel()
                                                                                                                          .requestMatchers(r -> r.getHeader("X-Forwarded-Proto") != null)
                                                                                                                          .requiresSecure();
                                                                                                          }
                                                                                                      
                                                                                                          @Autowired
                                                                                                          public void configureGlobal(final AuthenticationManagerBuilder auth) throws Exception {
                                                                                                              auth.userDetailsService(userDetailsService).passwordEncoder(bcryptPasswordEncoder());
                                                                                                          }
                                                                                                      }
                                                                                                      

                                                                                                      My code is open-sourced and can be found at https://github.com/surajcm/Poseidon, I will try to troubleshoot on my own and will share the updates if I am able to resolve this issue

                                                                                                      ANSWER

                                                                                                      Answered 2021-Dec-07 at 19:14

                                                                                                      The problem is the password encoder. It is required to build the auto-configured UserDetailsService that you inject in the contructor of the class.

                                                                                                      You can break the cycle by making the bean factory method static:

                                                                                                      @Bean
                                                                                                      public static BCryptPasswordEncoder bcryptPasswordEncoder() {
                                                                                                          return new BCryptPasswordEncoder();
                                                                                                      }
                                                                                                      

                                                                                                      You can also move the factory method to different configuration class. But in my opinion, your WebSecurityConfig is the canonical place for the method.

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

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

                                                                                                      Vulnerabilities

                                                                                                      No vulnerabilities reported

                                                                                                      Install spring-boot

                                                                                                      The reference documentation includes detailed installation instructions as well as a comprehensive getting started guide.

                                                                                                      Support

                                                                                                      Are you having trouble with Spring Boot? We want to help!.
                                                                                                      Find more information at:
                                                                                                      Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
                                                                                                      Find more libraries
                                                                                                      Explore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits​
                                                                                                      Save this library and start creating your kit
                                                                                                      Install
                                                                                                      Maven
                                                                                                      Gradle
                                                                                                      CLONE
                                                                                                    • HTTPS

                                                                                                      https://github.com/spring-projects/spring-boot.git

                                                                                                    • CLI

                                                                                                      gh repo clone spring-projects/spring-boot

                                                                                                    • sshUrl

                                                                                                      git@github.com:spring-projects/spring-boot.git

                                                                                                    • Share this Page

                                                                                                      share link

                                                                                                      Reuse Pre-built Kits with spring-boot

                                                                                                      Consider Popular Application Framework Libraries

                                                                                                      Try Top Libraries by spring-projects

                                                                                                      spring-framework

                                                                                                      by spring-projectsJava

                                                                                                      spring-security

                                                                                                      by spring-projectsJava

                                                                                                      spring-petclinic

                                                                                                      by spring-projectsCSS

                                                                                                      spring-mvc-showcase

                                                                                                      by spring-projectsJava

                                                                                                      spring-data-examples

                                                                                                      by spring-projectsJava

                                                                                                      Compare Application Framework Libraries with Highest Support

                                                                                                      Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
                                                                                                      Find more libraries
                                                                                                      Explore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits​
                                                                                                      Save this library and start creating your kit