Spring JSF Integration pure Java Config (No web.xml) - spring

I'm trying to integrate Spring 4 and JSF 2.x using java config. I am trying to modify the source from the following project to accomplish this.
https://github.com/spring-projects/spring-webflow-samples/tree/master/booking-faces
However, I am stuck can anyone help me. From what I understand I need a FacesServlet but how do i configure that using java config.
pom.xml (Not yet perfect still trying to figure out what I need)
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Test</groupId>
<artifactId>TestId</artifactId>
<packaging>war</packaging>
<version>1</version>
<name>TestId Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<spring.version>4.0.5.RELEASE</spring.version>
<spring.security.version>3.2.4.RELEASE</spring.security.version>
<jstl.version>1.2</jstl.version>
<webflow-version>2.3.3.RELEASE</webflow-version>
<mojarra-version>2.2.5</mojarra-version>
</properties>
<repositories>
<repository>
<id>prime-repo</id>
<name>Prime Repo</name>
<url>http://repository.primefaces.org</url>
</repository>
</repositories>
<dependencies>
<!-- Spring 4 dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Spring webflow -->
<dependency>
<groupId>org.springframework.webflow</groupId>
<artifactId>spring-faces</artifactId>
<version>${webflow-version}</version>
</dependency>
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${spring.security.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${spring.security.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<!-- jstl for jsp page -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<!-- jsf -->
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>${mojarra-version}</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>${mojarra-version}</version>
</dependency>
<!-- primefaces -->
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>4.0</version>
</dependency>
<!-- slf4j logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jul-to-slf4j</artifactId>
<version>1.7.7</version>
</dependency>
<!-- logback -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.1.2</version>
</dependency>
</dependencies>
<build>
<finalName>TestId</finalName>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
AppConfig.java
package org.bdo.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
#Configuration
#ComponentScan(basePackages = "org.bdo")
#Import(value = { WebMvcConfig.class })
public class AppConfig
{
}
WebMvcConfig.java
package org.bdo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.faces.mvc.JsfView;
import org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter;
import org.springframework.web.servlet.view.UrlBasedViewResolver;
#Configuration
public class WebMvcConfig {
#Bean
public UrlBasedViewResolver faceletsViewResolver() {
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setViewClass(JsfView.class);
resolver.setPrefix("/WEB-INF/");
resolver.setSuffix(".xhtml");
return resolver;
}
#Bean
public SimpleControllerHandlerAdapter simpleControllerHandlerAdapter() {
return new SimpleControllerHandlerAdapter();
}
}
DispatcherServletInitializer.java
package org.config;
import javax.servlet.Filter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import com.sun.faces.config.ConfigureListener;
public class DispatcherServletInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] { AppConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
#Override
protected String[] getServletMappings() {
return new String[] { "/spring/*" };
}
#Override
protected Filter[] getServletFilters() {
return new Filter[] { new CharacterEncodingFilter() };
}
#Override
public void onStartup(ServletContext servletContext)
throws ServletException {
// Use JSF view templates saved as *.xhtml, for use with Facelets
servletContext.setInitParameter("javax.faces.DEFAULT_SUFFIX", ".xhtml");
// Enable special Facelets debug output during development
servletContext.setInitParameter("javax.faces.PROJECT_STAGE",
"Development");
// Causes Facelets to refresh templates during development
servletContext.setInitParameter("javax.faces.FACELETS_REFRESH_PERIOD",
"1");
// Declare Spring Security Facelets tag library
servletContext.setInitParameter("javax.faces.FACELETS_LIBRARIES",
"/WEB-INF/springsecurity.taglib.xml");
servletContext.addListener(ConfigureListener.class);
// Let the DispatcherServlet be registered
super.onStartup(servletContext);
}
}
intro.xhtml
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
</h:head>
<h:body>
<p:spinner />
</h:body>
</html>
Partial Stack Trace
21:38:51.479 [localhost-startStop-1] DEBUG o.springframework.jndi.JndiTemplate - Looking up JNDI object with name [spring.liveBeansView.mbeanDomain]
21:38:51.479 [localhost-startStop-1] DEBUG o.s.jndi.JndiPropertySource - JNDI lookup for name [spring.liveBeansView.mbeanDomain] threw NamingException with message: Name [spring.liveBeansView.mbeanDomain] is not bound in this Context. Unable to find [spring.liveBeansView.mbeanDomain].. Returning null.
21:38:51.479 [localhost-startStop-1] DEBUG o.s.c.e.PropertySourcesPropertyResolver - Searching for key 'spring.liveBeansView.mbeanDomain' in [systemProperties]
21:38:51.479 [localhost-startStop-1] DEBUG o.s.c.e.PropertySourcesPropertyResolver - Searching for key 'spring.liveBeansView.mbeanDomain' in [systemEnvironment]
21:38:51.479 [localhost-startStop-1] DEBUG o.s.c.e.PropertySourcesPropertyResolver - Could not find key 'spring.liveBeansView.mbeanDomain' in any property source. Returning [null]
21:38:51.479 [localhost-startStop-1] DEBUG o.s.web.servlet.DispatcherServlet - Published WebApplicationContext of servlet 'dispatcher' as ServletContext attribute with name [org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcher]
21:38:51.479 [localhost-startStop-1] INFO o.s.web.servlet.DispatcherServlet - FrameworkServlet 'dispatcher': initialization completed in 189 ms
21:38:51.479 [localhost-startStop-1] DEBUG o.s.web.servlet.DispatcherServlet - Servlet 'dispatcher' configured successfully
May 27, 2014 9:38:51 PM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory C:\Users\Admin\Desktop\New Folder (4)\sts-bundle\vfabric-tc-server-developer-2.9.5.SR1\base-instance\webapps\manager
May 27, 2014 9:38:51 PM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory C:\Users\Admin\Desktop\New Folder (4)\sts-bundle\vfabric-tc-server-developer-2.9.5.SR1\base-instance\webapps\ROOT
May 27, 2014 9:38:51 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
May 27, 2014 9:38:51 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 3271 ms
21:38:53.156 [tomcat-http--4] DEBUG o.s.web.servlet.DispatcherServlet - DispatcherServlet with name 'dispatcher' processing GET request for [/SpringJSF/spring/intro]
21:38:53.157 [tomcat-http--4] WARN o.s.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/SpringJSF/spring/intro] in DispatcherServlet with name 'dispatcher'
21:38:53.157 [tomcat-http--4] DEBUG o.s.web.servlet.DispatcherServlet - Successfully completed request
May 27, 2014 9:39:06 PM org.apache.coyote.AbstractProtocol pause
INFO: Pausing ProtocolHandler ["http-bio-8080"]
May 27, 2014 9:39:06 PM org.apache.catalina.core.StandardService stopInternal
INFO: Stopping service Catalina
May 27, 2014 9:39:07 PM org.apache.catalina.core.ApplicationContext log
INFO: Destroying Spring FrameworkServlet 'dispatcher'
21:39:07.403 [localhost-startStop-2] INFO o.s.w.c.s.AnnotationConfigWebApplicationContext - Closing WebApplicationContext for namespace 'dispatcher-servlet': startup date [Tue May 27 21:38:51 CST 2014]; parent: Root WebApplicationContext
May 27, 2014 9:39:07 PM org.apache.catalina.core.ApplicationContext log
INFO: Closing Spring root WebApplicationContext
21:39:07.403 [localhost-startStop-2] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'lifecycleProcessor'
21:39:07.403 [localhost-startStop-2] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#8d8962: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor.enhancedConfigurationProcessor]; parent: org.springframework.beans.factory.support.DefaultListableBeanFactory#3c718
21:39:07.403 [localhost-startStop-2] INFO o.s.w.c.s.AnnotationConfigWebApplicationContext - Closing Root WebApplicationContext: startup date [Tue May 27 21:38:50 CST 2014]; root of context hierarchy
21:39:07.403 [localhost-startStop-2] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'lifecycleProcessor'
21:39:07.403 [localhost-startStop-2] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#3c718: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,appConfig,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor.enhancedConfigurationProcessor,webMvcConfig,faceletsViewResolver,simpleControllerHandlerAdapter]; root of factory hierarchy
21:39:07.403 [localhost-startStop-2] DEBUG o.s.b.f.s.DisposableBeanAdapter - Invoking destroy() on bean with name 'webMvcConfig'
21:39:07.403 [localhost-startStop-2] DEBUG o.s.b.f.s.DisposableBeanAdapter - Invoking destroy() on bean with name 'appConfig'
May 27, 2014 9:39:07 PM org.apache.coyote.AbstractProtocol stop
INFO: Stopping ProtocolHandler ["http-bio-8080"]

in your servlet initializer, use this:
/** Faces Servlet */
ServletRegistration.Dynamic facesServlet = servletContext.addServlet("Faces Servlet", FacesServlet.class);
facesServlet.setLoadOnStartup(1);
facesServlet.addMapping("*.xhtml");

Related

SpringBoot + Spring Security OAuth2 2.0 Resource Server JWT at Startup Expectation is not calling Authorisation Server

Summary :
Testing out Spring Security OAuth2 Resource Server JWT with SpringBoot 2.7.7 which uses Spring Security 5.7.6 to query Authorisation Server at startup.
According to :
https://docs.spring.io/spring-security/reference/5.7/servlet/oauth2/resource-server/jwt.html#_startup_expectations
Startup Expectations
When this property and these dependencies are used, Resource Server
will automatically configure itself to validate JWT-encoded Bearer
Tokens.
It achieves this through a deterministic startup process:
Query the Provider Configuration or Authorization Server Metadata endpoint for the jwks_url property
Query the jwks_url endpoint for supported algorithms
Configure the validation strategy to query jwks_url for valid public keys of the algorithms found
Configure the validation strategy to validate each JWTs iss claim against idp.example.com.
A consequence of this process is that the authorization server must be
up and receiving requests in order for Resource Server to successfully
start up.
If the authorization server is down when Resource Server queries it
(given appropriate timeouts), then startup will fail.
I have the property defined in application.properties AND the dependencies in pom.xml as above.
However, my very small example to try this out does not work ( e.g. The Resource Server does not appear to be querying the Authorisation Server at all at startup, and therefore the Resource Server starts-up successfully.
I was expecting my very small app to fail at startup as per documentation, but it did not ! Went as far as shutting down the Authorisation Server, and the SpringBoot Resources Server app still starts up.
Here's what I did :
1) pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.7</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>org.example</groupId>
<artifactId>oauth2-resource-server</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>oauth2-resource-server</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
<spring-cloud.version>2021.0.5</spring-cloud.version>
<bootstrap.version>5.2.3</bootstrap.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-jose</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!--dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency-->
<!--dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency-->
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>${bootstrap.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
2. application.properties
server.port=8081
spring.thymeleaf.cache=false
spring.security.oauth2.resourceserver.jwt.issuer-uri=http://openam.localtest.me:8080/openam/oauth2/realms/subrealm/
spring.security.oauth2.resourceserver.jwt.jwk-set-uri=http://openam.localtest.me:8080/openam/oauth2/realms/subrealm/connect/jwk_uri
3. Configuration class:
package org.example.oauth2resourceserver;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.security.web.SecurityFilterChain;
#Configuration
#EnableWebSecurity
public class OAuth2ResourceServerSecurityConfiguration {
#Value("${spring.security.oauth2.resourceserver.jwt.jwk-set-uri}")
String jwkSetUri;
#Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests((authorize) -> authorize
.antMatchers(HttpMethod.GET, "/**").hasAuthority("SCOPE_message:read")
.antMatchers(HttpMethod.POST, "/**").hasAuthority("SCOPE_message:write")
.anyRequest().authenticated()
)
.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
return http.build();
}
#Bean
JwtDecoder jwtDecoder() {
return NimbusJwtDecoder.withJwkSetUri(this.jwkSetUri).build();
}
}
4. Controller
package org.example.oauth2resourceserver;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
#Controller
public class ExampleMVCController {
#GetMapping("/")
public String main(Model model) {
return "welcome";
}
#GetMapping("/welcome")
public String welcome(Model model) {
return "welcome";
}
}
5. Application
package org.example.oauth2resourceserver;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Oauth2ResourceServerApplication {
public static void main(String[] args) {
SpringApplication.run(Oauth2ResourceServerApplication.class, args);
}
}
With the Authorisation Server down, output on the console when I run the Resource Server is:
2022-12-28 03:32:38.148 INFO 1377958 --- [ main] o.e.o.Oauth2ResourceServerApplication : Starting Oauth2ResourceServerApplication using Java 11.0.15 on xxxxx-Inspiron-15-7510 with PID 1377958 (/home/xxxxx/projects/oauth2-resource-server/target/classes started by jsalvo in /home/xxxxx/projects/oauth2-resource-server)
2022-12-28 03:32:38.150 INFO 1377958 --- [ main] o.e.o.Oauth2ResourceServerApplication : No active profile set, falling back to 1 default profile: "default"
2022-12-28 03:32:38.561 INFO 1377958 --- [ main] o.s.cloud.context.scope.GenericScope : BeanFactory id=12f14043-de4d-3b01-a8aa-ef038a41274e
2022-12-28 03:32:38.733 INFO 1377958 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8081 (http)
2022-12-28 03:32:38.739 INFO 1377958 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-12-28 03:32:38.739 INFO 1377958 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.70]
2022-12-28 03:32:38.819 INFO 1377958 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-12-28 03:32:38.820 INFO 1377958 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 634 ms
2022-12-28 03:32:38.931 INFO 1377958 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Will secure any request with [org.springframework.security.web.session.DisableEncodeUrlFilter#748ac6f3, org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#68f6e55d, org.springframework.security.web.context.SecurityContextPersistenceFilter#2bfaba70, org.springframework.security.web.header.HeaderWriterFilter#5584d9c6, org.springframework.security.web.csrf.CsrfFilter#3bf54172, org.springframework.security.web.authentication.logout.LogoutFilter#58af5076, org.springframework.security.oauth2.server.resource.web.BearerTokenAuthenticationFilter#650c405c, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#9301672, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#2577a95d, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#6fff46bf, org.springframework.security.web.session.SessionManagementFilter#17e9bc9e, org.springframework.security.web.access.ExceptionTranslationFilter#4da39ca9, org.springframework.security.web.access.intercept.AuthorizationFilter#2954f6ab]
2022-12-28 03:32:39.140 INFO 1377958 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8081 (http) with context path ''
2022-12-28 03:32:39.152 INFO 1377958 --- [ main] o.e.o.Oauth2ResourceServerApplication : Started Oauth2ResourceServerApplication in 1.27 seconds (JVM running for 1.512)
What am I missing ?
What code in Spring Security OAuth2 Resource Server does the call to the Authorisation Server at startup ?
UPDATE 2022-12-28
As suggested by the comments, I have completely removed my OAuth2ResourceServerSecurityConfiguration above. Still no luck.
On looking at the source code for OAuth2ResourceServerJwtConfiguration.JwtDecoderConfiguration :
It appears that you must only specify one of the following properties, but not both:
spring.security.oauth2.resourceserver.jwt.issuer-uri
spring.security.oauth2.resourceserver.jwt.jwk-set-uri
The method at :
JwtDecoderConfiguration.jwtDecoderByIssuerUri() method has an #IssuerUriCondition annotation that dictates a condition where you must only have the spring.security.oauth2.resourceserver.jwt.issuer-uri property defined.
So I commented out the other property ( commented out spring.security.oauth2.resourceserver.jwt.jwk-set-uri from application.properties), but when I debug into that method via IntelliJ, it steps at line 139 below but it does not step / stop at line 141 within the lambda, which is where the code that actually calls the authorisation server, even if I try to Step-In ( F7 ) from line 139:
In short, I am still at a loss. Anyone have any ideas ?

HTTP Status 404 – Not Found for basic Spring Boot program

I receive the "HTTP Status 404 – Not Found" even though the Tomcat server seems to have initialized and running in the localhost:8080.
The pom.xml is
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework</groupId>
<artifactId>gs-consuming-rest</artifactId>
<version>0.1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<!--<scope>provided</scope>-->
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
The Controller is
package com.example.demo;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class HelloController {
#RequestMapping("/")
public String hello(){
return "Hello!";
}
}
The Main Application code is
package com.example.demo;
import java.util.Arrays;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
#SpringBootApplication
public class HelloWorldApplication {
public static void main(String[] args) {
SpringApplication.run(HelloWorldApplication.class, args);
}
}
The console logs :
2019-08-09 19:53:07.161 INFO 13948 --- [ main] com.example.demo.HelloWorldApplication : Starting HelloWorldApplication on DESKTOP-BIMC3QL with PID 13948 (C:\Users\AdharshD\Documents\workspace-sts-3.9.9.RELEASE\HelloWorld\target\classes started by AdharshD in C:\Users\AdharshD\Documents\workspace-sts-3.9.9.RELEASE\HelloWorld)
2019-08-09 19:53:07.164 INFO 13948 --- [ main] com.example.demo.HelloWorldApplication : No active profile set, falling back to default profiles: default
2019-08-09 19:53:07.791 INFO 13948 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2019-08-09 19:53:07.810 INFO 13948 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2019-08-09 19:53:07.810 INFO 13948 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.21]
2019-08-09 19:53:07.891 INFO 13948 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2019-08-09 19:53:07.891 INFO 13948 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 679 ms
2019-08-09 19:53:08.076 INFO 13948 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2019-08-09 19:53:08.079 INFO 13948 --- [ main] com.example.demo.HelloWorldApplication : Started HelloWorldApplication in 1.211 seconds (JVM running for 1.855)
You are missing spring-boot-starter-web artifact. Artifact contains tells spring boot to scan the package (in which main method is present) and all his subpackage for configuration, components and controller. Since this artifact is missing, spring doesn’t register your controller and throws 404-Not found.

JSF components are not rendered when running Spring Boot app on Eclipse Tomcat

I have Spring Boot JSF application that runs fine on embedded Tomcat
but when trying to run it on Eclipse Tomcat, the jsf components are not getting rendered, here's my pom file:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework</groupId>
<artifactId>gs-accessing-data-jpa</artifactId>
<version>0.1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.4.RELEASE</version>
</parent>
<packaging>war</packaging>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.2.14</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.2.14</version>
</dependency>
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>6.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<!--
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
-->
</plugins>
</build>
<repositories>
<repository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/libs-release</url>
</repository>
<repository>
<id>org.jboss.repository.releases</id>
<name>JBoss Maven Release Repository</name>
<url>https://repository.jboss.org/nexus/content/repositories/releases</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/libs-release</url>
</pluginRepository>
</pluginRepositories>
</project>
The main class:
package hello;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import javax.faces.application.ProjectStage;
import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.HandlesTypes;
import org.apache.catalina.Context;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.CustomScopeConfigurer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;
import org.springframework.boot.context.embedded.tomcat.TomcatContextCustomizer;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.boot.web.servlet.ServletContextInitializer;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import com.sun.faces.config.FacesInitializer;
#SpringBootApplication
public class Application extends SpringBootServletInitializer {
private static final Logger log = LoggerFactory.getLogger(Application.class);
public static void main(String[] args) {
SpringApplication.run(Application.class);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
#Bean
public ServletContextInitializer servletContextCustomizer() {
return new ServletContextInitializer() {
#Override
public void onStartup(ServletContext sc) throws ServletException {
sc.setInitParameter(ProjectStage.PROJECT_STAGE_PARAM_NAME, ProjectStage.Development.name());
}
};
}
#Bean
public static CustomScopeConfigurer customScopeConfigurer() {
CustomScopeConfigurer configurer = new CustomScopeConfigurer();
configurer.setScopes(Collections.<String, Object>singletonMap(FacesViewScope.NAME, new FacesViewScope()));
return configurer;
}
#Bean
public EmbeddedServletContainerFactory embeddedServletContainerFactory() {
TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
tomcat.addContextCustomizers(new TomcatContextCustomizer() {
#Override
public void customize(Context context) {
context.addServletContainerInitializer(new FacesInitializer(),
getServletContainerInitializerHandlesTypes(FacesInitializer.class));
context.addWelcomeFile("index.xhtml");
context.addMimeMapping("eot", "application/vnd.ms-fontobject");
context.addMimeMapping("ttf", "application/x-font-ttf");
context.addMimeMapping("woff", "application/x-font-woff");
}
});
return tomcat;
}
#SuppressWarnings("rawtypes")
private Set<Class<?>> getServletContainerInitializerHandlesTypes(
Class<? extends ServletContainerInitializer> sciClass) {
HandlesTypes annotation = sciClass.getAnnotation(HandlesTypes.class);
if (annotation == null) {
return Collections.emptySet();
}
Class[] classesArray = annotation.value();
Set<Class<?>> classesSet = new HashSet<Class<?>>(classesArray.length);
for (Class clazz : classesArray) {
classesSet.add(clazz);
}
return classesSet;
}
}
Other configuration:
JSF are added to project facets
Maven dependencies are added in deployment assembly
When running the application on server, I don't get any errors in fact I see logs meaning that JSF was started successfully:
2017-01-28 16:04:47.145 INFO 6880 --- [ost-startStop-1] hello.Application : Started Application in 13.522 seconds (JVM running for 19.312)
2017-01-28 16:04:47.231 INFO 6880 --- [ost-startStop-1] j.e.resource.webcontainer.jsf.config : Initializing Mojarra 2.2.14 ( 20161114-2153 unable to get svn info) for context '/spring-hibernate-jsf-web'
2017-01-28 16:04:47.539 INFO 6880 --- [ost-startStop-1] j.e.r.webcontainer.jsf.application : JSF1048: PostConstruct/PreDestroy annotations present. ManagedBeans methods marked with these annotations will have said annotations processed.
2017-01-28 16:04:48.557 INFO 6880 --- [ost-startStop-1] j.e.resource.webcontainer.jsf.config : Monitoring file:/C:/Users/lenovo/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/spring-hibernate-jsf-web/WEB-INF/faces-config.xml for modifications
2017-01-28 16:04:48.630 INFO 6880 --- [ost-startStop-1] .w.PostConstructApplicationEventListener : Running on PrimeFaces 6.0
2017-01-28 16:04:48.790 INFO 6880 --- [ main] org.apache.coyote.ajp.AjpNioProtocol : Starting ProtocolHandler [ajp-nio-8009]
2017-01-28 16:04:48.799 INFO 6880 --- [ main] org.apache.catalina.startup.Catalina : Server startup in 20021 ms
2017-01-28 16:04:49.463 INFO 6880 --- [nio-8080-exec-2] .a.c.c.C.[.[.[/spring-hibernate-jsf-web] : Initializing Spring FrameworkServlet 'dispatcherServlet'
2017-01-28 16:04:49.463 INFO 6880 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
2017-01-28 16:04:49.511 INFO 6880 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 47 ms
When accessing the xhtml page, there are no errors but the jsf and Primefaces components doesn't get rendered. How can I fix this issue?
I found the issue, it's weird, while running the jar on embeded tomcat i was able to access the xhtml pages without the /faces/ prefix but on eclipse tomcat i have to add /faces/ prefix before the xhtml page in order to work properly.

Spring Boot WebSocket Rabbitmq Stomp Broker Not Keeping Connection

Couldn't find any other questions related to this specific error.
I can't seem to hook up my Spring Boot WebSocket demo project with RabbitMQ. Note that everything works fine when using the "simple" broker, but when hooking up the stomp broker with Rabbit, I get the following error (keeps trying to reconnect):
Java HotSpot(TM) Client VM warning: You have loaded library /tmp/libnetty-transport-native-epoll8916930274033685449.so which might have disabled stack guard. The VM will try to fix the stack guard now.
It's highly recommended that you fix the library with 'execstack -c <libfile>', or link it with '-z noexecstack'.
2016-03-07 22:35:13.993 INFO 4047 --- [ main] o.s.m.s.s.StompBrokerRelayMessageHandler : Started.
2016-03-07 22:35:14.045 INFO 4047 --- [eactor-tcp-io-1] r.io.net.impl.netty.tcp.NettyTcpClient : CONNECTED: [id: 0x034a269f, /127.0.0.1:39955 => /127.0.0.1:25672]
2016-03-07 22:35:14.151 INFO 4047 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2016-03-07 22:35:14.158 INFO 4047 --- [ main] com.chat.ChatApplication : Started ChatApplication in 8.921 seconds (JVM running for 17.336)
2016-03-07 22:35:21.028 INFO 4047 --- [eactor-tcp-io-1] r.io.net.impl.netty.tcp.NettyTcpClient : CLOSED: [id: 0x034a269f, /127.0.0.1:39955 :> /127.0.0.1:25672]
2016-03-07 22:35:21.030 INFO 4047 --- [eactor-tcp-io-1] r.io.net.impl.netty.tcp.NettyTcpClient : Failed to connect to /127.0.0.1:25672. Attempting reconnect in 5000ms.
Just to be sure I'm pointing at the right point, I run:
matthew#matthew ~/code/chat $ epmd -names
epmd: up and running on port 4369 with data:
name rabbit at port 25672
Here's my WebSocketConfig:
package com.chat.shared.websocket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import com.chat.user.services.UserPresenceService;
#Configuration
#EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
#Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableStompBrokerRelay("/topic", "/queue").setRelayPort(25672);
config.setApplicationDestinationPrefixes("/app");
}
#Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").withSockJS();
}
#Bean
public UserPresenceService presenceChannelInterceptor() {
return new UserPresenceService();
}
#Override
public void configureClientInboundChannel(ChannelRegistration registration) {
registration.setInterceptors(presenceChannelInterceptor());
}
#Override
public void configureClientOutboundChannel(ChannelRegistration registration) {
registration.taskExecutor().corePoolSize(8);
registration.setInterceptors(presenceChannelInterceptor());
}
}
and finally my dependencies:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.chat</groupId>
<artifactId>chat</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>chat</name>
<description>WebSocket Project</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.2.RELEASE</version>
<relativePath />
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-messaging</artifactId>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-core</artifactId>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-net</artifactId>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.0.34.Final</version>
</dependency>
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.projectreactor</groupId>
<artifactId>reactor-tcp</artifactId>
<version>1.0.0.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
I have a feeling my problem has to do with the netty/reactor dependencies I'm bringing in. Any input is appreciated.
First of all you really should be consistent with the Spring Framework (Boot) dependencies and don't use Reactor 1.0.0, but exactly the latest 2.0.7.RELEASE.
Not sure from here that you need reactor-tcp at all...
Regarding RabbitMQ part. You should be sure that you really have installed the STOMP plugin: https://www.rabbitmq.com/stomp.html.
Note: the default STOMP port is 61613.

JPA configured app with Spring annotations

I am converting a pure Hibernate annotation configured app to pure Jpa (from sessionFactory to entityManager) with spring. So an example code is below:
#Configuration
#EnableTransactionManagement
#PropertySource("classpath:application.properties")
public class DBConfiguration implements TransactionManagementConfigurer
{
#Resource
Environment mEnvironment;
#Bean
public DataSource dataSource()
{
HikariDataSource dataSource = new HikariDataSource();
dataSource.setDriverClassName(mEnvironment.getRequiredProperty("db.driver"));
dataSource.setJdbcUrl(mEnvironment.getRequiredProperty("db.url"));
dataSource.setUsername(mEnvironment.getRequiredProperty("db.username"));
dataSource.setPassword(mEnvironment.getRequiredProperty("db.password"));
return dataSource;
}
public Properties hibernateProperties()
{
Properties properties = new Properties();
properties.put("hibernate.dialect", mEnvironment.getProperty("hibernate.dialect"));
properties.put("hibernate.show_sql", mEnvironment.getProperty("hibernate.show_sql"));
return properties;
}
#Bean
public LocalContainerEntityManagerFactoryBean sessionFactory() throws IOException
{
JpaVendorAdapter vendor = new HibernateJpaVendorAdapter();
LocalContainerEntityManagerFactoryBean sessionFactory = new LocalContainerEntityManagerFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setJpaVendorAdapter(vendor);
sessionFactory.setPackagesToScan("com.utilisoft.urlshortener");
sessionFactory.setJpaProperties(hibernateProperties());
sessionFactory.afterPropertiesSet();
return sessionFactory;
}
#Bean
public JpaTransactionManager transactionManager()
{
JpaTransactionManager transactionManager = new JpaTransactionManager();
try
{
transactionManager.setEntityManagerFactory(sessionFactory().getObject());
} catch (IOException e)
{
e.printStackTrace();
}
return transactionManager;
}
#Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
return new PersistenceExceptionTranslationPostProcessor();
}
#Override
public PlatformTransactionManager annotationDrivenTransactionManager()
{
return transactionManager();
}
}
Then in my DAO I simply have (just for testing purposes for now):
#Repository("bean")
public class UrlDaoImpl implements UrlDao
{
#PersistenceContext
EntityManager entityFactory;
#Override
public Shortener getShortener(long aPk)
{
return (Shortener) entityFactory.find(Shortener.class, aPk);
}
}
And then I am simply trying to test whether it works by doing that in a different class:
public static void main(String[] args)
{
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.registerShutdownHook();
//The class containing all my config
context.register(DBConfiguration.class);
context.refresh();
UrlServiceImpl bean = (UrlServiceImpl)context.getBean("bean");
long aa = 1;
Shortener url = (Shortener) bean.getShortener(aa);
System.out.println(url.getToken());
context.close();
}
And the error I am getting is:
11:59:20,779 INFO AnnotationConfigWebApplicationContext:510 - Refreshing Root WebApplicationContext: startup date [Wed Mar 18 11:59:20 GMT 2015]; root of context hierarchy
11:59:20,864 INFO AnnotationConfigWebApplicationContext:208 - Registering annotated classes: [class com.utilisoft.urlshortener.config.DBConfiguration]
11:59:21,029 INFO PostProcessorRegistrationDelegate$BeanPostProcessorChecker:309 - Bean 'DBConfiguration' of type [class com.utilisoft.urlshortener.config.DBConfiguration$$EnhancerBySpringCGLIB$$3671bce8] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
Exception in thread "main" java.lang.NoClassDefFoundError: org.springframework.beans.FatalBeanException
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1111)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1006)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:956)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:747)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at com.utilisoft.urlshortener.Main.main(Main.java:17)
11:59:21,549 INFO AnnotationConfigWebApplicationContext:862 - Closing Root WebApplicationContext: startup date [Wed Mar 18 11:59:20 GMT 2015]; root of context hierarchy
11:59:21,550 WARN AnnotationConfigWebApplicationContext:880 - Exception thrown from LifecycleProcessor on context close
java.lang.IllegalStateException: LifecycleProcessor not initialized - call 'refresh' before invoking lifecycle methods via the context: Root WebApplicationContext: startup date [Wed Mar 18 11:59:20 GMT 2015]; root of context hierarchy
at org.springframework.context.support.AbstractApplicationContext.getLifecycleProcessor(AbstractApplicationContext.java:357)
at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:877)
at org.springframework.context.support.AbstractApplicationContext$1.run(AbstractApplicationContext.java:804)
Update:
I added
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>3.2.2.RELEASE</version>
</dependency>
and now it's telling me:
2:16:33,266 INFO AnnotationConfigWebApplicationContext:510 - Refreshing Root WebApplicationContext: startup date [Wed Mar 18 12:16:33 GMT 2015]; root of context hierarchy
Exception in thread "main" java.lang.NoSuchMethodError: org.springframework.beans.factory.support.DefaultListableBeanFactory.getDependencyComparator()Ljava/util/Comparator;
at org.springframework.context.annotation.AnnotationConfigUtils.registerAnnotationConfigProcessors(AnnotationConfigUtils.java:136)
at org.springframework.context.annotation.AnnotationConfigUtils.registerAnnotationConfigProcessors(AnnotationConfigUtils.java:120)
at org.springframework.context.annotation.AnnotatedBeanDefinitionReader.<init>(AnnotatedBeanDefinitionReader.java:83)
at org.springframework.context.annotation.AnnotatedBeanDefinitionReader.<init>(AnnotatedBeanDefinitionReader.java:66)
at org.springframework.web.context.support.AnnotationConfigWebApplicationContext.loadBeanDefinitions(AnnotationConfigWebApplicationContext.java:188)
at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:129)
at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:537)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:452)
at com.utilisoft.urlshortener.Main.main(Main.java:17)
Update:
My pom.xml file is as follows:
<properties>
<spring.version>4.1.5.RELEASE</spring.version>
<hibernate.version>4.3.8.Final</hibernate.version>
<sql.server.conector.version>4.0</sql.server.conector.version>
<freemarker.version>2.3.21</freemarker.version>
</properties>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.1.5.RELEASE</version>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- DBConnectionPool -->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>2.3.2</version>
</dependency>
<!-- DBCP -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.0.1</version>
</dependency>
<!--SQL Server Connector -->
<dependency>
<groupId>com.microsoft.sqlserver.jdbc</groupId>
<artifactId>sqljdbc4</artifactId>
<version>${sql.server.conector.version}</version>
</dependency>
<!-- Servlet Api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- Commons Lang-3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.2</version>
</dependency>
<!-- slf4j-log4j -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.1</version>
</dependency>
</dependencies>
The new message I am getting is:
12:43:37,492 INFO AnnotationConfigWebApplicationContext:510 - Refreshing Root WebApplicationContext: startup date [Wed Mar 18 12:43:37 GMT 2015]; root of context hierarchy
12:43:37,591 INFO AnnotationConfigWebApplicationContext:208 - Registering annotated classes: [class com.utilisoft.urlshortener.config.DBConfiguration]
12:43:37,754 INFO PostProcessorRegistrationDelegate$BeanPostProcessorChecker:309 - Bean 'DBConfiguration' of type [class com.utilisoft.urlshortener.config.DBConfiguration$$EnhancerBySpringCGLIB$$ad11f992] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
Exception in thread "main" java.lang.NoClassDefFoundError: org.springframework.beans.FatalBeanException
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1111)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1006)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:956)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:747)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at com.utilisoft.urlshortener.Main.main(Main.java:17)
Looks like you miss the spring-beans-4.1.5.RELEASE.jar in your classpath. Download and add it. This jar contains the missing class org.springframework.beans.FatalBeanException

Resources