I'm trying to generate a pdf file from data in a database using JasperReports with a java servlet. The first time I generated a pdf file successfully with data in database. Then I made some changes in my database table and recreated jrxml file and created a jasper file using that jrxml file. But now when I am trying to generate a pdf, the pdf file is always empty.
Code in my Servlet
response.setContentType("application/pdf");
try {
HttpSession hs = request.getSession();
String id = (String) hs.getAttribute("id");
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/exam", "root", "pass");
Statement statement = con.createStatement();
ResultSet resultSet = statement.executeQuery
("SELECT marks, date_time FROM result where sub_id = 1 and user_id = 3");
ServletOutputStream set = response.getOutputStream();
InputStream re = getServletConfig().getServletContext().getResourceAsStream("./results.jasper");
JRResultSetDataSource resultSetDataSource = new JRResultSetDataSource(resultSet);
JasperRunManager.runReportToPdfStream(re,set, new HashMap(), resultSetDataSource);
} catch (Exception e) {
}
How could I solve this?
Change every catch to
...
} catch (Exception e) {
e.printStackTrace();
}
That will provide details of what is going wrong, and where.
Related
A web app, the client side is jsp and backend is JAVA, DB is simple sqlite.
In the DB there is a table that contains "files" called Reports, and users are allowed to download each file in the DB only ONCE "Due to security requirements", and I have been trying to find a way to do that.
Is there anyway I can write a jsp code that allows the users to download the requested file once from the DB?
I don't know if it is useful but this is the JAVA piece of code that is used to download from the DB.
String sql = "SELECT file, filename FROM reports INNER JOIN download USING(tipid) WHERE reports.tipid = ?"+
"AND download.ts_" + ae_num+ " = 0;";
PreparedStatement stmt = c.prepareStatement(sql);
String tipNum = request.getParameter("tipid");
if (tipNum != null) {
stmt.setString(1, tipNum);
//stmt.setString(2, tipNum);
ResultSet res = stmt.executeQuery();
BufferedInputStream fileBlob = null;
String filename = "";
while (res.next()) {
fileBlob = new BufferedInputStream(res.getBinaryStream("file"), DEFAULT_BUFFER_SIZE);
filename = res.getString("filename");
}
if (fileBlob != null) {
System.out.println(filename);
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
BufferedOutputStream output = new BufferedOutputStream(response.getOutputStream(),
DEFAULT_BUFFER_SIZE);
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = fileBlob.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
output.close();
fileBlob.close();
Date now = new Date();
sql = "UPDATE download SET ts_" + ae_num + " = " + now.getTime() + " WHERE tipid = ?;";
System.out.println(sql);
stmt = c.prepareStatement(sql);
stmt.setString(1, tipNum);
stmt.executeUpdate();
stmt.close();
c.commit();
c.close();
The current problem I'm having is that whenever a user is trying to download the requested file and whether the user chose to open/save or cancel, it will be counted as a downloaded file, even with a cancel.
Any ideas? Would using cookies in JSP help to implement that? If so can someone guide me? Or how to solve the download count issue
If you have control over the database, you could possibly have another table with the user_id, file_id, download_status column. That way you could always have the records who downloaded the file.
I'm trying to save an image in Postgresql Database but unable to do that I'm trying to call a function in which I need to Pass image in bytea code.
function to store Image is
CREATE OR REPLACE FUNCTION products_update_image(product_id character varying, img bytea)
RETURNS void AS
'BEGIN UPDATE PRODUCTS SET IMAGE=img::bytea WHERE ID=product_id; END;'
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION products_update_image(character varying, bytea)
OWNER TO postgres;
Answer is very simple for this question. Recently I also worked on this and faced same issue that you are facing, you can use below code.
// Save an image from server to physical location
String destinationFile = "C:\\Program Files (x86)\\openbravopos-2.30.2\\image1.jpg";
// This will call a function which will save an image on your given Location
saveImage(image, destinationFile);
// You don't need to call procedure here just pass this query
PreparedStatement pstmt = con.prepareStatement("UPDATE PRODUCTS SET IMAGE = ? WHERE ID = ?");
// Location of image with it's name
File file = new File("Location\\image1.jpg");
FileInputStream in = new FileInputStream(file);
try
{
pstmt.setBinaryStream(1, in, (int) file.length());
pstmt.setString(2, id);
pstmt.executeUpdate();
}
catch (Exception ee)
{
System.out.println("Exception is:- " + ee);
}
// Function that saved Image on local Location
public static void saveImage(String imageUrl, String destinationFile) throws IOException
{
URL url = new URL(imageUrl);
InputStream is = url.openStream();
OutputStream os = new FileOutputStream(destinationFile);
byte[] b = new byte[2048];
int length;
while ((length = is.read(b)) != -1)
{
os.write(b, 0, length);
}
is.close();
os.close();
}
I hope this will work for you as this worked for me
I got this while trying to execute
File f = new File("file location");
FileInputStream fis = new FileInputStream(f);
PreparedStatement ps = db.prepareStatement("INSERT INTO table (title,file,id) VALUES('title',?,7)");
ps.setBinaryStream(1, fis, (int)f.length());
ps.execute();
ps.close();
title - VARCHAR2
file - BLOB
id - FK to another table
Operations with another tables are working, everything is fine but this one. I tried to change statement, drop and recreate table. Without result
I am creating a website with jsp&servlet
and I want to ask :
What's the best way to store an image in a database (mysql) and retrieve it
to using it as profile's picture
And how can i do that?
Thanks you all in advance.
Two common solutions :
directly in the database in a byte field
on the disk, with the path stored in database (I personnaly like to use as name the SHA1 of the file, so I cannot have two times the same file, with the path being a/b/cdef if the SHA1 is abcdef)
Both solutions work very well. The first solution has for advantage to have only one file to backup, to enable rollback, and so on. The second may be more natural as a disk file system is made to store files.
save image in a folder on the server.
save image path in db .
at the time of display get the image path from db and retrieve image.
Store image in database.
import java.sql.*;
import java.io.*;
public class insertImage{
public static void main(String[] args) {
System.out.println("Insert Image Example!");
String driverName = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/";;
String dbName = "databasename";
String userName = "root";
String password = "root";
Connection con = null;
try{
Class.forName(driverName);
con = DriverManager.getConnection(url+dbName,userName,password);
Statement st = con.createStatement();
File imgfile = new File("images.jpg");
FileInputStream fin = new FileInputStream(imgfile);
PreparedStatement pre = con.prepareStatement("insert into Tablename values(?)");
pre.setBinaryStream(3,fin,(int)imgfile.length());
pre.executeUpdate();
System.out.println("Inserting Successfully!");
pre.close();
con.close();
}
catch (Exception e){
System.out.println(e.getMessage());
}
}
}
Retrieve image from database using Servlet
http://www.roseindia.net/servlets/retreiveimage.shtml
I am trying to download video file stored as blob in Mysql. The file gets downloaded fine but it gets corrupted i guess. The formats to downloaded are ogg, webm n mp3. The problem is that wen i try to convert any video using ffmpeg, it says "invalid data found during processing".
I am using the following code
Blob image = null;
Connection con = null;
ResultSet rs = null;
try{
Class.forName("com.mysql.jdbc.Driver");
con = MySqlConnect.getDBConnection();
String sql = "select videos, filename from sun.videostore where id ='"+fileID+"'";
Statement stmt = con.createStatement();
rs = stmt.executeQuery(sql);
while (rs.next()) {
String filename = rs.getString("filename");
Blob video = rs.getBlob("videos");
File file1 = new File("C:\\DowloadFile\\" + filename);
FileOutputStream foStream = new FileOutputStream(file1);
if( video != null){
int length = (int) video.length();
InputStream is2 = video.getBinaryStream();
int b = 0;
while(b!=-1){
b=is2.read();
foStream.write(b);
}
}
}
}catch(Exception e){
System.out.println("Ecxeption in getting data from DB = "+e);
}'
No i have checked my uploaded file, it is not corrupted....I have tried a different way to upload the video into DB.
File video = new File(filename);
fis = new FileInputStream(video);
ps.setBinaryStream(2, fis, (int) video.length());//preparedStatement
If i upload the file in above way, i get a correct file on downloading.