KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > compiere > apps > Attachment


1 /******************************************************************************
2  * The contents of this file are subject to the Compiere License Version 1.1
3  * ("License"); You may not use this file except in compliance with the License
4  * You may obtain a copy of the License at http://www.compiere.org/license.html
5  * Software distributed under the License is distributed on an "AS IS" basis,
6  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
7  * the specific language governing rights and limitations under the License.
8  * The Original Code is Compiere ERP & CRM Business Solution
9  * The Initial Developer of the Original Code is Jorg Janke and ComPiere, Inc.
10  * Portions created by Jorg Janke are Copyright (C) 1999-2001 Jorg Janke, parts
11  * created by ComPiere are Copyright (C) ComPiere, Inc.; All Rights Reserved.
12  * Contributor(s): ______________________________________.
13  *****************************************************************************/

14 package org.compiere.apps;
15
16 import java.awt.*;
17 import java.awt.event.*;
18 import javax.swing.*;
19 import java.io.*;
20 import java.util.*;
21 import java.sql.*;
22 import oracle.sql.*;
23 import oracle.jdbc.driver.*;
24
25 import org.compiere.util.*;
26 import org.compiere.plaf.*;
27 import org.compiere.swing.*;
28
29 /**
30  * Attachment
31  *
32  * @author Jorg Janke
33  * @version $Id: Attachment.java,v 1.9 2003/02/14 06:44:13 jjanke Exp $
34  */

35 public final class Attachment extends JDialog implements ActionListener
36 {
37     /**
38      * Constructor.
39      * loads Attachment, if ID <> 0
40      * @param frame frame
41      * @param WindowNo window no
42      * @param AD_Attachment_ID attachment
43      * @param AD_Table_ID table
44      * @param Record_ID record key
45      */

46     public Attachment(Frame frame, int WindowNo, int AD_Attachment_ID,
47         int AD_Table_ID, int Record_ID)
48     {
49         super(frame, Msg.getMsg(Env.getCtx(), "Attachment"), true);
50         Log.trace(Log.l3_Util, "Attachment - ID=" + AD_Attachment_ID
51             + ", Table=" + AD_Table_ID + ", Record=" + Record_ID);
52         //
53
m_WindowNo = WindowNo;
54         m_AD_Attachment_ID = AD_Attachment_ID;
55         m_AD_Table_ID = AD_Table_ID;
56         m_Record_ID = Record_ID;
57         //
58
try
59         {
60             jbInit();
61         }
62         catch (Exception JavaDoc ex)
63         {
64             Log.error("Attachment", ex);
65         }
66         if (AD_Attachment_ID == 0)
67             bDelete.setEnabled(false);
68         else
69             loadAttachment();
70         //
71
text.requestFocus();
72         AEnv.positionCenterWindow(frame, this);
73     } // Attachment
74

75     private int m_WindowNo;
76     private int m_AD_Attachment_ID, m_AD_Table_ID, m_Record_ID;
77
78     /** Indicator for no data */
79     private static final String JavaDoc NONE = ".";
80     /** File to be loaded */
81     private File m_file = null;
82     /** Data from BLOB */
83     private byte[] m_data = null;
84     //
85
private CPanel mainPanel = new CPanel();
86     private BorderLayout mainLayout = new BorderLayout();
87     private CText text = new CText();
88     private CButton bOpen = new CButton();
89     private CPanel northPanel = new CPanel();
90     private CButton bLoad = new CButton();
91     private BorderLayout northLayout = new BorderLayout();
92     private CLabel title = new CLabel();
93     private ConfirmPanel confirmPanel = new ConfirmPanel(true);
94     private CPanel toolBar = new CPanel(new FlowLayout(FlowLayout.LEADING, 5,5));
95     private CButton bDelete = new CButton();
96     private GImage gifPanel = new GImage();
97     private JSplitPane centerPane1 = new JSplitPane();
98
99     /**
100      * Static setup.
101      * <pre>
102      * - northPanel
103      * - toolBar
104      * - title
105      * - centerPanel
106      * - gifPanel (left)
107      * - text (right)
108      * - confirmPanel
109      * </pre>
110      * @throws Exception
111      */

112     void jbInit() throws Exception JavaDoc
113     {
114         CompiereColor.setBackground(this);
115         mainPanel.setLayout(mainLayout);
116         mainLayout.setHgap(5);
117         mainLayout.setVgap(5);
118         this.getContentPane().add(mainPanel);
119
120         northPanel.setLayout(northLayout);
121         northPanel.add(title, BorderLayout.CENTER);
122         northPanel.add(toolBar, BorderLayout.WEST);
123         toolBar.add(bLoad);
124         toolBar.add(bDelete);
125         toolBar.add(bOpen);
126         mainPanel.add(northPanel, BorderLayout.NORTH);
127
128         bOpen.setEnabled(false);
129         bOpen.setIcon(Env.getImageIcon("Editor24.gif"));
130         bOpen.setMargin(new Insets(0, 2, 0, 2));
131         bOpen.setText(Msg.getMsg(Env.getCtx(), "Open"));
132         bOpen.addActionListener(this);
133         bLoad.setIcon(Env.getImageIcon("Import24.gif"));
134         bLoad.setMargin(new Insets(0, 2, 0, 2));
135         bLoad.setText(Msg.getMsg(Env.getCtx(), "Load"));
136         bLoad.addActionListener(this);
137         bDelete.setIcon(Env.getImageIcon("Delete24.gif"));
138         bDelete.setMargin(new Insets(0, 2, 0, 2));
139         bDelete.setText(Msg.getMsg(Env.getCtx(), "Delete"));
140         bDelete.addActionListener(this);
141         title.setHorizontalAlignment(SwingConstants.CENTER);
142         title.setHorizontalTextPosition(SwingConstants.CENTER);
143         //
144
text.setBackground(CompierePLAF.getInfoBackground());
145         text.setPreferredSize(new Dimension(200, 200));
146         //
147
mainPanel.add(confirmPanel, BorderLayout.SOUTH);
148         confirmPanel.addActionListener(this);
149         //
150
mainPanel.add(centerPane1, BorderLayout.CENTER);
151         centerPane1.add(gifPanel, JSplitPane.LEFT);
152         centerPane1.add(text, JSplitPane.RIGHT);
153     } // jbInit
154

155     /**
156      * Load Attachment
157      */

158     private void loadAttachment()
159     {
160         Log.trace(Log.l2_Sub, "Attachment.load");
161         String JavaDoc SQL = "SELECT Text, Title, BinaryData FROM AD_Attachment WHERE AD_Attachment_ID="
162             + m_AD_Attachment_ID;
163         try
164         {
165             Statement stmt = DB.createStatement();
166             ResultSet rs = stmt.executeQuery(SQL);
167             if (rs.next())
168             {
169                 // Set Text
170
String JavaDoc sText = rs.getString(1);
171                 if (sText == null)
172                     text.setText("");
173                 else
174                     text.setText(sText);
175
176                 // Set Name/Title
177
String JavaDoc sName = rs.getString(2);
178                 if (sName == null || sName.equals("") || sName.equals(NONE))
179                 {
180                     sName = NONE;
181                     bOpen.setEnabled(false);
182                 }
183                 else
184                     bOpen.setEnabled(true);
185                 title.setText(sName);
186                 this.setTitle(Msg.getMsg(Env.getCtx(), "Attachment") + " " + sName);
187
188                 // BLOB
189
BLOB blob = ((OracleResultSet)rs).getBLOB(3);
190                 int length = (int)blob.length();
191                 Log.trace(Log.l4_Data, "Attachment.load - BLOB length=" + length);
192                 if (length > 0)
193                     m_data = blob.getBytes(1, length);
194                 displayData(m_data);
195             }
196             else
197             {
198                 m_AD_Attachment_ID = 0;
199                 bDelete.setEnabled(false);
200                 ADialog.error(m_WindowNo, this, "AttachmentNotFound");
201             }
202             rs.close();
203             stmt.close();
204         }
205         catch (SQLException e)
206         {
207             Log.error("Attachment.load", e);
208             m_AD_Attachment_ID = 0;
209         }
210     } // loadAttachment
211

212     /**
213      * Display gif or jpg in gifPanel
214      * @param data data
215      */

216     private void displayData(byte data[])
217     {
218         String JavaDoc t = title.getText().toLowerCase().trim();
219         Log.trace(Log.l3_Util, "Attachment.displayData - " + t + " - " + (data==null ? "null" : String.valueOf(data.length)));
220         // Can we display it
221
if (data == null || data.length == 0)
222             gifPanel.setImage(null);
223         else if (t.endsWith(".gif") || t.endsWith(".jpg"))
224         {
225             Log.trace(Log.l4_Data, "Attachment.displayData - Set Image");
226             Image image = Toolkit.getDefaultToolkit().createImage(data);
227             gifPanel.setImage(image);
228         }
229         else
230         {
231             Log.trace(Log.l4_Data, "Attachment.displayData - Cannot display");
232             gifPanel.setImage(null);
233         }
234         pack();
235     } // displayData
236

237     /**
238      * Action Listener
239      * @param e event
240      */

241     public void actionPerformed(ActionEvent e)
242     {
243         // Save and Return
244
if (e.getActionCommand().equals(ConfirmPanel.A_OK))
245         {
246             saveAttachment();
247             dispose();
248         }
249         // Cancel
250
else if (e.getActionCommand().equals(ConfirmPanel.A_CANCEL))
251             dispose();
252         // Delete and Return
253
else if (e.getSource() == bDelete)
254         {
255             deleteAttachment();
256             dispose();
257         }
258         // Load Attachment
259
else if (e.getSource() == bLoad)
260             getFileName();
261         // Open Attachment
262
else if (e.getSource() == bOpen)
263             openAttachment();
264
265     } // actionPerformed
266

267     /*************************************************************************/
268
269     /**
270      * Save Attachment
271      */

272     private void saveAttachment()
273     {
274         Log.trace(Log.l1_User, "Attachment.save");
275         // Constants for Insert/Update
276
Timestamp today = new Timestamp(System.currentTimeMillis());
277         int userID = Env.getContextAsInt(Env.getCtx(), "#AD_User_ID");
278         //
279
String JavaDoc sName = title.getText();
280         if (sName == null || sName.equals(""))
281             sName = NONE;
282         // Create Attachment
283
if (m_AD_Attachment_ID == 0)
284         {
285             m_AD_Attachment_ID = DB.getKeyNextNo(Env.getCtx(), m_WindowNo, "AD_Attachment");
286             String JavaDoc SQL = "INSERT INTO AD_Attachment (AD_Attachment_ID,"
287                 + "AD_Client_ID,AD_Org_ID,IsActive,Created,CreatedBy,Updated,UpdatedBy,"
288                 + "Title, AD_Table_ID, Record_ID, Text, BinaryData) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,Empty_BLOB())";
289             try
290             {
291                 PreparedStatement pstmt = DB.prepareStatement(SQL);
292                 pstmt.setInt(1, m_AD_Attachment_ID);
293                 pstmt.setInt(2, Env.getContextAsInt(Env.getCtx(), m_WindowNo, "AD_Client_ID"));
294                 pstmt.setInt(3, Env.getContextAsInt(Env.getCtx(), m_WindowNo, "AD_Org_ID"));
295                 pstmt.setString(4, "Y");
296                 pstmt.setTimestamp(5, today);
297                 pstmt.setInt(6, userID);
298                 pstmt.setTimestamp(7, today);
299                 pstmt.setInt(8, userID);
300                 pstmt.setString(9, sName);
301                 pstmt.setInt(10, m_AD_Table_ID);
302                 pstmt.setInt(11, m_Record_ID);
303                 pstmt.setString(12, text.getText());
304                 int i = pstmt.executeUpdate();
305                 Log.trace(Log.l4_Data, "Attachment.save (insert) - Records=" + i);
306             }
307             catch (SQLException ei)
308             {
309                 Log.error("Attachment.save (insert)", ei);
310             }
311         }
312         // Update Attachment (text info)
313
else
314         {
315             String JavaDoc SQL = "UPDATE AD_Attachment "
316                 + "SET Title=?, Text=?, Updated=?, UpdatedBy=? "
317                 + "WHERE AD_Attachment_ID=" + m_AD_Attachment_ID;
318             try
319             {
320                 PreparedStatement pstmt = DB.prepareStatement(SQL);
321                 pstmt.setString(1, sName);
322                 pstmt.setString(2, text.getText());
323                 pstmt.setTimestamp(3, today);
324                 pstmt.setInt(4, userID);
325                 //
326
int i = pstmt.executeUpdate();
327                 Log.trace(Log.l4_Data, "Attachment.save (update) - Records=" + i);
328             }
329             catch (SQLException eu)
330             {
331                 Log.error("Attachment.save (update)", eu);
332             }
333         }
334
335         // Upload BLOB
336
if (m_file != null)
337         {
338             boolean success = true;
339             String JavaDoc sql = "SELECT BinaryData FROM AD_Attachment WHERE AD_Attachment_ID=? FOR UPDATE";
340             try
341             {
342                 Connection con = DB.createConnection(false, Connection.TRANSACTION_SERIALIZABLE);
343                 PreparedStatement pstmt = con.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
344                 pstmt.setInt(1, m_AD_Attachment_ID);
345                 ResultSet rs = pstmt.executeQuery();
346                 if (rs.next())
347                 {
348                     BLOB blob = ((OracleResultSet)rs).getBLOB(1);
349                     long blobLength = blob.length();
350                     int size = blob.getBufferSize();
351                     Log.trace(Log.l3_Util, "Attachment.save blob - "
352                         + m_file.getAbsolutePath() + ", Size=" + m_file.length()
353                         + ", Buffer=" + size + ", BLOB length=" + blobLength);
354                     try
355                     {
356                         FileInputStream fis = new FileInputStream (m_file);
357                         OutputStream os = blob.getBinaryOutputStream();
358                         byte[] buffer = new byte[size];
359                         int length = -1;
360                         while ((length = fis.read(buffer)) != -1)
361                             os.write(buffer, 0, length);
362                         fis.close();
363                         os.close();
364                         Log.trace(Log.l4_Data, "Attachment.save - New length=" + blob.length());
365                     }
366                     catch (IOException ioe)
367                     {
368                         Log.error("Attachment.save (blob-io)", ioe);
369                         success = false;
370                     }
371                 }
372                 else
373                 {
374                     Log.error("Attachment.save - No Record for BLOB");
375                     success = false;
376                 }
377                 rs.close();
378                 pstmt.close();
379                 con.close();
380             }
381             catch (SQLException e)
382             {
383                 Log.error ("Attachment.save (blob)", e);
384                 success = false;
385             }
386             if (!success)
387             {
388                 title.setText(NONE);
389                 m_file = null;
390             }
391         } // load blob
392
} // saveAttachment
393

394     /**
395      * Get File Name
396      */

397     private void getFileName()
398     {
399         Log.trace(Log.l1_User, "Attachment.getFileName");
400         JFileChooser chooser = new JFileChooser();
401         chooser.setDialogType(JFileChooser.OPEN_DIALOG);
402         chooser.setDialogTitle(Msg.getMsg(Env.getCtx(), "AttachmentNew"));
403         if (!title.getText().equals(NONE))
404         {
405             File f = new File(title.getText());
406             chooser.setSelectedFile(f);
407         }
408         int returnVal = chooser.showOpenDialog(this);
409         String JavaDoc fileName = "";
410         if (returnVal == JFileChooser.APPROVE_OPTION)
411         {
412             fileName = chooser.getSelectedFile().getName();
413             Log.trace(Log.l4_Data, "Get: " + fileName);
414             m_file = chooser.getSelectedFile();
415             // Show
416
title.setText(fileName);
417             bOpen.setEnabled(true);
418         }
419         else
420         {
421             title.setText(NONE);
422             m_file = null;
423         }
424         this.setTitle(Msg.getMsg(Env.getCtx(), "Attachment") + " " + title.getText());
425
426         // load and show image
427
String JavaDoc t = fileName.toLowerCase();
428         if (t.endsWith(".gif") || t.endsWith(".jpg"))
429         {
430             try
431             {
432                 FileInputStream fis = new FileInputStream (m_file);
433                 ByteArrayOutputStream os = new ByteArrayOutputStream();
434                 byte[] buffer = new byte[1024*8]; // 8kB
435
int length = -1;
436                 while ((length = fis.read(buffer)) != -1)
437                     os.write(buffer, 0, length);
438                 fis.close();
439                 displayData(os.toByteArray());
440                 os.close();
441             }
442             catch (IOException ioe)
443             {
444                 Log.error("Attachment.getFileName", ioe);
445             }
446         }
447     } // getFileName
448

449     /**
450      * Delete Attachment
451      */

452     private void deleteAttachment()
453     {
454         Log.trace(Log.l1_User, "Attachment.delete");
455         if (m_AD_Attachment_ID != 0 && ADialog.ask(m_WindowNo, this, "AttachmentDelete?"))
456         {
457             String JavaDoc SQL = "DELETE AD_Attachment WHERE AD_Attachment_ID=" + m_AD_Attachment_ID;
458             try
459             {
460                 int i = DB.createStatement().executeUpdate(SQL);
461                 Log.trace(Log.l4_Data, "Attachment.delete - Records=" + i);
462             }
463             catch (SQLException e)
464             {
465                 Log.error("Attachment.delete", e);
466             }
467         }
468     } // deleteAttachment
469

470     /**
471      * Open Attachment
472      */

473     private void openAttachment()
474     {
475         Log.trace(Log.l1_User, "Attachment.open");
476         if (m_data == null || m_data.length == 0)
477             return;
478
479         String JavaDoc fileName = title.getText();
480         String JavaDoc ext = fileName.substring (fileName.lastIndexOf("."));
481         Log.trace(Log.l4_Data, "Ext=" + ext);
482
483         JFileChooser chooser = new JFileChooser();
484         chooser.setDialogType(JFileChooser.SAVE_DIALOG);
485         chooser.setDialogTitle(Msg.getMsg(Env.getCtx(), "AttachmentSave"));
486         if (!fileName.equals(NONE))
487         {
488             File f = new File(fileName);
489             chooser.setSelectedFile(f);
490         }
491         int returnVal = chooser.showSaveDialog(this);
492         File saveFile = null;
493         if (returnVal == JFileChooser.APPROVE_OPTION)
494             saveFile = chooser.getSelectedFile();
495
496         // Save to file
497
if (saveFile != null)
498         {
499             Log.trace(Log.l3_Util, "Attachment.open", "Save to " + saveFile.getAbsolutePath());
500             try
501             {
502                 FileOutputStream fos = new FileOutputStream(saveFile);
503                 fos.write(m_data);
504                 fos.close();
505             }
506             catch (IOException ioe)
507             {
508                 Log.error("Attachment.open", ioe);
509             }
510         }
511     } // openAttachment
512

513     /*************************************************************************/
514
515     /**
516      * Graphic Image Panel
517      */

518     class GImage extends JPanel
519     {
520         /**
521          * Graphic Image
522          */

523         public GImage()
524         {
525             super();
526         } // GImage
527

528         /** The Image */
529         private Image m_image = null;
530
531         /**
532          * Set Image
533          * @param image image
534          */

535         public void setImage (Image image)
536         {
537             m_image = image;
538             if (m_image == null)
539                 return;
540
541             MediaTracker mt = new MediaTracker(this);
542             mt.addImage(m_image, 0);
543             try {
544                 mt.waitForID(0);
545             } catch (Exception JavaDoc e) {}
546             Dimension dim = new Dimension(m_image.getWidth(this), m_image.getHeight(this));
547             this.setPreferredSize(dim);
548         } // setImage
549

550         /**
551          * Paint
552          * @param g graphics
553          */

554         public void paint (Graphics g)
555         {
556             Insets in = getInsets();
557             if (m_image != null)
558                 g.drawImage(m_image, in.left, in.top, this);
559         } // paint
560

561         /**
562          * Update
563          * @param g graphics
564          */

565         public void update (Graphics g)
566         {
567             paint(g);
568         } // update
569
} // GImage
570

571 } // Attachment
572
Popular Tags