Hibernate and Karaf java.lang.ClassNotFoundException: - java

I am working on a project using Hibernate 4.3.11.Final and karaf 4.0.2. When loading the hibernate config I get the following exception, However the class that fails loading is in the bundle. I Hope somebody can help me with this problem. I have been trying to fix it for several days and I am running out of ideas.
Thanks
org.osgi.framework.ServiceException: Service factory exception: Unable to load class [ com.asm.infraMngr.database.entity.GroupRoleRoleItem] declared in Hibernate configuration <mapping/> entry
at org.apache.felix.framework.ServiceRegistrationImpl.getFactoryUnchecked(ServiceRegistrationImpl.java:352)[org.apache.felix.framework-5.2.0.jar:]
at org.apache.felix.framework.ServiceRegistrationImpl.getService(ServiceRegistrationImpl.java:247)[org.apache.felix.framework-5.2.0.jar:]
at org.apache.felix.framework.ServiceRegistry.getService(ServiceRegistry.java:343)[org.apache.felix.framework-5.2.0.jar:]
at org.apache.felix.framework.Felix.getService(Felix.java:3692)[org.apache.felix.framework-5.2.0.jar:]
at org.apache.felix.framework.BundleContextImpl.getService(BundleContextImpl.java:470)[org.apache.felix.framework-5.2.0.jar:]
at com.asm.infraMngr.database.sessionFactory.HibernateUtil.getSessionFactory(HibernateUtil.java:39)[119:com.asm.infraMngr.database:0.0.1]
at com.asm.infraMngr.database.sessionFactory.HibernateUtil.getSession(HibernateUtil.java:29)[119:com.asm.infraMngr.database:0.0.1]
at com.asm.infraMngr.database.security.daoImpl.UsersDaoImpl.addUser(UsersDaoImpl.java:64)[119:com.asm.infraMngr.database:0.0.1]
at com.asm.infraMngr.AppTesting.activator.Activator.start(Activator.java:50)[122:com.asm.infraMngr.AppTesting:0.0.1]
at org.apache.felix.framework.util.SecureAction.startActivator(SecureAction.java:697)[org.apache.felix.framework-5.2.0.jar:]
at org.apache.felix.framework.Felix.activateBundle(Felix.java:2220)[org.apache.felix.framework-5.2.0.jar:]
at org.apache.felix.framework.Felix.startBundle(Felix.java:2138)[org.apache.felix.framework-5.2.0.jar:]
at org.apache.felix.framework.BundleImpl.start(BundleImpl.java:977)[org.apache.felix.framework-5.2.0.jar:]
at org.apache.felix.framework.BundleImpl.start(BundleImpl.java:964)[org.apache.felix.framework-5.2.0.jar:]
at org.apache.karaf.bundle.command.Install.execute(Install.java:96)[23:org.apache.karaf.bundle.core:4.0.2]
at org.apache.karaf.shell.impl.action.command.ActionCommand.execute(ActionCommand.java:83)[43:org.apache.karaf.shell.core:4.0.2]
at org.apache.karaf.shell.impl.console.osgi.secured.SecuredCommand.execute(SecuredCommand.java:67)[43:org.apache.karaf.shell.core:4.0.2]
at org.apache.karaf.shell.impl.console.osgi.secured.SecuredCommand.execute(SecuredCommand.java:87)[43:org.apache.karaf.shell.core:4.0.2]
at org.apache.felix.gogo.runtime.Closure.executeCmd(Closure.java:480)[43:org.apache.karaf.shell.core:4.0.2]
at org.apache.felix.gogo.runtime.Closure.executeStatement(Closure.java:406)[43:org.apache.karaf.shell.core:4.0.2]
at org.apache.felix.gogo.runtime.Pipe.run(Pipe.java:108)[43:org.apache.karaf.shell.core:4.0.2]
at org.apache.felix.gogo.runtime.Closure.execute(Closure.java:182)[43:org.apache.karaf.shell.core:4.0.2]
at org.apache.felix.gogo.runtime.Closure.execute(Closure.java:119)[43:org.apache.karaf.shell.core:4.0.2]
at org.apache.felix.gogo.runtime.CommandSessionImpl.execute(CommandSessionImpl.java:94)[43:org.apache.karaf.shell.core:4.0.2]
at org.apache.karaf.shell.impl.console.ConsoleSessionImpl.run(ConsoleSessionImpl.java:268)[43:org.apache.karaf.shell.core:4.0.2]
at java.lang.Thread.run(Thread.java:745)[:1.8.0_40]
Caused by: org.hibernate.MappingException: Unable to load class [ com.asm.infraMngr.database.entity.GroupRoleRoleItem] declared in Hibernate configuration <mapping/> entry
at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:2281)[97:org.hibernate.core:4.3.11.Final]
at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:2229)[97:org.hibernate.core:4.3.11.Final]
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2209)[97:org.hibernate.core:4.3.11.Final]
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2162)[97:org.hibernate.core:4.3.11.Final]
at org.hibernate.cfg.Configuration.configure(Configuration.java:2077)[97:org.hibernate.core:4.3.11.Final]
at org.hibernate.osgi.OsgiSessionFactoryService.getService(OsgiSessionFactoryService.java:102)[100:org.hibernate.osgi:4.3.11.Final]
at org.apache.felix.framework.ServiceRegistrationImpl.getFactoryUnchecked(ServiceRegistrationImpl.java:347)[org.apache.felix.framework-5.2.0.jar:]
... 25 more
Caused by: java.lang.ClassNotFoundException: com.asm.infraMngr.database.entity.GroupRoleRoleItem not found by org.hibernate.core [97]
at org.apache.felix.framework.BundleWiringImpl.findClassOrResourceByDelegation(BundleWiringImpl.java:1558)[org.apache.felix.framework-5.2.0.jar:]
at org.apache.felix.framework.BundleWiringImpl.access$400(BundleWiringImpl.java:79)[org.apache.felix.framework-5.2.0.jar:]
at org.apache.felix.framework.BundleWiringImpl$BundleClassLoader.loadClass(BundleWiringImpl.java:1998)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)[:1.8.0_40]
at java.lang.Class.forName0(Native Method)[:1.8.0_40]
at java.lang.Class.forName(Class.java:264)[:1.8.0_40]
at org.hibernate.internal.util.ReflectHelper.classForName(ReflectHelper.java:193)[97:org.hibernate.core:4.3.11.Final]
at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:2278)[97:org.hibernate.core:4.3.11.Final]
Below my hibernate config
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">org.apache.derby.jdbc.EmbeddedDriver</property>
<property name="hibernate.connection.url">jdbc:derby:ASM_DB;create=true</property>
<property name="hibernate.connection.username">test</property>
<property name="hibernate.connection.password">test</property>
<property name="hibernate.dialect">org.hibernate.dialect.DerbyTenSevenDialect</property>
<property name="hibernate.hbm2ddl.auto">create-drop</property>
<mapping class="com.asm.infraMngr.database.entity.Users" />
<mapping class="com.asm.infraMngr.database.entity.Group" />
<mapping class="com.asm.infraMngr.database.entity.GroupRole" />
<mapping class="com.asm.infraMngr.database.entity.GroupRoleRoleItem" />
<mapping class="com.asm.infraMngr.database.entity.ItService" />
<mapping class="com.asm.infraMngr.database.entity.HttpInfo" />
<mapping class="com.asm.infraMngr.database.entity.JmxInfo" />
<mapping class="com.asm.infraMngr.database.entity.ServerInfo" />
<mapping class="com.asm.infraMngr.database.entity.SshInfo" />
<mapping class="com.asm.infraMngr.database.entity.UserAttempts" />
<mapping class="com.asm.infraMngr.database.entity.ServiceAudit" />
</session-factory>
</hibernate-configuration>
#
I am loading the hibernate session with the following class
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.ServiceReference;
public class HibernateUtil {
private SessionFactory sf;
public Session getSession() {
return getSessionFactory().openSession();
}
private SessionFactory getSessionFactory() {
if ( sf == null ) {
Bundle thisBundle = FrameworkUtil.getBundle( HibernateUtil.class );
// Could get this by wiring up OsgiTestBundleActivator as well.
BundleContext context = thisBundle.getBundleContext();
ServiceReference sr = context.getServiceReference( SessionFactory.class.getName() );
sf = (SessionFactory) context.getService( sr );
}
return sf;
}
}
The POM dependencies are the following
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<hibernate.core.version>4.3.11.Final</hibernate.core.version>
<bundle.symbolicName>com.asm.infraMngr.database</bundle.symbolicName>
<bundle.namespace>com.asm.infraMngr.database</bundle.namespace>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<version>2.4.0</version>
<extensions>true</extensions>
<!--
the following instructions build a simple set of public/private classes into an OSGi bundle
-->
<configuration>
<manifestLocation>META-INF</manifestLocation>
<instructions>
<Bundle-SymbolicName>${bundle.symbolicName}</Bundle-SymbolicName>
<Bundle-Version>${pom.version}</Bundle-Version>
<Bundle-Activator>com.asm.infraMngr.database.activator.ActivatorDBModule</Bundle-Activator>
<Spring-Context>*;publish-context:=false;create-asynchronously:=true</Spring-Context>
<Bundle-ClassPath>.,./config/</Bundle-ClassPath>
<DynamicImport-Package>*</DynamicImport-Package>
<Bundle-ManifestVersion>2</Bundle-ManifestVersion>
<Bundle-ActivationPolicy>lazy</Bundle-ActivationPolicy>
<Export-Package>
com.asm.infraMngr.database.services.dao,
com.asm.infraMngr.database.security.dao,
com.asm.infraMngr.database.entity
</Export-Package>
<Import-Package>
org.hibernate;version=${hibernate.core.version},
org.hibernate.cfg;version=${hibernate.core.version},
org.hibernate.service;version=${hibernate.core.version},
org.hibernate.proxy;version=${hibernate.core.version},
org.hibernate.mapping;version=${hibernate.core.version},
org.hibernate.annotations;version=${hibernate.core.version},
org.hibernate.envers.*;version=${hibernate.core.version},
org.hibernate.boot.registry;version=${hibernate.core.version},
org.osgi.framework;version=1.0,
org.jvnet.jaxb2_commons.lang;version=0,
org.jvnet.jaxb2_commons.locator;version=0,
org.apache.log4j;version=1.2.15,
org.apache.derby.jdbc;version=10.12.1.1,
javax.xml.datatype;version=0.0.0
</Import-Package>
</instructions>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.core.version}</version>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>xml-apis</groupId>
<artifactId>xml-apis</artifactId>
</exclusion>
<exclusion>
<groupId>xerces</groupId>
<artifactId>xercesImpl</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-envers</artifactId>
<version>${hibernate.core.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.servicemix.bundles</groupId>
<artifactId>org.apache.servicemix.bundles.derby</artifactId>
<version>10.12.1.1_1</version>
</dependency>
<dependency>
<groupId>org.jvnet.hyperjaxb3</groupId>
<artifactId>hyperjaxb3-ejb-runtime</artifactId>
<version>0.5.6</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jvnet.jaxb2_commons</groupId>
<artifactId>runtime</artifactId>
<version>0.4.1.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.osgi</groupId>
<artifactId>org.osgi.core</artifactId>
<version>5.0.0</version>
<!--scope>provided</scope-->
</dependency>
</dependencies>
The class that is not loading is as follows
package com.asm.infraMngr.database.entity;
import com.asm.infraMngr.database.enums.RoleEnum;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;
import org.hibernate.envers.AuditTable;
import org.hibernate.envers.Audited;
import org.jvnet.hyperjaxb3.item.Item;
import javax.persistence.*;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
#XmlAccessorType(XmlAccessType.FIELD)
#Entity(name = "GroupRoleRoleItem")
#Table(name = "GROUP_ROLE_ROLE_ITEM")
#Inheritance(strategy = InheritanceType.JOINED)
#DynamicUpdate(true)
#SelectBeforeUpdate(true)
#Audited
#AuditTable("GROUP_ROLE_ROLE_ITEM_AUD")
public class GroupRoleRoleItem
implements Item<RoleEnum>
{
#XmlElement(name = "Role")
protected RoleEnum item;
#XmlAttribute(name = "Hjid")
protected Long hjid;
/**
* Gets the value of the item property.
*
* #return
* possible object is
* {#link RoleEnum }
*
*/
#Basic
#Column(name = "ITEM", length = 50)
#Enumerated(EnumType.STRING)
public RoleEnum getItem() {
return item;
}
/**
* Sets the value of the item property.
*
* #param value
* allowed object is
* {#link RoleEnum }
*
*/
public void setItem(RoleEnum value) {
this.item = value;
}
/**
* Gets the value of the hjid property.
*
* #return
* possible object is
* {#link Long }
*
*/
#Id
#Column(name = "HJID")
#GeneratedValue(strategy = GenerationType.AUTO)
public Long getHjid() {
return hjid;
}
/**
* Sets the value of the hjid property.
*
* #param value
* allowed object is
* {#link Long }
*
*/
public void setHjid(Long value) {
this.hjid = value;
}
}
After further troubleshooting I got a comment from another post to include org.hibernate.internal.util on the Import-Package tag. After this the original problem was solved. now I have a new exception. Then exception states the hibernate.cfg.xml file is not found, however the file is in the location written in the exception which is "/config/hibernate.cfg.xml"
org.osgi.framework.ServiceException: Service factory exception: /config/hibernate.cfg.xml not found
at org.apache.felix.framework.ServiceRegistrationImpl.getFactoryUnchecked(ServiceRegistrationImpl.java:352)[org.apache.felix.framework-5.2.0.jar:]
at org.apache.felix.framework.ServiceRegistrationImpl.getService(ServiceRegistrationImpl.java:247)[org.apache.felix.framework-5.2.0.jar:]
at org.apache.felix.framework.ServiceRegistry.getService(ServiceRegistry.java:343)[org.apache.felix.framework-5.2.0.jar:]
at org.apache.felix.framework.Felix.getService(Felix.java:3692)[org.apache.felix.framework-5.2.0.jar:]
at org.apache.felix.framework.BundleContextImpl.getService(BundleContextImpl.java:470)[org.apache.felix.framework-5.2.0.jar:]
at com.asm.infraMngr.database.sessionFactory.HibernateUtil.getSessionFactory(HibernateUtil.java:39)[135:com.asm.infraMngr.database:0.0.1]
at com.asm.infraMngr.database.sessionFactory.HibernateUtil.getSession(HibernateUtil.java:29)[135:com.asm.infraMngr.database:0.0.1]
at com.asm.infraMngr.database.security.daoImpl.UsersDaoImpl.addUser(UsersDaoImpl.java:64)[135:com.asm.infraMngr.database:0.0.1]
at com.asm.infraMngr.AppTesting.activator.Activator.start(Activator.java:50)[136:com.asm.infraMngr.AppTesting:0.0.1]
at org.apache.felix.framework.util.SecureAction.startActivator(SecureAction.java:697)[org.apache.felix.framework-5.2.0.jar:]
at org.apache.felix.framework.Felix.activateBundle(Felix.java:2220)[org.apache.felix.framework-5.2.0.jar:]
at org.apache.felix.framework.Felix.startBundle(Felix.java:2138)[org.apache.felix.framework-5.2.0.jar:]
at org.apache.felix.framework.BundleImpl.start(BundleImpl.java:977)[org.apache.felix.framework-5.2.0.jar:]
at org.apache.felix.framework.BundleImpl.start(BundleImpl.java:964)[org.apache.felix.framework-5.2.0.jar:]
at org.apache.karaf.bundle.command.Install.execute(Install.java:96)[23:org.apache.karaf.bundle.core:4.0.2]
at org.apache.karaf.shell.impl.action.command.ActionCommand.execute(ActionCommand.java:83)[43:org.apache.karaf.shell.core:4.0.2]
at org.apache.karaf.shell.impl.console.osgi.secured.SecuredCommand.execute(SecuredCommand.java:67)[43:org.apache.karaf.shell.core:4.0.2]
at org.apache.karaf.shell.impl.console.osgi.secured.SecuredCommand.execute(SecuredCommand.java:87)[43:org.apache.karaf.shell.core:4.0.2]
at org.apache.felix.gogo.runtime.Closure.executeCmd(Closure.java:480)[43:org.apache.karaf.shell.core:4.0.2]
at org.apache.felix.gogo.runtime.Closure.executeStatement(Closure.java:406)[43:org.apache.karaf.shell.core:4.0.2]
at org.apache.felix.gogo.runtime.Pipe.run(Pipe.java:108)[43:org.apache.karaf.shell.core:4.0.2]
at org.apache.felix.gogo.runtime.Closure.execute(Closure.java:182)[43:org.apache.karaf.shell.core:4.0.2]
at org.apache.felix.gogo.runtime.Closure.execute(Closure.java:119)[43:org.apache.karaf.shell.core:4.0.2]
at org.apache.felix.gogo.runtime.CommandSessionImpl.execute(CommandSessionImpl.java:94)[43:org.apache.karaf.shell.core:4.0.2]
at org.apache.karaf.shell.impl.console.ConsoleSessionImpl.run(ConsoleSessionImpl.java:268)[43:org.apache.karaf.shell.core:4.0.2]
at java.lang.Thread.run(Thread.java:745)[:1.8.0_40]
Caused by: org.hibernate.HibernateException: /config/hibernate.cfg.xml not found
at org.hibernate.internal.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:173)[97:org.hibernate.core:4.3.11.Final]
at org.hibernate.cfg.Configuration.getConfigurationInputStream(Configuration.java:2095)[97:org.hibernate.core:4.3.11.Final]
at org.hibernate.cfg.Configuration.configure(Configuration.java:2076)[97:org.hibernate.core:4.3.11.Final]
at org.hibernate.osgi.OsgiSessionFactoryService.getService(OsgiSessionFactoryService.java:102)[100:org.hibernate.osgi:4.3.11.Final]

I was able to solve the problem, form some reason Karaf keeps references on an old hibernate bundle even after uninstalling the bundle, so the hibernate config file was not found by karaf. To solve the problem I deleted the "data" directory in karaf to restart fresh. Then I installed all the dependencies and finally my bundle. Then the hibernate config file was found on the bundle started up correctly.

Related

Using deprecated '-debug' fallback for parameter name resolution. Compile the affected code with '-parameters' instead or avoid its introspection

I am using Spring Boot 3.0.0, Eclipse IDE 2022-12, Java language level/JDK 19.
File pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.0</version>
<relativePath/>
</parent>
<groupId>com.example</groupId>
<artifactId>spring_jwt</artifactId>
<version>1.0.0-SNAPSHOT</version>
<name>spring-boot-security-jwt</name>
<description>spring_jwt</description>
<properties>
<java.version>19</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-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.5</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-hibernate5-jakarta</artifactId>
<version>2.14.0</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
<!-- Jasper report start. -->
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports</artifactId>
<version>6.20.0</version>
</dependency>
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports-fonts</artifactId>
<version>6.20.0</version>
</dependency>
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports-functions</artifactId>
<version>6.20.0</version>
</dependency>
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports-metadata</artifactId>
<version>6.20.0</version>
</dependency>
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports-chart-themes</artifactId>
<version>6.20.0</version>
</dependency>
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports-annotation-processors</artifactId>
<version>6.20.0</version>
</dependency>
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports-castor</artifactId>
<version>6.20.0</version>
</dependency>
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>liberation-fonts</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports-chart-customizers</artifactId>
<version>6.20.0</version>
</dependency>
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports-custom-visualization</artifactId>
<version>6.20.0</version>
</dependency>
<!-- Jasper report end. -->
<!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils -->
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.4</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13.3</version>
</dependency>
<!-- <dependency>-->
<!-- <groupId>org.springframework.boot</groupId>-->
<!-- <artifactId>spring-boot-devtools</artifactId>-->
<!-- <scope>runtime</scope>-->
<!-- <optional>true</optional>-->
<!-- </dependency>-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<!-- <dependency>-->
<!-- <groupId>org.flywaydb</groupId>-->
<!-- <artifactId>flyway-core</artifactId>-->
<!-- <version>9.1.3</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>com.stimulsoft</groupId>-->
<!-- <artifactId>stimulsoft-reports-report</artifactId>-->
<!-- <version>2022.3.3</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>com.stimulsoft</groupId>-->
<!-- <artifactId>stimulsoft-reports-web</artifactId>-->
<!-- <version>2022.3.3</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>com.stimulsoft</groupId>-->
<!-- <artifactId>stimulsoft-reports-base</artifactId>-->
<!-- <version>2022.3.3</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>com.stimulsoft</groupId>-->
<!-- <artifactId>stimulsoft-reports-viewer</artifactId>-->
<!-- <version>2022.3.3</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>com.stimulsoft</groupId>-->
<!-- <artifactId>stimulsoft-reports-samples</artifactId>-->
<!-- <version>2022.3.3</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>com.stimulsoft</groupId>-->
<!-- <artifactId>stimulsoft-reports-webviewer</artifactId>-->
<!-- <version>2022.3.3</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>com.stimulsoft</groupId>-->
<!-- <artifactId>stimulsoft-reports-lib</artifactId>-->
<!-- <version>2022.3.3</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>com.stimulsoft</groupId>-->
<!-- <artifactId>stimulsoft-reports-webdesigner</artifactId>-->
<!-- <version>2022.3.3</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>com.stimulsoft</groupId>-->
<!-- <artifactId>reports</artifactId>-->
<!-- <version>2022.3.3</version>-->
<!-- <type>pom</type>-->
<!-- </dependency>-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>3.0.0</version>
</plugin>
<!-- <plugin>-->
<!-- <groupId>org.flywaydb</groupId>-->
<!-- <artifactId>flyway-maven-plugin</artifactId>-->
<!-- <version>9.1.3</version>-->
<!-- </plugin>-->
</plugins>
</build>
<repositories>
<repository>
<id>xpand</id>
<name>xpand</name>
<url>https://maven.xpand-it.com/artifactory/releases/</url>
</repository>
<repository>
<id>maven_central</id>
<name>maven_central</name>
<url>https://repo.maven.apache.org/maven2/</url>
</repository>
</repositories>
</project>
I have many controllers like these: File UnitController.java
package com.example.controller;
import com.example.BLModel.Unit;
import com.example.BLModel.UnitId;
import com.example.service.UnitService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Optional;
#CrossOrigin(origins = "*", maxAge = 3600)
#RestController
#RequestMapping("/unit")
public class UnitController {
private static final Logger LOGGER = LoggerFactory.getLogger(UnitController.class);
#Autowired
UnitService unitService;
/**
* Get all units belong to a tenant_id .<br/>
* GET http://localhost:80/unit/1/all .
*
* #param tenant_id
* #return
*/
#GetMapping(value = "/{tenant_id}/all")
public ResponseEntity<List<Unit>> getAllUnits(#PathVariable("tenant_id") Short tenant_id) {
LOGGER.info("Call method getAllUnits() .");
return new ResponseEntity<>(unitService.getAll(tenant_id), HttpStatus.OK);
}
/**
* Get a unit by its composite primary key.<br/>
* GET http://localhost:80/unit/1/42 .
*
* #param tenant_id
* #param id
* #return
*/
#GetMapping(value = "/{tenant_id}/{id}")
public ResponseEntity<Unit> viewDetailUnit(#PathVariable("tenant_id") Short tenant_id,
#PathVariable("id") Short id) {
LOGGER.info("Call method viewDetailUnit() .");
UnitId unitId = new UnitId();
unitId.setId(id);
unitId.setTenantId(tenant_id);
Optional<Unit> unitOptional = unitService.getById(unitId);
Unit result = null;
if (unitOptional.isPresent()) {
result = unitOptional.get();
}
return new ResponseEntity<>(result, HttpStatus.OK);
}
/**
* Add a new unit.<br/>
* POST http://localhost:80/unit
*
* #param input
* #return
*/
#PostMapping()
public ResponseEntity<Unit> addUnit(#RequestBody Unit input) {
LOGGER.info("Call method addUnit() .");
Unit unit = new Unit();
unit.setUnitName(input.getUnitName());
unit.setDescription(input.getDescription());
unit.setActiveStatus(input.getActiveStatus());
Unit unitResult = unitService.add(unit);
return new ResponseEntity<>(unitResult, HttpStatus.OK);
}
/**
* Edit a unit.<br/>
* PATCH http://localhost:80/unit/1/42 .
*
* #param tenant_id
* #param id
* #param input
* #return
*/
#PatchMapping(value = "/{tenant_id}/{id}")
public ResponseEntity<Unit> editUnit(#PathVariable("tenant_id") Short tenant_id,
#PathVariable("id") Short id,
#RequestBody Unit input) {
LOGGER.info("Call method editUnit() .");
UnitId unitId = new UnitId();
unitId.setTenantId(tenant_id);
unitId.setId(id);
Unit unit = (unitService.getById(unitId)).get();
unit.setActiveStatus(input.getActiveStatus());
unit.setDescription(input.getDescription());
unit.setUnitName(input.getUnitName());
Unit unitResult = unitService.add(unit);
return new ResponseEntity<>(unitResult, HttpStatus.OK);
}
/**
* Delete a specific unit.<br/>
* DELETE http://localhost:80/unit/1/42 .
*
* #param tenant_id
* #param id
* #return
*/
#DeleteMapping(value = "/{tenant_id}/{id}")
public ResponseEntity<Object> deleteUnit(#PathVariable("tenant_id") Short tenant_id,
#PathVariable("id") Short id) {
UnitId unitId = new UnitId();
unitId.setId(id);
unitId.setTenantId(tenant_id);
unitService.delete(unitId);
return new ResponseEntity<>(null, HttpStatus.OK);
}
}
File TimesheetSignController.java
package com.example.controller;
import com.example.BLModel.TimesheetSign;
import com.example.BLModel.TimesheetSignId;
import com.example.service.TimesheetSignService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Optional;
#CrossOrigin(origins = "*", maxAge = 3600)
#RestController
#RequestMapping("/timesheet_sign")
public class TimesheetSignController {
private static final Logger LOGGER = LoggerFactory.getLogger(TimesheetSignController.class);
#Autowired
TimesheetSignService timesheetSignService;
/**
* Get all time_sheet_sign by its tenant_id .<br/>
* GET http://localhost:80/time_sheet_sign/1/all .
*
* #param tenant_id
* #return
*/
#GetMapping(value = "/{tenant_id}")
public ResponseEntity<List<TimesheetSign>> getAllAccounts(#PathVariable("tenant_id") Short tenant_id) {
LOGGER.info("Call method getAllAccounts() .");
return new ResponseEntity<>(timesheetSignService.getAll(tenant_id), HttpStatus.OK);
}
/**
* Get a specific time_sheet_sign item by its composite primary key.
* GET http://localhost:80/1/42
*
* #param tenant_id
* #param id
* #return
*/
#GetMapping(value = "/{tenant_id}/{id}")
public ResponseEntity<TimesheetSign> viewDetailAccount(#PathVariable("tenant_id") Short tenant_id,
#PathVariable("id") Short id) {
LOGGER.info("Call method viewDetailAccount() .");
TimesheetSignId timesheetSignId = new TimesheetSignId();
timesheetSignId.setId(id);
timesheetSignId.setTenantId(tenant_id);
Optional<TimesheetSign> timesheetSignOptional = timesheetSignService.getById(timesheetSignId);
TimesheetSign timesheetSignResult = null;
if (timesheetSignOptional.isPresent()) {
timesheetSignResult = timesheetSignOptional.get();
}
return new ResponseEntity<>(timesheetSignResult, HttpStatus.OK);
}
/**
* Create a new time_sheet_sign .<br/>
* POST http://localhost:80/time_sheet_sign
*
* #param input
* #return
*/
#PostMapping()
public ResponseEntity<TimesheetSign> addAccount(#RequestBody TimesheetSign input) {
LOGGER.info("Call method addAccount() .");
TimesheetSign timesheetSign = new TimesheetSign();
timesheetSign.setTimesheetSignCode(input.getTimesheetSignCode());
timesheetSign.setActiveStatus(input.getActiveStatus());
timesheetSign.setIsDefault(input.getIsDefault());
timesheetSign.setIsSystem(input.getIsSystem());
timesheetSign.setIsHalfDay(input.getIsHalfDay());
TimesheetSign timesheetSignResult = timesheetSignService.add(timesheetSign);
return new ResponseEntity<>(timesheetSignResult, HttpStatus.OK);
}
/**
* Edit time_sheet_sign by its composite primary key.
* PATCH http://localhost:80/time_sheet_sign/1/42 .
*
* #param tenant_id
* #param id
* #param input
* #return
*/
#PatchMapping(value = "/{tenant_id}/{id}")
public ResponseEntity<TimesheetSign> editAccount(#PathVariable("tenant_id") Short tenant_id,
#PathVariable("id") Short id,
#RequestBody TimesheetSign input) {
LOGGER.info("Call method editAccount() .");
TimesheetSignId timesheetSignId = new TimesheetSignId();
timesheetSignId.setTenantId(tenant_id);
timesheetSignId.setId(id);
TimesheetSign timesheetSign = (timesheetSignService.getById(timesheetSignId)).get();
timesheetSign.setTimesheetSignName(input.getTimesheetSignName());
timesheetSign.setIsHalfDay(input.getIsHalfDay());
timesheetSign.setIsSystem(input.getIsSystem());
timesheetSign.setTimesheetSignCode(input.getTimesheetSignCode());
timesheetSign.setSalaryRate(input.getSalaryRate());
TimesheetSign timesheetSignResult = timesheetSignService.add(timesheetSign);
return new ResponseEntity<>(timesheetSignResult, HttpStatus.OK);
}
/**
* Delete time_sheet_sign by its composite primary key.
* DELETE http://localhost:80/time_sheet_sign/1/42 .
*
* #param tenant_id
* #param id
* #return
*/
#DeleteMapping(value = "/{tenant_id}/{id}")
public ResponseEntity<Object> deleteAccount(#PathVariable("tenant_id") Short tenant_id,
#PathVariable("id") Short id) {
TimesheetSignId timesheetSignId = new TimesheetSignId();
timesheetSignId.setId(id);
timesheetSignId.setTenantId(tenant_id);
timesheetSignService.delete(timesheetSignId);
return new ResponseEntity<>(null, HttpStatus.OK);
}
}
[2m2022-12-19T08:18:19.517+07:00[0;39m [32m INFO[0;39m [35m7048[0;39m [2m---[0;39m [2m[nio-8082-exec-1][0;39m [36mo.s.web.servlet.DispatcherServlet [0;39m [2m:[0;39m Initializing Servlet 'dispatcherServlet'
[2m2022-12-19T08:18:19.520+07:00[0;39m [32m INFO[0;39m [35m7048[0;39m [2m---[0;39m [2m[nio-8082-exec-1][0;39m [36mo.s.web.servlet.DispatcherServlet [0;39m [2m:[0;39m Completed initialization in 3 ms
[2m2022-12-19T08:18:21.177+07:00[0;39m [33m WARN[0;39m [35m7048[0;39m [2m---[0;39m [2m[nio-8082-exec-8][0;39m [36mocalVariableTableParameterNameDiscoverer[0;39m [2m:[0;39m Using deprecated '-debug' fallback for parameter name resolution. Compile the affected code with '-parameters' instead or avoid its introspection: com.example.controller.UnitController
[2m2022-12-19T08:18:21.313+07:00[0;39m [33m WARN[0;39m [35m7048[0;39m [2m---[0;39m [2m[nio-8082-exec-8][0;39m [36mocalVariableTableParameterNameDiscoverer[0;39m [2m:[0;39m Using deprecated '-debug' fallback for parameter name resolution. Compile the affected code with '-parameters' instead or avoid its introspection: com.example.controller.TimesheetSignController
[2m2022-12-19T08:18:21.331+07:00[0;39m [33m WARN[0;39m [35m7048[0;39m [2m---[0;39m [2m[nio-8082-exec-8][0;39m [36mocalVariableTableParameterNameDiscoverer[0;39m [2m:[0;39m Using deprecated '-debug' fallback for parameter name resolution. Compile the affected code with '-parameters' instead or avoid its introspection: com.example.controller.TaxAgentInfoController
Full log https://gist.github.com/donhuvy/45b15558e76164e83bdbc0117c9cf64f
How to avoid/resolve this warning?
P/S: Comment about not dupplicated question. In this question and solution https://stackoverflow.com/a/74601911/3728901 , use maven-compiler-plugin , not spring-boot-maven-plugin .
This is a known bug and there is a Spring Issue for it. But it is not harmful and you do not need to take any action unless you just don't want warnings in your logs.
From the issue:
"It looks like the core bean factory is unnecessarily retrieving constructor parameter names during the constructor autowiring algorithm, despite no constructor argument names having been specified. That's a bug we're going to fix in [Spring Framework] 6.0.3."
and
"For the time being, you may simply disable the warn log category for org.springframework.core.LocalVariableTableParameterNameDiscoverer. There is unnecessary reading of class files in the meantime but otherwise no harm for your application."

java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: News is not mapped [from News where status =: active]

I connected Spring 5.0.19.RELEASE and Hibernate 5.2.10.Final.
I'm getting an error: java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: News is not mapped [from News where status =: active].
The same error is also obtained with other requests (for example "from News").
The work of the application reaches the DAO layer and executes a query from the database.
When I trying to get information from BD and display this list in the web app.
I'm a newbie in Java.
I tried the options below:
why-org-hibernate-hql-internal-ast-querysyntaxexception-customer-is-not-mapped
Hibernate error - QuerySyntaxException: users is not mapped [from
users]
but it doesn't work.
I hope to get help in my confused situation.
My DataBase in MySQL
CREATE TABLE `news` (
`idnews` int NOT NULL AUTO_INCREMENT,
`title` varchar(200) COLLATE utf8_bin DEFAULT NULL,
`brief` varchar(500) COLLATE utf8_bin DEFAULT NULL,
`content` varchar(5000) COLLATE utf8_bin DEFAULT NULL,
`date` timestamp NULL DEFAULT NULL,
`status` varchar(45) COLLATE utf8_bin NOT NULL,
PRIMARY KEY (`idnews`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_bin
Error:
Jun 22, 2021 9:10:23 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/spring-myproject] threw exception [Request processing failed; nested exception is java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: News is not mapped [from News where status =: active]] with root cause
org.hibernate.hql.internal.ast.QuerySyntaxException: News is not mapped
at org.hibernate.hql.internal.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:171)
at org.hibernate.hql.internal.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:91)
at org.hibernate.hql.internal.ast.tree.FromClause.addFromElement(FromClause.java:79)
at org.hibernate.hql.internal.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:324)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3696)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:3585)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:720)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:576)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:313)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:261)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:266)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:189)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:141)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:115)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:77)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:153)
at org.hibernate.internal.AbstractSharedSessionContract.getQueryPlan(AbstractSharedSessionContract.java:546)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:655)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:679)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:102)
at myproject.dao.impl.SQLNewsDAO.all(SQLNewsDAO.java:28)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:78)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:343)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:197)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:295)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
at jdk.proxy3/jdk.proxy3.$Proxy26.all(Unknown Source)
at myproject.service.impl.NewsServiceImpl.takeAll(NewsServiceImpl.java:28)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:78)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:343)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:197)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:295)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
at jdk.proxy3/jdk.proxy3.$Proxy27.takeAll(Unknown Source)
at myproject.command.GoToMainIndexPage.execute(GoToMainIndexPage.java:27)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:78)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:893)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:799)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:981)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:873)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:626)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:858)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:690)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:888)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1597)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:831)
Entity:
package myproject.entity;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="news")
public class News implements Serializable {
private static final long serialVersionUID = 5421029433949953632L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="idnews")
private int idnews;
#Column(name="title")
private String title;
#Column(name="brief")
private String brief;
#Column(name="content")
private String content;
#Column(name="date")
private LocalDateTime date;
#Column(name="status")
private String status;
public News() {
}
public News(int idnews, String title, String brief) {
super();
this.setIdnews(idnews);
this.title = title;
this.setBrief(brief);
}
public News(int idnews, String title, String brief, String content, LocalDateTime date) {
super();
this.setIdnews(idnews);
this.title = title;
this.setBrief(brief);
this.setContent(content);
this.setDate(date);
}
public int getIdnews() {
return idnews;
}
public void setIdnews(int idnews) {
this.idnews = idnews;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBrief() {
return brief;
}
public void setBrief(String brief) {
this.brief = brief;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getDate() {
DateTimeFormatter newFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
String formattedDateTime = date.format(newFormat);
return formattedDateTime;
}
public void setDate(LocalDateTime date) {
this.date = date;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((brief == null) ? 0 : brief.hashCode());
result = prime * result + ((content == null) ? 0 : content.hashCode());
result = prime * result + ((date == null) ? 0 : date.hashCode());
result = prime * result + idnews;
result = prime * result + ((status == null) ? 0 : status.hashCode());
result = prime * result + ((title == null) ? 0 : title.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
News other = (News) obj;
if (brief == null) {
if (other.brief != null)
return false;
} else if (!brief.equals(other.brief))
return false;
if (content == null) {
if (other.content != null)
return false;
} else if (!content.equals(other.content))
return false;
if (date == null) {
if (other.date != null)
return false;
} else if (!date.equals(other.date))
return false;
if (idnews != other.idnews)
return false;
if (status == null) {
if (other.status != null)
return false;
} else if (!status.equals(other.status))
return false;
if (title == null) {
if (other.title != null)
return false;
} else if (!title.equals(other.title))
return false;
return true;
}
#Override
public String toString() {
return "id: " + this.idnews + "\n" +
"title:" + this.title + "\n" +
"brief:" + this.brief + "\n" +
"content: " + this.content + "\n" +
"date: " + this.date + "\n" +
"status: " + this.status;
}
}
Controller layer
package myproject.command;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import myproject.entity.News;
import myproject.service.NewsService;
import myproject.service.ServiceException;
#Controller
#RequestMapping("/mainIndexPage")
public class GoToMainIndexPage {
#Autowired
private NewsService newsService;
#RequestMapping("/showMainPage")
public String execute(Model theModel) throws ServletException, IOException, ServiceException {
List<News> news = newsService.takeAll();
theModel.addAttribute("news", news);
return "main_index_page";
}
}
Service layer
package myproject.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import myproject.dao.DAOException;
import myproject.dao.NewsDAO;
import myproject.entity.News;
import myproject.service.NewsService;
import myproject.service.ServiceException;
#Service
public class NewsServiceImpl implements NewsService {
#Autowired
private NewsDAO newsDAO;
//#Override
#Transactional
public List<News> takeAll() throws ServiceException {
System.out.println(1);
List<News> news;
try {
news = newsDAO.all();
} catch (DAOException e) {
throw new ServiceException(e.getMessage(), e);
}
return news;
}
}
DAO layer
package myproject.dao.impl;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import myproject.dao.DAOException;
import myproject.dao.NewsDAO;
import myproject.entity.News;
#Repository
public class SQLNewsDAO implements NewsDAO {
// need to inject the session factory
#Autowired
private SessionFactory sessionFactory;
#Override
#Transactional
public List<News> all() throws DAOException {
System.out.println(2);
Session currentSession = sessionFactory.getCurrentSession();
Query<News> theQuery = currentSession.createQuery("from News where status =: active", News.class); /*"from News where status = 'active'"*/
List<News> news = theQuery.getResultList();
return news;
}
}
ApplicationContext
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- Step 3: Add support for component scanning -->
<context:component-scan base-package="myproject" />
<!-- Step 4: Add support for conversion, formatting and validation support -->
<mvc:annotation-driven />
<!-- Step 5: Define Spring MVC view resolver -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- Step 6 Add support for reading web resources: css, images, js, etc
... -->
<mvc:resources location="/resources/"
mapping="/resources/**" />
<bean
class="org.springframework.context.support.ResourceBundleMessageSource"
id="messageSource">
<property value="resources/messages" name="basenames" />
</bean>
<!-- Step 7 Define Database DataSource / connection pool -->
<bean id="myDataSource"
class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl"
value="jdbc:mysql://localhost:3306/news_management_spring_hibernate?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC" />
<property name="user" value="111" />
<property name="password" value="111" />
<!-- these are connection pool properties for C3P0 -->
<property name="minPoolSize" value="5" />
<property name="maxPoolSize" value="20" />
<property name="maxIdleTime" value="30000" />
</bean>
<!-- Step 8 Setup Hibernate session factory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="packagesToScan" value="src.main.java.myproject.entity" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- Step 9 Setup Hibernate transaction manager -->
<bean id="myTransactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- Step 10 Enable configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="myTransactionManager" />
</beans>
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>by.htp.spring.main</groupId>
<artifactId>spring-myproject</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>spring-myproject Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- Generic properties -->
<maven.compiler.release>1.8</maven.compiler.release>
<!-- Web -->
<jsp.version>2.2</jsp.version>
<jstl.version>1.2</jstl.version>
<servlet.version>3.1.0</servlet.version>
<!-- Spring -->
<spring-framework.version>5.0.19.RELEASE</spring-framework.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<!-- BD -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
<version>8.0.23</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.10.Final</version>
</dependency>
<!-- Dependency Spring Framework -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-taglibs -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- Other -->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.14.1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.14.1</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.2.8</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.3.0.1</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.0.1</version>
</dependency>
<dependency>
<groupId>com.sun.activation</groupId>
<artifactId>javax.activation</artifactId>
<version>1.2.0</version>
</dependency>
<dependency>
<groupId>org.mindrot</groupId>
<artifactId>jbcrypt</artifactId>
<version>0.4</version>
</dependency>
<!-- New depend -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>5.4.26.Final</version>
</dependency>
</dependencies>
<build>
<finalName>spring-myproject</finalName>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<url>http://localhost:8080/manager/text</url>
<server>tomcat-server</server>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>${project.build.sourceEncoding}</encoding>
<showWarnings>true</showWarnings>
<showDeprecation>true</showDeprecation>
</configuration>
</plugin>
</plugins>
</build>
</project>
main_index_page.jsp (view)
<!--News-->
<div class="list_news">
<c:forEach var="AllNewsFromBD" items="${news}"> <!--requestScope.-->
<div class="list_news_block">
<div class="">
<h5 class="title_news">
<c:out value="${AllNewsFromBD.title}" />
</h5>
<p class="">
<c:out value="${AllNewsFromBD.brief}" />
</p>
<c:if test="${sessionScope.auth == true}">
<div class="">
<a href="Controller?command=go_to_one_news_page&idnews=<c:out value="${AllNewsFromBD.idnews}"/>">
<c:out value="${ReadMore}" /></a>
</div>
</c:if>
<br/>
</div>
</div>
</c:forEach>
</div>
There are lot of posts on stackoverflow in which addressing the same issue. But I was unable to find a definite solution for this.
Please help
You could try this:
Query<News> theQuery = currentSession.createQuery("select news from News news where news.status = :active", News.class);
theQuery.setParameter("status", active);
return theQuery.getResultList();

Hibernate Session null-pointer exception

I have been stuck with this issue for days cannot figure it out, I mean I know the sessionFactory must be null as the stacktrace indicates but I cannot understand why? The exception always comes back to the line:
Session session = hibernateUtil.getSessionFactory().getCurrentSession();
Here is a trimmed version of the stacktrace:
DEBUG - Creating new transaction with name [com.sga.app.dao.DisplayStatsDAO$$EnhancerBySpringCGLIB$$f03b1e71.getForename]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
DEBUG - Acquired Connection [jdbc:oracle:thin:system/system#localhost:1521/XE, UserName=SYSTEM, Oracle JDBC driver] for JDBC transaction
DEBUG - Switching JDBC Connection [jdbc:oracle:thin:system/system#localhost:1521/XE, UserName=SYSTEM, Oracle JDBC driver] to manual commit
DEBUG - Returning cached instance of singleton bean 'sessionFactory'
DEBUG - Initiating transaction rollback
DEBUG - Rolling back JDBC transaction on Connection [jdbc:oracle:thin:system/system#localhost:1521/XE, UserName=SYSTEM, Oracle JDBC driver]
DEBUG - Releasing JDBC Connection [jdbc:oracle:thin:system/system#localhost:1521/XE, UserName=SYSTEM, Oracle JDBC driver] after transaction
DEBUG - Returning JDBC Connection to DataSource
DEBUG - Invoking afterPropertiesSet() on bean with name 'error'
DEBUG - Rendering view [org.springframework.web.servlet.view.JstlView: name 'error'; URL [/WEB-INF/jsps/error.jsp]] in DispatcherServlet with name 'dispatcher'
DEBUG - Added model object 'userBean' of type [com.sga.app.beans.UserBean] to request in view with name 'error'
DEBUG - Added model object 'org.springframework.validation.BindingResult.userBean' of type [org.springframework.validation.BeanPropertyBindingResult] to request in view with name 'error'
DEBUG - Added model object 'displayStatsDAO' of type [com.sga.app.dao.DisplayStatsDAO] to request in view with name 'error'
DEBUG - Added model object 'org.springframework.validation.BindingResult.displayStatsDAO' of type [org.springframework.validation.BeanPropertyBindingResult] to request in view with name 'error'
DEBUG - Added model object 'username' of type [java.lang.String] to request in view with name 'error'
DEBUG - Forwarding to resource [/WEB-INF/jsps/error.jsp] in InternalResourceView 'error'
java.lang.NullPointerException
at com.sga.app.dao.DisplayStatsDAO.getForename(DisplayStatsDAO.java:66)
at com.sga.app.dao.DisplayStatsDAO$$FastClassBySpringCGLIB$$52d44a3e.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
And my DAO:
package com.sga.app.dao;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.sga.app.beans.UserBean;
import com.sga.app.hibernate.HibernateUtil;
#Component("displayStatsDAO")
#Repository
#Transactional
#Configuration
public class DisplayStatsDAO extends HttpServlet implements Serializable {
private static final long serialVersionUID = 1L;
public static final String TEST = "testing";
public String string = TEST;
public String example = "example String";
public String forename;
public Session session;
private HibernateUtil hibernateUtil;
#Bean
public DisplayStatsDAO displayStatsDAO() {
return new DisplayStatsDAO();
}
public DisplayStatsDAO() {
}
#Transactional
public String getForename() {
#SuppressWarnings("rawtypes")
ArrayList result = new ArrayList();
String returnValue = "";
Session session = hibernateUtil.getSessionFactory().getCurrentSession();
if (session == null) {
System.out.println("NULL SESSION");
} else {
try {
session.beginTransaction();
Authentication authentication = SecurityContextHolder
.getContext().getAuthentication();
String userLoggedIn = authentication.getName();
System.out.println("SESSION IS ACTIVE");
System.out.println(userLoggedIn);
Criteria criteria = session.createCriteria(UserBean.class);
criteria.add(Restrictions.like("username", userLoggedIn));
List<UserBean> user = (List<UserBean>) criteria.list();
session.getTransaction().commit();
for (UserBean userDetails : user) {
result.add(userDetails.getForename());
returnValue = userDetails.getForename().toString();
}
} catch (HibernateException e) {
e.printStackTrace();
}
System.out.println("Return value is " + returnValue);
}
return returnValue;
}
public Session getSession() {
return session;
}
public void setSession(Session session) {
this.session = session;
}
public String getLoggedInUserName() {
Authentication authentication = SecurityContextHolder.getContext()
.getAuthentication();
String userLoggedIn = authentication.getName();
return userLoggedIn;
}
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.getRequestDispatcher("userstats.jsp").forward(req, resp);
}
}
hibernate.cfg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="hibernate.connection.driver_class">
oracle.jdbc.OracleDriver
</property>
<property name="hibernate.connection.url">
jdbc:oracle:thin:system/system#localhost:1521/XE
</property>
<property name="hibernate.connection.username">system</property>
<property name="hibernate.connection.password">password</property>
<!-- Oracle dialect declaration -->
<property name="hibernate.dialect">
org.hibernate.dialect.Oracle10gDialect
</property>
<property name="show_sql">true</property>
<mapping resource="com/sga/app/xml/sga.hbm.xml"></mapping>
</session-factory>
</hibernate-configuration>
HibernateUtil.java:
package com.sga.app.hibernate;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class HibernateUtil {
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;
public HibernateUtil() {
sessionFactory = createSessionFactory();
}
public SessionFactory getSessionFactory() {
return HibernateUtil.sessionFactory;
}
private static SessionFactory createSessionFactory() {
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
serviceRegistry = new ServiceRegistryBuilder().applySettings(
configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
}
}
Pom.xml:
<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>SgaWebApp</groupId>
<artifactId>SgaWebApp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.0.0.GA</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.2.0.Final</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-validator</groupId>
<artifactId>commons-validator</artifactId>
<version>1.4.1</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>3.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>3.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>3.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.1.4.Final</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.4</version>
</dependency>
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.12.1.GA</version>
</dependency>
</dependencies>
</project>
app.hbm.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD
3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.sga.app.beans.UserBean" table="USERS">
<id name="username" type="varchar">
<column name="USERNAME"></column>
</id>
<property name="roundScore" type="int">
<column name="ROUNDSCORE"></column>
</property>
<property name="fairways_hit" type="int">
<column name="FAIRWAYS_HIT"></column>
</property>
<property name="gir" type="int">
<column name="GIR"></column>
</property>
<property name="sand_saves" type="int">
<column name="SAND_SAVES"></column>
</property>
<property name="putts" type="int">
<column name="PUTTS"></column>
</property>
</class>
</hibernate-mapping>
userstats.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql"%>
<%# taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>
<%# taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link href="${pageContext.request.contextPath}/static/css/main.css"
rel="stylesheet" type="text/css">
<title>SGA-user stats</title>
</head>
<body>
</div>
<br />
<!-- Logout option -->
<div id="logoutOptionDiv" align="right">
<a id="logoutOption" style="color: blue;"
href='<c:url value="/j_spring_security_logout"></c:url>'>Logout</a>
</div>
<br />
<h2 class="displayStatsLeaderboardHeader">Your stats</h2>
<table class="displayStatsTable" border="1">
<tr>
<td>Username</td>
<td>Forename</td>
<td>Surname</td>
</tr>
<tr>
<td class="displayStatsTableData">${stats}</td>
<td class="displayStatsTableData">${stats.string}</td>
<td class="displayStatsTableData">${stats.example}</td>
</tr>
</table>
</body>
</html>
Your hibernateUtil field is null. In fact, why did you introduce an instance field for that? Nothing is injected into it and you call a instance method on this null field. Make the method static as:
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
and then :
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
Try This :-
Replace your HibernateUtil class with this one:-
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
and you should also try
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionfactory.openSession();
instead of
Session session = hibernateUtil.getSessionFactory().getCurrentSession();
I hope it will work,.
Updated
#Autowired
private HibernateUtil hibernateUtil;
The null-pointer exception was eradicated when I changed the line:
Session session = hibernateUtil.getSessionFactory().getCurrentSession();
to:
session = HibernateUtil.createSessionFactory().openSession();
I thought the problem was that I was originally attempting to get a session that was currently closed but I'd have expected to receive the 'session is closed!' message that I've seen previously? Anyway the null-pointer exception has been resolved.
(the code within the createSessionFactory() method in HibernateUtil was not changed)

Spring MVC 4.1.x RestFul Service throwing Not Acceptable for Json

I have made a Rest Service using Spring MVC4.1.X, but whenever I try to return Json o/p to browser iam getting the following error
The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers.
Iam using #Response body for auto conversion of a Java pojo into JSON objects. I have tried almost all the solution given on stackoverflow .
my controller class
package com.spring.rest.ambulance;
import java.io.IOException;
import net.sf.json.JSONObject;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.spring.dao.AmbulanceDAO;
import com.spring.dao.AmbulanceDAOImpl;
import com.spring.model.Ambulance;
#RestController
#RequestMapping("/Ambulance")
public class AmbulanceRestController {
#Autowired
private AmbulanceDAO ambulanceDAO;
#RequestMapping(value = "/hello", method = RequestMethod.GET)
public #ResponseBody String getAllUsers(ModelMap model) {
String jsonData = "[{\"id\":\"3253123\",\"firstname\":\"Chris\",\"lastname\":\"Johnson\",\"address\":\"211, Geoffrey Drive\",\"city\":\"Newark\",\"phone\":\"999-888-6666\",\"email\":\"chrisj#yahoo.com\"},{\"id\":\"67643837\",\"firstname\":\"Bill\",\"lastname\":\"Derkson\",\"address\":\"201, Sleepy Hollow Drive\",\"city\":\"Newark\",\"phone\":\"999-777-2222\",\"email\":\"billd#gmail.com\"}]";
return jsonData;
}
#RequestMapping(value = "/{id}")
public #ResponseBody Ambulance getAmbulanceProviders(ModelMap model,
#PathVariable("id") int Id) {
String jsonData = null ;
Ambulance ambulance = ambulanceDAO.getById(Id);
ObjectMapper objmapper = new ObjectMapper();
try {
jsonData = objmapper.writeValueAsString(ambulance);
//System.out.println(objmapper.writeValueAsString(ambulance));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ambulance;
}
Entity being returned
package com.spring.model;
import org.codehaus.jackson.map.ObjectMapper;
public class Ambulance {
private int ID;
private String vehicleNumber;
private String ambulanceType;
private String ambulanceProviderName;
/**
* #return the iD
*/
public int getID() {
return ID;
}
/**
* #param iD
* the iD to set
*/
public void setID(int iD) {
ID = iD;
}
/**
* #return the vehicleNumber
*/
public String getVehicleNumber() {
return vehicleNumber;
}
/**
* #param vehicleNumber
* the vehicleNumber to set
*/
public void setVehicleNumber(String vehicleNumber) {
this.vehicleNumber = vehicleNumber;
}
/**
* #return the ambulanceType
*/
public String getAmbulanceType() {
return ambulanceType;
}
/**
* #param ambulanceType
* the ambulanceType to set
*/
public void setAmbulanceType(String ambulanceType) {
this.ambulanceType = ambulanceType;
}
/**
* #return the ambulanceProviderName
*/
public String getAmbulanceProviderName() {
return ambulanceProviderName;
}
/**
* #param ambulanceProviderName
* the ambulanceProviderName to set
*/
public void setAmbulanceProviderName(String ambulanceProviderName) {
this.ambulanceProviderName = ambulanceProviderName;
}
#Override
public String toString() {
return "{ID="+ID+",AmbulanceProvderName="+ambulanceProviderName+",AmbulanceType="+ambulanceType+",VehicleNumber="+vehicleNumber+"}";
}
}
DAO Ambulance get by Id
public Ambulance getById(int id) {
// TODO Auto-generated method stub
Ambulance ambulance = new Ambulance();
/* JdbcTemplate jdbcTemplate = new JdbcTemplate();
System.out.println(dataSource);
jdbcTemplate.setDataSource(dataSource);*/
System.out.println(jdbcTemplate.getDataSource());
String sql = "SELECT * FROM AMBULANCE WHERE AMBULANCEID = ?";
ambulance = (Ambulance)jdbcTemplate.queryForObject(sql,new Object[] { id }, new AmbulanceRowMapper());
return ambulance;
}
pom.xml
<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>SpringWebAppRestServices</groupId>
<artifactId>SpringWebAppRestServices</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.8.5</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.3</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
</project>
Originally this issue occurs when the request sends an accept header that differs from the response's content-type. I don't know if this is the case, there's not enough source provided.
However, another a bit more trickier situation when the same error occurs is when the framework is not able to convert the response to an appropriate representation, e.g. on account of bad getters/setters or missing dependencies.
In the code you posted I see an issue with your dependencies. Spring 4.1 needs minimum Jackson 2.1, and in the version Jackson 2 and above a package change occurred from codehaus to fasterxml. Replace the two of your Jackson dependencies with the following one
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.1.2</version>
</dependency>
or better yet go for a newer version. Single dependency is enough it will transitively pull com.fasterxml.jackson.core:jackson-annotations:jar and com.fasterxml.jackson.core:jackson-core:jar
I think you might have to ensure that your Request is having the following in your header:
GET
Accept: application/json

Filetype conversion using apache camel from csv to xml

I am trying to convert a csv file into xml file using apache camel i am facing problem in mar shalling and unmarshalling ....The code of this program is ......
package com.mycompany.camel.java;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import org.apache.camel.dataformat.bindy.annotation.CsvRecord;
import org.apache.camel.dataformat.bindy.annotation.DataField;
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
#CsvRecord(separator = ",", skipFirstLine = true)
public class EmployeeDTO implements Serializable{
#XmlAttribute
#DataField(pos = 1)
private int employeeId;
#XmlAttribute
#DataField(pos = 2)
private String firstName;
#XmlAttribute
#DataField(pos = 3)
private String lastName;
#XmlAttribute
#DataField(pos = 4)
private String role;
}
package com.mycompany.camel.java;
import org.apache.camel.CamelContext;
import org.apache.camel.RoutesBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.dataformat.bindy.csv.BindyCsvDataFormat;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.spi.DataFormat;
public class ConvertorRoute implements RoutesBuilder{
#Override
public void addRoutesToCamelContext(CamelContext context) throws Exception {
context.addRoutes(new RouteBuilder() {
public void configure() {
try {
DataFormat bindy = new BindyCsvDataFormat("com.mycompany.camel.java");
from("file://C:/Users/rahul/Desktop/Employee.csv").
unmarshal(bindy).
marshal().
xstream().
to("file://C:/Users/rahul/Desktop/employee.xml");
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public static void main(String[] args) {
try{
CamelContext context = new DefaultCamelContext();
ConvertorRoute route = new ConvertorRoute();
route.addRoutesToCamelContext(context);
context.start();
Thread.sleep(5000);
context.stop();
}catch(Exception exe){
exe.printStackTrace();
}
}
}
Error i am facing is:
org.apache.camel.FailedToCreateRouteException: Failed to create route route1 at: >>> Marshal[org.apache.camel.model.dataformat.XStreamDataFormat#1aa9f99] <<< in route: Route[[From[file://C:/Users/JaHnAvI/Desktop?fileName=Employe... because of Data format 'xstream' could not be created. Ensure that the data format is valid and the associated Camel component is present on the classpath
at org.apache.camel.model.RouteDefinition.addRoutes(RouteDefinition.java:879)
at org.apache.camel.model.RouteDefinition.addRoutes(RouteDefinition.java:172)
at org.apache.camel.impl.DefaultCamelContext.startRoute(DefaultCamelContext.java:722)
at org.apache.camel.impl.DefaultCamelContext.startRouteDefinitions(DefaultCamelContext.java:1789)
at org.apache.camel.impl.DefaultCamelContext.doStartCamel(DefaultCamelContext.java:1575)
at org.apache.camel.impl.DefaultCamelContext.doStart(DefaultCamelContext.java:1444)
at org.apache.camel.support.ServiceSupport.start(ServiceSupport.java:60)
at org.apache.camel.impl.DefaultCamelContext.start(DefaultCamelContext.java:1412)
at com.mycompany.camel.java.ConvertorRoute.main(ConvertorRoute.java:36)
Caused by: java.lang.IllegalArgumentException: Data format 'xstream' could not be created. Ensure that the data format is valid and the associated Camel component is present on the classpath
at org.apache.camel.model.DataFormatDefinition.getDataFormat(DataFormatDefinition.java:89)
at org.apache.camel.model.DataFormatDefinition.getDataFormat(DataFormatDefinition.java:79)
at org.apache.camel.model.MarshalDefinition.createProcessor(MarshalDefinition.java:150)
at org.apache.camel.model.ProcessorDefinition.makeProcessor(ProcessorDefinition.java:461)
at org.apache.camel.model.ProcessorDefinition.addRoutes(ProcessorDefinition.java:179)
at org.apache.camel.model.RouteDefinition.addRoutes(RouteDefinition.java:876)
... 8 more
org.apache.camel.FailedToCreateRouteException: Failed to create route route1 at: >>> Marshal[org.apache.camel.model.dataformat.XStreamDataFormat#1aa9f99] <<< in route: Route[[From[file://C:/Users/JaHnAvI/Desktop?fileName=Employe... because of Data format 'xstream' could not be created. Ensure that the data format is valid and the associated Camel component is present on the classpath
at org.apache.camel.model.RouteDefinition.addRoutes(RouteDefinition.java:879)
at org.apache.camel.model.RouteDefinition.addRoutes(RouteDefinition.java:172)
at org.apache.camel.impl.DefaultCamelContext.startRoute(DefaultCamelContext.java:722)
at org.apache.camel.impl.DefaultCamelContext.startRouteDefinitions(DefaultCamelContext.java:1789)
at org.apache.camel.impl.DefaultCamelContext.doStartCamel(DefaultCamelContext.java:1575)
at org.apache.camel.impl.DefaultCamelContext.doStart(DefaultCamelContext.java:1444)
at org.apache.camel.support.ServiceSupport.start(ServiceSupport.java:60)
at org.apache.camel.impl.DefaultCamelContext.start(DefaultCamelContext.java:1412)
at com.mycompany.camel.java.ConvertorRoute.main(ConvertorRoute.java:36)
Caused by: java.lang.IllegalArgumentException: Data format 'xstream' could not be created. Ensure that the data format is valid and the associated Camel component is present on the classpath
at org.apache.camel.model.DataFormatDefinition.getDataFormat(DataFormatDefinition.java:89)
at org.apache.camel.model.DataFormatDefinition.getDataFormat(DataFormatDefinition.java:79)
at org.apache.camel.model.MarshalDefinition.createProcessor(MarshalDefinition.java:150)
at org.apache.camel.model.ProcessorDefinition.makeProcessor(ProcessorDefinition.java:461)
at org.apache.camel.model.ProcessorDefinition.addRoutes(ProcessorDefinition.java:179)
at org.apache.camel.model.RouteDefinition.addRoutes(RouteDefinition.java:876)
... 8 more
Please help me in fixing this error.....
Thanks in advance.....
I tested same example in my local machine with the following dependencies.
file paths are not correct if you are running it in windows.
check the code below.
pom.xml
<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>CamelBasic</groupId>
<artifactId>CamelBasic</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<camel-version>2.12.0</camel-version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-core</artifactId>
<version>${camel-version}</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-csv</artifactId>
<version>${camel-version}</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-xstream</artifactId>
<version>${camel-version}</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>14.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-bindy</artifactId>
<version>${camel-version}</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
path example:
file:D:\CamelTestData\csvDir?fileName=input.csv
It worked for me.
Did you include the dependency for Xstream in your maven file? If you are using maven please add the following to your project file:
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-xstream</artifactId>
<version>x.x.x</version>
<!-- use the same version as your Camel core version -->
</dependency>
The error clearly states you are missing a component

Categories