servlet has to be reloaded everyday - servlets

I have created a servlet to access a database and giving response to a BB application...it was running fine during development...but after loading it on a tomcat server 6.0 after goining live the servlet has to be reloaded every morning on the tomcat server....after that it works fine during the whole day..but the next morning when i request something it gives a blank page as response and my server admin tells the servlet has to be reloaded ...
other application hosted on the server are working fine and do not need a restart...
what might be the problem....
adding the code ..if it helps
package com.ams.servlets;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
import com.cms.dbaccess.DataAccess;
import com.cms.utils.ApplicationConstants;
import com.cms.utils.ApplicationHelper;
import java.sql.ResultSet;
public class BBRequestProcessorServlet extends HttpServlet {
/**
*
*/String userString;
private static final long serialVersionUID = 1L;
String jsonString = "";
ResultSet rs = null;
Connection connection = null;
Statement statement=null;
public enum db_name
{
//Test
resource_management_db,osms_inventory_db;
}
public void init(ServletConfig config)throws ServletException
{
super.init(config);
System.out.println("Inside init");
}
public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException
{
try{
connection = DataAccess.connectToDatabase("xxx", connection);
statement = DataAccess.createStatement(connection);
statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
rs = statement.executeQuery("query is here");
}
catch(SQLException e)
{
e.printStackTrace();
}
String db =request.getParameter("db");
System.out.println("DATABASE NAME :"+ db);
if(db.equalsIgnoreCase("xxx")){
//Call to populate JSONArray with the fetch ResultSet data
jsonString = ApplicationHelper.populateJSONArray(rs);
}
response.setContentType(ApplicationConstants.JSON_CONTENT_TYPE);
PrintWriter out = response.getWriter();
out.print(jsonString);
out.flush();
out.close();
System.out.println("json object sent");
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
the only errors i could find was
Jul 20, 2012 9:57:24 AM org.apache.catalina.loader.WebappClassLoader validateJarFile
INFO: validateJarFile(/usr/local/tomcat/apache-tomcat-6.0.20/webapps/MobileServlet /WEB-INF/lib/servlet-api.jar) - jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class

The culprit is most likely the way how you handle external DB resources like the Connection. This problem can happen when you keep a DB Connection open all the time without closing it. When a DB Connection is been opened for a too long time, then the DB will timeout and reclaim it. This is most likely what was happening overnight.
You should redesign your DataAccess and BBRequestProcessorServlet that way so that you are nowhere keeping hold of Connection, Statement and ResultSet as an instance variable, or worse, a static variable of the class. The Connection should be created in the very same scope as where you're executing the SQL query/queries and it should be closed in the finally block of the very same try block as where you've created it.
By the way your jsonString should absolutely also not be declared as an instance variable of the servlet, it's not threadsafe this way.
See also:
Is it safe to use a static java.sql.Connection instance in a multithreaded system?
How do servlets work? Instantiation, sessions, shared variables and multithreading
As to the error which you're seeing in the log, you should definitely remove the offending JAR. See also How do I import the javax.servlet API in my Eclipse project?

I am guessing and will be more clear after seeing your logs.
Its seems like you have putted your servlet-api.jar in the WEB-INF lib but its already in tomcat's lib.

Related

After accidentally deleting Data Dictionary (app:dictionary) Alfresco doesn't start

One operator deleted Data Dictionary and restarted Alfresco 3.4.12 Enterprise Edition. The context /alfresco doesn't start with the following exception:
17:43:11,100 INFO [STDOUT] 17:43:11,097 ERROR [web.context.ContextLoader] Context initialization failed
org.alfresco.error.AlfrescoRuntimeException: 08050000 Failed to find 'app:dictionary' node
at org.alfresco.repo.action.scheduled.ScheduledPersistedActionServiceImpl.locatePersistanceFolder(ScheduledPersistedActionServiceImpl.java:132)
Looking at the source code in org.alfresco.repo.action.scheduled.ScheduledPersistedActionServiceImpl.java, the path is hardwired.
Then we followed the tip from https://community.alfresco.com/thread/202859-error-failed-to-find-appdictionary-node, editing bootstrap-context.xml, comment out the class.
After the change the error went over, now the RenditionService couldn't start.
We're looking for a way to recover the deleted node, since we can obtain the nodeid from the database. So we created a small class and invoke it through spring in bootstrap-context.xml, but it's failing due to permissions. Could you take a look at the code and tell us what's wrong. The code is:
package com.impulseit.test;
import javax.transaction.UserTransaction;
import org.alfresco.repo.node.archive.NodeArchiveService;
import org.alfresco.repo.node.archive.RestoreNodeReport;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.repository.NodeRef;
public class RestoreNode {
private NodeArchiveService nodeArchiveService;
private ServiceRegistry serviceRegistry;
private String nodeName ="archive://SpacesStore/adfc0cfe-e20b-467f-ad71-253aea8f9ac9";
public void setNodeArchiveService(NodeArchiveService value)
{
this.nodeArchiveService = value;
}
public void setServiceRegistry(ServiceRegistry value)
{
this.serviceRegistry = value;
}
public void doRestore() {
RunAsWork<Void> runAsWork = new RunAsWork<Void>()
{
public Void doWork() throws Exception
{
NodeRef nodeRef = new NodeRef(nodeName);
//RestoreNodeReport restoreNodeReport =
UserTransaction trx_A = serviceRegistry.getTransactionService().getUserTransaction();
trx_A.begin();
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());
RestoreNodeReport restored = nodeArchiveService.restoreArchivedNode(nodeRef);
trx_A.commit();
return null;
}
};
AuthenticationUtil.runAs(runAsWork,AuthenticationUtil.getSystemUserName());
}
public RestoreNode() {
}
}
The exception is:
19:31:21,747 User:admin ERROR [node.archive.NodeArchiveServiceImpl] An unhandled exception stopped the restore
java.lang.NullPointerException
at org.alfresco.repo.security.permissions.impl.model.PermissionModel.getPermissionReference(PermissionModel.java:1315)
at org.alfresco.repo.security.permissions.impl.PermissionServiceImpl.getPermissionReference(PermissionServiceImpl.java:956)
at org.alfresco.repo.security.permissions.impl.PermissionServiceImpl.hasPermission(PermissionServiceImpl.java:976)
Thank you in advance.
Luis

Error while running client code in EJB

Getting error while running client code in EJB:
Exception in thread "Main Thread" java.lang.NoClassDefFoundError:
weblogic/kernel/KernelStatus at
weblogic.jndi.Environment.(Environment.java:78) at
weblogic.jndi.WLInitialContextFactory.getInitialContext(WLInitialContextFactory.java:117)
at
javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:667)
at
javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:288)
at javax.naming.InitialContext.init(InitialContext.java:223) at
javax.naming.InitialContext.(InitialContext.java:197) at
User.main(User.java:21)
I added wlfullclient.jar, server's Remote interface jar, also I saw article in which I saw to add wlclient.jar and weblogic.jar but then also got same error.
Help highly appreciated.
Client code:
import com.amdocs.Stateful.*;
import java.util.Hashtable;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class User
{
public static void main(String args[]){
Hashtable<String,String> ht = new Hashtable<String,String>();
ht.put(InitialContext.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory");// you have to start from root location to search for JNDI tree
//JNDI registry tree is normally maintained as Binary tree, JNDi is normally binary tree which have root node at top
ht.put(InitialContext.PROVIDER_URL,"t3://localhost:7001"); // address of registry
try{
System.out.println("Hello");
InitialContext ic = new InitialContext(ht); // start searching wrt what we set in ht , it's constructor takes HashTable only
System.out.println("Hello2");
MyCartRemote ref=(MyCartRemote)ic.lookup("MyCartBeanJNDI#com.amdocs.Stateful.MyCartRemote");
ref.add("Hi");
ref.add("Jeetendra");
MyCartRemote ref1=(MyCartRemote)ic.lookup("MyCartBeanJNDI#com.amdocs.Stateful.MyCartRemote");
ref1.add("Hi");
ref1.add("Subhash");
ref1.add("Ghai");
System.out.println("Object 1 data: "+ref.show());
System.out.println("Object 2 data: "+ref1.show());
}
catch (NamingException e){ e.printStackTrace(); }
}
}
Try removing WebLogic System Libraries from the Bootstrap Entries section. It worked for me when i got the same error.

Local SQLite connection on JDeveloper

I'm completely new to ADF Mobile and have previously made a connection to and SQLite DB with NetBeans. I'm replicating the code, and I'm getting an Import java.sql.DriverManager not found error (in bold).
package mobile;
import java.sql.Connection;
**import java.sql.DriverManager;**
import java.sql.*;
public class Connect {
public Connect() {
super();
}
public class JavaConnect {
static Connection conn = null;
static ResultSet rs = null;
static PreparedStatement pst = null;
public static Connection DBConnect() {
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:AlternativeIdentification.sqlite");
System.out.println("Connection established");
return conn;
} catch (Exception ex) {
System.out.println("Error: " + ex);
return null;
}
}
Download https://code.google.com/p/sqlite-jdbc/. Then in your JDeveloper go to Tools>ManageLibraries and create a new library. Check the 'DeployedByDefault' checkbox there and add the JAR in the library (>addEntry). Then go to your Project, go to ProjectProperties and then to Libraries and Classpath and click on Add Library to add your new library to your project. Rebuild your project or restart JDeveloper in the worst case and you should be fine.

display image on servlet using imageio java 1.5 update 22

I have a webapplication for displaying images using imageio on a servlet. The webapp works fine when hosted in tomcat 7 using jre 1.6. But the same webapp when deployed on tomcat 5.5 with servlet 2.4 and Jre 1.5 it doesnt work. To access the image i pass an identifier as parameter and i get the image which is a blob column in DB. Initially i developed the application on tomcat 7 instance using eclipse and it worked fine. Compiler version compatibility is selected as 1.5 and Dynamic web module version is 2.4. In the below code i have checked the jdbc connectivity, it works fine and i can display textual information. Also i have checked separately whether the BufferedImage is having some data by checking for null and it seemed to have data. But the servlet simply fails to showup the image and i just end up getting a blank screen.
works on tomcat 7
[http://localhost:8081/testimage/ReturnImage?code=AUS]
doesnt work on tomcat 5.5
[http://localhost:8080/testimage/ReturnImage?code=AUS]
The servlet just displays a blank screen for the latter.
Below is the code for my servlet.
package flags;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
import java.awt.image.BufferedImage;
public class ReturnImage extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//PrintWriter out = response.getWriter();
// OutputStream outimg = response.getOutputStream();
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(
"jdbc:mysql://192.168.2.2:3306/world", "root", "abcdef");
//out.println("Connecting to database <br>");
Statement statement = connection.createStatement();
String param;
param = request.getParameter("code");
String sql = "Select Name,Flag,Code from world.Country where Code='"+ param + "'";
ResultSet res = statement.executeQuery(sql);
while (res.next()) {
String Name = res.getString("Name");
String Code = res.getString("Code");
BufferedImage image = javax.imageio.ImageIO.read(res.getBlob("Flag").getBinaryStream());
//out.println(System.getProperty("java.runtime.version"));
//out.println(Code + " ");
//out.println(Name + "<br>");
if (image == null) {
//out.println("null image");
}
ImageIO.write(image, "gif", outimg);
outimg.close();
}
res.close();
statement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Image shows the servlet output in two different tomcat instances. Tomcat 5.5 uses JDK1.5 and Tomcat 7 uses JDK 1.6
You probably need the setContentType set correctly (as you currently do).
However, have you tried using a different format, like PNG (and of course, use "image/png" as content type)? I'm not sure Java 1.5 has a GIF writer, due to the LZW licensing issues of the past. Note that the ImageIO.write methods have a boolean return type, to check if anything was written. In any case, PNG should always work.
PS: Unless you are planning to modify the image in the servlet, it is of course much faster to store the image in the right format in the blob, and just passing it down to the client without decoding/encoding it.

Error running a simple MDB application

I am trying to run the following program.I am using glassfish server 3.1.2 to enable this MDB to run.Then too I am unanble to run it.
package com.mdb;
import javax.jms.ConnectionFactory;
import javax.jms.Queue;
import javax.jms.Connection;
import javax.jms.Session;
import javax.jms.QueueBrowser;
import javax.jms.Message;
import javax.jms.JMSException;
import javax.annotation.Resource;
import java.util.Enumeration;
import javax.ejb.Stateless;
/**
* The MessageBrowser class inspects a queue and displays the messages it
* holds.
*/
#Stateless
public class MessageClient {
#Resource(mappedName = "jms/ConnectionFactory")
private static ConnectionFactory connectionFactory;
#Resource(mappedName = "jms/Queue")
private static Queue queue;
/**
* Main method.
*
* #param args the queue used by the example
*/
public static void main(String[] args) {
Connection connection = null;
try {
System.out.println("1");
connection = connectionFactory.createConnection();
System.out.println("2");
Session session = connection.createSession(
false,
Session.AUTO_ACKNOWLEDGE);
QueueBrowser browser = session.createBrowser(queue);
Enumeration msgs = browser.getEnumeration();
if (!msgs.hasMoreElements()) {
System.out.println("No messages in queue");
} else {
while (msgs.hasMoreElements()) {
Message tempMsg = (Message) msgs.nextElement();
System.out.println("Message: " + tempMsg);
}
}
} catch (JMSException e) {
System.err.println("Exception occurred: " + e.toString());
} finally {
if (connection != null) {
try {
connection.close();
} catch (JMSException e) {
}
}
}
}
}
The problem is I get the follwing exsception upon runing it.
Exception in thread "main" java.lang.NullPointerException
at com.mdb.MessageClient.main(MessageClient.java:35)
What may be the problem here?
What you have build is not a MDB. It's a stateless session bean that browses a queue.
A MDB has the #MessageDriven annotation. It's invoked whenever a message comes in.
Apart from that, you might want to use the "lookup" attribute instead of the "mappedName" one. The latter is from an ancient time when people weren't sure yet about anything, and needed a temporary hack to make things magically work.
Your usage of static fields and the static main method inside a stateless bean make no sense at all. If you're accessing your bean via that main method you're not using the bean at all and you're just calling an isolated global-like method. If anything, this might be the source of your NPE.
The fix isn't really simple. You're seemingly completely confused between Java EE and Java SE, and between instances and static methods.

Resources