Calling EJB Session outside of doGet or doPost - java

I am having a bit of problem figuring out whether I can actually call methods of the session bean in a method that doesn't take the HttpServletRequest and HttpServletResponse parameters ?
Having realized that the code works in doGet and doPost methods I have modified a custom made method to take the parameters of request and response, and suddenly it has started working.
My goal is to have the method working (calling session bean methods) without having a request and response in the method parameters.
However here is the code of the problematic version which grants NullPointerException on itemRegistrationSession.openConnection();
package web;
import java.io.IOException;
import java.util.ArrayList;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import auction.itemRegistrationRemote;
import auction.userRegistrationRemote;
/**
* Servlet implementation class processItem
*/
#WebServlet("/processItem")
public class processItem extends HttpServlet {
private static final long serialVersionUID = 1L;
#EJB itemRegistrationRemote itemRegistrationSession;
#EJB userRegistrationRemote processRegistrationSession;
/**
* #see HttpServlet#HttpServlet()
*/
public processItem() {
super();
getCategories();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//ArrayList<String> categories = getCategories(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected ArrayList<String> getCategories() {
System.out.println("Hello from getCategories()");
itemRegistrationSession.openConnection();
System.out.println("Hello2 from getCategories()");
ArrayList<String> categories = itemRegistrationSession.getCategories();
itemRegistrationSession.closeConnection();
return categories;
}
}
package auction;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.ejb.LocalBean;
import javax.ejb.Singleton;
/**
* Session Bean implementation class itemRegistration
*/
#Singleton
public class itemRegistration implements itemRegistrationRemote {
Connection con;
PreparedStatement prepStat;
ResultSet resultSet;
final String ITEM_NAME = "ITEM_NAME";
final String CATEGORY_NAME = "CATEGORY_NAME";
final String USER_NAME = "USER_NAME";
final String ITEM_MODEL = "ITEM_MODEL";
final String ITEM_DESCRIPTION = "ITEM_DESCRIPTION";
/**
* Default constructor.
*/
public itemRegistration() {
// TODO Auto-generated constructor stub
}
#Override
public void openConnection() {
System.out.println("Openning connection for itemRegistration");
try {
String driver = "org.apache.derby.jdbc.EmbeddedDriver";
Class.forName(driver).newInstance();
} catch (InstantiationException e) {
System.out.println("Openning database connection - Instantiation Exception " + e.getMessage());
} catch (IllegalAccessException e) {
System.out.println("Openning database connection - IllegalAccessException " + e.getMessage());
} catch (ClassNotFoundException e) {
System.out.println("Openning database connection - ClassNotFoundException " + e.getMessage());
}
try {
con = DriverManager.getConnection("jdbc:derby:C:/Users/Adrian/MyDB;upgrade=true", "adrian", "testero");
} catch (SQLException e) {
System.out.println("Openning database connection - SQLException " + e.getMessage());
}
} // End of openConnection method
#Override
public void closeConnection() {
try {
resultSet.close();
prepStat.close();
con.close();
} catch (SQLException e) {
System.out.println("Closing database connection - SQLException " + e.getMessage());
}
} // End of closeConnection method
#Override
public ArrayList<String> getCategories() {
ArrayList<String> categories = new ArrayList<String>();
try {
prepStat = con.prepareStatement("SELECT * FROM CATEGORY");
resultSet = prepStat.executeQuery();
int i = 1;
while (resultSet.next()) {
categories.add(resultSet.getString(i));
i++;
}
} catch (SQLException e) {
System.out.println("getCategories SQLException - " + e.getMessage());
}
return categories;
}
}

Sounds like the dependency inject for the
#EJB itemRegistrationRemote itemRegistrationSession
isn't working. Trying adding a log statement showing the value of the itemRegistrationSession object to see if that member got initialized correctly.

You're getting the exception because by the time you call getCategories() the EJBs have not been injected yet.
At constructor invocation time injection hasn't occurred yet, keep in mind that the object is just being created so the container hasn't had time to inject anything, the proper way to do this is by using the #PostConstruct annotation. From the javadoc:
The PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization...
so you need to move the getCategories() invocation to a #PostConstruct annotated method, like this:
#WebServlet("/processItem")
public class processItem extends HttpServlet {
private static final long serialVersionUID = 1L;
#EJB itemRegistrationRemote itemRegistrationSession;
#EJB userRegistrationRemote processRegistrationSession;
/**
* #see HttpServlet#HttpServlet()
*/
public processItem() {
super();
}
#Postconstruct
void init() {
getCategories();
}...

Related

How can I get the data form SQL table in jsp file?

So after reading what was suggested to me.
here are all the files I'm using.
There's one problem, the method Authorfindall() in the AuthorServlet file is giving me an error that it's undeclared, which's not true because it's in the AuthorService file.
Can I get some help please?
Thank you.
Author class
package user.domain;
public class Author {
private String email;
private String name;
private String affiliation;
public String getEmail(){
return email;
}
public void setEmail(String email){
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAffiliation(){
return affiliation;
}
public void setAffiliation(String affiliation){
this.affiliation = affiliation;
}
#Override
public String toString() {
return "Author [ email=" + email + ", name="
+ name + ", affiliation=" + affiliation +"]";
}
}
Author service
package user.service;
import java.util.List;
import user.dao.UserDao;
import user.domain.Author;
public class AuthorService {
private UserDao userDao = new UserDao();
public List<Object> Authorfindall() throws InstantiationException, IllegalAccessException, ClassNotFoundException {
// TODO Auto-generated method stub
return userDao.Authorfindall();
}
}
Author Servlet
package user.web.servlet;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import user.service.AuthorService;
import user.domain.Author;
/**
* Servlet implementation class AuthorServlet
*/
#WebServlet("/AuthorServlet")
public class AuthorServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
AuthorService authorservice = new AuthorService();
try {
request.setAttribute("AuthorList", authorservice.Authorfindall());
} catch (InstantiationException | IllegalAccessException
| ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
List<Object> li = authorservice.Authorfindall();
for(int i = 0; i < li.size();i++){
System.out.println(li.get(i).toString());
}
} catch (InstantiationException | IllegalAccessException
| ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
request.getRequestDispatcher("/Queryresult/author.jsp").forward(request, response);
}
}
UserDao
Public Class UserDao {
public List<Object> Authorfindall()throws InstantiationException,
IllegalAccessException, ClassNotFoundException{
List<Object> list = new ArrayList<>();
try {
Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
Connection connect = DriverManager
.getConnection("jdbc:mysql://127.0.0.1:3306/sampledb?"
+ "user=root&password=Shafiko93!");
String sql = "select * from author";
PreparedStatement preparestatement = connect.prepareStatement(sql);
ResultSet resultSet = preparestatement.executeQuery();
while(resultSet.next()){
Author author = new Author();
author.setEmail(resultSet.getString("email"));
author.setName(resultSet.getString("name"));
author.setAffiliation(resultSet.getString("affiliation"));
list.add(author);
}
} catch(SQLException e) {
throw new RuntimeException(e);
}
return list;
}
}

cookies giving unusual values along with set values in servlet

I have set cookies in a servlet class and read those cookies values in another servlet class. In another servlet class along with the set cookies values, I am getting some unusual values.
My Home.java servlet class results set ::
first result
Hello JSESSIONID, Hello A502A7144AE035ED9B1A2549F5C7B74B
Hello first_name, Hello RACHEL
Hello last_name, Hello KIM
second result
Hello JSESSIONID, Hello A502A7144AE035ED9B1A2549F5C7B74B
Hello first_name, Hello CAIRO
Hello last_name, Hello SENGAL
in both the results I am getting the set cookies values and names but along with them I am getting JSESSIONID and A502A7144AE035ED9B1A2549F5C7B74B. I can't understand from where do these cookies values are appearing? How can I remove this? Why are these values appearing?
My code :
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletConfig;
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;
/**
* Servlet implementation class Authenticate
*/
#WebServlet("/Authenticate")
public class Authenticate extends HttpServlet {
private static final long serialVersionUID = 1L;
public Authenticate() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try
{
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String firstname = request.getParameter("firstname");
String lastname = request.getParameter("lastname");
out.print("Welcome "+ firstname);
// Create cookies for first and last names.
Cookie f_name = new Cookie("first_name", firstname);
Cookie l_name = new Cookie("last_name", lastname);
// Add both the cookies in the response header.
response.addCookie( f_name );
response.addCookie( l_name );
//creating submit button
out.print("<form action='Home' method='post' >");
out.print("<input type='submit' value='cookie click' />");
out.print("</form>");
out.close();
}
catch(Exception ex)
{
System.out.println("exception occured");
System.out.println(ex.toString());
}
}
}
Code for Home servlet
#WebServlet("/Home")
public class Home extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Home() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie ck[] = request.getCookies();
if (ck != null) {
for (int i = 0; i < ck.length; i++) {
out.print("Hello " + ck[i].getName() + ", ");
out.print("Hello " + ck[i].getValue());
out.print("<br />");
}
}
out.close();
} catch (Exception e) {
System.out.println(e);
}
}
}

No response from HttpServlet with AsyncContext

I'm trying to implement async servlet on Tomcat, that will send update to client every time an HttpSessionAttributeListener.attributeReplaced() is triggered. Client side is configured to receive Server Sent Events.
Although the listener receives the updates, the browser does not receive any response. Browser's developer pane shows, that the request is pending and it ends with error 500 after the timeout set by the AsyncContext.setTimeout(). I run out of ideas, why this is happening.
JS
var source = new EventSource('/acount/sse');
source.onmessage = function (event) {
console.log(event.data);
document.querySelector('#messageArea p').innerHTML += event.data;
};
And this is my servlet code:
Servlet
public class SSE extends HttpServlet implements HttpSessionAttributeListener {
public static final String ATTR_ENTRY_PROCESSOR_PROGRESS = "entryProcessorProgress";
private AsyncContext aCtx;
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", true);
resp.setContentType("text/event-stream");
resp.setHeader("Cache-Control", "no-cache");
resp.setHeader("Connection", "keep-alive");
resp.setCharacterEncoding("UTF-8");
aCtx = req.startAsync(req, resp);
aCtx.setTimeout(80000);
}
#Override
public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
write(httpSessionBindingEvent);
}
#Override
public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {
}
#Override
public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {
write(httpSessionBindingEvent);
}
private void write(HttpSessionBindingEvent httpSessionBindingEvent) {
if (httpSessionBindingEvent.getName().equals(ATTR_ENTRY_PROCESSOR_PROGRESS)) {
try {
String message = "data: " + httpSessionBindingEvent.getValue() + "\n\n";
aCtx.getResponse().getWriter().write(message);
aCtx.getResponse().getWriter().flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
The problem:
I tried your code and there was a java.lang.NullPointerException in:
aCtx.getResponse().getWriter().write(message);
Because the aCtx is null.
You have mixed the Servlet and Listener, but when the Listeners methods are called, the AsyncContext initialization is not. Therefore nothings go to the browser.
I splitted your code in Servlet an Listener and smuggled the AsychContext object through a session attribute. So it was accessible in the listener.
And it works.
The Complete Code:
The HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Server Event Listener</title>
</head>
<body>
<div id="messageArea">
<p></p>
</div>
<script>
var source = new EventSource('/yourPath/ServerSentEvent');
source.onmessage = function (event) {
console.log(event.data);
document.querySelector('#messageArea p').innerHTML += event.data;
};
</script>
</body>
</html>
The Servlet:
package testingThings.ServerSentEvent;
import java.io.IOException;
import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet(asyncSupported = true, value = {"/ServerSentEvent"})
public class ServerSentEvent extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// add #WebServlet(asyncSupported = true) instead
// http://stackoverflow.com/questions/7855712/how-to-avoid-request-set-async-supported-true-to-enable-async-servlet-3-0-proces
// req.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", true);
resp.setContentType("text/event-stream");
resp.setHeader("Cache-Control", "no-cache");
resp.setHeader("Connection", "keep-alive");
resp.setCharacterEncoding("UTF-8");
AsyncContext aCtx = req.startAsync(req, resp);
aCtx.setTimeout(80000);
// add a asyncContext a session Attribute
req.getSession().setAttribute("asyncContext", aCtx);
//start logging in listener
req.getSession().setAttribute("entryProcessorProgress", "trigger output");
}
}
The HttpSessionAttributeListener:
package testingThings.ServerSentEvent;
import java.io.IOException;
import javax.servlet.AsyncContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
#WebListener
public class SessionAttributeListener implements HttpSessionAttributeListener {
public static final String ATTR_ENTRY_PROCESSOR_PROGRESS = "entryProcessorProgress";
#Override
public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
write(httpSessionBindingEvent);
}
#Override
public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {
}
#Override
public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {
write(httpSessionBindingEvent);
}
private void write(HttpSessionBindingEvent httpSessionBindingEvent) {
if (httpSessionBindingEvent.getName().equals(ATTR_ENTRY_PROCESSOR_PROGRESS)) {
try {
// get the AsyncContext from the session
AsyncContext aCtx = (AsyncContext) httpSessionBindingEvent.getSession().getAttribute("asyncContext");
String message = "data: " + httpSessionBindingEvent.getValue() + "<br>\n\n";
aCtx.getResponse().getWriter().write(message);
aCtx.getResponse().getWriter().flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

Java WebApp: ClassNotFoundException com.rabbitmq.client.ConnectionFactory

I have the following maven dependency:
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>3.5.6</version>
</dependency>
And i have the following servlet:
package servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeoutException;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import model.DVD;
/**
* Servlet implementation class LoginServlet
*/
public class IndexServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public IndexServlet()
{
super();
// TODO Auto-generated constructor stub
}
/**
* #see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException
{
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
// TODO Auto-generated method stub
String QUEUE_NAME = "hello";
try
{
/// some code
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
channel.basicPublish("", QUEUE_NAME, null, obj.getBytes());
System.out.println(" [x] Sent '" + dvd.getName() + "'");
channel.close();
connection.close();
} catch (IOException | TimeoutException | NumberFormatException exp)
{
exp.printStackTrace();
}
response.sendRedirect("/A3_Producer/");
}
}
I run Maven build with clean install and after that I start the web application in a tomcat server. The welcome page loads, but when I hit the Submit button and enter in this servlet, I get an ClassNotFoundException when trying to make a ConnectionFactory object.
I added the jar too to build path but it didn't fix the problem.
What can I do to fix it?
In order to make this work, you need to place the client jar into the tomcatinstallation/lib lib folder. ($CATALINA_HOME/lib)

Database connection suffers of concurrent threads

I've recently starting working on a java webapp (JSP / Servlet) that was developed by the internal developer of a company.
This app randomly doesn't return data, and inspecting the log I found some NullPointerExceptions related to the classes' member variable which holds the database connection. Following the stack trace it seems that a second thread closes the connection after it ended its task leaving the first thread without a connection.
By the needs of the company the app uses different databases, one which rules appdata, and others which contain data the app has to retrieve. So every class attached to the main servlet may connect to one or more databases depending on the task it has to accomplish.
I'm not familiar with JavaEE but giving a look at the database connection class, I see nothing which protect threads from conflicting each other.
Which is the correct way to handle such connections?
This is the code of the Database handler:
package it.metmi.mmasgis.utils;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class DBManager
{
private String szDatabase;
private String szUsername;
private String szPassword;
private String szError;
private Connection db;
private boolean bConnected;
private Logger logger;
public DBManager(String szDBName)
{
this(szDBName, "", "");
}
public DBManager(String szDBName, String szName, String szPass)
{
szDatabase = szDBName;
szUsername = szName;
szPassword = szPass;
bConnected = false;
szError = "";
logger = LogManager.getFormatterLogger(DBManager.class.getName());
}
public boolean connect()
{
logger.entry();
try {
Class.forName("com.mysql.jdbc.Driver");
if(!szDatabase.isEmpty())
{
String szCon = "jdbc:mysql://localhost/" + szDatabase;
if(!szUsername.isEmpty())
{
szCon += "?user=" + szUsername;
if(!szPassword.isEmpty())
szCon += "&password=" + szPassword;
}
db = DriverManager.getConnection(szCon);
bConnected = true;
} else {
logger.error("No database name!!");
System.exit(0);
}
} catch(SQLException | ClassNotFoundException e) {
szError = e.getMessage();
e.printStackTrace();
logger.error("Can't connect: %s", e);
}
return logger.exit(bConnected);
}
public void disconnect()
{
logger.entry();
try {
db.close();
bConnected = false;
} catch(SQLException e) {
e.printStackTrace();
logger.error("Can't disconnect: %s", e);
}
logger.exit();
}
public boolean isConnected()
{
return bConnected;
}
public String getError()
{
return szError;
}
public ArrayList<HashMap<String,String>> query(String szQuery)
{
logger.entry(szQuery);
ArrayList<HashMap<String,String>> aResults = new ArrayList<HashMap<String,String>>();
int iCols = 0;
try {
Statement stmt = db.createStatement();
logger.info("Query: %s", szQuery);
ResultSet rs = stmt.executeQuery(szQuery);
ResultSetMetaData rsmd = rs.getMetaData();
iCols = rsmd.getColumnCount();
while(rs.next())
{
HashMap<String,String> pv = new HashMap<String,String>();
for(int i = 0; i < iCols; i++)
{
String szCol = rsmd.getColumnLabel(i + 1);
String szVal = rs.getString(i + 1);
pv.put(szCol, szVal);
}
aResults.add(pv);
}
rs.close();
stmt.close();
} catch(SQLException e) {
e.printStackTrace();
szError = e.getMessage();
logger.error("Error executing query: %s", e);
}
return logger.exit(aResults);
}
public boolean update(String szQuery)
{
logger.entry(szQuery);
boolean bResult = false;
try {
Statement stmt = db.createStatement();
logger.info("Query: %s", szQuery);
stmt.executeUpdate(szQuery);
bResult = true;
stmt.close();
} catch(SQLException e) {
e.printStackTrace();
szError = e.getMessage();
bResult = false;
logger.error("Error executing query: %s", e);
}
return logger.exit(bResult);
}
}
The class Task which all the servlet classes are based on, is a simple abstract class:
package it.metmi.mmasgis.servlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public abstract class Task
{
public abstract void doTask(HttpServletRequest request, HttpServletResponse response);
}
The class which throws NullPointerExceptions it this one, during the invocation of db.disconnect(). This class is called rapidly via AJAX 4 or 5 times from the interface written in JS.
package it.metmi.mmasgis.servlet.params;
import it.metmi.mmasgis.servlet.Task;
import it.metmi.mmasgis.utils.Const;
import it.metmi.mmasgis.utils.DBManager;
import it.metmi.mmasgis.utils.Query;
import it.metmi.mmasgis.utils.Utility;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class ClassType extends Task
{
private DBManager db = null;
private Logger logger = LogManager.getFormatterLogger(ClassType.class.getName());
#Override
public void doTask(HttpServletRequest request, HttpServletResponse response)
{
logger.entry(request, response);
String szCensimento = Utility.getParameter(request, "censimento");
String szCategoria = Utility.getParameter(request, "category");
ArrayList<HashMap<String,String>> aClasses = new ArrayList<HashMap<String,String>>();
PrintWriter out = null;
logger.debug("Census: %s", szCensimento);
logger.debug("Category: %s", szCategoria);
db = new DBManager(szCensimento, Const.DB_USER, Const.DB_PASS);
if(db.connect())
{
String szQuery = String.format(Query.classes, szCategoria, szCategoria);
aClasses = db.query(szQuery);
db.disconnect();
}
try {
out = response.getWriter();
jsonEncode(aClasses, out);
} catch(IOException e) {
e.printStackTrace();
logger.error("Failed to encode JSON: %s", e);
}
logger.exit();
}
private void jsonEncode(ArrayList<HashMap<String,String>> aData, PrintWriter out)
{
HashMap<String,Object> result = new HashMap<String,Object>();
result.put("results", aData);
result.put("success", true);
Gson gson = new GsonBuilder().create();
gson.toJson(result, out);
}
}
If the webapp would use only one database, it could be rewritten as a Singleton, but in this way I have no idea on how to handle different connections for different databases.
How can avoid these exceptions?
The problem was that the connection object was declared as member.
Moving the variable inside the methods resolved.

Categories

Resources