Spring Security connecting authentification with a database - spring

I'm new to spring security with tomcat, i've beeing following a video, and i did everything there but when i try to login i get a HTTP 500 Error:
with the exception: javax.servlet.ServletException: Filter execution threw an exception
and root cause : java.lang.NoClassDefFoundError: Could not initialize class org.springframework.jdbc.core.StatementCreatorUtils
Here is my spring-config file:
<authentication-manager>
<authentication-provider user-service-ref="userDetailsService" />
</authentication-manager>
<beans:bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
<beans:property name="url" value="jdbc:mysql://localhost:3306/formation" />
<beans:property name="username" value="root" />
<beans:property name="password" value="" />
</beans:bean>
<beans:bean id="userDetailsService" class="org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl">
<beans:property name="dataSource" ref="dataSource"/>
</beans:bean>
and the pom:
.
.
.
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>3.2.6.RELEASE</version>
</dependency>
.
.
.
the error says NoClassDefFoundError but i don't know about what class is he talking about?
what am i doing wrong here?

Related

Springboot 2.2.1RELEASE -required a bean of type 'org.springframework.jdbc.core.jdbctemplate'

Currently am working on Spring boot version 2.1.7.Now i moved to Spring boot version 2.2.1 RELEASE. when i run my jar file its failed and its showing an error like
required a bean of type 'org.springframework.jdbc.core.jdbctemplate'
pom.xml
<dependencies>
<!-- Spring boot framework -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot</artifactId>
</dependency>
</dependencies>
Java Class file
#Component
public class StoredProcedureExecutor
{
#Autowired
JdbcTemplate jdbc;
}
module-context.xml
<bean id="dataSource" class="org.apache.tomcat.jdbc.pool.DataSource"
depends-on="dalConfiguration" destroy-method="close">
<property name="driverClassName" value="#{dalConfiguration.driverClassName}" />
<property name="url" value="#{dalConfiguration.url}" />
<property name="username" value="#{dalConfiguration.username}" />
<property name="password" value="#{dalConfiguration.password}" />
<property name="initialSize" value="#{dalConfiguration.poolInitialSize}" />
<property name="maxIdle" value="#{dalConfiguration.poolMaxIdle}" />
<property name="maxActive" value="#{dalConfiguration.poolMaxActive}" />
<property name="timeBetweenEvictionRunsMillis" value="1800" />
<property name="minEvictableIdleTimeMillis" value="1800" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
I have tried below solutions.
Added spring-boot-starter-jdbc dependencies in pom.xml file.
Remove .m2\repository\org\springframework\spring-jdbc and update project
But still getting the same error.Is there any spring boot version issue?

Spring 4 Hikari Connection Pool ClassCastException

I wish to use Hikari Connection Pool in my Spring 4 application. The database is Google Cloud SQL Postgres database.
I have the following dependency in pom.xml:
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.1.1</version>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>3.3.1</version>
</dependency>
In my applicationContext.xml, I have:
<bean id="hikariConfig" class="com.zaxxer.hikari.HikariConfig">
<property name="poolName" value="springHikariCP" />
<property name="connectionTestQuery" value="SELECT 1" />
<property name="dataSourceClassName" value="org.postgresql.Driver" />
<property name="maximumPoolSize" value="10" />
<property name="idleTimeout" value="30000" />
<property name="dataSourceProperties">
<props>
<prop key="url">jdbc:postgresql://google/mydatabase?cloudSqlInstance=projectId:regionName:myInstance&socketFactory=com.google.cloud.sql.postgres.SocketFactory</prop>
<prop key="user">postgres</prop>
<prop key="password">mypassword</prop>
</props>
</property>
</bean>
<bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
<constructor-arg ref="hikariConfig" />
</bean>
But I'm getting the following exception:
Caused by: java.lang.ClassCastException: Cannot cast org.postgresql.Driver to javax.sql.DataSource
at java.lang.Class.cast(Class.java:3369)
at com.zaxxer.hikari.util.UtilityElf.createInstance(UtilityElf.java:102)
What could be going wrong?
The org.postgresql.jdbc.Driver is not a javax.sql.DataSource, it is a java.sql.Driver, so it doesn't work for the property dataSourceClassName as that property expects a javax.sql.DataSource class name.
If you want to use the driver (and not a DataSource), then you should use the property driverClassName.
So:
<bean id="hikariConfig" class="com.zaxxer.hikari.HikariConfig">
<property name="poolName" value="springHikariCP" />
<property name="connectionTestQuery" value="SELECT 1" />
<property name="driverClassName" value="org.postgresql.Driver" />
...
Use Hikari recommended datasource for PostgreSQL: org.postgresql.ds.PGSimpleDataSource
<property name="dataSourceClassName" value="org.postgresql.ds.PGSimpleDataSource" />
Database Driver DataSource class
PostgreSQL pgjdbc-ng com.impossibl.postgres.jdbc.PGDataSource
PostgreSQL PostgreSQL org.postgresql.ds.PGSimpleDataSource

spring-cloud load datasource bean earlier than parse property placeHolder

After I import spring-cloud-context jar into my spring-boot2 project, it failed to parse property placeHolder in my datasource bean "org.apache.tomcat.jdbc.pool.DataSource" config. But the same property placeHolder in other bean config is parsed successfully.
Other datasource bean like "com.alibaba.druid.pool.DruidDataSource" also has the same problem. Which configuration class in spring-cloud-context cause the spring load datasource bean so eagerly?
spring config:
<bean id="dataSourceTarget" class="org.apache.tomcat.jdbc.pool.DataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="${mysql.url}" />
<property name="username" value="${mysql.username}" />
<property name="password" value="${mysql.password}" />
<property name="testWhileIdle" value="true" />
<property name="testOnBorrow" value="true" />
<property name="testOnReturn" value="false" />
<property name="validationInterval" value="60000" />
<property name="validationQuery" value="select 1 from dual" />
<property name="maxActive" value="100" />
<property name="minIdle" value="1" />
</bean>
<bean id="configTest1" class="wzp.rest.service.ConfigTest"
primary="true">
<property name="password" value="${mysql.password}" />
</bean>
pom.xml:
<!-- feign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
<version>1.4.4.RELEASE</version>
<exclusions>
<exclusion>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-archaius</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-netflix-archaius</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-netflix-ribbon</artifactId>
</exclusion>
<exclusion>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-hystrix</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId>
</dependency>
I used MapperFactoryBean of mybatis to load mapper, and MapperFactoryBean load sqlSessionFactory and datasource bean earlier than PropertySourcesPlaceholderConfigurer changing the placeholder.
When I use org.mybatis.spring.mapper.MapperScannerConfigurer to load mapper, the problem gone.
#ConditionalOnMissingBean makes all factory beans and their dependent beans initialed early, and their getObjectType function called before placeholders in their definition was parsed. Then spring cloud config client in spring-cloud-context jar makes normal PropertySourcesPlaceholderConfigurer can not parse and update placeholders of these beans. This behavior can be forbade by setting for whom do not use cloud config:
spring.cloud.config.enabled=false
spring.cloud.refresh.enabled=false

No qualifying bean of type 'java.lang.Class<org.springframework.data.repository.Repository<?, ?>>' available

I use spring data jpa (using CrudRepository interface) in my project and have declared my repository interface like this :
/**
* Repository implementation {#link CrudRepository} for {#link Client} entity
* #author rsone.
*/
public interface ClientRepository extends CrudRepository<Client, Integer> {
}
And have my hibernate config like bellow :
<tx:annotation-driven transaction-manager="hibernateTransactionManager" />
<context:component-scan base-package="com.rsone.mga.*" />
<jpa:repositories base-package="com.rsone.mga.repository" entity-manager-factory-ref="entityManagerFactory" transaction-manager-ref="hibernateTransactionManager"/>
<bean id="datasource" parent="abstractDataSource">
<property name="dataSourceName" value="mgaDS" />
<property name="driverClass" value="${database.mga.jdbc.driver}" />
<property name="jdbcUrl" value="${database.mga.jdbc.url}" />
<property name="user" value="${database.mga.jdbc.user}" />
<property name="password" value="${database.mga.jdbc.pass}" />
<property name="preferredTestQuery" value="SELECT 1 FROM DUAL" />
</bean> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
<property name="fetchSize" value="5000" />
<property name="cacheQueries" value="true" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="datasource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
</props>
</property>
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="datasource"/>
<property name="jpaVendorAdapter" ref="jpaVendorAdapter"/>
<!-- spring based scanning for entity classes>-->
<property name="packagesToScan" value="com.scor.mga.db"/>
</bean>
<!-- Enables the Hibernate #Transactional programming model -->
<tx:annotation-driven transaction-manager="hibernateTransactionManager" />
<bean id="hibernateTransactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"/>
<!--<property name="generateDdl" value="true"/>-->
<property name="database" value="SQL_SERVER"/>
</bean>
But When I try to run my project it give me that error (knowing that the base package of my repositories is com.rsone.mga.repository) :
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.lang.Class<org.springframework.data.repository.Repository<?, ?>>' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1466)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1097)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1059)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:835)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741)
Edit
I use version 1.11.0.RELEASE of spring-data-jpa:
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.11.0.RELEASE</version>
</dependency>
I had the same problem in my maven project.
So this below is not working
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.1.RELEASE</version>
</parent>
together with
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-cassandra</artifactId>
<version>1.5.4.RELEASE</version>
</dependency>
Solution
It was solved by updating to the newest Spring boot release :
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.1.RELEASE</version>
</parent>
Doing this already solved the problem.
It looks like the spring data tags are not backwards compatible with previous versions (other than the managed version).
So I would also recommend removing the version tag from the spring-data-cassandra dependency. Apparently Spring boot 1.5.1.RELEASE manages spring-data-cassandra 1.5.0.RELEASE.
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-cassandra</artifactId>
</dependency>
It doesn't seem to be an error in your configuration files.
It look like you have an #Autowired on a field of type java.lang.Class<org.springframework.data.repository.Repository<?, ?>> in one of the beans that are scanned.

My Spring application leaks database connections whereas I use the default Roo configuration

I am encountering an serious issue with my application. It leaks database connections whereas I use the default Spring Roo datasource configuration as follows:
<bean class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" id="dataSource">
<property name="driverClassName" value="${database.driverClassName}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.username}" />
<property name="password" value="${database.password}" />
<property name="testOnBorrow" value="true" />
<property name="testOnReturn" value="true" />
<property name="testWhileIdle" value="true" />
<property name="timeBetweenEvictionRunsMillis" value="1800000" />
<property name="numTestsPerEvictionRun" value="3" />
<property name="minEvictableIdleTimeMillis" value="1800000" />
<property name="validationQuery" value="SELECT 1" />
<property name="maxActive" value="2"/>
<property name="logAbandoned" value="true"/>
<property name="removeAbandoned" value="true"/>
</bean>
Here is the controller method that causes the leak:
#RequestMapping(value = "getMessages", method = RequestMethod.GET, produces = "application/json")
#ResponseBody
public DeferredResult<List<Message>> getMessages(#RequestParam final Long senderId) {
// TODO: check that recipientId was not changed by malicious user!!
final Long recipientId = memberService.retrieveCurrentMember().getId();
final String messageRequestKey = new StringBuilder().append(senderId).append(":").append(recipientId).toString();
final DeferredResult<List<Message>> deferredResult = new DeferredResult<List<Message>>(null, Collections.emptyList());
messageRequests.put(messageRequestKey, deferredResult);
deferredResult.onCompletion(new Runnable() {
#Override
public void run() {
messageRequests.remove(messageRequestKey);
}
});
List<Message> unReadMessages = messageService.findUnreadMessages(senderId, recipientId);
if (!unReadMessages.isEmpty()) {
deferredResult.setResult(unReadMessages);
}
return deferredResult;
}
It appears that connections are not returned to the pool by the above method (which is polled continuously by ajax).
Can anyone please help?
EDIT:
Hibernate config:
<persistence-unit name="persistenceUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>
<!-- value="create" to build a new database on each run; value="update" to modify an existing database; value="create-drop" means the same as "create" but also drops tables when Hibernate closes; value="validate" makes no changes to the database -->
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.ImprovedNamingStrategy"/>
<property name="hibernate.connection.charSet" value="UTF-8"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hibernate.use_sql_comments" value="true"/>
<property name="hibernate.connection.release_mode" value="after_transaction"/>
</properties>
</persistence-unit>
Hibernate version:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.1.8.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.1.8.Final</version>
<exclusions>
<exclusion>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
</exclusion>
<exclusion>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
I'm not sure if you are using hibernate? If so take a look at the setting hibernate.connection.release_mode . We had this issue and putting it to after_transaction solved all our connection issues.
EDIT
Our config:
<beans:bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<beans:property name="dataSource" ref="mvcDatasource" />
<beans:property name="persistenceUnitName" value="mvcPersistenceUnit" />
<beans:property name="persistenceProvider">
<beans:bean class="org.hibernate.ejb.HibernatePersistence" />
</beans:property>
<!-- Fix Hibernate not properly connected with spring -->
<beans:property name="jpaVendorAdapter">
<beans:bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</beans:property>
<beans:property name="jpaPropertyMap">
<beans:map>
<!-- Connection release fix -->
<beans:entry key="hibernate.connection.release_mode" value="after_transaction" />
<beans:entry key="hibernate.dialect" value="${hibernate.dialect}" />
...
</beans:map>
</beans:property>
</beans:bean>

Resources