I have a table with bytea data type on a PostgreSQL table.
I am trying to write and retrieve a pdf file from the bytea data using JDBC resultset.
However the file is corrupted while trying to display it after retrieving it.
Here is my code:
private void insertBytea(java.io.File file) {
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
Logger.getLogger(BeteaTest.class.getName()).log(Level.SEVERE, null, ex);
}
try {
java.sql.Connection connectDB = java.sql.DriverManager.getConnection("jdbc:postgresql://localhost:5433/funsoft", "postgres", "xxx");
connectDB.setAutoCommit(false);
java.sql.PreparedStatement pstmt = connectDB.prepareStatement("INSERT INTO test_binary (test_bytea) VALUES(?)");
java.io.FileInputStream fis;
try {
fis = new java.io.FileInputStream(file);
pstmt.setBinaryStream(1, fis, (int) file.length());
pstmt.executeUpdate();
connectDB.commit();
pstmt.close();
java.sql.PreparedStatement pstmtR = connectDB.prepareStatement("SELECT * FROM test_binary LIMIT 1");
// pstmtR.setString(1, file.getName());
java.sql.ResultSet rs = pstmtR.executeQuery();
while (rs.next()) {
byte[] imgBytes = rs.getBytes(2);
//java.io.InputStream ios = rs.getBinaryStream(2);
java.io.ByteArrayInputStream byteaStream = new java.io.ByteArrayInputStream(imgBytes);
java.io.File tempFile;
try {
tempFile = java.io.File.createTempFile("REP" + com.afrisoftech.lib.DateLables.getDateLabel() + "_", ".pdf");
java.io.FileOutputStream fileIS = new java.io.FileOutputStream(tempFile);
fileIS.write(imgBytes);
fileIS.close();
// this is where i am trying to display the file
com.afrisoftech.lib.PDFRenderer.renderPDF(tempFile);
} catch (IOException ex) {
Logger.getLogger(BeteaTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
try {
fis.close();
} catch (IOException ex) {
ex.printStackTrace();
Logger.getLogger(BeteaTest.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(BeteaTest.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (SQLException ex) {
ex.printStackTrace();
Logger.getLogger(BeteaTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
Related
I'm trying to copy a file with .dat extension from a certain directory decided by the user into the project directory. When I try to read the saved object selected by the user, the program always gives IOException.
File f = new File(chooser.getSelectedFile().getPath());
if(f.exists() && !f.isDirectory()) {
FileInputStream flusso= null;
ObjectInputStream leggiObj=null;
try {
flusso = new FileInputStream(chooser.getSelectedFile().getPath());
System.out.println(chooser.getSelectedFile().getPath());
leggiObj = new ObjectInputStream(flusso);
if (leggiObj.readObject().getClass().equals(DatiProgresso.class)) {
DatiProgresso dp = (DatiProgresso) leggiObj.readObject();//<----THIS LINE GIVES THE EXEPTION
leggiObj.close();
flusso.close();
System.out.println("Ciao");
FileOutputStream fop = new FileOutputStream("salvataggi/" + dp.getNome() + ".dat");
ObjectOutputStream scriviObj = new ObjectOutputStream(fop);
scriviObj.writeObject(dp);
scriviObj.flush();
fop.close();
} else {
JOptionPane.showMessageDialog(this, "Unacceptable file", "Error", JOptionPane.ERROR_MESSAGE);
}
} catch (HeadlessException ex) {
System.out.println("HeadlessException");
ex.printStackTrace();
} catch (FileNotFoundException ex) {
System.out.println("FileNotFoundException");
ex.printStackTrace();
} catch (IOException ex) {
System.out.println("IOException");
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
System.out.println("ClassNotFoundException");
ex.printStackTrace();
}
}
}
else
{
JOptionPane.showMessageDialog(this, "Unacceptable file", "Error" ,JOptionPane.ERROR_MESSAGE);
}
DatiProgresso dp = (DatiProgresso) leggiObj.readObject();
This line gives the exception.
leggiObj.readObject().getClass().equals(DatiProgresso.class) - here you read your object from the data stream. On next line you attempt to read 2nd object from the stream. If there is no another object then stream fails.
I'm trying to display data between two dates through Jasper report
and these are my codes:
String date1=jDateChooser1.getDateFormatString();
String date2=jDateChooser2.getDateFormatString();
try {
Connection conn = null;
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(facilitiReports.class.getName()).log(Level.SEVERE, null, ex);
}
String url = "jdbc:sqlserver://localhost:1433;databaseName=bradb";
Connection conn = null;
try {
conn = DriverManager.getConnection(url, "sa", "oraclee");
} catch (SQLException ex) {
Logger.getLogger(facilitiReports.class.getName()).log(Level.SEVERE, null, ex);
}
JasperDesign jd = null;
try {
jd = JRXmlLoader.load("D:\\NetBeansProjects\\bra\\src\\facilitiReport.jrxml");
} catch (JRException ex) {
Logger.getLogger(facilitiReports.class.getName()).log(Level.SEVERE, null, ex);
}
String sql="SELECT * FROM facilitiTable WHERE facilitiDate BETWEEN='" + date1+ "' AND '" + date2+ "' ";
JRDesignQuery newq=new JRDesignQuery();
newq.setText(sql);
jd.setQuery(newq);
JasperReport jr = null;
try {
jr = JasperCompileManager.compileReport(jd);
} catch (JRException ex) {
Logger.getLogger(facilitiReports.class.getName()).log(Level.SEVERE, null, ex);
}
JasperPrint jp = null;
try {
jp = JasperFillManager.fillReport(jr, null, conn);
} catch (JRException ex) {
Logger.getLogger(facilitiReports.class.getName()).log(Level.SEVERE, null, ex);
}
JasperViewer.viewReport(jp);
try {
conn.close();
} catch (SQLException ex) {
Logger.getLogger(facilitiReports.class.getName()).log(Level.SEVERE, null, ex);
}
the error that appears,is:
net.sf.jasperreports.engine.JRException: Error executing SQL statement for : null
at net.sf.jasperreports.engine.query.JRJdbcQueryExecuter.createDatasource(JRJdbcQueryExecuter.java:240) at net.sf.jasperreports.engine.query.JRJdbcQueryExecuter.createDatasource(JRJdbcQueryExecuter.java:240)
at net.sf.jasperreports.engine.fill.JRFillDataset.createQueryDatasource(JRFillDataset.java:1087)
at net.sf.jasperreports.engine.fill.JRFillDataset.initDatasource(JRFillDataset.java:668)
at net.sf.jasperreports.engine.fill.JRBaseFiller.setParameters(JRBaseFiller.java:1281)
at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:900)
at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:845)
at net.sf.jasperreports.engine.fill.JRFiller.fill(JRFiller.java:61)
at net.sf.jasperreports.engine.JasperFillManager.fill(JasperFillManager.java:446)
at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:849)
done,,
the error were in these two lines:
String date1=jDateChooser1.getDateFormatString();
String date2=jDateChooser2.getDateFormatString();
and final codes are:
String date1 = ((JTextField) jDateChooser1.getDateEditor().getUiComponent()).getText();
String date2 = ((JTextField) jDateChooser2.getDateEditor().getUiComponent()).getText();
try {
Connection conn = null;
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(facilitiReports.class.getName()).log(Level.SEVERE, null, ex);
}
String url = "jdbc:sqlserver://localhost:1433;databaseName=bradb";
Connection conn = null;
try {
conn = DriverManager.getConnection(url, "sa", "oraclee");
} catch (SQLException ex) {
Logger.getLogger(facilitiReports.class.getName()).log(Level.SEVERE, null, ex);
}
JasperDesign jd = null;
try {
jd = JRXmlLoader.load("E:\\bra\\src\\facilitiReport2.jrxml");
} catch (JRException ex) {
Logger.getLogger(facilitiReports.class.getName()).log(Level.SEVERE, null, ex);
}
String sql = "SELECT * FROM facilitiTable WHERE deptDate BETWEEN '" + date1 + "' AND '" + date2 + "' ";
JRDesignQuery newq = new JRDesignQuery();
newq.setText(sql);
jd.setQuery(newq);
JasperReport jr = null;
try {
jr = JasperCompileManager.compileReport(jd);
} catch (JRException ex) {
Logger.getLogger(facilitiReports.class.getName()).log(Level.SEVERE, null, ex);
}
JasperPrint jp = null;
try {
jp = JasperFillManager.fillReport(jr, null, conn);
} catch (JRException ex) {
Logger.getLogger(facilitiReports.class.getName()).log(Level.SEVERE, null, ex);
}
JasperViewer.viewReport(jp);
try {
conn.close();
} catch (SQLException ex) {
Logger.getLogger(facilitiReports.class.getName()).log(Level.SEVERE, null, ex);
}
I saved a file with a serialized String array that contains 3 arrays (1 String and 2 Double).
How can i read it back and redo the 3 arrays?
Here's how I write it :
String[] storeAllArrays[] = {prod, cant, pret};
ObjectOutputStream out;
try {
out = new ObjectOutputStream(new FileOutputStream("test.ser"));
out.writeObject(storeAllArrays);
out.flush();
out.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(Test2.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Test2.class.getName()).log(Level.SEVERE, null, ex);
}
EDIT : Here's what i tried :
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream("test.ser"));
String[] arrayT = (String[]) in.readObject();
in.close();
JOptionPane.showMessageDialog(this, ArrayT);
} catch (IOException ex) {
Logger.getLogger(Test2.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(Test2.class.getName()).log(Level.SEVERE, null, ex);
}
Simple example of serializing and deserializing
String[] prod = { "pr", "od" };
String[] cant = { "10.0", "20.0" };
String[] pret = { "30.0", "40.0" };
String[] storeAllArrays[] = {prod, cant, pret};
Logger logger = Logger.getLogger(SerializerSample.class.getName());
String serializedPath = "/tmp/store_test.ser";
ObjectOutputStream out;
try {
out = new ObjectOutputStream(new FileOutputStream(serializedPath));
out.writeObject(storeAllArrays);
out.flush();
out.close();
} catch (FileNotFoundException ex) {
logger.log(Level.SEVERE, null, ex);
} catch (IOException ex) {
logger.log(Level.SEVERE, null, ex);
}
try {
InputStream file = new FileInputStream(serializedPath);
InputStream buffer = new BufferedInputStream(file);
ObjectInput input = new ObjectInputStream(buffer);
String[] storeAllArraysREAD[] = (String[][]) input.readObject();
logger.log(Level.INFO, storeAllArraysREAD.toString());
} catch (ClassNotFoundException ex) {
logger.log(Level.SEVERE, "Cannot perform input. Class not found.",
ex);
} catch (IOException ex) {
logger.log(Level.SEVERE, "Cannot perform input.", ex);
}
I would write the String and two doubles, as a String and two doubles.
DataOutputStream dos = new DataOutputStream(new FileOutputStream("test.data"));
dos.writeUTF(prod);
dos.writeDouble(cant);
dos.writeDouble(pret);
dos.close();
to read
DataInputStream dis = new DataInputStream(new FileInputStream("test.data"));
prod = dis.readUTF();
cant = dis.readDouble();
pret = dis.readDouble();
dis.close();
if you must use ObjectOutputStream you can use ObjectInputStream
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("test.data"));
String[] array = (String[]) dis.readObject();
dis.close();
Have you ever heard of ObjectInputStream? It's for reading files created with ObjectOutputStream. You construct one like this:
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("test.ser"));
Then you can read your arrays in like this:
Object[] array = (Object[]) ois.readObject();
I want to store data (encrypted with DES) and then take the encrypted data from database and present it as a list. But I have a problem. Here is the code.
public void EncryptDemo(){
try {
FileInputStream keyfis = new FileInputStream("mainkey.key");
byte[] encodedKey = new byte[keyfis.available()];
keyfis.read(encodedKey);
keyfis.close();
Key KeyFromFile = new SecretKeySpec(encodedKey, "DES");
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
String text=txtToEncryptData.getText(), output;
cipher.init(Cipher.ENCRYPT_MODE, KeyFromFile);
DataDemo = cipher.doFinal(text.getBytes());
InsertIntoDataBase();
//I store it as varbinary in database
} catch (FileNotFoundException ex) {
Logger.getLogger(MainGUI.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(MainGUI.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(MainGUI.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchPaddingException ex) {
Logger.getLogger(MainGUI.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidKeyException ex) {
Logger.getLogger(MainGUI.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalBlockSizeException ex) {
Logger.getLogger(MainGUI.class.getName()).log(Level.SEVERE, null, ex);
} catch (BadPaddingException ex) {
Logger.getLogger(MainGUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void DecryptDemo(){
try {
FileInputStream keyfis = new FileInputStream("mainkey.key");
byte[] encodedKey = new byte[keyfis.available()];
keyfis.read(encodedKey);
keyfis.close();
Key KeyFromFile = new SecretKeySpec(encodedKey, "DES");
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, KeyFromFile);
String sql = "{call SelectAll}";
CallableStatement call = conn.prepareCall(sql);
call.execute();
ResultSet result = call.getResultSet();
DefaultListModel model = new DefaultListModel();
while(result.next()){
DataDemo = result.getBytes("TestData");
byte[] plainText = cipher.doFinal(DataDemo);
String after = new String(plainText);
model.addElement(after);
}
lstDecryptResult.setModel(model);
} catch (SQLException ex) {
Logger.getLogger(MainGUI.class.getName()).log(Level.SEVERE, null, ex);
} catch (FileNotFoundException ex) {
Logger.getLogger(MainGUI.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(MainGUI.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(MainGUI.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchPaddingException ex) {
Logger.getLogger(MainGUI.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidKeyException ex) {
Logger.getLogger(MainGUI.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalBlockSizeException ex) {
Logger.getLogger(MainGUI.class.getName()).log(Level.SEVERE, null, ex);
} catch (BadPaddingException ex) {
Logger.getLogger(MainGUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
The encrypt and storing is allright. But when I take data from database, I get this error when decrypt (at byte[] plainText = cipher.doFinal(DataDemo);)
Jul 19, 2013 11:40:05 AM databaseencryptdecryptdemo.MainGUI DecryptDemo
SEVERE: null
javax.crypto.IllegalBlockSizeException: Input length must be multiple of 8 when decrypting with padded cipher
Anyone have a solution for this???
You should divide DataDemo variable into 8 byte pieces.
public List<Byte[]> divideInto8(Byte[] bytes) {
int length = bytes.length;
List<Byte[]> returnValues = new ArrayList<Byte[]>();
for (int i = 0; i < length; i = i + 8) {
Byte[] thebytes = new Byte[8];
for (int j = 0; j < 8; j++) {
thebytes[j] = bytes[i * 8 + j];
}
returnValues.add(thebytes);
}
return returnValues;
}
I found the solution. But I think it's not the best.
I changed the type of table DataDemo from varbinary to image and everything became alright. But my data size store in database is heavier (about 4 times) than the oigin data.
But at least I solved my problem.
Does anyone have a better solution? I willing to hear from you.
I made a program to produce a file with numbers in it
But the program is not typing any thing in the file it created!
This is the code:
private void OpenMenuActionPerformed(java.awt.event.ActionEvent evt) {
ModFile=new File(NameText.getText() + ".mod");
FileWriter writer = null;
try {
writer = new FileWriter(ModFile);
} catch (IOException ex) {
Logger.getLogger(ModMakerGui.class.getName()).log(Level.SEVERE, null, ex);
}
if(!ModFile.exists()){
try {
ModFile.createNewFile();
System.out.println("Mod file has been created to the current directory");
writer.write(CodesBox.getText());
} catch (IOException ex) {
Logger.getLogger(ModMakerGui.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
When i create a random file, i don't see any thing when i open it!
Please help
Thanks Amir for helping but i noticed i should use FileOutputStream and DataOutputStream...
So, i need help again cause the same problem appeared :(
File ModFile =new File(NameText.getText() + ".mod");
try {
FileOutputStream fos = new FileOutputStream(ModFile);
DataOutputStream dos = new DataOutputStream(fos);
int i = Integer.parseInt(CodesBox.getText());
dos.writeInt(i);
// and other processing
} catch (IOException ex) {
Logger.getLogger(ModMakerGui.class.getName()).log(Level.SEVERE, null, ex);
}finally{
try{
dos.close();
} catch(IOException e) {
e.printStackTrace();
}
}
NetBeans said they cannot find the symbol dos at (dos.close();)
Please help me here again
You have to check that file name is present in NameText.getText().
You dont need to create file, if file dont exist FileWriter will create it self.
You should Close file after processing
private void OpenMenuActionPerformed(java.awt.event.ActionEvent evt) {
//check before file name is nt null
File ModFile =new File("somefile" + ".mod");
FileWriter writer = null;
try {
writer = new FileWriter(ModFile);
writer.write("test..................");
// and other processing
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}finally{
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
to use FileOutputStream and write byte array follow the following code
private static void OpenMenuActionPerformed(java.awt.event.ActionEvent evt) {
//check before file name is nt null
File ModFile =new File("somefile" + ".mod");
FileOutputStream writer = null;
String toProcess = "00D0C0DE00D0C0DE F000000000000000";
try {
writer = new FileOutputStream(ModFile);
writer.write(toProcess.getBytes(),0,toProcess.getBytes().length);
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}finally{
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}