3c. Simple Servlet application to demonstrate Non-Blocking Read Operation


index.html

<html>
<head>
<title>Non Blocking IO</title>
<meta charset="UTF-8">
<meta http-equiv="Refresh" content="0; URL=NonBlockingServlet">
</head>
<body>
</body>
</html>


-------------------------------  NonBlockingServlrt.java ---------------------

package nonblkapp;

import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class NonBlockingServlet extends HttpServlet {
protected void service(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8);
try (PrintWriter out = response.getWriter()) {
out.println("<h1>FileReader</h1>");
String filename="/WEB-INF/booklist.txt";
ServletContext c=getServletContext();
InputStream in=c.getResourceAsStream(filename);
String path="http://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/ReadingNonBloclingServlet";
URL url=new URL(path);
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
conn.setChunkedStreamingMode(2); conn.setDoOutput(true);
conn.connect();
if(in!=null)
{
InputStreamReader inr=new InputStreamReader(in);
BufferedReader br = new BufferedReader(inr);
String text="";
System.out.println("Reading started....");
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
while((text=br.readLine())!=null)
{
out.print(text+"<br>");
try{
Thread.sleep(1000);
out.flush();
}
catch(InterruptedException ex){}
out.print("reading completed....");
bw.flush();
bw.close();
}
}
}
}


--------------------------- ReadingListener.java --------------------------

package nonblkapp;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.AsyncContext;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
public class ReadingListener implements ReadListener {
private ServletInputStream input = null;
private AsyncContext ac = null;
ReadingListener(ServletInputStream in,  AsyncContext c)
{
 input = in;
ac = c;
}
@Override
public void onDataAvailable() throws IOException {
}
public void onAllDataRead() throws IOException {
ac.complete();
}
public void onError(final Throwable t) {
ac.complete();
t.printStackTrace();
}
}




Comments