i read a file txt with java code and then i display it's content with js in html page but the content changes over time so i can't acces to file if the content was change:
the java code :
the methode that read file and return a string that containing the txt file content
public static String getLog() throws IOException{
StringBuilder sb = new StringBuilder();
String path=logging.getRealPath();
InputStream ips;
try {
ips = new FileInputStream(path);
InputStreamReader ipsr=new InputStreamReader(ips);
BufferedReader br=new BufferedReader(ipsr);
String ligne;
while((ligne=br.readLine())!=null){
sb.append("<br>"+ligne);
br.close();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sb.toString();
}
and the js function
<script type="text/javascript">
function getALLLog(){
var arrayNew = "<%=logging.getLog()%>";
document.getElementById("log").innerHTML=arrayNew;
}
</script>
the html code is like:
<div style="padding:15px" >
<span id="ALL" style="cursor: pointer;font-weight:bold;" onclick="getALLLog()">ALL</span>
</div>
<div id="log"></div>
so the content is displayed for the first time after filling the file nothing appears
Your java getLog() function gets evaluated only once when the server generates html. After that javascript variable arrayNew holds the log contents. When you click on the ALL span you don't actually call your java server - only client-side javascript, so you just showing the same content over and over.
If you want server to be called when you click some button on the web page you need to use AJAX or just refresh the entire page.
Related
I want to show the BootStrap's progress bar while am downloading file from Sevlet API.
Application architecture designed like - From React JS using SuperAgent am invoking Servlet API which is responsible for writing a Excel file and it will return that Excel file to the SuperAgent to download the same.
While doing this process i want to show the BootStrap's progress bar for UX.
Please find my code below
Servlet API code for writting a Excel file and return the same to SuperAgent
try {
String reportname = "Invoice";
resp.setContentType("application/vnd.ms-excel");
resp.setHeader("Content-Disposition", "attachment; filename=" +
reportname + ".xls");
HSSFWorkbook workbook1=service.getCommercialInvoiceService(id);
ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
workbook1.write(outByteStream);
byte [] outArray = outByteStream.toByteArray();
int fileSize=outArray.length;
outStream = resp.getOutputStream();
outStream.write(outArray);
outStream.flush();
outStream.close();
resp.setHeader("Content-Length", ""+fileSize);
} catch (IOException ioe) {
throw new ServletException(ioe);
}
ReactJS method which is using SuperAgent to download file from Servlet API
handleInvoice(e) {
e.preventDefault()
var item = this.state.item;
var lines = item.order;
var request = require('superagent');
var apiBaseUrl = "api/Invoice";
var req = request.get(apiBaseUrl);
req.query({ item : item.id})
req.end(function(err,res) {
if(err) {
alert(" error"+err);
confirmAlert({
message: 'Invoice is not prepared properly.....',
confirmLabel: 'Ok',
});
}
else {
window.location= 'api/Invoice?item=' + item.id,'';
element.click();
}
});
}
I want to show the below bootstrap's progress bar while downloading the file.
<div class="progress">
<div class="progress-bar" role="progressbar" aria-valuenow="" aria-
valuemin="0" aria-valuemax="100" style="width: 60%;">
</div>
</div>
How do i integrate progress bar in ReactJS code ( SuperAgent is invoking the Java Servlet API).
Your code which writes the headers and data is as follows..
int fileSize=outArray.length;
outStream = resp.getOutputStream();
outStream.write(outArray);
outStream.flush();
outStream.close();
resp.setHeader("Content-Length", ""+fileSize);
Note that the content length is being set after the output stream has been written to. HTTP responses consist of a series of headers followed the content, which you write to via the OutputStream. Here you have simply set the content length after streaming the content. So this value is not sent at the start of the response.
The content length of the output is not mandatory (it might not be known by the process streaming it). But of course you can't produce a progress bar unless you know the length of the data. Simply set the content length before writing the data so it makes it into the response headers.
int fileSize=outArray.length;
resp.setHeader("Content-Length", ""+fileSize);
outStream = resp.getOutputStream();
outStream.write(outArray);
outStream.flush();
outStream.close();
I'm using JSoup to parse a bunch of XML links from a HTML page. I connect to the page, and parse it for all anchor tags like so:
Document htmlDoc = null;
location = location.replace("\\", "/").replace("http:/", "http://") + "/";
try {
htmlDoc = Jsoup.connect(location).get();
} catch (IOException e) {
e.printStackTrace();
}
return htmlDoc.select("a");
It's finding the page, and loading just under half of the <a> tags that have links to the xml documents. For some reason though, it's stopping just under half way. When I use IntelliJ and I try to view the last xml link in the list, I'm seeing this:
However, the highlighted <a> tag appears just under half way down the page, meaning it is only retrieving about half of the desired tags. It's worth noting that this HTML page is huge and I'm expecting about 9,000 <a> tags to be returned. At the moment I'm getting 4383.
Is this a common issue with JSoup? Does it have some sort of timeout, or memory cap?
Edit
So, I pulled the pure HTML code that my program is pulling down from the server, and this is what I'm seeing:
<td valign="top"><img src="/icons/text.gif" alt="[TXT]" /></td>
<td>IEHRES30J8M4_1378047310463.xml</td>
<td align="right">01-Sep-2013 15:55 </td>
</tr>
</tbody>
</table>
</body>
</html>
Now, this is showing all the necessary closing tags. It isn't just stopping half way through the tags. Either JSoup tidies up the HTML if it runs out of memory, or it thinks that is the whole content of the web page?
Further Issue
I found a method called maxBodySize in the Jsoup.Connection object. I set the maxBodySize to 1048576 (10MB). The file that is being retrieved is 4MB in size, however this still hasn't fixed the issue. Here is the amended code:
Document htmlDoc = null;
location = location.replace("\\", "/").replace("http:/", "http://") + "/";
try {
logger.info("Parsing XML Files from " + location);
Connection conn = Jsoup.connect(location);
conn.maxBodySize(1048576);
htmlDoc = conn.get();
} catch (IOException e) {
e.printStackTrace();
}
return htmlDoc.select("a");
After further inspection, I found that my web page loads itself in two increments. I imagine it is because of the sheer volume of data. The last entry in my jSoup array of <a> tags corresponded to the last <a> on the first increment of the page.
I got around this by pulling the HTML down separately with this method:
private static String getHtml(String location) throws IOException {
URL url = new URL(location);
URLConnection conn = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String input;
StringBuilder builder = new StringBuilder();
while((input = in.readLine()) != null)
{
builder.append(input);
}
return builder.toString();
}
And then calling the Jsoup.parse method on the resulting string. This meant I had all the data, and it actually improves performance (although for the life of me I don't know how).
I tested jsoup with generated HTML files containing more than 50.000 (fifty-thousand)
anchor-tags.
Jsoup parsed these files completely and was able to select all of the anchor elements
and href attributes correctly...
So imho it's no fundamental jsoup issue.
I have a simple JSP page, which contains 2 buttons: View and Export. When View button is clicked I will fetch data from DB, keep a copy into session and write an HTML code into a label with the data. Later when user clicks Export I want to generate an excel file in the server(with the data from session) and download it to clientside.
Excel file is successfully created at serverside. I am using an AJAX request from clientside to download Excel file from server.
JSP code:
try{
String filepath=ExportToExcel(session.getAttribute("InvestmentDetails"));
//Setting file to download
response.setContentType( "application/x-download");
response.setHeader("Content-Disposition","attachment; filename=\"SIPInvestment_531.xls\"");
response.setStatus(200);
InputStream in = null;
ServletOutputStream outs = response.getOutputStream();
try {
File filetodownload=new File(filepath);
response.setContentLength(Integer.parseInt(String.valueOf(filetodownload.length())));
in = new BufferedInputStream(new FileInputStream(filetodownload));
int ch;
while ((ch = in.read()) != -1) {
outs.print((char) ch);
}
}
finally {
if (in != null) in.close();
}
outs.flush();
outs.close();
}
catch(Exception ex){
str=ex.getMessage();
}
Here is the Javascript:
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
}
}
xmlhttp.open("POST","/SIP/rptClientInvestmentDetails.jsp?requesttype=export",false);
xmlhttp.send();
The request reaches on JSP page. And without any exception it writes to response outputstream. But no download is pop up from browser. What can be the problem?
Ajax should be used for meta-languages, not for binary files.
A simple
<a href="/SIP/rptClientInvestmentDetails.jsp?requesttype=export"
target="_blank">Export</a>
is all you need.
If you make sure you said the response.setHeader("Content-Disposition","attachment you should drop the target-attribute as BalusC suggested.
I think you can use location.href="Provide the java class function name".This will transfer the control from jsp to java function without using the ajax call
I am trying to retrieve images from database.
Currently i was able to show :
`com.mysql.jdbc.Blob#2aba2aba `
in my jsp output.
May i know how to convert that into an image?
i have use the below to call out the above
photo[i].getPhotoFileData();
This is more of an issue with the way HTML documents work than with your JSP. You need to understand that HTML doesn't embed images directly. Instead, it uses <img> tags to reference images hosted at different URLs.
In order to display an image stored in a database on an HTML page you're going to need a separate servlet that can handle requests for the image. Your JSP should render an HTML document like the following:
<html>
<head>
...
</head>
<body>
...
<img src="www.mydomain.com/images/1234.png" />
...
</body>
</html>
Then you would create a separate servlet to handle all the requests to /images which would make a database call and send the raw bytes from the blob it gets back to the response's output stream. Make sure you also set the Content-Type header correctly based on what image encoding you're using.
In order to send the image back to the requester you have one of two options. You can get the blob's bytes as an array and write that to the OutputStream (e.g. out.write(blob.getBytes(0,blob.length());). Or you can use the getBinaryStream() method and then copy bytes from the InputStream to the OutputStream. Here's an example of that:
public static void copy(Blob from, OutputStream to)
throws IOException {
byte[] buf = new byte[4096];
try(InputStream is = from.getBinaryStream()) {
while (true) {
int r = is.read(buf);
if (r == -1) {
break;
}
to.write(buf, 0, r);
}
}
}
NB: This code has not been tested or even compiled, it should only be used as a starting point.
You're getting a Blob object - not it's contents. If you want to get raw byte data you have to ask the Blob object for it, e.g.:
Blob blob = photo[i].getPhotoFileData();
byte[] data = blob.getBytes(0, blob.length());
If you want to create an image on the fly, then just call:
BufferedImage img = ImageIO.read(new ByteArrayInputStream(data));
You can then save the image or ... actually I don't know what else. Thing. Stuff. Display it. Print. Limitless possibilities! Just like at zombo.com!
first convert blob to input stream to string . then use that String instead of image URL .
Converting blob to String
try {
Blob blob = staticOffer.getImage(); //blob of image from db
strOut = new StringBuffer();
String aux;
BufferedReader br;
br = new BufferedReader(new InputStreamReader(blob.getBinaryStream()));
while ((aux=br.readLine())!=null) {
strOut.append(aux);
}
offerPicStr = strOut.toString();
} catch (Exception e) {
e.printStackTrace();
}
Now use that string it html/jsp in following way
<img src="data:image/jpeg;base64,${offerPicStr}" width="100" height="100"></img>
I trying to upload a zip file. In my project i am using DWR in the client side and Java in server side. As i have seen in DWR tutorials for uploading data(Its not in their website. They are providing it with dwr.rar bundle) they getting input by the below lines.
var image = dwr.util.getValue('uploadImage');
var file = dwr.util.getValue('uploadFile');
var color = dwr.util.getValue('color');
dwr.util.getValue() is a utility to get the value of any element, in this case a file object.//Mentioned in the tutorial.
So, i get a zip file using that utility by the below code.
Javascript:
function uploadZip(){
var file = dwr.util.getValue("uploadFile");
dwr.util.setValue("uploadFile", null);
DataUpload.uploadData(file, function(data){
if(data != null){
$("#zipURL").html("<p>Upload Completed!!!</p>");
$("#zipURL").append("Location: "+data.path2);
}
});
}
HTML:
<html>
<head>ZIP Uploader
</head>
<body>
<table>
<tr><td>Select File: </td><td><input type="file" id="uploadFile" /></td>
<tr><td><input type="button" value="Upload" onclick="uploadZip()" /></td></tr> </table>
<div id="result"><span id="imgURL"></span>
<span id="zipURL"></span></div>
</body>
</html>
The Java Code is:
public class DataUpload {
private static String DATA_STORE_LOC = "D:/BeenodData/Trials/";
public Path uploadData(InputStream file) throws IOException{//In the tutorial the
//parameters are in type of BufferedImage & String.
//They used it for image and text file respectively.
//In an another example(out of DWR site) they used InputStream for receiving
//image
try {
byte[] buffer = new byte[1024];
int c;
File f2 = new File(DATA_STORE_LOC+dat+".zip");
path.setPath2(DATA_STORE_LOC+dat+".zip");
FileOutputStream fos = new FileOutputStream(f2);
c = file.read();
System.out.println(c);
while ((c = file.read()) != -1) {
fos.write(c);
}
file.close();
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return path;
}
This code runs without error. But the output is a Empty zip file. I know i doing something wrong. I unable to find that.
Actually, i am receiving a zip file as
InputStream.
How should i have to write a
InputStream(a zip file) to a zip.file
using java?
What will happen if i set the java
method parameter as ZipFile file? I
didnt tried it, yet because, i am
still searching a good tutorial to
learn about it.
Any Suggestion or Links would be more appreciative!!!!!
Thanks in Advance!!!
Here you have 2 examples about creating a ZIP file:
http://www.java2s.com/Tutorial/Java/0180_File/0601_ZipOutputStream.htm
Here is an example about reading a ZIP file:
http://www.kodejava.org/examples/334.html
I have also implemented the Same kind of backend Code in Java, and I was facing the same Issue of Zip file being made, but its content being empty.
Later I found that the Request I was making to API, in that the file I was Attaching was not in --data-binary format. So, I then made the request in this Format.
curl --data-binary #"/mnt/c/checknew.zip" http://localhost/api/upload
I am not sure what request format you are making either in multipart/form-data or Base-64 encoded.
My code worked when I made a Base-64 encoded Request (i.e --data-binary)