utf-8 oracle clob, write/read pdf in java? - java

my mission is to change 2 php pages with a java webapp that writes an upload pdf file to a clob and reads it when user ask for a download.
I threated the pdf as a byte array and have been able to read/write it correctly
the big problem is the backward compatibility: files written by php are not readable by my java webapp and vice-versa
thanks in advance for help
NOTE: Do not answer me to use a Blob, I know it is the easy way but in this case we have to assume we cannot make an alter table on the db due to backward compatibility
Here's my code to read the clob into a byte array:
byte[] result = null;
InputStream is = null;
ByteArrayOutputStream bos = null;
//...prepare the query to get clob as first column in the resultset
ResultSet rs = stmt.executeQuery();
int len;
int size = 1024;
byte[] buf;
if(rs.next()) {
is = rs.getBinaryStream(1);
bos = new ByteArrayOutputStream();
buf = new byte[size];
while ((len = is.read(buf, 0, size)) != -1)
bos.write(buf, 0, len);
bos.flush();
bos.close();
is.close();
result = bos.toByteArray();
}
rs.close();
here's the code to write the byte array into clob:
//...some other sql stuff here...
stmt = conn.prepareStatement("SELECT clob_col FROM my_table WHERE prim_key = ? FOR UPDATE");
stmt.setString(1, param);
ResultSet rs = stmt.executeQuery();
Clob myclob=null;
if(rs.next())
myclob=rs.getClob(1);
OutputStream writer = myclob.setAsciiStream(1L);
writer.write(allegato);
writer.flush();
writer.close();
stmt = conn.prepareStatement("UPDATE my_table SET clob_col = ? WHERE prim_key = ? ");
stmt.setClob(1, myclob);
stmt.setString(2, param);
stmt.executeUpdate();
oracle encoding is ITALIAN_ITALY.WE8ISO8859P1
php encoding is ITALIAN_ITALY.UTF8

A possible solution:
write to clob the hex rapresentation of the byte array, and do the same in read phase
the main advantage are
- few changes in php and java
- no changes to db (alter table)
- indipendent from db encoding
in php we use bin2hex and hex2bin functions before to write and after read the clob
in java we implement 2 easy equivalent functions of bin2hex and hex2bin:
public static byte[] HexToBin(String str){
try{
byte[] result=new byte[str.length()/2];
for (int i = 0; i < result.length; i++)
result[i]=(byte) Integer.parseInt(str.substring(2*i, (2*i)+2), 16);
return result;
}catch(Exception x){
x.printStackTrace();
return null;
}
}
public static String BinToHex(byte[] b){
try{
StringBuffer sb=new StringBuffer();
for (byte bb:b) {
String hexStr = String.format("%02x", bb);
sb.append((hexStr.length()<2)?"0":"");
sb.append(hexStr);
}
return sb.toString();
}catch(Exception x){
x.printStackTrace();
return null;
}
}

Related

Trying to insert image/xml file as blob in cassandra database

Actually I need to insert xml file in cassandra database. So initially am trying to insert image as a blob content later I change the code to insert xml but am facing issues in insert and retrieve the blob content as image. Can anyone suggest which is the best practice to insert image/xml file in cassandra database.
FileInputStream fis=new FileInputStream("C:/Users/anand.png");
byte[] b= new byte[fis.available()+1];
int length=b.length;
fis.read(b);
System.out.println(length);
ByteBuffer buffer =ByteBuffer.wrap(b);
PreparedStatement ps = session.prepare("insert into usersimage (firstname,lastname,age,email,city,length,image) values(?,?,?,?,?,?,?)");
BoundStatement boundStatement = new BoundStatement(ps);
int age=22;
//System.out.println(buffer);
session.execute( boundStatement.bind( "xxx","D",age,"xxx#gmail.com","xxx",length,buffer));
//session.execute( boundStatement.bind( buffer, "Andy", length));
PreparedStatement ps1 = session.prepare("select * from usersimage where email =?");
BoundStatement boundStatement1 = new BoundStatement(ps1);
ResultSet rs =session.execute(boundStatement1.bind("ramya1#gmail.com"));
ByteBuffer bImage=null;
for (Row row : rs) {
bImage = row.getBytes("image") ;
length=row.getInt("length");
}
byte image[]= new byte[length];
image=Bytes.getArray(bImage);
HttpServletResponse response = null;
#SuppressWarnings("null")
OutputStream out = response.getOutputStream();
response.setContentType("image/png");
response.setContentLength(image.length);
out.write(image);
Am facing issues while retrieving the blob content as image. could anyone please help me on this.
You are inserting data to an email and selecting from another;
A better way to read the bytes of an image would be:
BufferedImage originalImage = ImageIO.read(new File("C:/Users/anand.png"));
ByteArrayOutputStream imageStream = new ByteArrayOutputStream();
ImageIO.write(originalImage, "png", imageStream );
imageStream.flush();
byte[] imageInByte = imageStream.toByteArray();

Trying to insert Base64 image to sql server database

//Convert binary image file to byte array to base64 encoded string
FileInputStream mFileInputStream = new FileInputStream("C:\\basicsworkspace\\base64upload\\src\\main\\resources\\basic.png");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int bytesRead = 0;
while ((bytesRead = mFileInputStream.read(b)) != -1) {
bos.write(b, 0, bytesRead);
}
byte[] ba = bos.toByteArray();
byte[] encoded = Base64.getEncoder().encode(ba);
connection = DriverManager.getConnection(connectionString);
String insertSql = "INSERT INTO test (image) VALUES "
+ "("+encoded+")";
System.out.println(insertSql);
prepsInsertProduct = connection.prepareStatement(
insertSql);
System.out.println(prepsInsertProduct.execute());
Trying to insert image to sql server and need to have the image as base64 format. I am getting below exception. Please let me know what type of datatype and how to insert image as base64 in sql server.
Output :
INSERT INTO test (image) VALUES ([B#7229724f)
java.sql.SQLException: Invalid SQL statement or JDBC escape, terminating ']' not found.
at net.sourceforge.jtds.jdbc.SQLParser.parse(SQLParser.java:1270)
at net.sourceforge.jtds.jdbc.SQLParser.parse(SQLParser.java:165)
at net.sourceforge.jtds.jdbc.JtdsPreparedStatement.<init>(JtdsPreparedStatement.java:111)
at net.sourceforge.jtds.jdbc.JtdsConnection.prepareStatement(JtdsConnection.java:2492)
at net.sourceforge.jtds.jdbc.JtdsConnection.prepareStatement(JtdsConnection.java:2450)
at base64upload.base64upload.App.main(App.java:70)
You are just concatenating string with toString() value of byte array. That's incorrect. You should use another approach:
String insertSql = "INSERT INTO test (image) VALUES (?)";
System.out.println(insertSql);
prepsInsertProduct = connection.prepareStatement(insertSql);
// here set your array
prepsInsertProduct.setBytes(encoded);

Prevent downloaded files from replacing or overwriting each other

How to download all file types in MySQL database using Java app and prevent one file from replacing the other?
How can I include all file types in my filepath=("D:\\sch work\\skirt\\filename.pdf"); so that I am able to download pdf, docx, jpeg etc, from a MySQL database using Java mouse click event on a JTable?
I have two problems.
I can only open a PDF files although I want to open docs, JPEG and img files.
Every time I download another file from a different row it replaces the existing one. I would like to keep all of them
Below please find my code for mouse click event and please suggest what I should add for it to work as I need it.
private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {
String filePath =("D:\\sch work\\skirt\\filename.pdf");
int BUFFER_SIZE = 4096;
try {
int cert_code= jTable1.getSelectedRow();
String tableClick=(jTable1.getModel().getValueAt(cert_code,3).toString());
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/employee_certificate","root","");
String sql= "SELECT cert FROM certificate WHERE cert_code =?" ;
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, tableClick);
ResultSet rs=pstmt.executeQuery();
if(rs.next()){
Blob blob = rs.getBlob("cert");
InputStream inputStream = blob.getBinaryStream();
OutputStream outputStream = new FileOutputStream(filePath);
int bytesRead = -1;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outputStream.close();
//JOptionPane.showMessageDialog(null,"file saved")
} }
catch (Exception e)
{JOptionPane.showMessageDialog(null,e);}
}
If you want something other than PDF, you should store what's in that cert blob, so you can send out the appropriate filename/type:
You get PDF because that's the exact+only file type you write out to:
String filePath =("D:\\sch work\\skirt\\filename.pdf");
^^^
Perhaps something more like (in pseudo-code):
select cert,filename,filetype from ...
filepath = 'd:\sch work\skirt' + filename
header('Content-type: ' + filetype);
here is my answer.God bless Marc B abundantly.
private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {
int BUFFER_SIZE = 4096;
try {
int cert_code= jTable1.getSelectedRow();
String tableClick=(jTable1.getModel().getValueAt(cert_code,3).toString());
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/employee_certificate","root","");
String sql= "SELECT cert, cert_name FROM certificate WHERE cert_code =?" ;
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, tableClick);
ResultSet rs=pstmt.executeQuery();
if(rs.next()){
String filename = rs.getString("cert_name");
Blob blob = rs.getBlob("cert");
InputStream inputStream = blob.getBinaryStream();
String filePath ="D:\\sch work\\skirt\\"+filename;
OutputStream outputStream = new FileOutputStream(filePath);
int bytesRead = -1;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outputStream.close();
//JOptionPane.showMessageDialog(null,"file saved")
} }
catch (Exception e)
{JOptionPane.showMessageDialog(null,e);}
}

How to download file using JavaScript/ExtJs?

In jsp i get file from BD and want to download it on client:
<%
String num = request.getParameter("param");
Statement sta = null;
sta = conn.createStatement();
String fileName="";
String sql=("SELECT files,filename FROM filestock WHERE num =(SELECT filestock_id FROM parcels_temp WHERE num="+num+")");
ResultSet rs=sta.executeQuery(sql);
while(rs.next()){
byte[] file = rs.getBytes("files");
fileName=rs.getString("filename");
}
FileOutputStream fs = new FileOutputStream(new File(fileName));
BufferedOutputStream bs = new BufferedOutputStream(fs);
bs.write(file);
bs.close();
fs.close();
rs.close();
ps.close();
%>
I will PDF file. So i have some questions:
1. What i gonna do with file to send it to JavaScript.
2. Can i save this file using ExtJs 3.4 or JavaScript?
UPDATE
Now i try to send file from server to client:
<%
String num = request.getParameter("param");
Statement sta = null;
sta = conn.createStatement();
String fileName="";
byte[] file=null;
int bufferSize = 8192;
String sql=("SELECT files,filename FROM filestock WHERE num =(SELECT filestock_id FROM parcels_temp WHERE num="+num+")");
ResultSet rs=sta.executeQuery(sql);
while(rs.next()){
file = rs.getBytes("files");
fileName=rs.getString("filename");
}
File dFile=new File(fileName);
InputStream in1 = request.getInputStream();
int read;
while ((read = in1.read(file, 0, bufferSize)) != -1) {
out.write(file, 0, read);
}
sta.close();
rs.close();
conn.close();
%>
But get error:
The method write(char[], int, int) in the type Writer is not applicable for the arguments (byte[], int, int)
So how to do it?
UPDATE2
Using this code i dont get any errors but in firebug i see that server nothing send to client:
<%
String num = request.getParameter("param");
Statement sta = null;
sta = conn.createStatement();
String fileName="";
byte[] file=null;
int bufferSize = 8192;
String sql=("SELECT files,filename FROM filestock WHERE num =(SELECT filestock_id FROM parcels_temp WHERE num="+num+")");
ResultSet rs=sta.executeQuery(sql);
while(rs.next()){
file = rs.getBytes("files");
fileName=rs.getString("filename");
}
//File dFile=new File(fileName);
FileOutputStream fout = fout = new FileOutputStream(fileName);
//BufferedInputStream in1 = new BufferedInputStream(fout);
InputStream in1 = request.getInputStream();
int read;
while ((read = in1.read(file, 0, bufferSize)) != -1) {
fout.write(file, 0, read);
}
sta.close();
rs.close();
conn.close();
%>
You have simply to create a Download URL with a Content-Disposition Header.
Now the bad/good news (It depends on the point of view). You can not store a file through JavaScript onto a users-filesystem (expect the new File-API). But this will sandbox your filesystem. So you can't make the browser store that file onto a certain path.

Snippet to create a file from the contents of a blob in Java

I have some files stored in a database blob column in Oracle 9.
I would like to have those files stored in the file system.
This should be pretty easy, but I don't find the right snipped.
How can I do this in java?
PreparedStatement ptmst = ...
ResutlSet rs = pstmt.executeQuery();
rs.getBlob();
// mistery
FileOutputStream out = new FileOutputStream();
out.write(); // etc et c
I know it should be something like that... what I don't know is what is commented as mistery
Thanks
EDIT
I finally got this derived from David's question.
This is my lazy implementation:
PreparedStatement pstmt = connection.prepareStatement("select BINARY from MYTABLE");
ResultSet rs = pstmt.executeQuery();
while( rs.next() ) {
Blob blob = rs.getBlob("BINARY");
System.out.println("Read "+ blob.length() + " bytes ");
byte [] array = blob.getBytes( 1, ( int ) blob.length() );
File file = File.createTempFile("something-", ".binary", new File("."));
FileOutputStream out = new FileOutputStream( file );
out.write( array );
out.close();
}
You'd want to get the blob as an inputstream and dump its contents to the outputstream. So 'misery' should be something like:
Blob blob = rs.getBlob(column);
InputStream in = blob.getBinaryStream();
OutputStream out = new FileOutputStream(someFile);
byte[] buff = new byte[4096]; // how much of the blob to read/write at a time
int len = 0;
while ((len = in.read(buff)) != -1) {
out.write(buff, 0, len);
}
If you find yourself doing a lot of IO work like this, you might look into using Apache Commons IO to take care of the details. Then everything after setting up the streams would just be:
IOUtils.copy(in, out);
There is another way of doing the same operation faster. Actually the answer above works fine but like IOUtils.copy(in,out) it takes a lot of time for big documents. The reason is you are trying to write your blob by 4KB iteration. Simplier solution :
Blob blob = rs.getBlob(column);
InputStream in = blob.getBinaryStream();
OutputStream out = new FileOutputStream(someFile);
byte[] buff = blob.getBytes(1,(int)blob.getLength());
out.write(buff);
out.close();
Your outputStream will write the blob in one shot.
Edit
Sorry didn't see the Edit section on the intial Post.

Categories

Resources