How can I display an already saved image in mongodb using angularjs? - java

I already know how to save images in mongodb using angularjs and java to save it in my mongodb, it is working fine.
Now, I need to get the saved image from mongodb and display it in an html page using AngularJS.
ps: I am aware of ngSrc.
My html:
<form method="post" enctype="multipart/form-data" name="formCadastroFotos" id="formCadastroFotos" role="form" novalidate>
<div class="form-group">
<label for="foto">Upload da Foto</label>
<input type="file" name="foto" id="foto" onchange="angular.element(this).scope().uploadFile(this.files)">
</div>
<br>
<div class="alert alert-success" ng-show="show" role="alert">
<center>
<strong>OK!</strong> Foto cadastrada com sucesso.
</center>
</div>
<div class="alert alert-danger" ng-show=showErro role="alert">
<center>
<strong>Erro!</strong> Foto não foi cadastrada com sucesso.
</center>
</div>
</form>
My js:
var myApp = angular.module('AntInformaticaApp', ['ngMessages']);
myApp.controller('CadastroFotosController', ['$scope', '$http', ' $window', function ($scope, $http, $window) {
console.log("Entrou no javascript para envio da foto.");
$scope.uploadFile = function(files) {
var fd = new FormData();
//Take the first selected file
fd.append("file", files[0]);
$http.post('cadastroFotos', fd, {
withCredentials: true,
headers: {'Content-Type': undefined }}).then(function(response) {
$scope.showOk();
}, function(response) {
console.log("erro");
$scope.showNOk();
});
};
$scope.logout = function(){
window.location = '/logout';
}
$scope.showOk = function(){
$scope.show=true;
}
$scope.showNOk = function(){
$scope.showErro=true;
}
}]);
It is going correctly to my java controller:
#Controller
public class CadastroFotosController {
#RequestMapping(value="/cadastroFotos", method=RequestMethod.POST)
public #ResponseBody MsgRetornoDTO cadastroPecas(#RequestParam("file") MultipartFile file) throws IOException {
MsgRetornoDTO retorno = new MsgRetornoDTO();
retorno = UtilGeral.salvaFotoMongo(file);
return retorno;
}
}
public static MsgRetornoDTO salvaFotoMongo(MultipartFile file){
MsgRetornoDTO retorno = new MsgRetornoDTO();
if (!file.isEmpty()) {
try {
Mongo mongo = new Mongo("localhost", 27017);
DB db = mongo.getDB("antinformatica");
DBCollection collection = db.getCollection("dummyCol");
String newFileName = file.getOriginalFilename();
File imageFile = new File(file.getOriginalFilename());
imageFile.createNewFile();
FileOutputStream fos = new FileOutputStream(imageFile);
fos.write(file.getBytes());
fos.close();
// create a "photo" namespace
GridFS gfsPhoto = new GridFS(db, "photo");
// get image file from local drive
GridFSInputFile gfsFile = gfsPhoto.createFile(imageFile);
// set a new filename for identify purpose
gfsFile.setFilename(newFileName);
// save the image file into mongoDB
gfsFile.save();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (MongoException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("empty file.");
}
retorno.setCodReturn(0);
retorno.setDescReturn("OK");
return retorno;
}
I appreciate your time helping, thanks.

have you got the answer if you get it please reply me or post it i am in same stuck. I also save image in mongodb via Angular.And I know how to fetch that image by download and dont know how to display in html page. If you get it please email id- symonkt#gmail.com

Related

Why Post controller to upload a file is not working

#PostMapping("/post")
public String write(#RequestParam("file") MultipartFile files, BoardDto boardDto) {
try {
String origFilename = files.getOriginalFilename();
String filename = new MD5Generator(origFilename).toString();
String savePath = System.getProperty("user.dir") + "\\files";
if (!new File(savePath).exists()) {
try {
new File(​savePath).mkdir();
} catch(Exception e){
e.getStackTrace();
}
}
String filePath = savePath + "\\" + filename;
files.transferTo(new File(​filePath));
​
FileDto fileDto = new FileDto();
fileDto.setOrigFilename(origFilename);
fileDto.setFilename(filename);
fileDto.setFilePath(filePath);
​
Long fileId = fileService.saveFile(fileDto);
boardDto.setFileId(fileId);
boardService.savePost(boardDto);
} catch(Exception e) {
e.printStackTrace();
}
return "redirect:/";
}
​
​
if (!new File(savePath).exists()) {
^
constructor File.File(Long,String,String,String) is not applicable
Description: I am working on a file upload project. but it's not working. File is just entity class and It's someone else's code. the guy worked fine but I'm not
You can try to rewrite this code using Files API.
For example: ...if (Files.notExists(Paths.get(savePath))) {...
It looks like you create too many File objects.
You can upload a file to a Spring controller using logic as follows:
Basic HTML that sends a file to a /upload controller:
<p>Upload an image</p>
<form method="POST" onsubmit="myFunction()" action="/upload" enctype="multipart/form-data">
<input type="file" name="file" /><br/><br/>
<input type="submit" value="Submit" />
</form>
<div>
Here is the controller:
// Upload a file.
#RequestMapping(value = "/upload", method = RequestMethod.POST)
#ResponseBody
public ModelAndView singleFileUpload(#RequestParam("file") MultipartFile file) {
try {
byte[] bytes = file.getBytes();
String name = file.getOriginalFilename() ;
// DO something with the file.
} catch (IOException e) {
e.printStackTrace();
}
return new ModelAndView(new RedirectView("photo"));
}

Getting HTML input value and using that value as a Java variable

Sorry for the long post and janky question.
I'm trying to figure out how to use an input textbox inside a form as a way to get the name of a city. With the city name, I'll then use it inside a method (getCitybyId) inside the MainController.
I'll then use it as the city name inside my api URL
Example:"http://api.openweathermap.org/data/2.5/weather?q=citynamevariable&appid=APIKey&units=imperial"
Is there any way I could do this? I'm pretty new to using spring boot and API's, and I have been trying to figure this out for a while.
Here's my code
MainController:
#RestController
public class MainController extends HttpServlet {
DataRepo dataRepo;
#RequestMapping(value = "/get", method = RequestMethod.GET)
public ModelAndView get(#RequestParam("name") String id) {
ModelAndView mv = new ModelAndView ("redirect:/");
String city = getCitybyId(id);
try{
JSONObject json = new JSONObject(city);
mv.addObject("Name", json.getString("name"));
mv.addObject("Temperature", json.getJSONObject("main").get("temp").toString());
mv.addObject("feels_like", json.getJSONObject("main").get("feels_like").toString());
mv.addObject("humidity", json.getJSONObject("main").get("humidity").toString());
mv.addObject("Wind", json.getJSONObject("wind").get("speed").toString());
}
catch (Exception e){
System.out.println(e.toString());
}
return mv;
}
private String getCitybyId(String name) {
try {
String apiKey = "key";
URL urlForGetRequest = new URL("http://api.openweathermap.org/data/2.5/weather?q=PUTCITYNAMEHERE&appid=key&units=imperial");
// These two are test to see if the method is actually getting data.
//String apiKey = "key";
// URL urlForGetRequest = new URL("https://superheroapi.com/api/" + apiKey + "/" + id);
HttpURLConnection connection = (HttpURLConnection) urlForGetRequest.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
int status = connection.getResponseCode();
System.out.println(status);
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = in.readLine()) != null) {
response.append(line);
}
in.close();
return response.toString();
}
else {
return "Unexpected HTTP response";
}
} catch (Exception e) {
return "Exception: " + e.getMessage();
}
}
}
class City
{
private String name;
public String getName()
{
return name;
}
public City()
{
name = "DEFAULT";
}
public City(String n)
{
name = n;
}
}
HTML code
<!DOCTYPE html>
<html>
<head>
<title> Homework 4 application</title>
<style><%#include file ="../css/style.css"%></style>
</head>
<body>
<h1>Please Select A City</h1>
<form method="get" action="/get/">
<input type="text" id = "name" name="name" />
<input type="submit" value="Submit">
</form>
<div>
<h2>City</h2> <h3><%=request.getParameter("Name")%></h3>
<h2>Temperature</h2> <h3><%=request.getParameter("Temperature")%> Fahrenheit</h3>
<h2>Feels Like</h2> <h3><%=request.getParameter("feels_like")%> Fahrenheit</h3>
<h2>Humidity</h2> <h3><%=request.getParameter("humidity")%>%</h3>
<h2>Wind Speed</h2> <h3><%=request.getParameter("Wind")%> Mph</h3>
</div>
<hr>
<div>
<h2>Previously Requested Cities</h2>
<table class = "lemun">
<tr>
<td>City</td>
<td>Temperature</td>
<td>Feels Like</td>
<td>Humidity</td>
<td>Wind Speed</td>
</tr>
<c:forEach var = "Data" items = "${dataList}">
<tr>
<td>${Data.getName}</td>
<td>${Data.getTemperature}</td>
<td>${Data.getFeels_Like}</td>
<td>${Data.getHumidity}</td>
<td>${Data.getWind}</td>
</tr>
</c:forEach>
</table>
</div>
</hr>
</body>
</html>
Basically, I'm trying to use the User input from the textbox as a value for the cityname inside the openweathermap URL. Is this possible? If so may you show a way to do it?

Why File uploading by custom java tag returns null

I am trying to write a java custom tag to uploaded file.But while uploading file it returns null as output.any help can appreciated
Tag Handler class:
public class SavePostTag extends SimpleTagSupport {
boolean isMultiPart;
public void doTag() throws JspException, IOException {
PageContext ctx = (PageContext)getJspContext();
HttpServletRequest request = (HttpServletRequest)ctx.getRequest();
try {
final Part tmpFile = request.getPart("file");
String fileName = request.getHeader("content-disposition");
ir.mahdiii.entity.File file = new ir.mahdiii.entity.File(Constant.repositoryPath + fileName, UrlGenerator.getInstance().generateRndUrl());
DbManager.getInstance().saveFileInfo(file);
FileOutputStream fileOutputStream = new FileOutputStream(file);
int tmp = 0;
FileInputStream fileInputstream = (FileInputStream)tmpFile.getInputStream();
while ((tmp = fileInputstream.read(new byte[1024])) != -1) {
fileOutputStream.write(tmp);
}
fileOutputStream.close();
} catch (ServletException | ClassNotFoundException | SQLException | NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
getJspContext().getOut().write("SUCCESS");
}
JSP file:
<c:if test="${param.status eq 'success'}">
<j:savepost/>
</c:if>
<div class="row">
<form action="/web/?page=admin&status=success" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit">
</form>
</div>
but at the line final Part **tmpFile = request.getPart("file"); it returns null.
any idea?

Uploading multiple files using jsp & servlets [duplicate]

This question already has answers here:
How can I upload files to a server using JSP/Servlet?
(14 answers)
Closed 2 years ago.
I am currently working on a dynamic web application that I want the user to be able to upload multiple files at once for the application to use. I don't know how many files the user may upload at once; it could be 2 or it could 100+ files. I am new to JSP dynamic web applications and I have started with a single upload file but I am not really sure where to go from here. I've looked at few examples searching but I haven't been able to find exactly what I was looking for. This is what I have so far:
Servlet:
package Servlets;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class UploadServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
if (isMultipart)
{
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
try
{
// Parse the request
List items = upload.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext())
{
FileItem item = (FileItem) iterator.next();
if (!item.isFormField())
{
String fileName = item.getName();
String root = getServletContext().getRealPath("/");
File path = new File(root + "/uploads");
if (!path.exists())
{
boolean status = path.mkdirs();
}
File uploadedFile = new File(path + "/" + fileName);
System.out.println(uploadedFile.getAbsolutePath());
if(fileName!="")
item.write(uploadedFile);
else
out.println("file not found");
out.println("<h1>File Uploaded Successfully....:-)</h1>");
}
else
{
String abc = item.getString();
out.println("<br><br><h1>"+abc+"</h1><br><br>");
}
}
}
catch (FileUploadException e)
{
out.println(e);
}
catch (Exception e)
{
out.println(e);
}
}
else
{
out.println("Not Multipart");
}
}
}
.JSP File:
<form method="post" action="UploadServlet" enctype="multipart/form-data">
Select file to upload:
<p><input type="file" name="dataFile" id="fileChooser" />
<input type="submit" value="Upload" multiple="multiple" /></p>
</form>
I am looking for a way to upload multiple files instead of just one and show them in a list.
Check the FileUPload Using Servlet 3.0
It has a working code for uploading Single File Using Servlet3.0 As you can see code is now much simplified . And there is no dependancy on apache Library.
just use below index.html
<html>
<head></head>
<body>
<form action="FileUploadServlet" method="post" enctype="multipart/form-data">
Select File to Upload:<input type="file" name="fileName" multiple/>
<br>
<input type="submit" value="Upload"/>
</form>
</body>
</html>
Only change here is I have used multiple attribute for input type File
Oh... At the first glance, looks like a simple mistake. multiple is an attribute of file input, not of the submit button.
i have upload multiple files using jsp /servlet.
following is the code that i have used.
<form action="UploadFileServlet" method="post">
<input type="text" name="description" />
<input type="file" name="file" />
<input type="submit" />
</form>
on the other hand server side. use following code.
package com.abc..servlet;
import java.io.File;
---------
--------
/**
* Servlet implementation class UploadFileServlet
*/
public class UploadFileServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public UploadFileServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.sendRedirect("../jsp/ErrorPage.jsp");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out = response.getWriter();
HttpSession httpSession = request.getSession();
String filePathUpload = (String) httpSession.getAttribute("path")!=null ? httpSession.getAttribute("path").toString() : "" ;
String path1 = filePathUpload;
String filename = null;
File path = null;
FileItem item=null;
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
String FieldName = "";
try {
List items = upload.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext()) {
item = (FileItem) iterator.next();
if (fieldname.equals("description")) {
description = item.getString();
}
}
if (!item.isFormField()) {
filename = item.getName();
path = new File(path1 + File.separator);
if (!path.exists()) {
boolean status = path.mkdirs();
}
/* START OF CODE FRO PRIVILEDGE*/
File uploadedFile = new File(path + Filename); // for copy file
item.write(uploadedFile);
}
} else {
f1 = item.getName();
}
} // END OF WHILE
response.sendRedirect("welcome.jsp");
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
images.jsp
choose files:
storeimages.java servlet
public class storeimages extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
String sav_dir=""; //this will be a folder inside
//directory
PrintWriter out =response.getWriter();
//if you want u can give this at run time
sav_dir="6022"; //in my case folder name is 6022
//you can alse set this at dynamic
int flag = 0;
//now set the path
//this is the path where my images are stored
//now u can see the code
String savepath="K:/imageupload"+File.separator +sav_dir;
File file = new File(savepath);
if(!file.exists()){
file.mkdir();
}
String filename="";
List<Part> fileParts = request.getParts().stream().
filter(part->"file".equals(part.getName())).collect(Collectors.
toList());
for(Part filePart: fileParts){
filename=Paths.get(filePart.getSubmittedFileName()).
getFileName().toString();
filePart.write(savepath+File.separator+filename);
flag=1;
}
if(flag==1){
out.println("success");
}
else{
out.println("try again");
}
//now save this and run the project
}
}
You only have to write multiple, because multiple is a boolean var and only defining it, it will be true to your tag. Example below:
<input type="file" name="file" id="file" multiple/>
This will let you choose multiple files at once. Good luck
This is how I did. It will dynamically add and remove the field (multiple files). Validates it and on validation calls the action method i.e the servlet and store in the DB.
** html/jsp **
.jsp file
<div class="recent-work-pic">
<form id="upload_form" method="post" action="uploadFile" enctype="multipart/form-data" >
<input type="hidden" id="counter" value="1" >
Add
<div class="record"><input type="file" placeholder="Upload File" name="uploadFile_0" class="upload_input"></div>
<div id="add_field_div"></div>
<button type="submit" class="btn btn-read">Submit</button>
</form>
<p>${message}</p>
</div>
jquery validation
<script>
$(document).ready(function(){
$('#add_fields').click( function(){
add_inputs()
});
$(document).on('click', '.remove_fields', function() {
$(this).closest('.record').remove();
});
function add_inputs(){
var counter = parseInt($('#counter').val());
var html = '<div class="record"><input type="file" placeholder="Upload File" name="uploadFile_' + counter + '" class="upload_input">Remove</div>';
$('#add_field_div').append(html);
$('#counter').val( counter + 1 );
}
$('form#upload_form').on('submit', function(event) {
//Add validation rule for dynamically generated name fields
$('.upload_input').each(function() {
$(this).rules("add",
{
required: true,
messages: {
required: "File is required",
}
});
});
});
$("#upload_form").validate();
});
</script>
servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// KeycloakPrincipal principal = (KeycloakPrincipal) request.getUserPrincipal();
PrintWriter writer = response.getWriter();
Properties properties = new Properties();
properties.load(this.getClass().getClassLoader().getResourceAsStream("/resources/datenBank.properties"));
if (!ServletFileUpload.isMultipartContent(request)) {
writer.println("Fehler: Form must has enctype=multipart/form-data.");
writer.flush();
return;
}
String message = null;
InputStream inputStream = null;
Connection dbConnection = null;
String page = "";
try {
for (Part filePart : request.getParts()) {
System.out.println("filePart" + filePart.getName() + "-----" + filePart.getSize());
if (filePart != null && filePart.getSize() != 0) {
inputStream = filePart.getInputStream();
System.out.println("inputStream" + inputStream);
HttpSession session=request.getSession();
session.setAttribute("username",request.getRemoteUser());
Class.forName(properties.getProperty("driverClassName"));
dbConnection = DriverManager.getConnection(properties.getProperty("url"), properties.getProperty("username"), properties.getProperty("password"));
if (dbConnection != null) {
String sql = "INSERT INTO skl_lieferung (file_name, file_size, file_content,file_content_type, entry_time, user) values (?,?,?,?,?, ?)";
PreparedStatement statement = dbConnection.prepareStatement(sql);
if (inputStream != null) {
statement.setString(1, getFileName(filePart));
statement.setLong(2, filePart.getSize());
statement.setBlob(3, inputStream);
statement.setString(4, filePart.getContentType());
}
Calendar calendar = Calendar.getInstance();
java.sql.Date entryDate = new java.sql.Date(calendar.getTime().getTime());
statement.setDate(5, entryDate);
statement.setString(6, request.getRemoteUser());
//statement.setString(6, username);
int row = statement.executeUpdate();
if (row > 0) {
message = "Datei hochgeladen und in der Datenbank gespeichert";
}else {
message = "Fehler: Connection Problem";
}
} message = "Datei hochgeladen und in der Datenbank gespeichert";
}else {
page = "index.jsp";
System.out.println("cannot execute if condition");
message = "Das Upload-Feld darf nicht leer sein ";
RequestDispatcher dd = request.getRequestDispatcher(page);
dd.forward(request, response);
return;
}
}
}catch (Exception exc) {
page = "index.jsp";
message = "Fehler: " + exc.getMessage();
exc.printStackTrace();
} finally {
if (dbConnection != null) {
try {
dbConnection.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
page = "index.jsp";
request.setAttribute("message", message);
RequestDispatcher dd = request.getRequestDispatcher(page);
dd.forward(request, response);
}
}
}
private String getFileName(Part part) {
for (String content : part.getHeader("content-disposition").split(";")) {
if (content.trim().startsWith("filename")) {
return content.substring(content.indexOf('=') + 1).trim().replace("\"", "");
}
}
return null;
}
I hope people find it useful!!
To upload a single file you should use a single tag with attribute type="file". To allow multiple files uploading, include more than one input tags with different values for the name attribute. The browser associates a Browse button with each of them.
That is, use the below line multiple times:
<input type="file" name="dataFile" id="fileChooser" /><br><br>
Refer this link for details
I hope this helps.

How to manage back end process with Tomcat?

I have a web page that the user pushes a button and initiates an action in a proprietery app (which resides in Tomcat).
That action is a long running process and the only way I have to see what's going on is to log onto the server and look at a log file.
I wrote a quick Java function that reads the log file and gives feedback on what's happening. (Essentially it just tails the file and parses out the things I need)
I'd like to be able to add a jsp that I can view the output without logging into the server.
===
From a design standpoint, I understand that the JSP should return quickly with a result and not just keep on processing.
So my idea is to create a simple web page that queries the jsp for an update and writes the latest info to the screen. Wait 30 seconds, poll the server again, and append the latest update.
What I'm struggling to grasp is how to get the JSP to communicate with the back end process, and how that back end process should be spawned / killed.
This is a very occasional thing (once every two weeks, start to completion takes an hour or two), so I don't want a daemon running all the time. I want to be able to turn it on temporarily and turn it off.
If I spawn a process from within a simple servlet, how do I end that process when I'm done?
And how do I communicate with it?
You can create a java.lan.Runnable witch reads the file content an saves it into a buffer. The Runnable reads the file content withing a while loop for witch the break condition can be set from outside, Thread that is executing your Runnable will terminate whe the run method of your Runnable terminates.
In your JSP you can create a java.lang.Thread and pass an instance of your Runnable to it. Save th instace of the runable in the ServletContext so you can access it across the requests. If you want to terminate the polling than just set the break condition of your Runnable from the JSP, the rum method will terminate and thus the thread too.
You can use javascript setInterval() function and XMLHttpRequest refresh the page.
here is a sample basic implemntation (I hope this will meet your requirements):
Polling Runnable
package com.web;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
public class FilePollingThread implements Runnable {
private String filepath = null;
private boolean polling = false;
private StringBuffer dataWritenAfterLastPoll = null;
private String error = null;
public FilePollingThread(String filepath) {
this.filepath = filepath;
}
#Override
public void run() {
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(filepath)));
dataWritenAfterLastPoll = new StringBuffer();
polling = true;
String line = null;
while(polling) {
try {
line = br.readLine();
while(line == null) {
try {
Thread.sleep(500L);
} catch (InterruptedException e) {
e.printStackTrace();
error = e.toString();
}
line = br.readLine();
}
dataWritenAfterLastPoll.append(markUp(line));
} catch (IOException e) {
e.printStackTrace();
error = e.toString();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
error = e.toString();
} finally {
if(br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
error = e.toString();
}
}
}
}
private String markUp(String line) {
String markup = "";
if(line != null) {
markup = "<div style=\"height: 6px\"><span style=\"line-height: 1.1;\">" + line + "</span></div>\n";
}
return markup;
}
public synchronized void stopPolling() {
polling = false;
}
public synchronized String poll() {
String tmp = markUp(error == null ? "Not ready" : error);
if(dataWritenAfterLastPoll != null) {
tmp = dataWritenAfterLastPoll.toString();
dataWritenAfterLastPoll = new StringBuffer();
}
return tmp;
}
}
And a JSP witch initiats the polling an keep retrieving data
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="com.web.FilePollingThread" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Poll file</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<link rel="stylesheet" type="text/css" href="style/default.css"></link>
<script type="text/javascript">
var c = 1;
var ih;
var polling = false;
var filepath = null;
function startPolling(interval) {
ih = setInterval(function () {
try {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function () {
if(xmlHttp.readyState == 4) {
if(xmlHttp.status == 200) {
var w = getElementById('ajax_content');
w.innerHTML = w.innerHTML + xmlHttp.responseText;
getElementById('page_refresh').innerHTML = c++;
polling = true;
window.scrollTo(0, document.body.scrollHeight);
} else {
polling = false;
throw 'HTTP ' + xmlHttp.status;
}
}
};
xmlHttp.open('GET', 'pollfile.jsp?filepath=' + filepath + '&c=' + c, true);
xmlHttp.send();
} catch(e) {
alert('Error at startPolling: ' + e);
clearInterval(ih);
}
}, interval);
}
function startStopPolling() {
var orgPolling = polling;
try {
if(polling) {
polling = false;
clearInterval(ih);
doPolling();
} else {
polling = true;
doPolling();
startPolling(1000);
}
flipStartStopButtonsLabel();
} catch(e) {
polling = orgPolling;
flipStartStopButtonsLabel();
alert('Error at startStopPolling: ' + e);
}
}
function flipStartStopButtonsLabel() {
var label;
if(polling) {
c = 1;
label = 'Stop polling';
getElementById('page_refresh').innerHTML = '0';
} else {
label = 'Sart polling';
getElementById('page_refresh').innerHTML = 'stoped';
}
var buttons = document.getElementsByName('start_stop_polling');
if(buttons) {
for(var i = 0; i < buttons.length; i++) {
buttons[i].value = label;
}
}
}
function doPolling() {
var url = 'pollfile.jsp?polling=';
if(polling) {
filepath = getElementById('filepath');
if(filepath && filepath.value && filepath.value.length > 0) {
url += 'true&filepath=' + encodeURIComponent(filepath.value);
} else {
throw 'No filepath specified.';
}
} else {
url += 'false';
}
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function () {
if(xmlHttp.readyState == 4) {
if(xmlHttp.status != 200) {
throw 'HTTP ' + xmlHttp.status;
}
}
};
xmlHttp.open('POST', url, false);
xmlHttp.send();
}
function clearWindow() {
var w = getElementById('ajax_content');
if(w) {
w.innerHTML = '';
}
}
function getElementById(id) {
try {
if(id) {
elm = document.getElementById(id);
return elm;
}
} catch(e) {
alert('Error at getElementById: ' + e);
}
return null;
}
</script>
</head>
<body>
<%
String polling = request.getParameter("polling");
if("true".equals(polling)) {
String filepath = request.getParameter("filepath");
if(filepath != null && filepath.length() > 0) {
FilePollingThread pollingThread = new FilePollingThread(filepath);
new Thread(pollingThread, "polling thread for file '" + filepath + "'").start();
request.getServletContext().setAttribute("pollingThread", pollingThread);
}
} else if("false".equals(polling)) {
FilePollingThread pollingThread = (FilePollingThread) request.getServletContext().getAttribute("pollingThread");
if(pollingThread != null) {
pollingThread.stopPolling();
}
} else {
FilePollingThread pollingThread = (FilePollingThread) request.getServletContext().getAttribute("pollingThread");
if(pollingThread != null) {
response.getWriter().println(pollingThread.poll());
response.getWriter().close();
return;
}
}
%>
<div class="label">
<span>Page polling:</span>
</div>
<div style="float: left;">
<span id="page_refresh">0</span>
</div>
<div class="clear_both"> </div>
<form id="input_form" action="pollfile.jsp" method="get">
<div>
<div style="float: left;">
<label>Filepath:
<input style="height: 24px;" id="filepath" type="text" size="120" value=""/>
</label>
</div>
<div style="clear: both;"/>
<div style="float: left;">
<input style="height: 24px;" name="start_stop_polling" id="start_stop_polling_button" type="button" onclick="startStopPolling(); return false;" value="Start polling"/>
</div>
<div style="float: left;">
<input style="height: 24px;" name="clear_window" id="clear_window_button" type="button" onclick="clearWindow(); return false;" value="Clear"/>
</div>
<div style="clear: both;"> </div>
</div>
</form>
<div id="ajax_content">
</div>
<div>
<div style="float: left;">
<input style="height: 24px;" name="start_stop_polling" id="start_stop_polling_button" type="button" onclick="startStopPolling(); return false;" value="Start polling"/>
</div>
<div style="float: left;">
<input style="height: 24px;" name="clear_window" id="clear_window_button" type="button" onclick="clearWindow(); return false;" value="Clear"/>
</div>
<div style="clear: both;"> </div>
</div>
</body>
</html>
EDIT
there is a bug in FilePollingThread: if no data is available in the file the thread might get stuck in inner while loop. it should be
while(line == null && polling)
also the JSP will not work on IE (testet on IE9). It seems that the data writen to the response in the line
response.getWriter().println(pollingThread.poll());
contains the HTML of the hole page. If added to the target div IE seems not able to render it.
I made another version using a simple static HTML file an a servlet as it offers more controle on what is writen to response.
If you are interested in the code let me know.
You should consider using something like JMS to control your background process.
For control, your front-end code can send messages start/stop/inspect the process.
For monitoring, your process can publish to a JMS topic for your front end code to read.

Categories

Resources