initializing jpa entitymanagerfactory in applicationscope bean in jsf 2 - jsf-2

This is my first post on stackoverflow
I want to create EntityManagerFactory in the ApplicationScope bean in jsf 2.
Here is my bean
#ApplicationScoped
#ManagedBean(eager = true)
public class ApplicationContext implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private EntityManagerFactory entityManagerFactory = null;
private EntityManager entityManager = null;
public ApplicationContext(){
}
public EntityManagerFactory getEntityManagerFactory() {
return entityManagerFactory;
}
public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory) {
this.entityManagerFactory = entityManagerFactory;
}
public EntityManager getEntityManager() {
return entityManager;
}
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
#PostConstruct
public void applicationInitialized(){
System.out.println("application is being initialized");
this.entityManagerFactory = Persistence.createEntityManagerFactory("PersonalProject");
this.entityManager = this.entityManagerFactory.createEntityManager();
}
#PreDestroy
public void applicationDestroyed(){
System.out.println("application being destroyed");
}
}
I get a huge exception stacktrace for this.
com.sun.faces.mgbean.ManagedBeanCreationException: An error occurred performing resource injection on managed bean applicationContext
at com.sun.faces.mgbean.BeanBuilder.invokePostConstruct(BeanBuilder.java:229)
at com.sun.faces.mgbean.BeanBuilder.build(BeanBuilder.java:105)
at com.sun.faces.mgbean.BeanManager.createAndPush(BeanManager.java:409)
at com.sun.faces.mgbean.BeanManager.create(BeanManager.java:269)
at com.sun.faces.mgbean.BeanManager.create(BeanManager.java:256)
at com.sun.faces.config.ConfigureListener.contextInitialized(ConfigureListener.java:255)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4779)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5273)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1566)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1556)
at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: com.sun.faces.spi.InjectionProviderException
at com.sun.faces.vendor.WebContainerInjectionProvider.invokeAnnotatedMethod(WebContainerInjectionProvider.java:119)
at com.sun.faces.vendor.WebContainerInjectionProvider.invokePostConstruct(WebContainerInjectionProvider.java:99)
at com.sun.faces.mgbean.BeanBuilder.invokePostConstruct(BeanBuilder.java:223)
... 15 more
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.sun.faces.vendor.WebContainerInjectionProvider.invokeAnnotatedMethod(WebContainerInjectionProvider.java:117)
... 17 more
Caused by: Exception [EclipseLink-30005] (Eclipse Persistence Services - 2.1.3.v20110304-r9073): org.eclipse.persistence.exceptions.PersistenceUnitLoadingException
Exception Description: An exception was thrown while searching for persistence archives with ClassLoader: WebappClassLoader
context: /PersonalProject
delegate: false
repositories:
/WEB-INF/classes/
----------> Parent Classloader:
org.apache.catalina.loader.StandardClassLoader#6d4c1103
Internal Exception: javax.persistence.PersistenceException: Exception [EclipseLink-28018] (Eclipse Persistence Services - 2.1.3.v20110304-r9073): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Predeployment of PersistenceUnit [PersonalProject] failed.
Internal Exception: Exception [EclipseLink-7155] (Eclipse Persistence Services - 2.1.3.v20110304-r9073): org.eclipse.persistence.exceptions.ValidationException
Exception Description: The type [class java.lang.Object] for the attribute [content] on the entity class [class com.justme.model.entities.Post] is not a valid type for a serialized mapping. The attribute type must implement the Serializable interface.
at org.eclipse.persistence.exceptions.PersistenceUnitLoadingException.exceptionSearchingForPersistenceResources(PersistenceUnitLoadingException.java:126)
at org.eclipse.persistence.jpa.PersistenceProvider.createEntityManagerFactory(PersistenceProvider.java:136)
at org.eclipse.persistence.jpa.PersistenceProvider.createEntityManagerFactory(PersistenceProvider.java:65)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:83)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:60)
at com.justme.web.gui.ApplicationContext.applicationInitialized(ApplicationContext.java:49)
... 22 more
Caused by: javax.persistence.PersistenceException: Exception [EclipseLink-28018] (Eclipse Persistence Services - 2.1.3.v20110304-r9073): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Predeployment of PersistenceUnit [PersonalProject] failed.
Internal Exception: Exception [EclipseLink-7155] (Eclipse Persistence Services - 2.1.3.v20110304-r9073): org.eclipse.persistence.exceptions.ValidationException
Exception Description: The type [class java.lang.Object] for the attribute [content] on the entity class [class com.justme.model.entities.Post] is not a valid type for a serialized mapping. The attribute type must implement the Serializable interface.
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.predeploy(EntityManagerSetupImpl.java:1014)
at org.eclipse.persistence.internal.jpa.deployment.JPAInitializer.callPredeploy(JPAInitializer.java:88)
at org.eclipse.persistence.jpa.PersistenceProvider.createEntityManagerFactory(PersistenceProvider.java:127)
... 26 more
Caused by: Exception [EclipseLink-28018] (Eclipse Persistence Services - 2.1.3.v20110304-r9073): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Predeployment of PersistenceUnit [PersonalProject] failed.
Internal Exception: Exception [EclipseLink-7155] (Eclipse Persistence Services - 2.1.3.v20110304-r9073): org.eclipse.persistence.exceptions.ValidationException
Exception Description: The type [class java.lang.Object] for the attribute [content] on the entity class [class com.justme.model.entities.Post] is not a valid type for a serialized mapping. The attribute type must implement the Serializable interface.
at org.eclipse.persistence.exceptions.EntityManagerSetupException.predeployFailed(EntityManagerSetupException.java:210)
... 29 more
Caused by: Exception [EclipseLink-7155] (Eclipse Persistence Services - 2.1.3.v20110304-r9073): org.eclipse.persistence.exceptions.ValidationException
Exception Description: The type [class java.lang.Object] for the attribute [content] on the entity class [class com.justme.model.entities.Post] is not a valid type for a serialized mapping. The attribute type must implement the Serializable interface.
at org.eclipse.persistence.exceptions.ValidationException.invalidTypeForSerializedAttribute(ValidationException.java:1112)
at org.eclipse.persistence.internal.jpa.metadata.converters.SerializedMetadata.process(SerializedMetadata.java:86)
at org.eclipse.persistence.internal.jpa.metadata.accessors.mappings.MappingAccessor.processSerialized(MappingAccessor.java:1641)
at org.eclipse.persistence.internal.jpa.metadata.accessors.mappings.MappingAccessor.processJPAConverters(MappingAccessor.java:1433)
at org.eclipse.persistence.internal.jpa.metadata.accessors.mappings.MappingAccessor.processMappingConverter(MappingAccessor.java:1495)
at org.eclipse.persistence.internal.jpa.metadata.accessors.mappings.MappingAccessor.processMappingValueConverter(MappingAccessor.java:1513)
at org.eclipse.persistence.internal.jpa.metadata.accessors.mappings.BasicAccessor.process(BasicAccessor.java:367)
at org.eclipse.persistence.internal.jpa.metadata.MetadataDescriptor.processAccessors(MetadataDescriptor.java:1365)
at org.eclipse.persistence.internal.jpa.metadata.accessors.classes.ClassAccessor.processAccessors(ClassAccessor.java:963)
at org.eclipse.persistence.internal.jpa.metadata.accessors.classes.EntityAccessor.processAccessors(EntityAccessor.java:876)
at org.eclipse.persistence.internal.jpa.metadata.accessors.classes.EntityAccessor.process(EntityAccessor.java:691)
at org.eclipse.persistence.internal.jpa.metadata.MetadataProject.processStage2(MetadataProject.java:1531)
at org.eclipse.persistence.internal.jpa.metadata.MetadataProcessor.processORMMetadata(MetadataProcessor.java:474)
at org.eclipse.persistence.internal.jpa.deployment.PersistenceUnitProcessor.processORMetadata(PersistenceUnitProcessor.java:441)
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.predeploy(EntityManagerSetupImpl.java:968)
... 28 more
Mar 17, 2013 11:40:24 AM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Exception sending context initialized event to listener instance of class com.sun.faces.config.ConfigureListener
java.lang.RuntimeException: com.sun.faces.mgbean.ManagedBeanCreationException: An error occurred performing resource injection on managed bean applicationContext
at com.sun.faces.config.ConfigureListener.contextInitialized(ConfigureListener.java:292)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4779)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5273)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1566)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1556)
at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: com.sun.faces.mgbean.ManagedBeanCreationException: An error occurred performing resource injection on managed bean applicationContext
at com.sun.faces.mgbean.BeanBuilder.invokePostConstruct(BeanBuilder.java:229)
at com.sun.faces.mgbean.BeanBuilder.build(BeanBuilder.java:105)
at com.sun.faces.mgbean.BeanManager.createAndPush(BeanManager.java:409)
at com.sun.faces.mgbean.BeanManager.create(BeanManager.java:269)
at com.sun.faces.mgbean.BeanManager.create(BeanManager.java:256)
at com.sun.faces.config.ConfigureListener.contextInitialized(ConfigureListener.java:255)
... 10 more
Caused by: com.sun.faces.spi.InjectionProviderException
at com.sun.faces.vendor.WebContainerInjectionProvider.invokeAnnotatedMethod(WebContainerInjectionProvider.java:119)
at com.sun.faces.vendor.WebContainerInjectionProvider.invokePostConstruct(WebContainerInjectionProvider.java:99)
at com.sun.faces.mgbean.BeanBuilder.invokePostConstruct(BeanBuilder.java:223)
... 15 more
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.sun.faces.vendor.WebContainerInjectionProvider.invokeAnnotatedMethod(WebContainerInjectionProvider.java:117)
... 17 more
Caused by: Exception [EclipseLink-30005] (Eclipse Persistence Services - 2.1.3.v20110304-r9073): org.eclipse.persistence.exceptions.PersistenceUnitLoadingException
Exception Description: An exception was thrown while searching for persistence archives with ClassLoader: WebappClassLoader
context: /PersonalProject
delegate: false
repositories:
/WEB-INF/classes/
----------> Parent Classloader:
org.apache.catalina.loader.StandardClassLoader#6d4c1103
Internal Exception: javax.persistence.PersistenceException: Exception [EclipseLink-28018] (Eclipse Persistence Services - 2.1.3.v20110304-r9073): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Predeployment of PersistenceUnit [PersonalProject] failed.
Internal Exception: Exception [EclipseLink-7155] (Eclipse Persistence Services - 2.1.3.v20110304-r9073): org.eclipse.persistence.exceptions.ValidationException
Exception Description: The type [class java.lang.Object] for the attribute [content] on the entity class [class com.justme.model.entities.Post] is not a valid type for a serialized mapping. The attribute type must implement the Serializable interface.
at org.eclipse.persistence.exceptions.PersistenceUnitLoadingException.exceptionSearchingForPersistenceResources(PersistenceUnitLoadingException.java:126)
at org.eclipse.persistence.jpa.PersistenceProvider.createEntityManagerFactory(PersistenceProvider.java:136)
at org.eclipse.persistence.jpa.PersistenceProvider.createEntityManagerFactory(PersistenceProvider.java:65)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:83)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:60)
at com.justme.web.gui.ApplicationContext.applicationInitialized(ApplicationContext.java:49)
... 22 more
Caused by: javax.persistence.PersistenceException: Exception [EclipseLink-28018] (Eclipse Persistence Services - 2.1.3.v20110304-r9073): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Predeployment of PersistenceUnit [PersonalProject] failed.
Internal Exception: Exception [EclipseLink-7155] (Eclipse Persistence Services - 2.1.3.v20110304-r9073): org.eclipse.persistence.exceptions.ValidationException
Exception Description: The type [class java.lang.Object] for the attribute [content] on the entity class [class com.justme.model.entities.Post] is not a valid type for a serialized mapping. The attribute type must implement the Serializable interface.
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.predeploy(EntityManagerSetupImpl.java:1014)
at org.eclipse.persistence.internal.jpa.deployment.JPAInitializer.callPredeploy(JPAInitializer.java:88)
at org.eclipse.persistence.jpa.PersistenceProvider.createEntityManagerFactory(PersistenceProvider.java:127)
... 26 more
Caused by: Exception [EclipseLink-28018] (Eclipse Persistence Services - 2.1.3.v20110304-r9073): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Predeployment of PersistenceUnit [PersonalProject] failed.
Internal Exception: Exception [EclipseLink-7155] (Eclipse Persistence Services - 2.1.3.v20110304-r9073): org.eclipse.persistence.exceptions.ValidationException
Exception Description: The type [class java.lang.Object] for the attribute [content] on the entity class [class com.justme.model.entities.Post] is not a valid type for a serialized mapping. The attribute type must implement the Serializable interface.
at org.eclipse.persistence.exceptions.EntityManagerSetupException.predeployFailed(EntityManagerSetupException.java:210)
... 29 more
Caused by: Exception [EclipseLink-7155] (Eclipse Persistence Services - 2.1.3.v20110304-r9073): org.eclipse.persistence.exceptions.ValidationException
Exception Description: The type [class java.lang.Object] for the attribute [content] on the entity class [class com.justme.model.entities.Post] is not a valid type for a serialized mapping. The attribute type must implement the Serializable interface.
at org.eclipse.persistence.exceptions.ValidationException.invalidTypeForSerializedAttribute(ValidationException.java:1112)
at org.eclipse.persistence.internal.jpa.metadata.converters.SerializedMetadata.process(SerializedMetadata.java:86)
at org.eclipse.persistence.internal.jpa.metadata.accessors.mappings.MappingAccessor.processSerialized(MappingAccessor.java:1641)
at org.eclipse.persistence.internal.jpa.metadata.accessors.mappings.MappingAccessor.processJPAConverters(MappingAccessor.java:1433)
at org.eclipse.persistence.internal.jpa.metadata.accessors.mappings.MappingAccessor.processMappingConverter(MappingAccessor.java:1495)
at org.eclipse.persistence.internal.jpa.metadata.accessors.mappings.MappingAccessor.processMappingValueConverter(MappingAccessor.java:1513)
at org.eclipse.persistence.internal.jpa.metadata.accessors.mappings.BasicAccessor.process(BasicAccessor.java:367)
at org.eclipse.persistence.internal.jpa.metadata.MetadataDescriptor.processAccessors(MetadataDescriptor.java:1365)
at org.eclipse.persistence.internal.jpa.metadata.accessors.classes.ClassAccessor.processAccessors(ClassAccessor.java:963)
at org.eclipse.persistence.internal.jpa.metadata.accessors.classes.EntityAccessor.processAccessors(EntityAccessor.java:876)
at org.eclipse.persistence.internal.jpa.metadata.accessors.classes.EntityAccessor.process(EntityAccessor.java:691)
at org.eclipse.persistence.internal.jpa.metadata.MetadataProject.processStage2(MetadataProject.java:1531)
at org.eclipse.persistence.internal.jpa.metadata.MetadataProcessor.processORMMetadata(MetadataProcessor.java:474)
at org.eclipse.persistence.internal.jpa.deployment.PersistenceUnitProcessor.processORMetadata(PersistenceUnitProcessor.java:441)
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.predeploy(EntityManagerSetupImpl.java:968)
... 28 more
the root cause says that it is because the class Post does not implement serializable.
but it already implements it as follows.
public class Post implements Serializable {}
I am getting this problem only in ApplicationScoped ManagedBean.
If I try to create EntityManagerFactory using a ServletContextListener then it is created just fine.
what can be the problem?
Am I missing some knowledge about the ApplicationScoped bean?

It looks as if class Post had a field named content of type Object:
Exception Description: The type [class java.lang.Object] for the attribute [content] on the entity class [class com.justme.model.entities.Post] is not a valid type for a serialized mapping. The attribute type must implement the Serializable interface.
JPA does not know how to convert Object to a column type in a database.
One more thing. Your are using EntityManager as a field in ApplicationContext. EntityManager class is not thread-save, so using it in a application-scoped class would casus a lot of problems.
You had better remove EntityManager field, remove setEntityManager method and rewrite getEntityManager
public EntityManager getEntityManager() {
return entityManagerFactory.getEntityManager();
}
EntityManagerFactory is thread save.

Related

Spring Security LDAP Changes After 5.7

I am trying to understand the steps to support LDAP with Spring security...replacing our current basic authentication. Recently I made the changes to support the deprecation of the WebSecurityConfigurerAdapter and all is working fine. So now I want to swap out the basic authentication AuthenticationManager or AuthenticationProvider with their LDAP equivalents. There are several websites with partial information and I cant quite put the pieces together.
So I am starting with the spring guide on authenticating ldap (https://github.com/spring-guides/gs-authenticating-ldap) I took the "complete" example, modified for our version of Spring Boot 2.7.5 and the app starts and validates fine. I tried updating the example according to several websites from :
#Autowired
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.ldapAuthentication()
.userDnPatterns("uid={0},ou=people")
.groupSearchBase("ou=groups")
.contextSource()
.url("ldap://localhost:8389/dc=springframework,dc=org")
.and()
.passwordCompare()
.passwordEncoder(new BCryptPasswordEncoder())
.passwordAttribute("userPassword");
To :
#Bean
public EmbeddedLdapServerContextSourceFactoryBean contextSourceFactoryBean() {
EmbeddedLdapServerContextSourceFactoryBean contextSourceFactoryBean =
EmbeddedLdapServerContextSourceFactoryBean.fromEmbeddedLdapServer();
contextSourceFactoryBean.setPort(0);
return contextSourceFactoryBean;
}
#Bean
public AuthenticationManager authenticationManager(BaseLdapPathContextSource contextSource) {
LdapPasswordComparisonAuthenticationManagerFactory factory = new LdapPasswordComparisonAuthenticationManagerFactory(
contextSource, new BCryptPasswordEncoder());
factory.setUserDnPatterns("uid={0},ou=people");
factory.setPasswordAttribute("pwd");
return factory.createAuthenticationManager();
}
Thinking this closer to the recommendations and closer to what I would be using in our real project. Now when I try to build ... the test phase keeps failing with the following stack trace
ERROR[m] loginWithValidUserThenAuthenticated Time elapsed: 0 s <<< ERROR!
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'authenticationManager' defined in class path resource [com/example/authenticatingldap/WebSecurityConfig.class]: Unsatisfied dependency expressed through method 'authenticationManager' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'contextSourceFactoryBean': FactoryBean threw exception on object creation; nested exception is java.lang.IllegalStateException: Unable to load LDIF classpath*:*.ldif
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'contextSourceFactoryBean': FactoryBean threw exception on object creation; nested exception is java.lang.IllegalStateException: Unable to load LDIF classpath*:*.ldif
Caused by: java.lang.IllegalStateException: Unable to load LDIF classpath*:*.ldif
Caused by: com.unboundid.ldap.sdk.LDAPException: An entry with DN 'dc=springframework,dc=org' already exists in the server.
I am using the same ldif file that worked with the other configuration. The code follows the other examples and recommendation but the embedded LDAP server wont load the file. Has anyone seen and solved this problem? Once this is working, do we simply remove the Embedded LDAP bean and somehow point the configuration to the real LDAP server?

Declaring AuthenticationManager Bean throws exception "Cannot apply DaoAuthenticationConfigurer to already built object"

My UserServiceImpl class extends the UserDetailsService interface, and i have overriden the loadUserByUsername() method, I declared an AuthenticationManager bean, and using the builder, passed it my userDetailsService implementation and preferred password encoder.
Here's my security config class :
#Configuration
#EnableWebSecurity
public class UserManagmentConfig {
#Autowired
private UserDetailsService userDetailsService;
#Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
#Bean
public AuthenticationManager authenticationManager(AuthenticationManagerBuilder builder) throws Exception {
return builder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()).and().build();
}
}
And my WebAuthorization config :
public class WebAuthorizationConfig {
#Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.formLogin();
http.authorizeRequests().anyRequest().authenticated();
return http.build();
}
}
This is the exception i get when launching the app :
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'authenticationManager' defined in class path resource [app/ticketme/securityconfig/UserManagmentConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.authentication.AuthenticationManager]: Factory method 'authenticationManager' threw exception; nested exception is java.lang.IllegalStateException: Cannot apply org.springframework.security.config.annotation.authentication.configurers.userdetails.DaoAuthenticationConfigurer#14d513ca to already built object
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:658) ~[spring-beans-5.3.21.jar:5.3.21]
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:638) ~[spring-beans-5.3.21.jar:5.3.21]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1352) ~[spring-beans-5.3.21.jar:5.3.21]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1195) ~[spring-beans-5.3.21.jar:5.3.21]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582) ~[spring-beans-5.3.21.jar:5.3.21]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.21.jar:5.3.21]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.21.jar:5.3.21]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.21.jar:5.3.21]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.21.jar:5.3.21]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.21.jar:5.3.21]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:955) ~[spring-beans-5.3.21.jar:5.3.21]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918) ~[spring-context-5.3.21.jar:5.3.21]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.21.jar:5.3.21]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:147) ~[spring-boot-2.7.1.jar:2.7.1]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:734) ~[spring-boot-2.7.1.jar:2.7.1]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:408) ~[spring-boot-2.7.1.jar:2.7.1]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:308) ~[spring-boot-2.7.1.jar:2.7.1]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1306) ~[spring-boot-2.7.1.jar:2.7.1]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1295) ~[spring-boot-2.7.1.jar:2.7.1]
at app.ticketme.Main.main(Main.java:10) ~[classes/:na]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.authentication.AuthenticationManager]: Factory method 'authenticationManager' threw exception; nested exception is java.lang.IllegalStateException: Cannot apply org.springframework.security.config.annotation.authentication.configurers.userdetails.DaoAuthenticationConfigurer#14d513ca to already built object
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.3.21.jar:5.3.21]
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:653) ~[spring-beans-5.3.21.jar:5.3.21]
... 19 common frames omitted
Caused by: java.lang.IllegalStateException: Cannot apply org.springframework.security.config.annotation.authentication.configurers.userdetails.DaoAuthenticationConfigurer#14d513ca to already built object
at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.add(AbstractConfiguredSecurityBuilder.java:182) ~[spring-security-config-5.7.2.jar:5.7.2]
at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.apply(AbstractConfiguredSecurityBuilder.java:125) ~[spring-security-config-5.7.2.jar:5.7.2]
at org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder.apply(AuthenticationManagerBuilder.java:280) ~[spring-security-config-5.7.2.jar:5.7.2]
at org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder.userDetailsService(AuthenticationManagerBuilder.java:182) ~[spring-security-config-5.7.2.jar:5.7.2]
at org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration$DefaultPasswordEncoderAuthenticationManagerBuilder.userDetailsService(AuthenticationConfiguration.java:291) ~[spring-security-config-5.7.2.jar:5.7.2]
at app.ticketme.securityconfig.UserManagmentConfig.authenticationManager(UserManagmentConfig.java:31) ~[classes/:na]
at app.ticketme.securityconfig.UserManagmentConfig$$EnhancerBySpringCGLIB$$a7378581.CGLIB$authenticationManager$1(<generated>) ~[classes/:na]
at app.ticketme.securityconfig.UserManagmentConfig$$EnhancerBySpringCGLIB$$a7378581$$FastClassBySpringCGLIB$$2537ee3.invoke(<generated>) ~[classes/:na]
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244) ~[spring-core-5.3.21.jar:5.3.21]
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:331) ~[spring-context-5.3.21.jar:5.3.21]
at app.ticketme.securityconfig.UserManagmentConfig$$EnhancerBySpringCGLIB$$a7378581.authenticationManager(<generated>) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.3.21.jar:5.3.21]
... 20 common frames omitted
Sadly, most of the youtube tutorials use the deprecated WebSecurityConfigurerAdapter, what am i doing wrong here ? any help appreciated.
when you enable formLogin, the framework will build a authentication manager for you with the supplied beans that you instantiate.
Why you are building your own authenticaation manager i have no idea.
So lets go through the steps, when you select you want to use formLogin the framework creates an authentication manager with the beans you have provided. You have provided a passwordEncoder and you should also provide an implementation of the UserDetailsService interface. This should be supplied like a bean as such:
#Bean
CustomUserDetailsService customUserDetailsService() {
return new CustomUserDetailsService();
}
Spring will then create a DaoAuthenticationProvider and stick your password encoder in it and your custom UserDetailsService.
And your error message tells me that since you have already built a generic provider, the framework cant add more stuff to it.
You should read how to enable form login in the documentation FormLogin Spring security
and basically remove:
#Bean
public AuthenticationManager authenticationManager(AuthenticationManagerBuilder builder) throws Exception {
return builder.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder())
.and()
.build();
}

CxfClientGrailsPlugin - Web service client abcClient cannot be created before setting the clientInterface=[:] and serviceEndpointAddress

I am using cxf-client grails plugin for SOAP request:
I have added these client configuration into Config:
cxf {
client {
paymentRequestClient {
wsdl = "https://sandbox.demo.com/payments.wsdl"
namespace = "com.demo.soap"
clientInterface = com.demo.soap.PaymentPortType
serviceEndpointAddress = "https://sandbox.demo.com/payments.php"
}
}
}
After running grails wsdl2java grails has generated the required Java classes against the provided WSDL except for PaymentPortType class.
On running the application, I am getting this error:
Web service client paymentRequestClient cannot be created before setting the clientInterface=[:] and serviceEndpointAddress=https://sandbox.demo.com/payments.php properties
[ERROR] 2015-10-27 12:00:11,899 CxfClientGrailsPlugin - Web service client paymentRequestClient cannot be created before setting the clientInterface=[:] and serviceEndpointAddress=https://sandbox.demo.com/payments.php properties
Configuring Spring Security Core ...
... finished configuring Spring Security Core
Configuring Spring Security REST ...
... finished configuring Spring Security REST
[ERROR] 2015-10-27 12:00:39,401
org.codehaus.groovy.grails.web.context.GrailsContextLoaderListener - Error initializing the application: Error creating bean with name 'paymentRequestClient': Initialization of bean failed; nested exception is org.springframework.beans.TypeMismatchException: Failed to convert property value of type 'java.lang.String' to required type 'java.lang.Class' for property 'clientInterface'; nested exception is java.lang.IllegalArgumentException: Could not load class []!
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'paymentRequestClient': Initialization of bean failed; nested exception is org.springframework.beans.TypeMismatchException: Failed to convert property value of type 'java.lang.String' to required type 'java.lang.Class' for property 'clientInterface'; nested exception is java.lang.IllegalArgumentException: Could not load class []!
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.beans.TypeMismatchException: Failed to convert property value of type 'java.lang.String' to required type 'java.lang.Class' for property 'clientInterface'; nested exception is java.lang.IllegalArgumentException: Could not load class []!
... 4 more
Caused by: java.lang.IllegalArgumentException: Could not load class []!
... 4 more
What could be the possible issue?
You have this issue because Spring can't find the class com.demo.soap.PaymentPortType in the classpath

error deploy grails 1.3.7 app amazon

i develop a grails 1.3.7 and i now trying to deploy it on amazon cloud. i follow the steps explained on http://www.inoneo.com/en/blog/5/amazon-aws/deploy-a-grails-application-on-aws-elastic-beanstalk. amazon instance tomcat version is 7. I am able to connect using mysql native to amazon database. my production environment configuration is:
production {
dataSource {
user = "{userDB}"
password = "{passDB}"
pooled = true
dbCreate = "create"
driverClassName = "com.mysql.jdbc.Driver"
url = "jdbc:mysql://{endPointRSD}:3306/{databaseName}?user={userDB}&password={passDB}"
dialect = org.hibernate.dialect.MySQL5InnoDBDialect
properties {
validationQuery = "SELECT 1"
testOnBorrow = true
testOnReturn = true
testWhileIdle = true
timeBetweenEvictionRunsMillis = 1800000
numTestsPerEvictionRun = 3
minEvictableIdleTimeMillis = 1800000
}
}
}
However i get several errors. Seems to me i having troubles with transactional issues. But how can it happen when my app run just fine in development? Thanks
here goes the error
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#3': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'claseDemandaService': Cannot create inner bean '(inner bean)' while setting bean property 'target'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#3': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'usuarioService': Cannot resolve reference to bean 'transactionManager' while setting bean property 'transactionManager'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'transactionManager' is defined
... 3 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'claseDemandaService': Cannot create inner bean '(inner bean)' while setting bean property 'target'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#3': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'usuarioService': Cannot resolve reference to bean 'transactionManager' while setting bean property 'transactionManager'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'transactionManager' is defined
... 3 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#3': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'usuarioService': Cannot resolve reference to bean 'transactionManager' while setting bean property 'transactionManager'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'transactionManager' is defined
... 3 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'usuarioService': Cannot resolve reference to bean 'transactionManager' while setting bean property 'transactionManager'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'transactionManager' is defined
... 3 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'transactionManager' is defined
... 3 more
2014-09-13 13:51:42,393 [http-bio-8080-exec-5] ERROR errors.GrailsExceptionResolver - Exception occurred when processing request: [GET] /principal/encabezado

ClassCastException user object hierarchy in Grails using SpringSecurityCore Plugin

I´ve got some weird behaviour using Grails 2.2.4, SpringSecurityCore 2.0 RC in Production on a Tomcat 7 with Groovy Compiler 2.0.8, Java 1.7.0.
We build a plugin which realize basic behaviors. We included the SpringSecurityCore plugin in it with a person class named User. There are some domain classes in the basic plugin which got User fields.
Then we build an application which include our basic plugin. The application got a special application person class called RUser which extend from User. RUser is set to SpringSecurityCore as person class.
Problem:
The application runs about 1 to 3 days without errors, but then ClassCastExceptions are thrown trying to set a RUser object on a User field of a plugin domain class.
User classes:
Plugin User class:
class User implements Serializable {
transient springSecurityService
String username
String password
...
}
Application User class:
class RUser extends User implements Serializable{
Cart cart
boolean businessUser = false
boolean taxIncluded = false
...
}
Application Config.groovy:
grails.plugin.springsecurity.userLookup.userDomainClassName = 'RUser'
Participated classes of our basic plugin:
class UserRole implements Serializable {
User user
Role role
static UserRole create(User user, Role role, boolean flush = false) {
new UserRole(user: user, role: role).save(flush: flush, insert: true)
}
...
}
class UserHistory implements Serializable{
User user
List historyEntries
static hasMany = [historyEntries:HistoryEntry]
...
}
The errors occur in this example situations:
In a Filter:
54: UserHistory.withTransaction{
def currentUser =springSecurityService.currentUser
def history = UserHistory.findByUser(currentUser)
if(!history){
96: history = new UserHistory(user:user).save(flush:true)
}
}
2014-05-23 13:52:17,279 ERROR errors.GrailsExceptionResolver| IllegalArgumentException occurred when processing request: [GET] /index
java.lang.ClassCastException#7ff92284. Stacktrace follows:
java.lang.reflect.UndeclaredThrowableException
at org.grails.datastore.gorm.GormStaticApi.withTransaction(GormStaticApi.groovy:687)
at de.neomatt.history.HistoryFilters$_closure1_closure2_closure4.doCall(HistoryFilters.groovy:54)
at grails.plugin.cache.web.filter.PageFragmentCachingFilter.doFilter(PageFragmentCachingFilter.java:195)
at grails.plugin.cache.web.filter.AbstractFilter.doFilter(AbstractFilter.java:63)
at grails.plugin.springsecurity.web.filter.GrailsAnonymousAuthenticationFilter.doFilter(GrailsAnonymousAuthenticationFilter.java:53)
at grails.plugin.springsecurity.web.authentication.RequestHolderAuthenticationFilter.doFilter(RequestHolderAuthenticationFilter.java:49)
at grails.plugin.springsecurity.web.authentication.logout.MutableLogoutFilter.doFilter(MutableLogoutFilter.java:82)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
Caused by: java.lang.reflect.InvocationTargetException
at de.neomatt.history.HistoryFilters$_closure1_closure2_closure4_closure5.doCall(HistoryFilters.groovy:96)
... 10 more
Caused by: org.springframework.beans.MethodInvocationException: Property 'springSecurityService' threw exception; nested exception is java.lang.IllegalArgumentException: java.lang.ClassCastException#7ff92284
at java.lang.Class.newInstance0(Class.java:372)
at java.lang.Class.newInstance(Class.java:325)
... 11 more
Caused by: java.lang.IllegalArgumentException: java.lang.ClassCastException#7ff92284
... 13 more
2014-05-23 13:52:17,288 ERROR errors.GrailsExceptionResolver| IllegalArgumentException occurred when processing request: [GET] /reservation_demo/ToolsOne
Method name must not be null. Stacktrace follows:
java.lang.IllegalArgumentException: Method name must not be null
at grails.plugin.cache.web.ProxyAwareMixedGrailsControllerHelper.retrieveAction(ProxyAwareMixedGrailsControllerHelper.java:41)
at grails.plugin.cache.web.filter.PageFragmentCachingFilter.doFilter(PageFragmentCachingFilter.java:195)
at grails.plugin.cache.web.filter.AbstractFilter.doFilter(AbstractFilter.java:63)
at grails.plugin.cache.web.filter.PageFragmentCachingFilter.doFilter(PageFragmentCachingFilter.java:195)
at grails.plugin.cache.web.filter.AbstractFilter.doFilter(AbstractFilter.java:63)
at grails.plugin.springsecurity.web.filter.GrailsAnonymousAuthenticationFilter.doFilter(GrailsAnonymousAuthenticationFilter.java:53)
at grails.plugin.springsecurity.web.authentication.RequestHolderAuthenticationFilter.doFilter(RequestHolderAuthenticationFilter.java:49)
at grails.plugin.springsecurity.web.authentication.logout.MutableLogoutFilter.doFilter(MutableLogoutFilter.java:82)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
In a Controller:
RegistrationCode.withTransaction {
def user = lookupUserClass().findByUsername(registrationCode.username)
def role = Role.findByAuthority(roleName)
281: UserRole.create user, role
}
2014-05-26 13:02:24,780 ERROR errors.GrailsExceptionResolver| IllegalArgumentException occurred when processing request: [GET] /app/register/verifyRegistration
java.lang.ClassCastException#a7c83d. Stacktrace follows:
java.lang.IllegalArgumentException: java.lang.ClassCastException#a7c83d
at java.lang.Class.newInstance0(Class.java:372)
at java.lang.Class.newInstance(Class.java:325)
at de.neomatt.security.UserRole.create(UserRole.groovy:32)
at de.neomatt.security.RegisterController$_closure4_closure14.doCall(RegisterController.groovy:281)
at org.grails.datastore.gorm.GormStaticApi.withTransaction(GormStaticApi.groovy:687)
at de.neomatt.security.RegisterController$_closure4.doCall(RegisterController.groovy:271)
at grails.plugin.cache.web.filter.PageFragmentCachingFilter.doFilter(PageFragmentCachingFilter.java:195)
at grails.plugin.cache.web.filter.AbstractFilter.doFilter(AbstractFilter.java:63)
at grails.plugin.springsecurity.web.filter.GrailsAnonymousAuthenticationFilter.doFilter(GrailsAnonymousAuthenticationFilter.java:53)
at grails.plugin.springsecurity.web.authentication.RequestHolderAuthenticationFilter.doFilter(RequestHolderAuthenticationFilter.java:49)
at grails.plugin.springsecurity.web.authentication.logout.MutableLogoutFilter.doFilter(MutableLogoutFilter.java:82)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
The ClassCastExceptions occurs everywhere, where an object with type RUser is setted on a User field. The RUser object is retrieved from springSecurityService.currentUser or with the lookupUserClass().findBy(...) method.
protected Class<?> lookupUserClass() {
grailsApplication.getDomainClass(lookupUserClassName()).clazz
}
As mentioned before, the application runs without errors for a undefined period of time in a production environment (no reloading, no config changes). A new deployment of the same war solves the problem for the next few hours/days.
Any suggestions?
#neomatt

Resources