I'm trying to set up a web application with tomcat 7.0, java6 and hibernate 4.
Basically, you can say I have the same problem as in this thread: java.lang.ClassNotFoundException: org.hibernate.HibernateException , but I'm not able to solve it. I have checked build path, and everything else I've been able to think of.
So, when trying to have the servlet use the hibernate objects, I get this error:
HTTP Status 500 - Error instantiating servlet class controller.ControlServlet
Stack trace:
java.lang.ClassNotFoundException: org.hibernate.HibernateException
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1714)
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559)
controller.SearchCommand.<init>(SearchCommand.java:25)
controller.ControlServlet.<init>(ControlServlet.java:31)
sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
java.lang.reflect.Constructor.newInstance(Unknown Source)
java.lang.Class.newInstance0(Unknown Source)
java.lang.Class.newInstance(Unknown Source)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
java.lang.Thread.run(Unknown Source)
SearchCommand:
public class SearchCommand implements Command{
private BookingDAO dao;
public SearchCommand(){
this.dao = new BookingDAO(); // line 25
}
ControlServlet:
public ControlServlet() {
super();
commands.put("search", new SearchCommand());
}
BookingDAO:
public class BookingDAO {
private SessionFactory factory;
public BookingDAO(){
try {
factory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public void getHotel(Booking booking, int hotelId){
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Hotel hotel = (Hotel) session.get(Hotel.class, hotelId);
booking.setHotel(hotel);
tx.commit();
} catch (HibernateException e) {
if (tx != null)
tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
Classpath:
http://i.stack.imgur.com/e1S2a.jpg
Can anyone help me?
Related
i'm new in java.
I'm trying to connect mysql DB in java
i've got this
mysql.java file:
package program;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class mysql {
private static final String DATABASE_DRIVER = "com.mysql.jdbc.Driver";
private static final String DATABASE_URL = "jdbc:mysql://mysql.cba.pl:3306/dbname";
private static final String USERNAME = "login";
private static final String PASSWORD = "pass";
private static final String MAX_POOL = "250";
private Connection connection;
private Properties properties;
private Properties getProperties() {
if (properties == null) {
properties = new Properties();
properties.setProperty("user", USERNAME);
properties.setProperty("password", PASSWORD);
properties.setProperty("MaxPooledStatements", MAX_POOL);
}
return properties;
}
public Connection connect() {
if (connection == null) {
try {
Class.forName(DATABASE_DRIVER);
connection = DriverManager.getConnection(DATABASE_URL, getProperties());
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
return connection;
}
public void disconnect() {
if (connection != null) {
try {
connection.close();
connection = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
main java file:
package program;
public class main {
public static void main(String[] args){
mysql db = new mysql();
db.connect();
}
}
and i'm getting following errors
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at komunikator.mysql.connect(mysql.java:31)
at komunikator.main.main(main.java:7)
I downloaded ojdbc6-11.2.0.2.0.jar and put in my project folder, after that i add library from jar file.
What i'm doing wrong ?
I'm really new in java so i hope somebody can help me as well :)
I'm using Eclipse Standard/SDK
Version: Kepler Release
Build id: 20130614-0229
ou need to use com.mysql.jdbc_5.1.5 driver for mysql connection and paste jar file in to WEB-INF>Lib folder and use the path of jar file into property>buildpath and use external jar.
it will be a normal desktop application
ok, i changed it on com.mysql.jdbc_5.1.5 driver, i paste this in project path with others .java files and added like u said in properties.
Now i'm getting this:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
Last packet sent to the server was 0 ms ago.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1074)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2104)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:729)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:46)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:302)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:283)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at program.mysql.connect(mysql.java:32)
at program.main.main(main.java:7)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:256)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:276)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2027)
... 13 more
Is mysql.java file correct ?
Edit:
i tried change this
private static final String DATABASE_DRIVER = "com.mysql.jdbc.Driver";
on
"com.mysql.jdbc_5.1.5.Driver"
and i am gettin some less errors
java.lang.ClassNotFoundException: com.mysql.jdbc_5.1.5.Driver
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at program.mysql.connect(mysql.java:31)
at program.main.main(main.java:7)
Ok, almost i've got this. One thing more.
When im trying connect to on-line DB i got this:
SQLException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
SQLState: 08S01
VendorError: 0
on localhost DB (xamp) it's working fine
what is going on ?
I am having a random problem that when performing the connection with informix the following error occurs:
java.sql.SQLException: System or internal error java.io.IOException
at com.informix.util.IfxErrMsg.getSQLException(Unknown Source)
at com.informix.jdbc.IfxSqli.handleSocketException(Unknown Source)
at com.informix.jdbc.IfxSqli.receiveMessage(Unknown `enter code here`Source)
at com.informix.jdbc.IfxSqli.executePrepare(Unknown Source)
at com.informix.jdbc.IfxPreparedStatement.setupExecutePrepare(Unknown Source)
at com.informix.jdbc.IfxPreparedStatement.processSQL(Unknown Source)
at com.informix.jdbc.IfxPreparedStatement.<init>(Unknown Source)
at com.informix.jdbc.IfxSqliConnect.createPreparedStmt(Unknown Source)
at com.informix.jdbc.IfxSqliConnect.prepareStatement(Unknown Source)
at org.apache.tomcat.dbcp.dbcp2.DelegatingConnection.prepareStatement(DelegatingConnection.java:291)
at org.apache.tomcat.dbcp.dbcp2.DelegatingConnection.prepareStatement(DelegatingConnection.java:291)
at br.com.solcast.integrador.dao.sisdia.PedidoVendaDAO.carregar(PedidoVendaDAO.java:169)
at br.com.solcast.integrador.service.sisdia.PedidoVendaService.carregar(PedidoVendaService.java:99)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:144)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:161)
at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$TypeOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:205)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:99)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102)
at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:326)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305)
at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154)
at org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:473)
at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:388)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:341)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:228)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at br.com.solcast.integrador.security.RestAuthenticationFilter.doFilter(RestAuthenticationFilter.java:43)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:528)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1100)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:687)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Caused by: java.io.IOException
at com.informix.asf.IfxDataInputStream.readFully(Unknown Source)
at com.informix.asf.IfxDataInputStream.readSmallInt(Unknown Source)
... 61 more
My class that connects
public class DAOManager {
private DataSource src;
private Connection con;
public void open() throws SQLException {
try {
if(this.con==null || this.con.isClosed())
this.con = src.getConnection();
} catch(SQLException e) { throw e; }
}
public void close() throws SQLException {
try {
if(this.con!=null && !this.con.isClosed()) {
this.con.close();
this.con = null;
}
} catch(SQLException e) {
throw e;
} finally {
if (this.con != null) {
try { this.con.close(); } catch (SQLException e) { ; }
this.con = null;
}
}
}
public DAOManager() throws NamingException {
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
this.src = (DataSource)envContext.lookup("jdbc/cortex-sisdia");
}
public Object gerarDAO(DAO dao) throws SQLException
{
if (this.con == null || this.con.isClosed())
this.open();
switch (dao) {
case AGENDAMENTOOFICINA:
return new AgendamentoOficinaDAO(this.con);
case ESTOQUE:
return new EstoqueDAO(this.con);
case PEDIDOVENDA:
return new PedidoVendaDAO(this.con);
case PESSOA:
return new PessoaDAO(this.con);
case VEICULO:
return new AgendamentoOficinaDAO(this.con);
default:
return null;
}
}
#Override
protected void finalize()
{
try{
this.close();
} catch (SQLException e) {
e.printStackTrace();
}
finally{
try {
super.finalize();
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
After instantiating a new connection and executing a prepareStatement the error occurs randomly.
I try to connect to mysql database on my Java EE project but i get an error and I do not know where is the problem.
And this is SERVLET, CLASS AND ERRORS
The Java EE Servlet:
package com.hopital.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.hopital.database.Recup_Insert;
import com.hopital.forms.Connections;
#WebServlet("/hopital")
public class hopital extends HttpServlet {
private static final long serialVersionUID = 1L;
public hopital() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//extrait les cookies
Cookie[] cookies= request.getCookies();
if(cookies != null){
for(Cookie cookie: cookies){
if(cookie.getName().equals("login")){
request.setAttribute("login", cookie.getValue());
}
}
}
//session
HttpSession session= request.getSession();
String login= (String) session.getAttribute("login");
request.setAttribute("login", login);
//extrait les chambers
Recup_Insert tableChamber= new Recup_Insert();
request.setAttribute("chambres",tableChamber.recup_chmabre());
this.getServletContext().getRequestDispatcher("/WEB-INF/home.jsp").forward(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//verification de champs
Connections form= new Connections();
form.verifie(request);
request.setAttribute("form", form);
//stocke les champs entre
String login=request.getParameter("login");
String pass=request.getParameter("pass");
//cree un cookies
Cookie cookie=new Cookie("login",login);
cookie.setMaxAge(60*60*24*30);
response.addCookie(cookie);
// cree un session sur login et mot de passe
HttpSession session= request.getSession();
session.setAttribute("login", login);
session.setAttribute("pass", pass);
this.getServletContext().getRequestDispatcher("/WEB-INF/home.jsp").forward(request,response);
}
}
My class that contain the database connexion:
package com.hopital.database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.List;
import com.hopital.projet.chamber;
public class Recup_Insert {
public List<chamber> recup_chmabre(){
List<chamber> chambers= new ArrayList<chamber>();
//charger les drivers
try{
Class.forName("com.mysql.jdbc.Driver");
}catch( ClassNotFoundException e){
}
//Connexion
Connection connexion=null;
Statement statement=null;
ResultSet resultat = null;
try {
connexion = DriverManager.getConnection("jdbc:mysql://localhost:3306/hopital", "root", "3636");
statement= connexion.createStatement();
resultat= statement.executeQuery("SELECT * FROM CHAMBER;");
while(resultat.next()){
int etage = resultat.getInt("etage");
int ID_pat = resultat.getInt("ID_pat");
int num = resultat.getInt("num");
int nom_lits = resultat.getInt("nom_lits");
int occupee = resultat.getInt("occupee");
chamber chamber = new chamber();
chamber.setEtage(etage);
chamber.setID_pat(ID_pat);
chamber.setNum(num);
chamber.setOccupee(occupee);
chamber.setNom_lits(nom_lits);
chambers.add(chamber);
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
try{
if(resultat != null)resultat.close();
if(statement != null)statement.close();
if(connexion != null)connexion.close();
}catch(SQLException ignore){
}
}
return chambers;
}
}
AND THIS IS THE ERRORS AFTER RUNING:
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:983)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:339)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2252)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2285)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2084)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:795)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:44)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:400)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:327)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.hopital.database.Recup_Insert.recup_chmabre(Recup_Insert.java:29)
at com.hopital.servlet.hopital.doGet(hopital.java:44)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:217)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:214)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:298)
... 39 more
Check connection URL and credentials. Try connecting with the same parameters using some SQL client.
You got this error because you cannot connect to database.
Most probably you didn't start you server. Check either it running or not, then double check port where it is running. Also check spelling on table name in database it should be "hopital".
Check For mysql-connector-java-5.1.21-bin.jar file added to Properties=>libraries=>
if not then add external jar=>mysql-connector-java-5.1.21-bin.jar
also check port number of tomcat server and mysql.
i am developing JSF2 application with spring framework on tomcat 7 and when stopping tomcat, i am getting the following exception:
SEVERE: IOException while loading persisted sessions: java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException: java.util.WeakHashMap
java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException: java.util.WeakHashMap
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
at java.io.ObjectInputStream.readSerialData(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at org.apache.catalina.session.StandardSession.readObject(StandardSession.java:1595)
at org.apache.catalina.session.StandardSession.readObjectData(StandardSession.java:1060)
at org.apache.catalina.session.StandardManager.doLoad(StandardManager.java:284)
at org.apache.catalina.session.StandardManager.load(StandardManager.java:204)
at org.apache.catalina.session.StandardManager.startInternal(StandardManager.java:491)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5390)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.io.NotSerializableException: java.util.WeakHashMap
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at org.apache.catalina.session.StandardSession.writeObject(StandardSession.java:1671)
at org.apache.catalina.session.StandardSession.writeObjectData(StandardSession.java:1077)
at org.apache.catalina.session.StandardManager.doUnload(StandardManager.java:432)
at org.apache.catalina.session.StandardManager.unload(StandardManager.java:353)
at org.apache.catalina.session.StandardManager.stopInternal(StandardManager.java:518)
at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:232)
at org.apache.catalina.core.StandardContext.stopInternal(StandardContext.java:5569)
at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:232)
at org.apache.catalina.core.StandardContext.reload(StandardContext.java:3919)
at org.apache.catalina.loader.WebappLoader.backgroundProcess(WebappLoader.java:426)
at org.apache.catalina.core.ContainerBase.backgroundProcess(ContainerBase.java:1345)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1530)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1540)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1540)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.run(ContainerBase.java:1519)
... 1 more
Dec 29, 2013 3:52:07 PM org.apache.catalina.session.StandardManager startInternal
SEVERE: Exception loading sessions from persistent storage
java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException: java.util.WeakHashMap
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
at java.io.ObjectInputStream.readSerialData(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at org.apache.catalina.session.StandardSession.readObject(StandardSession.java:1595)
at org.apache.catalina.session.StandardSession.readObjectData(StandardSession.java:1060)
at org.apache.catalina.session.StandardManager.doLoad(StandardManager.java:284)
at org.apache.catalina.session.StandardManager.load(StandardManager.java:204)
at org.apache.catalina.session.StandardManager.startInternal(StandardManager.java:491)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5390)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.io.NotSerializableException: java.util.WeakHashMap
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at org.apache.catalina.session.StandardSession.writeObject(StandardSession.java:1671)
at org.apache.catalina.session.StandardSession.writeObjectData(StandardSession.java:1077)
at org.apache.catalina.session.StandardManager.doUnload(StandardManager.java:432)
at org.apache.catalina.session.StandardManager.unload(StandardManager.java:353)
at org.apache.catalina.session.StandardManager.stopInternal(StandardManager.java:518)
at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:232)
at org.apache.catalina.core.StandardContext.stopInternal(StandardContext.java:5569)
at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:232)
at org.apache.catalina.core.StandardContext.reload(StandardContext.java:3919)
at org.apache.catalina.loader.WebappLoader.backgroundProcess(WebappLoader.java:426)
at org.apache.catalina.core.ContainerBase.backgroundProcess(ContainerBase.java:1345)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1530)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1540)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1540)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.run(ContainerBase.java:1519)
... 1 more
UPDATE: found that the only class in my app that uses WeakHashMap is the custom view scope class for spring as follows:
import java.io.Serializable;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.event.PreDestroyViewMapEvent;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.Scope;
public class ViewScope implements Scope, Serializable, HttpSessionBindingListener {
private static final long serialVersionUID = -1483153100048704635L;
private static final Logger LOGGER = LoggerFactory.getLogger(ViewScope.class);
private final WeakHashMap<HttpSession, Set<ViewScopeViewMapListener>> sessionToListeners = new WeakHashMap<>();
#Override
public Object get(String name, ObjectFactory objectFactory) {
Map<String, Object> viewMap = FacesContext.getCurrentInstance().getViewRoot().getViewMap();
// noinspection SynchronizationOnLocalVariableOrMethodParameter
synchronized (viewMap) {
if (viewMap.containsKey(name)) {
return viewMap.get(name);
} else {
LOGGER.debug("Creating bean {}", name);
Object object = objectFactory.getObject();
viewMap.put(name, object);
return object;
}
}
}
#Override
public Object remove(String name) {
throw new UnsupportedOperationException();
}
#Override
public String getConversationId() {
return null;
}
#Override
public void registerDestructionCallback(String name, Runnable callback) {
LOGGER.debug("registerDestructionCallback for bean {}", name);
UIViewRoot viewRoot = FacesContext.getCurrentInstance().getViewRoot();
ViewScopeViewMapListener listener = new ViewScopeViewMapListener(viewRoot, name, callback, this);
viewRoot.subscribeToViewEvent(PreDestroyViewMapEvent.class, listener);
HttpSession httpSession = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
final Set<ViewScopeViewMapListener> sessionListeners;
synchronized (sessionToListeners) {
if (!sessionToListeners.containsKey(httpSession)) {
sessionToListeners.put(httpSession, new HashSet<ViewScopeViewMapListener>());
}
sessionListeners = sessionToListeners.get(httpSession);
}
// noinspection SynchronizationOnLocalVariableOrMethodParameter
synchronized (sessionListeners) {
Set<ViewScopeViewMapListener> toRemove = new HashSet<>();
for (ViewScopeViewMapListener viewMapListener : sessionListeners) {
if (viewMapListener.checkRoot()) {
toRemove.add(viewMapListener);
}
}
sessionListeners.removeAll(toRemove);
sessionListeners.add(listener);
}
if (!FacesContext.getCurrentInstance().getExternalContext().getSessionMap().containsKey("sessionBindingListener")) {
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("sessionBindingListener", this);
}
}
#Override
public Object resolveContextualObject(String key) {
return null;
}
#Override
public void valueBound(HttpSessionBindingEvent event) {
LOGGER.debug("Session event bound {}", event.getName());
}
#Override
public void valueUnbound(HttpSessionBindingEvent event) {
LOGGER.debug("Session event unbound {}", event.getName());
final Set<ViewScopeViewMapListener> listeners;
synchronized (sessionToListeners) {
if (sessionToListeners.containsKey(event.getSession())) {
listeners = sessionToListeners.get(event.getSession());
sessionToListeners.remove(event.getSession());
} else {
listeners = null;
}
}
if (listeners != null) {
for (ViewScopeViewMapListener listener : listeners) {
listener.doCallback();
}
}
}
public void clearFromListener(ViewScopeViewMapListener listener) {
LOGGER.debug("Removing listener from map");
HttpSession httpSession = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
if (httpSession != null) {
synchronized (sessionToListeners) {
if (sessionToListeners.containsKey(httpSession)) {
sessionToListeners.get(httpSession).remove(listener);
}
}
}
}
}
i don't know if i made the WeakHashMap transient will that affect the spring view scope or what ?
please advise how to solve this issue.
You get a java.io.NotSerializableException with the message java.util.WeakHashMap meaning that the WeakHashMap is not serializable.
From the stack trace one can see that Tomcat is trying to serialize a session (StandardSession.writeObjectData). That suggests that some attribute of your session is a WeakHashMap.
If you want your session to be serializable (which is useful for clustering and saving session data between server restarts), then you need to get rid of that (or wrap it in another object that handles the serialization correctly).
Either turn of session serialization, if you don't need it, or find out which attribute is the WeakHashMap (simply iterate over all of them and print the names of all WeakHashMap values).
I have tried with the following code to connect CASSANDRA Database on my local system.
Here is my code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DBConnect {
public static void main(String[] args) throws Exception{
Connection con = null;
try {
Class.forName("org.apache.cassandra.cql.jdbc.CassandraDriver");
con = DriverManager.getConnection("jdbc:cassandra://localhost:9160/mykeyspace");
String query = "select * from users";
Statement stmt = con.createStatement();
ResultSet result = stmt.executeQuery(query);
while (result.next()) {
System.out.println(result.getString("user_id"));
System.out.println(result.getString("fname"));
System.out.println(result.getString("lname"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (con != null) {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
con = null;
}
}
}}
and here is a error message which i recieve.
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/thrift/TEnum
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$100(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at org.apache.cassandra.cql.jdbc.Utils.<clinit>(Utils.java:62)
at org.apache.cassandra.cql.jdbc.CassandraDriver.connect(CassandraDriver.java:85)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at DBConnect.main(DBConnect.java:15)
Caused by: java.lang.ClassNotFoundException: org.apache.thrift.TEnum
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 17 more
I have added following Jar files.
apache-cassandra-thrift-1.2.5.jar
cassandra-jdbc-1.2.5.jar
slf4j-api-1.7.5.jar
slf4j-jdk14-1.7.5.jar
Please help me to solve this issue.
Thanks
The apache-cassandra-thrift depends on libthrift artifact. You need to add this jar in your classpath. You can find it here.