Tomcat 8, HikariCP, Hibernate and MySQL - 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>

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]

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.

NoClassDefFound error while Running with PowerMock

I am getting this error:
java.lang.NoClassDefFoundError: org/powermock/reflect/proxyframework/ClassLoaderRegisterProxyFramework
at org.powermock.tests.utils.impl.AbstractCommonTestSuiteChunkerImpl.registerProxyframework(AbstractCommonTestSuiteChunkerImpl.java:101)
at org.powermock.tests.utils.impl.AbstractCommonTestSuiteChunkerImpl.chunkClass(AbstractCommonTestSuiteChunkerImpl.java:114)
at org.powermock.tests.utils.impl.AbstractCommonTestSuiteChunkerImpl.<init>(AbstractCommonTestSuiteChunkerImpl.java:60)
at org.powermock.tests.utils.impl.AbstractCommonTestSuiteChunkerImpl.<init>(AbstractCommonTestSuiteChunkerImpl.java:54)
at org.powermock.tests.utils.impl.AbstractTestSuiteChunkerImpl.<init>(AbstractTestSuiteChunkerImpl.java:58)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.<init>(JUnit4TestSuiteChunkerImpl.java:49)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.<init>(AbstractCommonPowerMockRunner.java:32)
at org.powermock.modules.junit4.PowerMockRunner.<init>(PowerMockRunner.java:34)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:104)
at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:33)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createUnfilteredTest(JUnit4TestLoader.java:84)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:70)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:43)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:444)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: java.lang.ClassNotFoundException: org.powermock.reflect.proxyframework.ClassLoaderRegisterProxyFramework
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 25 more
I've added these dependencies in my pom.xml. I've already checked the stackflow for similar implementations and did a clean install. My project is building file but running tests is giving error. I am trying to run through eclipse.
<!-- Power Mock dependencies -->
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4-legacy</artifactId>
<version>1.7.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-reflect</artifactId>
<version>1.7.0</version>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-easymock</artifactId>
<version>1.7.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.easymock</groupId>
<artifactId>easymock</artifactId>
<version>3.4</version>
<scope>test</scope>
</dependency>
I am running java class with PowerMockRunner and injecting my test class using annotation InjectMock. Then mocking static class using MockStatic method. Also, i've added PrepareForTest annotation and added Class which has static methods in that location.
I updated my code and followed few examples, but this error is coming. What am i am doing wrong?
My code is like this.
class A{
void static method testA(String str){ .... do something; }
}
class B{
testB(String s)
{ A.testA(s);
}
}
Now when i try to run test case on my class A using PowerMockRunner. I've given annotations on testcase #preparefortest({A.class}) #runwith(PowerMockRunner.class)
I saw the same error when using PowerMock 1.7.1. In the absence of an explicit dependency, maven was pulling in version 1.6.5 of powermock-core. Adding an explicit dependency on version 1.7.1 of powermock-core fixed this error for me.
So your solution should be to add an explicit dependency on version 1.7.0 of powermock-core:
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-core</artifactId>
<version>1.7.0</version>
<scope>test</scope>
</dependency>

Unable to get Web App to work with mysql 5.1 and wildfly 10

I created a simple mvn webapp in netbeans and got it to work with h2. But I'm unable to get it to work with mysql as a datasource.
I've deployed the mysql 5.1.38 connector to Wildfly and it deploys and connects fine. I've added mysql to my persistence.xml as shown below. But it won't connect. I can connect to mysql in wildfly, mysql client, and within the services tab in wildfly.
After a lot of effort and research, I'm kind of lost.
InitBean
package toofar.demo.session;
import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.inject.Inject;
import toofar.demo.Person;
#Startup
#Singleton
public class InitBean {
#Inject
PersonFacade personFacade;
#PostConstruct
private void init() {
personFacade.create(new Person("sad", "Willy"));
System.err.println(personFacade.find("sad").getName());
}
}
PersonFacade
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import toofar.demo.Person;
#Stateless
public class PersonFacade extends AbstractFacade<Person> {
#PersistenceContext(unitName = "toofar_Demo_war_1.0PU")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}
public PersonFacade() {
super(Person.class);
}
}
AbstractFacade
package toofar.demo.session;
import java.util.List;
import javax.persistence.EntityManager;
public abstract class AbstractFacade<T> {
private Class<T> entityClass;
public AbstractFacade(Class<T> entityClass) {
this.entityClass = entityClass;
}
protected abstract EntityManager getEntityManager();
public void create(T entity) {
getEntityManager().persist(entity);
}
public void edit(T entity) {
getEntityManager().merge(entity);
}
public void remove(T entity) {
getEntityManager().remove(getEntityManager().merge(entity));
}
public T find(Object id) {
return getEntityManager().find(entityClass, id);
}
public List<T> findAll() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
return getEntityManager().createQuery(cq).getResultList();
}
public List<T> findRange(int[] range) {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
javax.persistence.Query q = getEntityManager().createQuery(cq);
q.setMaxResults(range[1] - range[0] + 1);
q.setFirstResult(range[0]);
return q.getResultList();
}
public int count() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
cq.select(getEntityManager().getCriteriaBuilder().count(rt));
javax.persistence.Query q = getEntityManager().createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
}
}
Entity Person
package toofar.demo;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class Person implements Serializable{
private static final long serialVersionUID = 1L;
#Id
String guid;
String name;
public Person() {
}
public Person(String guid, String name) {
this.guid = guid;
this.name = name;
}
public String getGuid() {
return guid;
}
public void setGuid(String guid) {
this.guid = guid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>toofar</groupId>
<artifactId>Demo</artifactId>
<version>1.0</version>
<packaging>war</packaging>
<name>Demo</name>
<properties>
<endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.1.Final</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>unknown.binary</groupId>
<artifactId>hibernate-jpamodelgen-4.3.1.Final</artifactId>
<version>SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<compilerArguments>
<endorseddirs>${endorsed.dir}</endorseddirs>
</compilerArguments>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.3</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.6</version>
<executions>
<execution>
<phase>validate</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<outputDirectory>${endorsed.dir}</outputDirectory>
<silent>true</silent>
<artifactItems>
<artifactItem>
<groupId>javax</groupId>
<artifactId>javaee-endorsed-api</artifactId>
<version>7.0</version>
<type>jar</type>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>unknown-jars-temp-repo</id>
<name>A temporary repository created by NetBeans for libraries and jars it could not identify. Please replace the dependencies in this repository with correct ones and delete this repository.</name>
<url>file:${project.basedir}/lib</url>
</repository>
</repositories>
</project>
Persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="toofar_Demo_war_1.0PU" transaction-type="JTA">
<jta-data-source>java:/toofar</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.show_sql" value="true"/>
</properties>
</persistence-unit>
</persistence>
Error log and stack trace
21:11:07,301 INFO [org.jboss.as.jpa] (ServerService Thread Pool -- 87) WFLYJPA0010: Starting Persistence Unit (phase 2 of 2) Service 'Demo-1.0.war#toofar_Demo_war_1.0PU'
21:11:07,302 WARN [org.jboss.jca.core.connectionmanager.pool.strategy.OnePool] (ServerService Thread Pool -- 87) IJ000604: Throwable while attempting to get a new connection: null: javax.resource.ResourceException: IJ031084: Unable to create connection
at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.createLocalManagedConnection(LocalManagedConnectionFactory.java:343)
at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.getLocalManagedConnection(LocalManagedConnectionFactory.java:350)
at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.createManagedConnection(LocalManagedConnectionFactory.java:285)
at org.jboss.jca.core.connectionmanager.pool.mcp.SemaphoreConcurrentLinkedDequeManagedConnectionPool.createConnectionEventListener(SemaphoreConcurrentLinkedDequeManagedConnectionPool.java:1319)
at org.jboss.jca.core.connectionmanager.pool.mcp.SemaphoreConcurrentLinkedDequeManagedConnectionPool.getConnection(SemaphoreConcurrentLinkedDequeManagedConnectionPool.java:496)
at org.jboss.jca.core.connectionmanager.pool.AbstractPool.getSimpleConnection(AbstractPool.java:626)
at org.jboss.jca.core.connectionmanager.pool.AbstractPool.getConnection(AbstractPool.java:598)
at org.jboss.jca.core.connectionmanager.AbstractConnectionManager.getManagedConnection(AbstractConnectionManager.java:590)
at org.jboss.jca.core.connectionmanager.AbstractConnectionManager.getManagedConnection(AbstractConnectionManager.java:563)
at org.jboss.jca.core.connectionmanager.AbstractConnectionManager.allocateConnection(AbstractConnectionManager.java:747)
at org.jboss.jca.adapters.jdbc.WrapperDataSource.getConnection(WrapperDataSource.java:138)
at org.jboss.as.connector.subsystems.datasources.WildFlyDataSource.getConnection(WildFlyDataSource.java:66)
at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcEnvironmentInitiator.java:180)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:68)
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)
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.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:847)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:874)
at org.jboss.as.jpa.hibernate5.TwoPhaseBootstrapImpl.build(TwoPhaseBootstrapImpl.java:44)
at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:154)
at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:117)
at org.wildfly.security.manager.WildFlySecurityManager.doChecked(WildFlySecurityManager.java:667)
at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1.run(PersistenceUnitServiceImpl.java:182)
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:745)
at org.jboss.threads.JBossThread.run(JBossThread.java:320)
Caused by: javax.resource.ResourceException: IJ031087: Failed to register DriverClass for: org.mysql.Driver
at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.getDriver(LocalManagedConnectionFactory.java:600)
at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.createLocalManagedConnection(LocalManagedConnectionFactory.java:318)
... 36 more
Caused by: java.lang.ClassNotFoundException: org.mysql.Driver from [Module "com.h2database.h2:main" from local module loader #5fcd892a (finder: local module finder #8b87145 (roots: C:\Users\tharper\Downloads\wildfly-10.0.0.Final\modules,C:\Users\tharper\Downloads\wildfly-10.0.0.Final\modules\system\layers\base))]
at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:198)
at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:363)
at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:351)
at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:93)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.getDriver(LocalManagedConnectionFactory.java:591)
... 37 more
21:11:07,349 WARN [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator] (ServerService Thread Pool -- 87) HHH000342: Could not obtain connection to query metadata : javax.resource.ResourceException: IJ000453: Unable to get managed connection for java:/toofar
21:11:07,349 INFO [org.hibernate.dialect.Dialect] (ServerService Thread Pool -- 87) HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
21:11:07,349 INFO [org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl] (ServerService Thread Pool -- 87) HHH000422: Disabling contextual LOB creation as connection was null
21:11:07,350 INFO [org.hibernate.envers.boot.internal.EnversServiceImpl] (ServerService Thread Pool -- 87) Envers integration enabled? : true
21:11:07,364 WARN [org.jboss.jca.core.connectionmanager.pool.strategy.OnePool] (ServerService Thread Pool -- 87) IJ000604: Throwable while attempting to get a new connection: null: javax.resource.ResourceException: IJ031084: Unable to create connection
at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.createLocalManagedConnection(LocalManagedConnectionFactory.java:343)
at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.getLocalManagedConnection(LocalManagedConnectionFactory.java:350)
at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.createManagedConnection(LocalManagedConnectionFactory.java:285)
at org.jboss.jca.core.connectionmanager.pool.mcp.SemaphoreConcurrentLinkedDequeManagedConnectionPool.createConnectionEventListener(SemaphoreConcurrentLinkedDequeManagedConnectionPool.java:1319)
at org.jboss.jca.core.connectionmanager.pool.mcp.SemaphoreConcurrentLinkedDequeManagedConnectionPool.getConnection(SemaphoreConcurrentLinkedDequeManagedConnectionPool.java:496)
at org.jboss.jca.core.connectionmanager.pool.AbstractPool.getSimpleConnection(AbstractPool.java:626)
at org.jboss.jca.core.connectionmanager.pool.AbstractPool.getConnection(AbstractPool.java:598)
at org.jboss.jca.core.connectionmanager.AbstractConnectionManager.getManagedConnection(AbstractConnectionManager.java:590)
at org.jboss.jca.core.connectionmanager.AbstractConnectionManager.getManagedConnection(AbstractConnectionManager.java:563)
at org.jboss.jca.core.connectionmanager.AbstractConnectionManager.allocateConnection(AbstractConnectionManager.java:747)
at org.jboss.jca.adapters.jdbc.WrapperDataSource.getConnection(WrapperDataSource.java:138)
at org.jboss.as.connector.subsystems.datasources.WildFlyDataSource.getConnection(WildFlyDataSource.java:66)
at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122)
at org.hibernate.jpa.internal.schemagen.JpaSchemaGenerator$ConnectionProviderJdbcConnectionAccess.<init>(JpaSchemaGenerator.java:629)
at org.hibernate.jpa.internal.schemagen.JpaSchemaGenerator$ConnectionProviderJdbcConnectionAccess.<init>(JpaSchemaGenerator.java:620)
at org.hibernate.jpa.internal.schemagen.JpaSchemaGenerator.determineAppropriateJdbcConnectionContext(JpaSchemaGenerator.java:402)
at org.hibernate.jpa.internal.schemagen.JpaSchemaGenerator.access$100(JpaSchemaGenerator.java:55)
at org.hibernate.jpa.internal.schemagen.JpaSchemaGenerator$GenerationProcess.execute(JpaSchemaGenerator.java:113)
at org.hibernate.jpa.internal.schemagen.JpaSchemaGenerator.performGeneration(JpaSchemaGenerator.java:65)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:885)
at org.jboss.as.jpa.hibernate5.TwoPhaseBootstrapImpl.build(TwoPhaseBootstrapImpl.java:44)
at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:154)
at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:117)
at org.wildfly.security.manager.WildFlySecurityManager.doChecked(WildFlySecurityManager.java:667)
at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1.run(PersistenceUnitServiceImpl.java:182)
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:745)
at org.jboss.threads.JBossThread.run(JBossThread.java:320)
Caused by: javax.resource.ResourceException: IJ031087: Failed to register DriverClass for: org.mysql.Driver
at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.getDriver(LocalManagedConnectionFactory.java:600)
at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.createLocalManagedConnection(LocalManagedConnectionFactory.java:318)
... 28 more
Caused by: java.lang.ClassNotFoundException: org.mysql.Driver from [Module "com.h2database.h2:main" from local module loader #5fcd892a (finder: local module finder #8b87145 (roots: C:\Users\tharper\Downloads\wildfly-10.0.0.Final\modules,C:\Users\tharper\Downloads\wildfly-10.0.0.Final\modules\system\layers\base))]
at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:198)
at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:363)
at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:351)
at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:93)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.getDriver(LocalManagedConnectionFactory.java:591)
... 29 more
21:11:07,400 ERROR [org.jboss.msc.service.fail] (ServerService Thread Pool -- 87) MSC000001: Failed to start service jboss.persistenceunit."Demo-1.0.war#toofar_Demo_war_1.0PU": org.jboss.msc.service.StartException in service jboss.persistenceunit."Demo-1.0.war#toofar_Demo_war_1.0PU": javax.persistence.PersistenceException: Unable to obtain JDBC Connection
at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:172)
at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:117)
at org.wildfly.security.manager.WildFlySecurityManager.doChecked(WildFlySecurityManager.java:667)
at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1.run(PersistenceUnitServiceImpl.java:182)
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:745)
at org.jboss.threads.JBossThread.run(JBossThread.java:320)
Caused by: javax.persistence.PersistenceException: Unable to obtain JDBC Connection
at org.hibernate.jpa.internal.schemagen.JpaSchemaGenerator$ConnectionProviderJdbcConnectionAccess.<init>(JpaSchemaGenerator.java:632)
at org.hibernate.jpa.internal.schemagen.JpaSchemaGenerator$ConnectionProviderJdbcConnectionAccess.<init>(JpaSchemaGenerator.java:620)
at org.hibernate.jpa.internal.schemagen.JpaSchemaGenerator.determineAppropriateJdbcConnectionContext(JpaSchemaGenerator.java:402)
at org.hibernate.jpa.internal.schemagen.JpaSchemaGenerator.access$100(JpaSchemaGenerator.java:55)
at org.hibernate.jpa.internal.schemagen.JpaSchemaGenerator$GenerationProcess.execute(JpaSchemaGenerator.java:113)
at org.hibernate.jpa.internal.schemagen.JpaSchemaGenerator.performGeneration(JpaSchemaGenerator.java:65)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:885)
at org.jboss.as.jpa.hibernate5.TwoPhaseBootstrapImpl.build(TwoPhaseBootstrapImpl.java:44)
at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:154)
... 7 more
Caused by: java.sql.SQLException: javax.resource.ResourceException: IJ000453: Unable to get managed connection for java:/toofar
at org.jboss.jca.adapters.jdbc.WrapperDataSource.getConnection(WrapperDataSource.java:146)
at org.jboss.as.connector.subsystems.datasources.WildFlyDataSource.getConnection(WildFlyDataSource.java:66)
at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122)
at org.hibernate.jpa.internal.schemagen.JpaSchemaGenerator$ConnectionProviderJdbcConnectionAccess.<init>(JpaSchemaGenerator.java:629)
... 15 more
Caused by: javax.resource.ResourceException: IJ000453: Unable to get managed connection for java:/toofar
at org.jboss.jca.core.connectionmanager.AbstractConnectionManager.getManagedConnection(AbstractConnectionManager.java:656)
at org.jboss.jca.core.connectionmanager.AbstractConnectionManager.getManagedConnection(AbstractConnectionManager.java:563)
at org.jboss.jca.core.connectionmanager.AbstractConnectionManager.allocateConnection(AbstractConnectionManager.java:747)
at org.jboss.jca.adapters.jdbc.WrapperDataSource.getConnection(WrapperDataSource.java:138)
... 18 more
Caused by: javax.resource.ResourceException: IJ031084: Unable to create connection
at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.createLocalManagedConnection(LocalManagedConnectionFactory.java:343)
at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.getLocalManagedConnection(LocalManagedConnectionFactory.java:350)
at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.createManagedConnection(LocalManagedConnectionFactory.java:285)
at org.jboss.jca.core.connectionmanager.pool.mcp.SemaphoreConcurrentLinkedDequeManagedConnectionPool.createConnectionEventListener(SemaphoreConcurrentLinkedDequeManagedConnectionPool.java:1319)
at org.jboss.jca.core.connectionmanager.pool.mcp.SemaphoreConcurrentLinkedDequeManagedConnectionPool.getConnection(SemaphoreConcurrentLinkedDequeManagedConnectionPool.java:496)
at org.jboss.jca.core.connectionmanager.pool.AbstractPool.getSimpleConnection(AbstractPool.java:626)
at org.jboss.jca.core.connectionmanager.pool.AbstractPool.getConnection(AbstractPool.java:598)
at org.jboss.jca.core.connectionmanager.AbstractConnectionManager.getManagedConnection(AbstractConnectionManager.java:590)
... 21 more
Caused by: javax.resource.ResourceException: IJ031087: Failed to register DriverClass for: org.mysql.Driver
at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.getDriver(LocalManagedConnectionFactory.java:600)
at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.createLocalManagedConnection(LocalManagedConnectionFactory.java:318)
... 28 more
Caused by: java.lang.ClassNotFoundException: org.mysql.Driver from [Module "com.h2database.h2:main" from local module loader #5fcd892a (finder: local module finder #8b87145 (roots: C:\Users\tharper\Downloads\wildfly-10.0.0.Final\modules,C:\Users\tharper\Downloads\wildfly-10.0.0.Final\modules\system\layers\base))]
at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:198)
at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:363)
at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:351)
at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:93)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.getDriver(LocalManagedConnectionFactory.java:591)
... 29 more
21:11:07,452 ERROR [org.jboss.as.controller.management-operation] (DeploymentScanner-threads - 1) WFLYCTL0013: Operation ("full-replace-deployment") failed - address: ([]) - failure description: {"WFLYCTL0080: Failed services" => {"jboss.persistenceunit.\"Demo-1.0.war#toofar_Demo_war_1.0PU\"" => "org.jboss.msc.service.StartException in service jboss.persistenceunit.\"Demo-1.0.war#toofar_Demo_war_1.0PU\": javax.persistence.PersistenceException: Unable to obtain JDBC Connection
Caused by: javax.persistence.PersistenceException: Unable to obtain JDBC Connection
Caused by: java.sql.SQLException: javax.resource.ResourceException: IJ000453: Unable to get managed connection for java:/toofar
Caused by: javax.resource.ResourceException: IJ000453: Unable to get managed connection for java:/toofar
Caused by: javax.resource.ResourceException: IJ031084: Unable to create connection
Caused by: javax.resource.ResourceException: IJ031087: Failed to register DriverClass for: org.mysql.Driver
Caused by: java.lang.ClassNotFoundException: org.mysql.Driver from [Module \"com.h2database.h2:main\" from local module loader #5fcd892a (finder: local module finder #8b87145 (roots: C:\\Users\\tharper\\Downloads\\wildfly-10.0.0.Final\\modules,C:\\Users\\tharper\\Downloads\\wildfly-10.0.0.Final\\modules\\system\\layers\\base))]"}}
21:11:07,464 INFO [org.jboss.as.server] (DeploymentScanner-threads - 1)
It turns out that wildfly was updating standalone.xml when I would do add a DS and netbeans was looking at standalone-full.xml

406 Not Acceptable: Spring MVC + 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")