406 Not Acceptable: Spring MVC + JSON - json

I know this question has been asked many times, although I tried what has been said but I still have this issue.
I'm trying to generate a simple JSON response working. Right now I get 406 Not Acceptable error. Tomcat says "The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers."
In tomcat/lib I have jackson jars. I'm using Spring 1.1.0 with Tomcat 7.
I addedd the dependencies in the pom.xml:
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.4.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.1.1</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
</dependencies>
CompaniesRestController.java
#RequestMapping(value = "/Companies", method = RequestMethod.GET)
#ResponseBody
public List<Companies> listCompaniess() {
return new java.util.ArrayList<Companies>(companiesService.loadCompaniess());
}
I added this code snippet in my applicationContext.xml, as described in the : reference:
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<util:list id="beanList">
<ref bean="stringHttpMessageConverter"/>
<ref bean="marshallingHttpMessageConverter"/>
</util:list>
</property
</bean>
<bean id="stringHttpMessageConverter"
class="org.springframework.http.converter.StringHttpMessageConverter"/>
<bean id="marshallingHttpMessageConverter"
class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
<property name="marshaller" ref="castorMarshaller" />
<property name="unmarshaller" ref="castorMarshaller" />
</bean>
But in vain, none of all that worked.
I'd be thankfull for your suggestions.
PS: I used scaffolding to generate my CRUD application.
-Regards
Actually, when I edit my
CompaniesRestController.java
#RequestMapping(value = "/Companies", method = RequestMethod.GET)
#ResponseBody
public String<Companies> listCompaniess() {
return new java.util.ArrayList<Companies>(companiesService.loadCompaniess()).toString();
}
or
#RequestMapping(value = "/Companies", method = RequestMethod.GET,produces="application/json")
public #ResponseBody Object[] listCompaniess() {
return new java.util.ArrayList<Companies>(companiesService.loadCompaniess()).toArray();
}
I no longer have the 406error, I get an array containing the records I have in my database, but as an array, not a json...
I've tried to make use if JSONObject, but still have the same issue, I used scaffolding to create my spring mvc application, and then I convert it to a Maven project so as to add jackson libraries and dependencies, but when I cenvert it, all the project collapses and throws the following errors:
2015-07-15 17:32:31,299 INFO [localhost-startStop-1] LobCreatorBuilder - HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
2015-07-15 17:32:31,314 WARN [localhost-startStop-1] JtaPlatformInitiator - HHH000427: Using deprecated org.hibernate.transaction.TransactionManagerLookup strategy [hibernate.transaction.manager_lookup_class], use newer org.hibernate.service.jta.platform.spi.JtaPlatform strategy instead [hibernate.transaction.jta.platform]
2015-07-15 17:32:31,314 INFO [localhost-startStop-1] JtaPlatformInitiator - HHH000428: Encountered legacy TransactionManagerLookup specified; convert to newer org.hibernate.service.jta.platform.spi.JtaPlatform contract specified via hibernate.transaction.jta.platform setting
2015-07-15 17:32:31,314 INFO [localhost-startStop-1] ASTQueryTranslatorFactory - HHH000397: Using ASTQueryTranslatorFactory
2015-07-15 17:32:31,361 INFO [localhost-startStop-1] Version - Hibernate Validator 4.2.0.Final
2015-07-15 17:32:31,642 INFO [localhost-startStop-1] TransactionFactoryInitiator - HHH000268: Transaction strategy: org.hibernate.engine.transaction.internal.jta.CMTTransactionFactory
No properties path set - looking for transactions.properties in classpath...
transactions.properties not found - looking for jta.properties in classpath...
Using init file: /D:/Users/ielhazit/Workspaces/MyEclipse%202015%20CI/.metadata/.me_tcat7/webapps/chouette/WEB-INF/classes/jta.properties
juil. 15, 2015 5:32:32 PM org.apache.catalina.core.ApplicationContext log
Infos: Initializing Spring FrameworkServlet 'chouette Servlet'
2015-07-15 17:32:32,471 ERROR [localhost-startStop-1] FrameworkServlet - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean#0': Invocation of init method failed; nested exception is java.lang.AbstractMethodError: org.hibernate.validator.engine.ConfigurationImpl.getDefaultParameterNameProvider()Ljavax/validation/ParameterNameProvider;
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1568)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:540)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:229)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:725)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:658)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:624)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:672)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:543)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:484)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1284)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1197)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1087)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5231)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5518)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:649)
at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1247)
at org.apache.catalina.startup.HostConfig$DeployDirectory.run(HostConfig.java:1897)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
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:744)
Caused by: java.lang.AbstractMethodError: org.hibernate.validator.engine.ConfigurationImpl.getDefaultParameterNameProvider()Ljavax/validation/ParameterNameProvider;
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:209)
at org.springframework.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:194)
at org.springframework.validation.beanvalidation.LocalValidatorFactoryBean.configureParameterNameProviderIfPossible(LocalValidatorFactoryBean.java:276)
at org.springframework.validation.beanvalidation.LocalValidatorFactoryBean.afterPropertiesSet(LocalValidatorFactoryBean.java:245)
at org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean.afterPropertiesSet(OptionalValidatorFactoryBean.java:40)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1627)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1564)
... 32 more
Any ideas
Thank you

The producible media types of the mapped request can also be configured by Spring's #RequestMapping.
Example : #RequestMapping(value = "/list", method = RequestMethod.GET, produces = "application/json")

Related

Tomcat 9.0.12 and mySQL (8.0.12) with springBoot (I guess)

I know the problem looks pretty old, but I shall apreciate any suggestion.
Because a hosting server accept only Tomcat 8, I changed a project which worked fine with Tomee Plume: made also some changes to Tomcat 8.5 (put some jar, e.g. catalina-ws, jaxrpc-1.4.0, wsdl4j.wso2-1.6.3.wso2v3),
Now, apparently weird, no project and neither Tocat 9 run with mySQL.
The pom file:
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<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</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.12</version>
<scope>provided</scope>
</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-logging</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.postgresql/postgresql -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.9</version>
</dependency>
</dependencies>
#SpringBootApplication(exclude = { SecurityAutoConfiguration.class })
#EnableJpaAuditing
#EntityScan(basePackages = "ro.prj.mysqlsboot.model")
#EnableJpaRepositories(basePackages = "ro.prj.mysqlsboot.model")
#ComponentScan(basePackages = "ro.prj.mysqlsboot.controller")
public class MysqlSbootApplication {
public static void main(String[] args) throws IOException {
SpringApplication.run(MysqlSbootApplication.class, args);
}
}
#Repository
#Component
public interface CondRepository extends JpaRepository<Cond, Integer>{
}
#Service
#RestController
#EntityScan(basePackages = "ro.rodit.mysqlsboot.model")
public class Controller {
#Autowired
CondRepository condRepo;
#GetMapping({"/login", ""})
public String getView() {
return "index";
}
#GetMapping("/gd")
#ResponseBody
public ModelAndView getId(#RequestParam Integer id) {
ModelAndView mv = new ModelAndView("index");
Cond cd = condRepo.findById(id).orElse(new Cond());
mv.addObject(cd);
return mv;
}
}
The Entity class:
#Entity
public class Cond {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#NotFound(action = NotFoundAction.IGNORE)
private Integer id;
//the other parameters, incl. getter & setters ...
}
Some tomcat message:
13-Jan-2020 12:09:08.045 INFO [ContainerBackgroundProcessor[StandardEngine[Catalina]]] jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke Deployment of deployment descriptor [C:\TomeePlume\apache-tomee-plume-7.0.0-M1\conf\Catalina\localhost\mavenMobils.xml] has finished in [8,748] ms
Hibernate:
select
cond0_.id as id1_0_0_,
cond0_.ecran as ecran2_0_0_,
cond0_.fcorectie_aer_liber as fcorecti3_0_0_,
cond0_.fcorectie_f1 as fcorecti4_0_0_,
cond0_.fcorectie_f2 as fcorecti5_0_0_,
cond0_.gradul_de_incarcare as gradul_d6_0_0_,
cond0_.i_adm as i_adm7_0_0_,
cond0_.i_adm_efg as i_adm_ef8_0_0_,
cond0_.izolatie as izolatie9_0_0_,
cond0_.k1 as k10_0_0_,
cond0_.k2 as k11_0_0_,
cond0_.manta as manta12_0_0_,
cond0_.material_cu_al as materia13_0_0_,
cond0_.mod_pozare55 as mod_poz14_0_0_,
cond0_.nr_cond_incarcate as nr_cond15_0_0_,
cond0_.rezist_termica_sol as rezist_16_0_0_,
cond0_.sectiunen as sectiun17_0_0_,
cond0_.temp_ambianta_de_referinta as temp_am18_0_0_,
cond0_.temp_funct_adm as temp_fu19_0_0_,
cond0_.temp_solului as temp_so20_0_0_,
cond0_.tensiune as tensiun21_0_0_
from
cond cond0_
where
cond0_.id=?
2020-01-13 12:09:16.153 TRACE 4064 --- [io-8080-exec-47] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [INTEGER] - [11]
13-Jan-2020 12:09:18.052 INFO [ContainerBackgroundProcessor[StandardEngine[Catalina]]] jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke Deploying deployment descriptor [C:\TomeePlume\apache-tomee-plume-7.0.0-M1\conf\Catalina\localhost\account.xml]
13-Jan-2020 12:09:18.053 WARNING [ContainerBackgroundProcessor[StandardEngine[Catalina]]] jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke The path attribute with value [/account] in deployment descriptor [C:\TomeePlume\apache-tomee-plume-7.0.0-M1\conf\Catalina\localhost\account.xml] has been ignored
13-Jan-2020 12:09:18.054 INFO [ContainerBackgroundProcessor[StandardEngine[Catalina]]] org.apache.tomee.catalina.TomcatWebAppBuilder.init ------------------------- localhost -> /account
13-Jan-2020 12:09:18.197 SEVERE [ContainerBackgroundProcessor[StandardEngine[Catalina]]] jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke Creation of the naming context failed: [javax.naming.OperationNotSupportedException: Context is read only]
13-Jan-2020 12:09:18.568 INFO [ContainerBackgroundProcessor[StandardEngine[Catalina]]] org.apache.openejb.config.ConfigurationFactory.configureApplication Configuring enterprise application: D:\NBean\Projects\Spring\gihub\registration-login-spring-xml-maven-jsp-mysql-master\registration-login-spring-xml-maven-jsp-mysql-master\target\account-1.0-SNAPSHOT
13-Jan-2020 12:09:18.738 INFO [ContainerBackgroundProcessor[StandardEngine[Catalina]]] org.apache.openejb.config.ConfigurationFactory.configureService Configuring Service(id=account-1.0-SNAPSHOT/jdbc/TestDB, type=Resource, provider-id=ProvidedByTomcat)
13-Jan-2020 12:09:18.740 INFO [ContainerBackgroundProcessor[StandardEngine[Catalina]]] org.apache.openejb.config.ConfigurationFactory.configureService Configuring Service(id=account-1.0-SNAPSHOT/jdbc/pol, type=Resource, provider-id=ProvidedByTomcat)
13-Jan-2020 12:09:18.740 INFO [ContainerBackgroundProcessor[StandardEngine[Catalina]]] org.apache.openejb.assembler.classic.Assembler.createRecipe Creating Resource(id=account-1.0-SNAPSHOT/jdbc/TestDB)
13-Jan-2020 12:09:18.745 INFO [ContainerBackgroundProcessor[StandardEngine[Catalina]]] org.apache.openejb.assembler.classic.Assembler.createRecipe Creating Resource(id=account-1.0-SNAPSHOT/jdbc/pol)
13-Jan-2020 12:09:18.748 INFO [ContainerBackgroundProcessor[StandardEngine[Catalina]]] org.apache.openejb.config.AutoConfig.processResourceRef Auto-linking resource-ref 'openejb/Resource/account-1.0-SNAPSHOT/jdbc/TestDB' in bean account.Comp380682656 to Resource(id=account-1.0-SNAPSHOT/jdbc/TestDB)
13-Jan-2020 12:09:18.748 INFO [ContainerBackgroundProcessor[StandardEngine[Catalina]]] org.apache.openejb.config.AutoConfig.processResourceRef Auto-linking resource-ref 'openejb/Resource/jdbc/TestDB' in bean account.Comp380682656 to Resource(id=account-1.0-SNAPSHOT/jdbc/TestDB)
13-Jan-2020 12:09:18.748 INFO [ContainerBackgroundProcessor[StandardEngine[Catalina]]] org.apache.openejb.config.AutoConfig.processResourceRef Auto-linking resource-ref 'openejb/Resource/account-1.0-SNAPSHOT/jdbc/pol' in bean account.Comp380682656 to Resource(id=account-1.0-SNAPSHOT/jdbc/pol)
13-Jan-2020 12:09:18.749 INFO [ContainerBackgroundProcessor[StandardEngine[Catalina]]] org.apache.openejb.config.AutoConfig.processResourceRef Auto-linking resource-ref 'openejb/Resource/jdbc/pol' in bean account.Comp380682656 to Resource(id=account-1.0-SNAPSHOT/jdbc/pol)
13-Jan-2020 12:09:18.782 INFO [ContainerBackgroundProcessor[StandardEngine[Catalina]]] org.apache.openejb.config.AppInfoBuilder.build Enterprise application "D:\NBean\Projects\Spring\gihub\registration-login-spring-xml-maven-jsp-mysql-master\registration-login-spring-xml-maven-jsp-mysql-master\target\account-1.0-SNAPSHOT" loaded.
13-Jan-2020 12:09:18.783 INFO [ContainerBackgroundProcessor[StandardEngine[Catalina]]] org.apache.openejb.assembler.classic.Assembler.createApplication Assembling app: D:\NBean\Projects\Spring\gihub\registration-login-spring-xml-maven-jsp-mysql-master\registration-login-spring-xml-maven-jsp-mysql-master\target\account-1.0-SNAPSHOT
12:09:19.026 [ContainerBackgroundProcessor[StandardEngine[Catalina]]] DEBUG org.jboss.logging - Logging Provider: org.jboss.logging.Slf4jLoggerProvider
12:09:19.113 [ContainerBackgroundProcessor[StandardEngine[Catalina]]] INFO o.h.validator.internal.util.Version - HV000001: Hibernate Validator 5.2.1.Final
13-Jan-2020 12:09:19.115 INFO [ContainerBackgroundProcessor[StandardEngine[Catalina]]] org.apache.openejb.assembler.classic.Assembler.destroyApplication Undeploying app: D:\NBean\Projects\Spring\gihub\registration-login-spring-xml-maven-jsp-mysql-master\registration-login-spring-xml-maven-jsp-mysql-master\target\account-1.0-SNAPSHOT
13-Jan-2020 12:09:19.115 SEVERE [ContainerBackgroundProcessor[StandardEngine[Catalina]]] jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke ContainerBase.removeChild: destroy:
org.apache.catalina.LifecycleException: An invalid Lifecycle transition was attempted ([before_destroy]) for component
StandardEngine[Catalina].StandardHost[localhost].StandardContext[/account]] in state [STARTING_PREP]

Receiving a CommunicationsException using Spring Data JPA and mysql database

on a project i am importing data from an oracle database into a mysql database.
The import is working fine.
I user hibernate envers to track changes on a specific field of an entity.
However, if i try to request the stored data via a rest endpoint (controller -> service -> repository) i receive a exception.
If i call the endpoint on a daily basis, the application works fine. But if the the endpoint is not triggered e.g. over the weekend, then the application fails.
Following the dependencies i am using in the project:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.1.RELEASE</version>
<relativePath/>
</parent>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.oracle.jdbc</groupId>
<artifactId>ojdbc8</artifactId>
<version>${oracle.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-java8</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-envers</artifactId>
</dependency>
<dependency>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-core</artifactId>
</dependency>
The application properties for the mysql database connection:
spring:
datasource:
url: jdbc:mysql://servername:3306/schema
username: username
password: password
initialize-mode: never
jpa:
open-in-view: false
database-platform: org.hibernate.dialect.MySQL5Dialect
liquibase:
change-log: classpath:/db/changelog/changelog-master.xml
The configuration of the primary database, I am using the default hikari connection pool.
#SpringBootApplication
#EnableScheduling
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
#Bean
#Primary
#ConfigurationProperties("spring.datasource")
public DataSourceProperties primaryDataSourceProperties() {
return new DataSourceProperties();
}
#Bean
#Primary
public DataSource primaryDataSource() {
return primaryDataSourceProperties()
.initializeDataSourceBuilder()
.build();
}
#Bean
#Primary
public JdbcTemplate primaryJdbcTemplate() {
return new JdbcTemplate(primaryDataSource());
}
}
The following exception do i receive, if the application was not called over a longer period:
2018-09-17T11:50:11.639708697Z com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: The last packet successfully received from the server was 271,547,086 milliseconds ago. The last packet sent successfully to the server was 271,547,087 milliseconds ago. is longer than the server configured value of 'wait_timeout'. You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property 'autoReconnect=true' to avoid this problem.
2018-09-17T11:50:11.639718269Z at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_181]
2018-09-17T11:50:11.639724140Z at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_181]
2018-09-17T11:50:11.639729703Z at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_181]
2018-09-17T11:50:11.639735197Z at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_181]
2018-09-17T11:50:11.639740378Z at com.mysql.jdbc.Util.handleNewInstance(Util.java:425) ~[mysql-connector-java-5.1.46.jar!/:5.1.46]
2018-09-17T11:50:11.639745633Z at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:990) ~[mysql-connector-java-5.1.46.jar!/:5.1.46]
2018-09-17T11:50:11.639751054Z at com.mysql.jdbc.MysqlIO.send(MysqlIO.java:3749) ~[mysql-connector-java-5.1.46.jar!/:5.1.46]
2018-09-17T11:50:11.639756342Z at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2512) ~[mysql-connector-java-5.1.46.jar!/:5.1.46]
2018-09-17T11:50:11.639772891Z at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2683) ~[mysql-connector-java-5.1.46.jar!/:5.1.46]
2018-09-17T11:50:11.639778495Z at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2486) ~[mysql-connector-java-5.1.46.jar!/:5.1.46]
2018-09-17T11:50:11.639783448Z at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1858) ~[mysql-connector-java-5.1.46.jar!/:5.1.46]
2018-09-17T11:50:11.639789900Z at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1966) ~[mysql-connector-java-5.1.46.jar!/:5.1.46]
2018-09-17T11:50:11.639795247Z at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeQuery(ProxyPreparedStatement.java:52) ~[HikariCP-2.7.8.jar!/:na]
2018-09-17T11:50:11.639800145Z at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeQuery(HikariProxyPreparedStatement.java) [HikariCP-2.7.8.jar!/:na]
2018-09-17T11:50:11.639805182Z at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:60) [hibernate-core-5.2.16.Final.jar!/:5.2.16.Final]
2018-09-17T11:50:11.639810237Z at org.hibernate.loader.Loader.getResultSet(Loader.java:2168) [hibernate-core-5.2.16.Final.jar!/:5.2.16.Final]
2018-09-17T11:50:11.639815102Z at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1931) [hibernate-core-5.2.16.Final.jar!/:5.2.16.Final]
2018-09-17T11:50:11.639819990Z at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1893) [hibernate-core-5.2.16.Final.jar!/:5.2.16.Final]
2018-09-17T11:50:11.639824896Z at org.hibernate.loader.Loader.doQuery(Loader.java:938) [hibernate-core-5.2.16.Final.jar!/:5.2.16.Final]
2018-09-17T11:50:11.639829655Z at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:341) [hibernate-core-5.2.16.Final.jar!/:5.2.16.Final]
2018-09-17T11:50:11.639834611Z at org.hibernate.loader.Loader.doList(Loader.java:2692) [hibernate-core-5.2.16.Final.jar!/:5.2.16.Final]
2018-09-17T11:50:11.639839395Z at org.hibernate.loader.Loader.doList(Loader.java:2675) [hibernate-core-5.2.16.Final.jar!/:5.2.16.Final]
2018-09-17T11:50:11.639844167Z at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2507) [hibernate-core-5.2.16.Final.jar!/:5.2.16.Final]
2018-09-17T11:50:11.639849073Z at org.hibernate.loader.Loader.list(Loader.java:2502) [hibernate-core-5.2.16.Final.jar!/:5.2.16.Final]
2018-09-17T11:50:11.639853943Z at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:502) [hibernate-core-5.2.16.Final.jar!/:5.2.16.Final]
2018-09-17T11:50:11.639858773Z at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:392) [hibernate-core-5.2.16.Final.jar!/:5.2.16.Final]
2018-09-17T11:50:11.639863765Z at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:216) [hibernate-core-5.2.16.Final.jar!/:5.2.16.Final]
2018-09-17T11:50:11.639868646Z at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1489) [hibernate-core-5.2.16.Final.jar!/:5.2.16.Final]
2018-09-17T11:50:11.639874051Z at org.hibernate.query.internal.AbstractProducedQuery.doList(AbstractProducedQuery.java:1445) [hibernate-core-5.2.16.Final.jar!/:5.2.16.Final]
2018-09-17T11:50:11.639882957Z at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1414) [hibernate-core-5.2.16.Final.jar!/:5.2.16.Final]
2018-09-17T11:50:11.639888299Z at org.hibernate.query.internal.AbstractProducedQuery.uniqueResult(AbstractProducedQuery.java:1457) [hibernate-core-5.2.16.Final.jar!/:5.2.16.Final]
2018-09-17T11:50:11.639893354Z at org.hibernate.envers.internal.reader.AuditReaderImpl.getRevisionNumberForDate(AuditReaderImpl.java:195) [hibernate-envers-5.2.16.Final.jar!/:5.2.16.Final]
.....(common frames ommitted)
2018-09-17T11:50:11.640471778Z Caused by: java.net.SocketException: Broken pipe (Write failed)
2018-09-17T11:50:11.640476371Z at java.net.SocketOutputStream.socketWrite0(Native Method) ~[na:1.8.0_181]
2018-09-17T11:50:11.640481083Z at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:111) ~[na:1.8.0_181]
2018-09-17T11:50:11.640485818Z at java.net.SocketOutputStream.write(SocketOutputStream.java:155) ~[na:1.8.0_181]
2018-09-17T11:50:11.640490460Z at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:82) ~[na:1.8.0_181]
2018-09-17T11:50:11.640495069Z at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:140) ~[na:1.8.0_181]
2018-09-17T11:50:11.640499775Z at com.mysql.jdbc.MysqlIO.send(MysqlIO.java:3731) ~[mysql-connector-java-5.1.46.jar!/:5.1.46]
2018-09-17T11:50:11.640504540Z ... 124 common frames omitted
2018-09-17T11:50:11.640508983Z
2018-09-17T11:50:11.640513301Z 2018-09-17 11:50:11.639 WARN 1 --- [ XNIO-2 task-5] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 08S01
The next time i call the application rest endpoint i receive the following exception:
2018-09-17 12:01:59.571 WARN 1 --- [ XNIO-2 task-6] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: null
2018-09-17 12:01:59.571 ERROR 1 --- [ XNIO-2 task-6] o.h.engine.jdbc.spi.SqlExceptionHelper : Connection is closed
2018-09-17 12:01:59.577 ERROR 1 --- [ XNIO-2 task-6] io.undertow.request : UT005023: Exception handling request to /userdata/changed/1
2018-09-17T12:01:59.578946831Z
2018-09-17T12:01:59.578952545Z org.springframework.web.util.NestedServletException: Request processing failed; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: could not prepare statement
2018-09-17T12:01:59.579639175Z Caused by: java.sql.SQLException: Connection is closed
2018-09-17T12:01:59.579643612Z at com.zaxxer.hikari.pool.ProxyConnection$ClosedConnection.lambda$getClosedConnection$0(ProxyConnection.java:490) ~[HikariCP-2.7.8.jar!/:na]
2018-09-17T12:01:59.579648391Z at com.sun.proxy.$Proxy75.prepareStatement(Unknown Source) ~[na:na]
2018-09-17T12:01:59.579652972Z at com.zaxxer.hikari.pool.ProxyConnection.prepareStatement(ProxyConnection.java:318) ~[HikariCP-2.7.8.jar!/:na]
2018-09-17T12:01:59.579657687Z at com.zaxxer.hikari.pool.HikariProxyConnection.prepareStatement(HikariProxyConnection.java) ~[HikariCP-2.7.8.jar!/:na]
2018-09-17T12:01:59.579662500Z at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$5.doPrepare(StatementPreparerImpl.java:145) ~[hibernate-core-5.2.16.Final.jar!/:5.2.16.Final]
2018-09-17T12:01:59.579667400Z at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:171) ~[hibernate-core-5.2.16.Final.jar!/:5.2.16.Final]
2018-09-17T12:01:59.579672405Z ... 117 common frames omitted
Maybe someone has any idea, why the connection to the database gets invalid.
Here are the settings of the hikari
Driver class com.mysql.jdbc.Driver found in Thread context class loader sun.misc.Launcher$AppClassLoader#18b4aac2
HikariPool-1 - configuration:
allowPoolSuspension.............false
autoCommit......................true
catalog.........................none
connectionInitSql...............none
connectionTestQuery.............none
connectionTimeout...............30000
dataSource......................none
dataSourceClassName.............none
dataSourceJNDI..................none
dataSourceProperties............{password=<masked>}
driverClassName................."com.mysql.jdbc.Driver"
healthCheckProperties...........{}
healthCheckRegistry.............none
idleTimeout.....................600000
initializationFailFast..........true
initializationFailTimeout.......1
isolateInternalQueries..........false
jdbc4ConnectionTest.............false
jdbcUrl.........................jdbc:mysql://server:3306/schema
leakDetectionThreshold..........0
maxLifetime.....................1800000
maximumPoolSize.................10
metricRegistry..................none
metricsTrackerFactory...........none
minimumIdle.....................10
password........................<masked>
poolName........................"HikariPool-1"
readOnly........................false
registerMbeans..................false
scheduledExecutor...............none
scheduledExecutorService........internal
schema..........................none
threadFactory...................internal
transactionIsolation............default
username........................"user"
validationTimeout...............5000
i expected the issue at the wrong part of my application. I configured the envers AuditReader as spring bean and injected a entity manager. The entity manager holds a database connection that breaks when the database is closing the connection after the configured timeout.
#Configuration
#RequiredArgsConstructor
public class AuditConfiguration {
private final EntityManagerFactory entityManagerFactory;
#Bean
public AuditReader auditReader() {
return AuditReaderFactory.get(entityManagerFactory.createEntityManager());
}
}
So i removed this configuration and create a entity manager for every request to the audit reader.
#Component
#RequiredArgsConstructor
public class AuditService {
private final EntityManagerFactory entityManagerFactory;
public int getLatestRevision() {
return AuditReaderFactory.get(entityManagerFactory.createEntityManager())
.getRevisionNumberForDate(from(now()))
.intValue();
}
}
With this setup hikari is handling the database connections correct and the exception does not occur anymore.
Use jdbc url as below , while making connection:
url: jdbc:mysql://servername:3306/schema?autoReconnect=true

Error on running spring boot jar file (Error creating bean with name 'dataSource')

I built a Jar file with IntelliJ and I'm running it through cmd and it's throwing this error:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Failed to determine a suitable driver class
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:587)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1250)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1099)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:251)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1065)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:815)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:721)
... 27 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Failed to determine a suitable driver class
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:579)
... 40 common frames omitted
Caused by: org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Failed to determine a suitable driver class
at org.springframework.boot.autoconfigure.jdbc.DataSourceProperties.determineDriverClassName(DataSourceProperties.java:236)
at org.springframework.boot.autoconfigure.jdbc.DataSourceProperties.initializeDataSourceBuilder(DataSourceProperties.java:176)
at org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration.createDataSource(DataSourceConfiguration.java:43)
at org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration$Hikari.dataSource(DataSourceConfiguration.java:81)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.base/java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
... 41 common frames omitted
This is my pom:
<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.MyProject</groupId>
<artifactId>MyProject</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>MyProject</name>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
<relativePath/>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<start-class>com.MyProject</start-class>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-batch</artifactId>
</dependency>
<dependency>
<groupId>commons-cli</groupId>
<artifactId>commons-cli</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
My application.properties:
spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:mysql://localhost:3306/my_db
spring.datasource.username=dev
spring.datasource.password=dev
hibernate.jdbc.batch_size=50
spring.jpa.properties.hibernate.order_inserts=true
When I run the application inside IntelliJ it works fine, this error throws only after I built and run through cmd: < java -cp "myproject.jar" com.MyProject >
My main and entity classes are well annotated and the mysql server is up.
The build config from IntelliJ:
I looked into myproject.jar file and the mysql jar was nor loaded. How can I build my jar with mysql jar already included?
Try
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
The default scope for maven dependencies is compile, hence jar won't be available at runtime.

Feign with zookeeper succeeds with normal app but fails with JUnit

I use the zookeeper as the service register, and that's my problem: when I run it directly as a spring boot application it succeeds, instead when I use the junit to test it, it fails.
The pom dependencies as as below:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zookeeper-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--<dependency>-->
<!--<groupId>org.springframework.cloud</groupId>-->
<!--<artifactId>spring-cloud-starter-hystrix</artifactId>-->
<!--</dependency>-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Camden.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
The Feign Code is as below:
#Configuration
public class BeanConfig {
#Bean
#LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
}
#FeignClient(value = "walletbackstage")
public interface IWalletBackstageClient {
#RequestMapping(value = "/walletRate/getWalletRateByType/{type}", method = RequestMethod.GET)
ResponseResult getWalletRateType(#PathVariable(name = "type") Integer type);
}
The run code is as below:
#SpringBootApplication
#EnableDiscoveryClient
#EnableFeignClients
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
The junit code is as below:
#RunWith(SpringRunner.class)
#SpringBootTest
public class TestClientTest {
#Autowired
IWalletBackstageClient walletBackstageClient;
#Test
public void testFegin() {
Object walletRateType = walletBackstageClient.getWalletRateType(1);
System.out.println(walletRateType);
}
}
The Exception is the following:
2017-07-13 11:39:55.182 WARN 9976 --- [lletbackstage-1] s.c.a.AnnotationConfigApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dependenciesBasedLoadBalancer' defined in org.springframework.cloud.zookeeper.discovery.ZookeeperRibbonClientConfiguration: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.netflix.loadbalancer.ILoadBalancer]: Factory method 'dependenciesBasedLoadBalancer' threw exception; nested exception is java.lang.NullPointerException
com.netflix.hystrix.exception.HystrixRuntimeException: IWalletBackstageClient#getWalletRateType(Integer) failed and no fallback available.
at com.netflix.hystrix.AbstractCommand$22.call(AbstractCommand.java:805)
at com.netflix.hystrix.AbstractCommand$22.call(AbstractCommand.java:790)
at rx.internal.operators.OperatorOnErrorResumeNextViaFunction$4.onError(OperatorOnErrorResumeNextViaFunction.java:140)
at rx.internal.operators.OnSubscribeDoOnEach$DoOnEachSubscriber.onError(OnSubscribeDoOnEach.java:87)
at rx.internal.operators.OnSubscribeDoOnEach$DoOnEachSubscriber.onError(OnSubscribeDoOnEach.java:87)
at com.netflix.hystrix.AbstractCommand$DeprecatedOnFallbackHookApplication$1.onError(AbstractCommand.java:1470)
at com.netflix.hystrix.AbstractCommand$FallbackHookApplication$1.onError(AbstractCommand.java:1395)
at rx.internal.operators.OnSubscribeDoOnEach$DoOnEachSubscriber.onError(OnSubscribeDoOnEach.java:87)
at rx.observers.Subscribers$5.onError(Subscribers.java:230)
at rx.internal.operators.OnSubscribeThrow.call(OnSubscribeThrow.java:44)
at rx.internal.operators.OnSubscribeThrow.call(OnSubscribeThrow.java:28)
at rx.Observable.unsafeSubscribe(Observable.java:10211)
at rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:51)
at rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:35)
at rx.Observable.unsafeSubscribe(Observable.java:10211)
at rx.internal.operators.OnSubscribeDoOnEach.call(OnSubscribeDoOnEach.java:41)
at rx.internal.operators.OnSubscribeDoOnEach.call(OnSubscribeDoOnEach.java:30)
at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)
at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)
at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
at rx.Observable.unsafeSubscribe(Observable.java:10211)
at rx.internal.operators.OnSubscribeDoOnEach.call(OnSubscribeDoOnEach.java:41)
at rx.internal.operators.OnSubscribeDoOnEach.call(OnSubscribeDoOnEach.java:30)
at rx.Observable.unsafeSubscribe(Observable.java:10211)
at rx.internal.operators.OnSubscribeDoOnEach.call(OnSubscribeDoOnEach.java:41)
at rx.internal.operators.OnSubscribeDoOnEach.call(OnSubscribeDoOnEach.java:30)
at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)
at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
at rx.Observable.unsafeSubscribe(Observable.java:10211)
at rx.internal.operators.OnSubscribeDoOnEach.call(OnSubscribeDoOnEach.java:41)
at rx.internal.operators.OnSubscribeDoOnEach.call(OnSubscribeDoOnEach.java:30)
at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)
at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
at rx.Observable.unsafeSubscribe(Observable.java:10211)
at rx.internal.operators.OperatorOnErrorResumeNextViaFunction$4.onError(OperatorOnErrorResumeNextViaFunction.java:142)
at rx.internal.operators.OnSubscribeDoOnEach$DoOnEachSubscriber.onError(OnSubscribeDoOnEach.java:87)
at rx.internal.operators.OnSubscribeDoOnEach$DoOnEachSubscriber.onError(OnSubscribeDoOnEach.java:87)
at com.netflix.hystrix.AbstractCommand$HystrixObservableTimeoutOperator$3.onError(AbstractCommand.java:1173)
at rx.internal.operators.OperatorSubscribeOn$1$1.onError(OperatorSubscribeOn.java:59)
at rx.observers.Subscribers$5.onError(Subscribers.java:230)
at rx.internal.operators.OnSubscribeDoOnEach$DoOnEachSubscriber.onError(OnSubscribeDoOnEach.java:87)
at rx.observers.Subscribers$5.onError(Subscribers.java:230)
at com.netflix.hystrix.AbstractCommand$DeprecatedOnRunHookApplication$1.onError(AbstractCommand.java:1429)
at com.netflix.hystrix.AbstractCommand$ExecutionHookApplication$1.onError(AbstractCommand.java:1360)
at rx.observers.Subscribers$5.onError(Subscribers.java:230)
at rx.observers.Subscribers$5.onError(Subscribers.java:230)
at rx.internal.operators.OnSubscribeThrow.call(OnSubscribeThrow.java:44)
at rx.internal.operators.OnSubscribeThrow.call(OnSubscribeThrow.java:28)
at rx.Observable.unsafeSubscribe(Observable.java:10211)
at rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:51)
at rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:35)
at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)
at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)
at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)
at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
at rx.Observable.unsafeSubscribe(Observable.java:10211)
at rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:51)
at rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:35)
at rx.Observable.unsafeSubscribe(Observable.java:10211)
at rx.internal.operators.OnSubscribeDoOnEach.call(OnSubscribeDoOnEach.java:41)
at rx.internal.operators.OnSubscribeDoOnEach.call(OnSubscribeDoOnEach.java:30)
at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)
at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
at rx.Observable.unsafeSubscribe(Observable.java:10211)
at rx.internal.operators.OperatorSubscribeOn$1.call(OperatorSubscribeOn.java:94)
at com.netflix.hystrix.strategy.concurrency.HystrixContexSchedulerAction$1.call(HystrixContexSchedulerAction.java:56)
at com.netflix.hystrix.strategy.concurrency.HystrixContexSchedulerAction$1.call(HystrixContexSchedulerAction.java:47)
at com.netflix.hystrix.strategy.concurrency.HystrixContexSchedulerAction.call(HystrixContexSchedulerAction.java:69)
at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:55)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:748)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dependenciesBasedLoadBalancer' defined in org.springframework.cloud.zookeeper.discovery.ZookeeperRibbonClientConfiguration: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.netflix.loadbalancer.ILoadBalancer]: Factory method 'dependenciesBasedLoadBalancer' threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1128)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1023)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:751)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541)
at org.springframework.cloud.context.named.NamedContextFactory.createContext(NamedContextFactory.java:110)
at org.springframework.cloud.context.named.NamedContextFactory.getContext(NamedContextFactory.java:79)
at org.springframework.cloud.context.named.NamedContextFactory.getInstance(NamedContextFactory.java:115)
at org.springframework.cloud.netflix.ribbon.SpringClientFactory.getInstance(SpringClientFactory.java:111)
at org.springframework.cloud.netflix.ribbon.SpringClientFactory.getClientConfig(SpringClientFactory.java:65)
at org.springframework.cloud.netflix.feign.ribbon.LoadBalancerFeignClient.getClientConfig(LoadBalancerFeignClient.java:78)
at org.springframework.cloud.netflix.feign.ribbon.LoadBalancerFeignClient.execute(LoadBalancerFeignClient.java:62)
at org.springframework.cloud.zookeeper.discovery.dependency.DependencyFeignClientAutoConfiguration$1.execute(DependencyFeignClientAutoConfiguration.java:81)
at feign.SynchronousMethodHandler.executeAndDecode(SynchronousMethodHandler.java:97)
at feign.SynchronousMethodHandler.invoke(SynchronousMethodHandler.java:76)
at feign.hystrix.HystrixInvocationHandler$1.run(HystrixInvocationHandler.java:108)
at com.netflix.hystrix.HystrixCommand$2.call(HystrixCommand.java:299)
at com.netflix.hystrix.HystrixCommand$2.call(HystrixCommand.java:295)
at rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:46)
... 26 more
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.netflix.loadbalancer.ILoadBalancer]: Factory method 'dependenciesBasedLoadBalancer' threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
... 51 more
Caused by: java.lang.NullPointerException
at org.springframework.cloud.zookeeper.discovery.ZookeeperServerList.getServers(ZookeeperServerList.java:80)
at org.springframework.cloud.zookeeper.discovery.ZookeeperServerList.getInitialListOfServers(ZookeeperServerList.java:68)
at org.springframework.cloud.zookeeper.discovery.dependency.DependenciesBasedLoadBalancer.<init>(DependenciesBasedLoadBalancer.java:52)
at org.springframework.cloud.zookeeper.discovery.ZookeeperRibbonClientConfiguration.dependenciesBasedLoadBalancer(ZookeeperRibbonClientConfiguration.java:88)
at org.springframework.cloud.zookeeper.discovery.ZookeeperRibbonClientConfiguration$$EnhancerBySpringCGLIB$$9f4ce39c.CGLIB$dependenciesBasedLoadBalancer$6(<generated>)
at org.springframework.cloud.zookeeper.discovery.ZookeeperRibbonClientConfiguration$$EnhancerBySpringCGLIB$$9f4ce39c$$FastClassBySpringCGLIB$$329718a4.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:356)
at org.springframework.cloud.zookeeper.discovery.ZookeeperRibbonClientConfiguration$$EnhancerBySpringCGLIB$$9f4ce39c.dependenciesBasedLoadBalancer(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
... 52 more
2017-07-13 11:39:55.224 INFO 9976 --- [ Thread-5] c.n.l.PollingServerListUpdater : Shutting down the Executor Pool for PollingServerListUpdater
2017-07-13 11:39:55.226 INFO 9976 --- [ Thread-4] o.s.w.c.s.GenericWebApplicationContext : Closing org.springframework.web.context.support.GenericWebApplicationContext#769d513: startup date [Thu Jul 13 11:39:48 CST 2017]; parent: org.springframework.context.annotation.AnnotationConfigApplicationContext#62e70ea3
2017-07-13 11:39:55.229 INFO 9976 --- [ Thread-4] o.s.c.support.DefaultLifecycleProcessor : Stopping beans in phase 0
2017-07-13 11:39:55.236 INFO 9976 --- [tor-Framework-0] o.a.c.f.imps.CuratorFrameworkImpl : backgroundOperationsLoop exiting
2017-07-13 11:39:55.253 INFO 9976 --- [ Thread-4] org.apache.zookeeper.ZooKeeper : Session: 0x15caffd3955c4d0 closed
2017-07-13 11:39:55.253 INFO 9976 --- [ain-EventThread] org.apache.zookeeper.ClientCnxn : EventThread shut down
2017-07-13 11:39:55.254 INFO 9976 --- [ Thread-4] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext#3f36e8d1: startup date [Thu Jul 13 11:39:50 CST 2017]; parent: org.springframework.web.context.support.GenericWebApplicationContext#769d513
Disconnected from the target VM, address: '127.0.0.1:63579', transport: 'socket'
Process finished with exit code -1

Tomcat 8, HikariCP, Hibernate and MySQL

Using a Connection Pool
I am using a Hikari Connection Pool to interact with the MySQl database backend in a Java based Web project. I decided to upgrade the library versions to their most recent stable versions and now I cannot connect to the database anymore.
Java 8
MySQL 5.7
Tomcat 8
Dependencies
I use the following Maven dependencies:
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>2.4.5</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-hikaricp</artifactId>
<version>5.2.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-envers</artifactId>
<version>5.2.0.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.2</version>
</dependency>
Hibernate
The project compiles fine, no libraries are missing. This is my hibernate configuration file:
<session-factory>
<property name="hibernate.connection.provider_class">com.zaxxer.hikari.hibernate.HikariConnectionProvider</property>
<property name="hibernate.hikari.dataSourceClassName">com.mysql.jdbc.jdbc2.optional.MysqlDataSource</property>
<property name="hibernate.hikari.dataSource.url">jdbc:mysql://localhost:3306/CitationUserDB?useSSL=false</property>
<property name="hibernate.hikari.dataSource.user">dbUser</property>
<property name="hibernate.hikari.dataSource.password">vErYsEcReT</property>
<property name="hibernate.hikari.dataSource.cachePrepStmts">true</property>
<property name="hibernate.hikari.dataSource.prepStmtCacheSize">250</property>
<property name="hibernate.hikari.dataSource.prepStmtCacheSqlLimit">2048</property>
<property name="hibernate.hikari.dataSource.useServerPrepStmts">true</property>
<mapping class="Database.Authentication.User"/>
</session-factory>
SessionFactory
I use this Hibernate Util class to get the session object.
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
/**
* Hibernate session management
*/
public class HibernateUtilUserAuthentication {
private static SessionFactory sessionFactory;
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) {
// loads configuration and mappings
Configuration configuration = new Configuration().configure("hibernate.userauthentication.cfg.xml");
ServiceRegistry serviceRegistry
= new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
// builds a session factory from the service registry
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
return sessionFactory;
}
}
Error
The following error is thrown, when the first database access happens in the source code. There seems to be a problem with the claspath, but all required libraries are there and I can see them in IntelliJ.
Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:244)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:208)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:189)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:51)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:217)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:189)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.handleTypes(MetadataBuildingProcess.java:352)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:111)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:83)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:418)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:87)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:691)
at Database.Authentication.HibernateUtilUserAuthentication.getSessionFactory(HibernateUtilUserAuthentication.java:104)
at Database.Authentication.UserAPI.authenticateUser(UserAPI.java:133)
at Database.Authentication.UserAuthentication.login(UserAuthentication.java:60)
at Bean.LoginBean.login(LoginBean.java:94)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.el.parser.AstValue.invoke(AstValue.java:247)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:267)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
... 32 more
Caused by: org.hibernate.HibernateException: java.lang.RuntimeException: java.lang.ClassNotFoundException: com.mysql.jdbc.jdbc2.optional.MysqlDataSource
at com.zaxxer.hikari.hibernate.HikariConnectionProvider.configure(HikariConnectionProvider.java:86)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:217)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:189)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.buildJdbcConnectionAccess(JdbcEnvironmentInitiator.java:145)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:66)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:88)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:234)
... 56 more
Caused by: java.lang.RuntimeException: java.lang.ClassNotFoundException: com.mysql.jdbc.jdbc2.optional.MysqlDataSource
at com.zaxxer.hikari.util.UtilityElf.createInstance(UtilityElf.java:120)
at com.zaxxer.hikari.pool.PoolUtilities.initializeDataSource(PoolUtilities.java:110)
at com.zaxxer.hikari.pool.BaseHikariPool.<init>(BaseHikariPool.java:157)
at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:60)
at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:48)
at com.zaxxer.hikari.HikariDataSource.<init>(HikariDataSource.java:80)
at com.zaxxer.hikari.hibernate.HikariConnectionProvider.configure(HikariConnectionProvider.java:82)
... 64 more
Caused by: java.lang.ClassNotFoundException: com.mysql.jdbc.jdbc2.optional.MysqlDataSource
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1305)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1139)
at com.zaxxer.hikari.util.UtilityElf.createInstance(UtilityElf.java:105)
... 70 more
But the library is there:
It is copied to Tomcat during deployment:
./webapps/Testapplication/WEB-INF/lib/mysql-connector-java-6.0.2.jar
I have no idea why the JDBC MySQL driver cannot be found. Any help is really appreciated.
Thank you in advance!
The package structure has changed in mysql-connector-java-6. Switch to mysql-connector-java-5.x
<!-- http://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.39</version>
</dependency>