Java Servlet Async Support - java

Recently i have started working on Java Servlet Async functionality. I have written sample code shown below to check aysnc Functionality. I am running it on single core processor. I am submitting 100 requests (image requests) from jsp. I have added "Request Submmited:::" SOP in code. It is displaying SOP for first 0 to 6 requests then after some time it is displaying SOP for 6 to 11.... why it is not displaying SOP for all 100 requests.
package com.test;
import java.io.FileInputStream;
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(urlPatterns={"/Test"}, asyncSupported = true)
public class Test extends HttpServlet {
private static final long serialVersionUID = 1L;
public Test() {
super();
}
int counter = 0;
#Override
protected void doGet(final HttpServletRequest request,
final HttpServletResponse response) throws ServletException,
IOException {
System.out.println("Request Submmited:::" + counter++);
final AsyncContext ctx = request.startAsync();
ctx.start(new Runnable() {
public void run() {
try {
String count = request.getParameter("test");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileInputStream fin = new FileInputStream(
"D:/TESTImages/8_0_0_NUCLEI" + count + ".jpg");
byte[] data = new byte[fin.available()];
fin.read(data);
response.getWriter().print(new String(data));
response.flushBuffer();
} catch (Exception e) {
e.printStackTrace();
}
ctx.complete();
}
});
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}

Seems that the default thread pool size is 5, for the pool that procesess async requests in your servlet container. Try providing init params as below:
#javax.servlet.annotation.WebServlet(urlPatterns={"/Test"}, asyncSupported = true,
initParams = { #WebInitParam(name = "threadpoolsize", value = "100") })

Related

I am using jdbc Bolt library for conecting to neo4j database. my code running perfectly through main method but not running on servlet (tomcat)

I am using the jdbc bolt library for connecting to a Neo4J database in Java. My code runs perfectly in main method, but after I switch it to servlet it gives error No suitable driver found for 'jdbc:neo4j:bolt://localhost'. What should I do?
//Test class
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Test {
public void test() {
try {
Connection con = DriverManager.getConnection("jdbc:neo4j:bolt://localhost", "neo4j", "neo4j");
String query = "MATCH (n) return id(n)";
PreparedStatement ps = con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
System.out.println("RESULT: " + rs.getObject("id(n)"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
//Servlet
import java.io.IOException;
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("/testingservlet")
public class testingservlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public testingservlet() {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
new Test().test();
} catch (Exception e) {
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
Use official java library for neo4j database connectivity.

How can I set an auto numeric name generator for image uploads, using a singleton pattern counter

So my Problem is that I have to create a Singleton pattern counter for numeric name giving. For example "1", "2", "3" etc. The idea is that every time i start the application and the Server(tomcat), it gets the last number and when I upload another image it should continue from there. Lets say the last one was "43", so the the next time I start the application it should know it and put "44" for the next image upload.
I'm not that good in Java so please give me some patience :)
This is my FileUploadServlet. It handles the request from the fileUploadForm.jsp by taking the file from the submit.
package upload;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import utils.FormatChecker;
import utils.UnzipFile;
//Servlet for handling the Upload request from the Index.jsp
#MultipartConfig
public class FileUploadServlet extends HttpServlet {
// Instace of the FileUpload object
private FileUploader uploader = new FileUploader();
// Instance of the FormatChecker object
private FormatChecker checker = new FormatChecker();
// Instance of the UnzipFile object
private UnzipFile unzip = new UnzipFile();
private static final long serialVersionUID = 1L;
private static final String SAVE_FOLDER = "C:\\Users\\cuche\\Desktop\\tomcat\\apache-tomcat-7.0.47\\webapps\\files";
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.sendRedirect("error.jsp");
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String contentType;
boolean isFormatValid;
Part filePart = request.getPart("file");
contentType = filePart.getContentType();
ServletContext context = getServletContext();
String appPath = context.getRealPath("/");
String fileNameOld = getFileName(filePart);
String fileNameNew = appPath + fileNameOld;
isFormatValid = checker.check(contentType);
pleas ignore the part with the FileUnziper
if (isFormatValid == true) {
if (contentType == ("application/x-zip-compressed")) {
unzip.FileUnziper(fileNameNew, SAVE_FOLDER);
} else {
//gets the content and saves in form of a stream
InputStream fileContent = filePart.getInputStream();
//using the uploadImage method of uploader class
uploader.uploadImage(fileNameNew, fileContent);
}
try {
response.sendRedirect("result.jsp");
} catch (IOException ex) {
response.getWriter().append(ex.getLocalizedMessage());
}
} else {
response.getWriter().append("Format is wrong");
}
}
// method for removing header for proper file upload
private String getFileName(Part part) {
for (String cd : part.getHeader("content-disposition").split(";")) {
if (cd.trim().startsWith("filename")) {
String filename = cd.substring(cd.indexOf('=') + 1).trim()
.replace("\"", "");
return filename.substring(filename.lastIndexOf('/') + 1)
.substring(filename.lastIndexOf('\\') + 1); // MSIE fix.
}
}
return null;
}
}
This is my FileUploader class
package upload;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* #author Iwan Cuche
* #date:
*/
public class FileUploader {
/**
* This method reads a File
*
* #param fileName
* #param stream
*/
public void uploadImage(String fileName, InputStream stream)
throws IOException {
try {
File file = new File(fileName);
OutputStream os = new FileOutputStream(file);
int data;
while ((data = stream.read()) != -1) {
os.write(data);
}
os.flush();
os.close();
System.out.println("Uploaded file successfully saved in "
+ file.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
throw e;
}
}
}
This is my Singleton class
package utils;
public class ServerCounter {
private static ServerCounter INSTANCE = new ServerCounter();
private ServerCounter() {};
public static ServerCounter getInstance() {
return INSTANCE;
}
}
I hope someone can help me because I'm not sure how to go at it.
In ServerCounter, add
private final AtomicLong counter = new AtomicLong();
public String nextval() { return String.valueOf(counter.incrementAndGet()); }
Each time you call INSTANCE.nextval() you'll get a fresh numeric string.
Clearly, each time you restart your application, the counter will restart.
ok, first you have to persist your counter if you want to get it after tomcat shutdown. we need listener for tomcat:
package utils;
public class ContextListener implements ServletContextListener{
void contextInitialized(ServletContextEvent sce){ // we could call loadFromFile here as well
}
//will be executed at tomcat shutdown
void contextDestroyed(ServletContextEvent sce){
ServerCounter .getInstance().writeToFile();
}
}
now the singleton(like in Marko's answer:)):
package utils;
public class ServerCounter {
private static ServerCounter INSTANCE = new ServerCounter();
private final AtomicLong counter;
private ServerCounter() {
//load value from file, do you need help by it?
long value = this.loadCounterFromFile();
counter = new AtomicLong(value);
};
private long loadCounterFromFile(){
BufferedReader br = null;
try {
//no problem if there is no file, we will return 0 in this case
br = new BufferedReader(new FileReader("C:\\Test\\counter.txt"));
String line = br.readLine();
if(line != null && line.length() > 0)
return Long.parseLong(line);
return 0;
//catch all exceptionse, because we could get NumberFormatException or FileNotFound from parseLong
} catch (Exception e) {
return 0;
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public static ServerCounter getInstance() {
return INSTANCE;
}
public String nextval() { return String.valueOf(counter.incrementAndGet()); }
//will be executed by listener
public void writeToFile(){
//write the counter to file
writeToFile(counter.get());
}
private void writeToFile(long value){
try{
//you need folder c:\Test, file will be created automatically if there is no file, it will override the old file
BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\Test\\counter.txt"));
//need "" to create String
bw.write("" + value);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
now you can use ServerCounter.getInstance.nextval() to increment the counter and get the value
last thing is, you need to put the listener to your webApplication:
<web-app>
...
<listener>
<listener-class>utils.ContextListener </listener-class>
</listener>
</web-app>
EDIT: ServerCounter was implementing ServletContextListener by mistake
EDIT2: added read/write file

getting HTTP Status 404 - 502.shtml The requested resource is not available.while uploading a file

I'm getting the above error while using servlet I've written. the war file is set on Tomcat ver 7.0.39 installed on cPanel. the servlet compiled and tested on local machine no problem. I've learnet that there is a problem that has something to do with the cPanel/PHP config. I tried to play with the cPanel configuration but no luck
I feel that it has nothing to do with the java code but I'll put the fileUploadServlet anyhow
EDIT: I was able to upload a very small-sized file so it has something to do with file size \ long procssing time
package servlet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;
import convertor.TextAnalayzer;
import exception.ZoharException;
import beans.ParashaBean;
import beans.UserBean;
import jdbcHandler.JDBCZhoarHandler;
import util.ParashaName;
import util.XmlUrelParaser;
#WebServlet(urlPatterns = { "/upload" }, loadOnStartup = 1)
#MultipartConfig
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 8626646959046203428L;
private JDBCZhoarHandler appHandler = new JDBCZhoarHandler();
public static final String ERROR_PARAMETER = "error";
public static final String COMMAND_PARAMETER = "command";
public static final String USER_ATTRIBUTE = "user";
public static final String HANDLER_ATTRIBUTE = "handler";
#Override
public void init() throws ServletException {
super.init();
try {
getServletConfig().getServletContext().setAttribute("list",
appHandler.viewParashot());
} catch (SQLException e) {
e.printStackTrace();
}
}
#Override
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String command = request.getParameter(COMMAND_PARAMETER);
String nextPage = "/login.jsp";
if ("convert".equals(command)) {
nextPage = this.upload(request, response);
} else if ("login".equals(command)) {
nextPage = this.login(request, response);
} else {
}// do nothing!!
this.getServletConfig().getServletContext()
.getRequestDispatcher(nextPage).forward(request, response);
}
private String login(HttpServletRequest request,
HttpServletResponse response) {
String name = request.getParameter("userName");
String password = request.getParameter("password");
JDBCZhoarHandler handler = new JDBCZhoarHandler();
try {
UserBean user = handler.getUser(name, password);
HttpSession session = request.getSession(true);
session.setAttribute(HANDLER_ATTRIBUTE, handler);
session.setAttribute(USER_ATTRIBUTE, user.getId());
return "/uploadFile.jsp";
} catch (Exception e) {
request.setAttribute(ERROR_PARAMETER, e.getMessage());
return "/login.jsp";
}
}
private String upload(HttpServletRequest request,
HttpServletResponse response) {
// view artifacts
HttpSession session = request.getSession(false);
ParashaName parashaName = new ParashaName();
JDBCZhoarHandler handler = (JDBCZhoarHandler) session
.getAttribute(HANDLER_ATTRIBUTE);
List<ParashaBean> list = null;
try {
list = handler.viewParashot();
} catch (SQLException e1) {
request.setAttribute(ERROR_PARAMETER, e1.getMessage());
}
session.setAttribute("list", list);
// Processing file
if ("convert".equals(request.getParameter("command"))) {
OutputStream out = null;
InputStream filecontent = null;
try {
// Create path components to save the file
XmlUrelParaser xml = new XmlUrelParaser();
SimpleDateFormat format = new SimpleDateFormat(
"dd-MM-yy_HH-mm-ss");
final Part filePart = request.getPart("file");
if (filePart.getSize() == 0) {
throw new ZoharException("you must upload a file first");
}
final String fileName = xml.getUR("incomingFilesDir")
+ session.getAttribute(USER_ATTRIBUTE)
+ parashaName.convert(Integer.parseInt(request
.getParameter("parasha")))
+ format.format(new Date()) + ".docx";
out = new FileOutputStream(new File(fileName));
filecontent = filePart.getInputStream();
int read = 0;
final byte[] bytes = new byte[1024];
while ((read = filecontent.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
TextAnalayzer ta = new TextAnalayzer();
Integer ID = (Integer)session.getAttribute("user");
ta.analayze(fileName,
Integer.parseInt(request.getParameter("parasha")),
Boolean.parseBoolean(request.getParameter("orginal")),
ID);
request.setAttribute(ERROR_PARAMETER, "Upload complete");
return "/uploadFile.jsp";
} catch (Exception e) {
request.setAttribute(ERROR_PARAMETER, e.getMessage());
} finally {
try {
if (out != null) {
out.close();
}
if (filecontent != null) {
filecontent.close();
}
} catch (IOException e) {
request.setAttribute(ERROR_PARAMETER, e.getMessage());
}
}
}
return "/login.jsp";
}
}
This is a resault of memory lack. Better memory-managing code solved the problem.

Call to an asynchronous servlet on WebSphere 8 results in AsyncIllegalStateException

I'm getting the following exception while calling a servlet:
com.ibm.ws.webcontainer.async.AsyncIllegalStateException: SRVE8010E: The current request does not support asynchronous servlet processing.
The servlet looks like this:
public class AsyncServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
AsyncContext async = req.startAsync();
async.start(new Runnable(){
#Override
public void run() {
System.out.println("Bazinga");
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
I've tried to set it as asynchronous using annotations:
#WebServlet(urlPatterns = "/asyncServlet", asyncSupported = true)
And also in web.xml after reading a post in a forum:
<servlet>
<display-name>AsyncServlet</display-name>
<servlet-name>AsyncServlet</servlet-name>
<servlet-class>com.lala.lala.AsyncServlet</servlet-class>
<init-param>
<param-name>com.ibm.ws.webcontainer.async-supported</param-name>
<param-value>true</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>AsyncServlet</servlet-name>
<url-pattern>/asyncServlet</url-pattern>
</servlet-mapping>
Still getting the AsyncIllegalStateException. How did you get async servlets run on WAS8?
I found something similar on one of the forums, maybe it will help:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet(urlPatterns = "/AsyncServlet", asyncSupported = true)
public class AsyncServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Record the servlet's thread
PrintWriter out = response.getWriter();
out.printf("<h3>Servlet's thread: %s</h3>", Thread.currentThread());
out.flush();
// Put the request into asynchronous mode
request.startAsync();
// Run an asynchronous task via servlet 3.0's abstractions
AsyncContext asyncCtx = request.getAsyncContext();
MyTask mt = new MyTask(asyncCtx);
asyncCtx.start(mt);
// Run another asynchronous task via java's abstractions
MyTask mt02 = new MyTask(asyncCtx);
new Thread(mt02).start();
out.printf("<h3>Servlet finishes its job</h3>");
}
public class MyTask implements Runnable {
AsyncContext asyncContext;
public MyTask(AsyncContext asyncContext) {
this.asyncContext = asyncContext;
}
#Override
public void run() {
ServletResponse response = asyncContext.getResponse();
try {
// do the time-consuming job
PrintWriter out = response.getWriter();
for (int i = 0; i < 5; i++) {
out.printf("<h2>Hello from thread: %s (%d)</h2>", Thread.currentThread(), i);
out.flush();
Thread.sleep(1 /* secs */ * 1000);
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
asyncContext.complete();
}
}
}
}
found here

Servlets and JSP blank

hi all I've typed out a page that queries the database then inputs something into the database but when I go to load the servlet/jsp page its comes back blank and am unsure what is happening or why? I'm coding in eclipse and after looking at the console and not getting anything printing out I figured there was something wrong with my code but I cannot see the problem.
Here is my servlet
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
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 javax.servlet.http.HttpSession;
/**
* Servlet implementation class TutorAssign
*/
#WebServlet("/TutorAssign")
public class TutorAssign extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public TutorAssign() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
private void sendBack(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(true);
//Set data you want to send back to the request (will be forwarded to the page)
//Can set string, int, list, array etc.
String sql = "SELECT l.id,s.name,l.day,l.time,l.room" +
" FROM subject s, lab l " +
" WHERE s.user_id="+(Integer)session.getAttribute("id");
try{
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/wae","root","");
System.out.println("got boobs");
System.out.println(session.getAttribute("id"));
Statement stmt = con.createStatement();
ResultSet res = stmt.executeQuery(sql);
System.out.println(res);
ArrayList<String> list1 = new ArrayList<String>();
ArrayList<String> list2 = new ArrayList<String>();
if (res.next()){
do{
list1.add(res.getString(1));
list2.add(res.getString(2)+" "+res.getString(3)+" "+res.getString(4)+" "+res.getString(5));
}while(res.next());
System.out.println("Outside");
String[] arr1 = list1.toArray(new String[list1.size()]);
String[] arr2 = list2.toArray(new String[list2.size()]);
System.out.println(list1);
request.setAttribute("res1", arr1);
request.setAttribute("res2", arr2);
}
}catch (SQLException e) {
}
catch (Exception e) {
}
//Decides what page to send the request data to
RequestDispatcher view = request.getRequestDispatcher("TutorAssign.jsp");
//Forward to the page and pass the request and response information
view.forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int user_id = Integer.parseInt(request.getParameter("id"));
int lab_id = 0;
String message = null;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/wae","root","");
System.out.println("got connection");
System.out.println(user_id);
Statement s = con.createStatement();
String sql = "INSERT INTO user_lab" +
" (user_id, lab_id)" +
" VALUES" +
" ('" + user_id + "'," +
" '" + lab_id + "')";
System.out.println(sql);
int i = s.executeUpdate(sql);
if (i==1) {
message = "Successfully assigned a tutor.";
response.sendRedirect("Lecturer_labs");
}
s.close();
con.close();
}
catch (SQLException e) {
message = "Error." + e.toString();
boolean error = true;
}
catch (Exception e) {
message = "Error." + e.toString();
boolean error = true;
}
if (message!=null) {
PrintWriter out = response.getWriter();
out.println("<B>" + message + "</B><BR>");
out.println("<HR><BR>");
}
}
// TODO Auto-generated method stub
}
I noticed that your doGet method has not been implemented.
I would assume that your sendBack code is not being called
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
sendBack(request,response);
}
You have several empty catch blocks. This means that if the program encounters some problem the error will be silently swallowed and you don't know what code got executed and what code was skipped, so the outcome is unknown. At least log the error in the catch block, like this (very basic example, using java.util.logging
} catch (SQLException e) {
logger.log(Level.INFO,"SQL Error encountered",e);
} catch (Exception e) {
logger.log(Level.INFO,"Other error encountered",e);
}
Start by getting your error handling right, and study the errors the program encounters.
Aside from that problem, as the others point out your doGet isn't implemented - so if you call the page with GET it won't do anything because doGet is empty. It should do something on POST though.

Categories