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)
Related
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();
Hello i am trying to implement swagger with Spring REST, i am not using Spring Boot to create REST API's, i have used normal Spring REST API.
The problem when i run the application and if i navigate to this url
http://localhost:8080/spring-mvc-restfull-crud-example/swagger-ui.html
i am getting only the header of swagger-ui, there is nothing else. I am using Java config instead of XML config.
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>com.boraji.tutorial.spring</groupId>
<artifactId>spring-mvc-restfull-crud-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<failOnMissingWebXml>false</failOnMissingWebXml>
</properties>
<dependencies>
<!-- Spring MVC Dependency -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<!-- Spring ORM -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<!-- Hibernate ORM -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.11.Final</version>
</dependency>
<!-- Hibernate-C3P0 Integration -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>5.2.11.Final</version>
</dependency>
<!-- c3p0 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!-- Mysql Connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.5</version>
</dependency>
<!-- Jackson API for JSON -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.7</version>
</dependency>
<!-- Servlet Dependency -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- this is for integrating swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-data-rest</artifactId>
<version>2.6.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<!-- Embedded Apache Tomcat required for testing web application -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<path>/</path>
</configuration>
</plugin>
</plugins>
</build>
WebConfig.java
package com.boraji.tutorial.spring.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import com.google.common.base.Predicates;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = { "com.boraji.tutorial.spring.controller" })
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
BookController.java
package com.boraji.tutorial.spring.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
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.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.boraji.tutorial.spring.model.Book;
import com.boraji.tutorial.spring.service.BookService;
import io.swagger.annotations.Api;
#CrossOrigin(origins = "*")
#RestController
public class BookController {
#Autowired
private BookService bookService;
/*---Add new book---*/
#PostMapping("/book")
public ResponseEntity<?> save(#RequestBody Book book) {
long id = bookService.save(book);
return ResponseEntity.ok().body("New Book has been saved with ID:" + id);
}
/*---Get a book by id---*/
#GetMapping("/book/{id}")
public ResponseEntity<Book> get(#PathVariable("id") long id) {
Book book = bookService.get(id);
return ResponseEntity.ok().body(book);
}
/*---get all books---*/
#GetMapping("/book")
public ResponseEntity<List<Book>> list() {
List<Book> books = bookService.list();
return ResponseEntity.ok().body(books);
}
/*---Update a book by id---*/
#PutMapping("/book/{id}")
public ResponseEntity<?> update(#PathVariable("id") long id, #RequestBody Book book) {
bookService.update(id, book);
return ResponseEntity.ok().body("Book has been updated successfully.");
}
/*---Delete a book by id---*/
#DeleteMapping("/book/{id}")
public ResponseEntity<?> delete(#PathVariable("id") long id) {
bookService.delete(id);
return ResponseEntity.ok().body("Book has been deleted successfully.");
}
}
In the resources folder, i have db.properties file
# MySQL properties
mysql.driver=com.mysql.cj.jdbc.Driver
mysql.url=jdbc:mysql://localhost:3306/bookdb
mysql.user=root
mysql.password=root
# Hibernate properties
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update
#C3P0 properties
hibernate.c3p0.min_size=5
hibernate.c3p0.max_size=20
hibernate.c3p0.acquire_increment=1
hibernate.c3p0.timeout=1800
hibernate.c3p0.max_statements=150
MyWebAppInitializer.java
package com.boraji.tutorial.spring.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { AppConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { WebConfig.class };
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
can you please anyone help me that what is wrong in this? is there anything that i need to add?
You have not defined Docket bean and neither you have used the #EnableSwagger2
The configuration of Swagger mainly centers around the Docket bean. Swagger 2 is enabled through the #EnableSwagger2 annotation. Refer the below code.
#Configuration
#EnableSwagger2
public class SwaggerConfig {
#Bean
public Docket customImplementation() {
return new Docket(DocumentationType.SWAGGER_2).pathMapping("/data").apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfo("ISW ADR Application",
"ADR or is another business line within the Issuer services business group."
+ "The primary functionalities of ADR are maintained within the DR system (mainframe) "
+ "Four main functionalities that are imported : "
+" 1) Dividend Announcements"
+ " 2) Depositary Service fees"
+ " 3) DR Fees"
+ " 4) DR Gross revenue.",
"ADR V2", "Terms of service", "xyz", "License of API", "API license URL");
}
}
You have not enabled swagger using #EnableSwagger2 and also have not returned a Docket Bean. Refer this.
#Configuration
#EnableSwagger2
public class SwaggerConfig {
#Bean
public Docket demoApi() {
return new Docket(DocumentationType.SWAGGER_2).select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo"))
.paths(PathSelectors.regex("/person.*")).build();
}
}
Before it work but now it is not working.And previously when it worked i use to get session Null in CrediCarddao.java for updating the customer status and inserting new creditcard record into database.
Apr 14, 2017 9:32:36 AM org.springframework.context.support.FileSystemXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.FileSystemXmlApplicationContext#68de145: startup date [Fri Apr 14 09:32:36 CDT 2017]; root of context hierarchy
Apr 14, 2017 9:32:36 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from file [C:\BCJ_DEC_2016\workspace\CoreJava\creditcardprocess\spring.xml]
Apr 14, 2017 9:32:37 AM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter initControllerAdviceCache
INFO: Looking for #ControllerAdvice: org.springframework.context.support.FileSystemXmlApplicationContext#68de145: startup date [Fri Apr 14 09:32:36 CDT 2017]; root of context hierarchy
Apr 14, 2017 9:32:37 AM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter initControllerAdviceCache
INFO: Looking for #ControllerAdvice: org.springframework.context.support.FileSystemXmlApplicationContext#68de145: startup date [Fri Apr 14 09:32:36 CDT 2017]; root of context hierarchy
Apr 14, 2017 9:32:37 AM org.springframework.context.support.FileSystemXmlApplicationContext refresh
WARNING: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'creditCardDao' defined in file [C:\BCJ_DEC_2016\workspace\CoreJava\creditcardprocess\target\classes\com\bcj\creditcardprocess\dao\CreditCardDao.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.bcj.creditcardprocess.dao.CreditCardDao]: Constructor threw exception; nested exception is java.lang.NullPointerException
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'creditCardDao' defined in file [C:\BCJ_DEC_2016\workspace\CoreJava\creditcardprocess\target\classes\com\bcj\creditcardprocess\dao\CreditCardDao.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.bcj.creditcardprocess.dao.CreditCardDao]: Constructor threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1155)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1099)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
at org.springframework.context.support.FileSystemXmlApplicationContext.(FileSystemXmlApplicationContext.java:140)
at org.springframework.context.support.FileSystemXmlApplicationContext.(FileSystemXmlApplicationContext.java:84)
at com.bcj.creditcardprocess.CreditCardMain.main(CreditCardMain.java:15)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.bcj.creditcardprocess.dao.CreditCardDao]: Constructor threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:154)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:89)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1147)
... 13 more
Caused by: java.lang.NullPointerException
at com.bcj.creditcardprocess.dao.CreditCardDao.(CreditCardDao.java:22)
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:423)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:142)
... 15 more
CreditCardMain.java*
package com.bcj.creditcardprocess;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import com.bcj.creditcardprocess.service.CreditCardService;
public class CreditCardMain {
public static void main(String[] args) {
#SuppressWarnings("resource")
ApplicationContext context = new FileSystemXmlApplicationContext("spring.xml");
CreditCardService obj = (CreditCardService) context.getBean("cCardService");
//CreditCardService cCardService = new CreditCardService();
obj.processCreditCard();
}
}
CreditCardService.java
package com.bcj.creditcardprocess.service;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.bcj.creditcardprocess.dao.CreditCardDao;
import com.bcj.creditcardprocess.model.Customer;
#Service
public class CreditCardService {
#Autowired
private CreditCardDao cCardDao;
public void setcCardDao(CreditCardDao cCardDao) {
this.cCardDao = cCardDao;
}
public void processCreditCard() {
List<Customer> customerList = cCardDao.getCustomerList();
// creating a pool of 5 threads
ExecutorService executor = Executors.newFixedThreadPool(5);
for (Iterator iterator = customerList.iterator(); iterator.hasNext();) {
Customer cust = (Customer) iterator.next();
System.out.println(cust);
WorkerThread thread = new WorkerThread();
thread.threadmain(customerList);
//Runnable worker = new WorkerThread(cust);
// calling execute method of ExecutorService
//executor.execute(worker);
/*WorkerThread thread = new WorkerThread();
thread.threadmain(customerList);
}
executor.shutdown();
while (!executor.isTerminated()) {
}
System.out.println("Finished all threads");*/
/*
* List<Object> result = (List<Object>) customerList; Iterator itr =
* result.iterator(); while(itr.hasNext()){ Object[] obj = (Object[])
* itr.next();
*
* System.out.println(String.valueOf(obj[0])+" "+String.valueOf(obj[1]
* ));
*
*/
/*
* for (int i = 0; i < 10; i++) { Runnable worker = new WorkerThread(obj
* ); executor.execute(worker);//calling execute method of
* ExecutorService }
*/
/*executor.shutdown();
while (!executor.isTerminated()) {
}
System.out.println("Finished all threads");*/
}
}
}
WorkerThread.java
package com.bcj.creditcardprocess.service;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.bcj.creditcardprocess.dao.CreditCardDao;
import com.bcj.creditcardprocess.model.CreditCard;
import com.bcj.creditcardprocess.model.Customer;
#Service
public class WorkerThread implements Runnable {
#Autowired
private CreditCardDao cCardDao;
public void setcCardDao(CreditCardDao cCardDao) {
this.cCardDao = cCardDao;
}
public WorkerThread() {
}
WorkerThread(Customer cust2) {
this.cust = cust2;
}
Customer cust;
public void run() {
System.out.println(Thread.currentThread().getName() + " (Start) message = " + cust.getFirstName());
try {
getCutomerDetailsByTextFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " (End)");
}
public synchronized void getCutomerDetailsByTextFile() throws IOException {
FileReader fr = new FileReader("details.txt");
BufferedReader br = new BufferedReader(fr);
String line = "";
while ((line = br.readLine()) != null) {
System.out.println(line);
String[] details = line.split(" ");
if (details[0].equalsIgnoreCase(cust.getFirstName()) && details[1].equalsIgnoreCase(cust.getLastName())
&& details[2].equals(cust.getSsn())) {
System.out.println(" ssn had");
if (Integer.parseInt(details[3]) > 700 && Integer.parseInt(cust.getAnnualIncome()) > 100000) {
CreditCard card = new CreditCard();
card.setCreditLimit(5000);
card.setCustomerId(cust.getId());
generateCardNumber(card, cust);
cust.setStatus("Approved");
} else if (Integer.parseInt(details[3]) > 600 && Integer.parseInt(details[3]) < 700
&& Integer.parseInt(cust.getAnnualIncome()) > 70000) {
CreditCard card = new CreditCard();
card.setCreditLimit(3000);
card.setCustomerId(cust.getId());
generateCardNumber(card, cust);
cust.setStatus("Approved");
} else {
cCardDao.updateCustomer(cust);
cust.setStatus("Declined");
}
break;
}
}
}
public void threadmain(List<Customer> customerList) {
ExecutorService executor = Executors.newFixedThreadPool(5);
for (Iterator iterator = customerList.iterator(); iterator.hasNext();) {
Customer cust = (Customer) iterator.next();
Runnable worker = new WorkerThread(cust);
executor.execute(worker);// calling execute method of
// ExecutorService
}
executor.shutdown();
while (!executor.isTerminated()) {
}
System.out.println("Finished all threads");
}
private void generateCardNumber(CreditCard cCard, Customer cust) {
Random rand = new Random();
String cardNumber = Integer.toString(rand.nextInt(9999) + 1000) + Integer.toString(rand.nextInt(9999) + 1000)
+ Integer.toString(rand.nextInt(9999) + 1000) + Integer.toString(rand.nextInt(9999) + 1000);
String cvv = Integer.toString(rand.nextInt(999) + 100);
Calendar cal = Calendar.getInstance();
Date today = cal.getTime();
cal.add(Calendar.YEAR, 3); // to get previous year add -1
Date next = cal.getTime();
SimpleDateFormat adf = new SimpleDateFormat("MM/YY");
String expiryDate = adf.format(next);
cCard.setCardNumber(cardNumber);
cCard.setCvv(cvv);
cCard.setExpiryDate(expiryDate);
cCardDao.persistCreditCard(cCard, cust);
}
}
CreditCardDao.java
package com.bcj.creditcardprocess.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.bcj.creditcardprocess.model.CreditCard;
import com.bcj.creditcardprocess.model.Customer;
#Repository
#Transactional
public class CreditCardDao {
#Autowired
private SessionFactory sessionFactory;
private Session session = sessionFactory.getCurrentSession();
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
// Session session = sessionFactory.getCurrentSession();
List<Customer> custs;
public List<Customer> getCustomerList() {
Transaction tx = session.beginTransaction();
List custs = session.createQuery("FROM Customer WHERE status='New'").list();
return custs;
}
public void persistCreditCard(CreditCard cCard, Customer cust) {
int x = cCard.getCustomerId();
Session session = sessionFactory.getCurrentSession();
Transaction tx = session.beginTransaction();
session.persist(cCard);
session.update(cust);
System.out.println("customer saved sucessfully" + cCard);
}
public void updateCustomer(Customer cust) {
Session session = sessionFactory.getCurrentSession();
Transaction tx = session.beginTransaction();
session.update(cust);
}
}
Spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<mvc:annotation-driven />
<context:component-scan base-package="com.bcj.creditcardprocess" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/views/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="cCardService" class="com.bcj.creditcardprocess.service.CreditCardService" />
<bean id="cCardDao" class="com.bcj.creditcardprocess.dao.CreditCardDao" />
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/citibank" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<!--Hibernate 4 SessionFactory Bean definition -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.bcj.creditcardprocess.model.CreditCard</value>
<value>com.bcj.creditcardprocess.model.Customer</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect
</prop>
<prop key="hibernate.hbm2ddl.auto">update
</prop>
<prop key="hibernate.show_sql">true</prop>
<!-- <prop key="hibernate.current_session_context_class">thread</prop> -->
</props>
</property>
</bean>
</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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.bcj</groupId>
<artifactId>creditcardprocess</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>creditcardprocess</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.3.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
</dependencies>
</project>
Maybe try to change
private Session session = sessionFactory.getCurrentSession();
to a function
public Session getSession() {
return sessionFactory.getCurrentSession();
}
I am thinking during the class initialization, the class is trying initialize private Session session. And sessionFactory is not ready yet.
Your getSessionFactory() in CreditCardDao.java is throwing the nullPointerExceptionbecause You haven't initialized the SessionFactory so it's initialy pointing to null.
You would do that like this:
private SessionFactory sessionFactory=//build sessionfactory code
Note that the SessionFactoryshould be created once only, you can use the singleton design pattern for that.
Am struggling for last three days with the error "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/demomongo/templateapp/login. (Reason: CORS header 'Access-Control-Allow-Origin' missing)."
Here is my code kindly help.
Login.html
<html ng-app="LoginApp">
<body>
<script src="angular.min.js"></script>
<script src="LoginApp.js"> </script>
<div ng-controller="loginController as login">
Username <input type="text" ng-model="username" /><br/>
Password <input type="text" ng-model="password" /><br/>
<button ng-click="validate()">Validate</button>
</div>
<br/> Register Me/New user
</body>
</html>
LoginApp.js
(function(){
var app;
app=angular.module('LoginApp',[]);
app.controller('loginController',function($scope,$http){
var dataObj = {
"name" : "Java Honk",
"password" : "NY"
};
$scope.validate = function() {
dataObj.name=$scope.username;
dataObj.password=$scope.password;
//if($scope.username=="sam" && $scope.password=="pwd")
// console.log("password match");
// else
//console.log("username/pwd not matching");
$http.post('http://localhost:8080/demomongo/templateapp/login', dataObj)
.success(function(responseData) {
$scope.responseData = responseData;
console.log(responseData);
}).error(function(data, status, headers, config) {
alert( "Exception details: " + JSON.stringify({data: data}));
});
}
});
})();
CORSFilter:
CORSFilter.java
package com.demo.mongo.example.filter;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.filter.OncePerRequestFilter;
public class CORSFilter extends OncePerRequestFilter {
private static final Log LOG = LogFactory.getLog(CORSFilter.class);
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
response.addHeader("Access-Control-Allow-Origin", "*");
if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {
LOG.trace("Sending Header....");
// CORS "pre-flight" request
response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
// response.addHeader("Access-Control-Allow-Headers", "Authorization");
response.addHeader("Access-Control-Allow-Headers", "Content-Type");
response.addHeader("Access-Control-Max-Age", "1");
}
filterChain.doFilter(request, response);
}
}
Template Controller.java
//templatecontroller.java
package com.demo.mongo.example.controller;
import java.util.List;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;
import com.demo.mongo.example.model.UserDetails;
#RestController
#RequestMapping("/templateapp")
public class TemplateController {
#CrossOrigin
#RequestMapping(value="/login", method = RequestMethod.POST,consumes = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody String validateUser(#RequestBody UserDetails udata,UriComponentsBuilder ucBuilder) {
/*UserDetails obj=new UserDetails();
List<UserDetails> values=obj.UserDetails(udata.getName(),udata.getPassword());
if(values.size()>0){
return "welcome udata.getName";
}
else
{
return "please register using registration link";
}*/
if(udata.getName().equalsIgnoreCase("admin") && udata.getPassword().equalsIgnoreCase("admin"))
{
return "welcome admin";
}
else
{
return "password mismatch/not an admin";
}
}
#CrossOrigin
#RequestMapping(value="/addUser", method = RequestMethod.POST,consumes = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody String addUser(#RequestBody UserDetails udata,UriComponentsBuilder ucBuilder) {
return " new user details: name "+ udata.getName() + " Email Id " + udata.getEmailid() ;
}
}
UserDetails.Java
package com.demo.mongo.example.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document
public class UserDetails {
#Id
private String name;
private String password;
private String emailid;
private int contact;
public UserDetails(){}
public UserDetails(String name,String password,String emailid,int contact){
this.name=name;
this.password=password;
this.emailid=emailid;
this.contact=contact;
}
public void setName(String name){
this.name=name;
}
public void setPassword(String password){
this.password=password;
}
public void setEmailid(String emailid){
this.emailid=emailid;
}
public void setContact(int contact){
this.contact=contact;
}
public String getPassword(){
return this.password;
}
public String getName(){
return this.name;
}
public int getContact(){
return this.contact;
}
public String getEmailid(){
return this.emailid;
}
}
**dispatcher-servlet.xml**
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="com.demo.mongo.example" />
<mvc:annotation-driven />
<!-- Factory bean that creates the Mongo instance -->
<bean id="mongo" class="org.springframework.data.mongodb.core.MongoFactoryBean">
<property name="host" value="localhost" />
</bean>
<!-- MongoTemplate for connecting and querying the documents in the database -->
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongo" ref="mongo" />
<constructor-arg name="databaseName" value="test" />
</bean>
<!-- Use this post processor to translate any MongoExceptions thrown in #Repository annotated classes -->
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
web.xml
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
</context-param>
<!-- Add this to your web.xml to enable "CORS" -->
<filter>
<filter-name>cors</filter-name>
<filter-class>com.demo.mongo.example.filter.CORSFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>cors</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
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>com.demo.mongo.example</groupId>
<artifactId>demomongo</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>demomongo Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.7.1</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.1-1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>3.0-alpha-1</version>
</dependency>
</dependencies>
<build>
<finalName>demomongo</finalName>
</build>
</project>
please help to fix which i did wrong.
You set header "Access-Control-Allow-Origin" in filter. If the header is not appearing make sure it is chained. Debug or log it.
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.