82be8d5e48e22359e3e227137560d70a378397be
[mir.git] / source / mircoders / entity / EntityImages.java
1 /*
2  * Copyright (C) 2001, 2002 The Mir-coders group
3  *
4  * This file is part of Mir.
5  *
6  * Mir is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * Mir is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with Mir; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  * In addition, as a special exception, The Mir-coders gives permission to link
21  * the code of this program with  any library licensed under the Apache Software License,
22  * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
23  * (or with modified versions of the above that use the same license as the above),
24  * and distribute linked combinations including the two.  You must obey the
25  * GNU General Public License in all respects for all of the code used other than
26  * the above mentioned libraries.  If you modify this file, you may extend this
27  * exception to your version of the file, but you are not obligated to do so.
28  * If you do not wish to do so, delete this exception statement from your version.
29  */
30
31 package mircoders.entity;
32
33 import java.io.File;
34 import java.io.IOException;
35 import java.io.InputStream;
36 import java.sql.Connection;
37 import java.sql.PreparedStatement;
38 import java.sql.ResultSet;
39 import java.sql.SQLException;
40 import java.sql.Statement;
41
42 import mir.config.MirPropertiesConfiguration;
43 import mir.log.LoggerWrapper;
44 import mir.misc.FileUtil;
45 import mir.storage.StorageObject;
46 import mir.storage.StorageObjectFailure;
47 import mircoders.media.ImageProcessor;
48
49 import org.postgresql.largeobject.BlobInputStream;
50 import org.postgresql.largeobject.LargeObject;
51 import org.postgresql.largeobject.LargeObjectManager;
52
53 /**
54  *
55  * @author RK, mh, mir-coders
56  * @version $Id: EntityImages.java,v 1.21.2.4 2004/01/18 17:30:58 zapata Exp $
57  */
58
59
60 public class EntityImages extends EntityUploadedMedia
61 {
62   private int maxImageSize = configuration.getInt("Producer.Image.MaxSize");
63   private int maxIconSize = configuration.getInt("Producer.Image.MaxIconSize");
64   private float minDescaleRatio = configuration.getFloat("Producer.Image.MinDescalePercentage")/100;
65   private int minDescaleReduction = configuration.getInt("Producer.Image.MinDescaleReduction");
66
67
68   public EntityImages()
69   {
70     super();
71
72     logger = new LoggerWrapper("Entity.UploadedMedia.Images");
73   }
74
75   public EntityImages(StorageObject theStorage) {
76     this();
77     setStorage(theStorage);
78   }
79
80   //
81   // methods
82
83
84   public InputStream getImage() throws StorageObjectFailure {
85     logger.debug("EntityImages.getimage started");
86     java.sql.Connection con=null;
87     Statement stmt=null;
88     BlobInputStream in;
89     InputStream img_in = null;
90
91     try {
92       con = storageObject.getPooledCon();
93       con.setAutoCommit(false);
94       LargeObjectManager lom;
95       java.sql.Connection jCon;
96       stmt = con.createStatement();
97       ResultSet rs = storageObject.executeSql(stmt,
98           "select image_data from images where id="+getId());
99       jCon = ((com.codestudio.sql.PoolManConnectionHandle)con)
100            .getNativeConnection();
101       lom = ((org.postgresql.Connection)jCon).getLargeObjectAPI();
102       if(rs!=null) {
103         if (rs.next()) {
104           LargeObject lob = lom.open(rs.getInt(1));
105           in = (BlobInputStream)lob.getInputStream();
106           img_in = new ImageInputStream(in, con, stmt);
107         }
108         rs.close();
109       }
110     }
111     catch (Throwable t) {
112       logger.error("EntityImages.getImage failed: " + t.toString());
113       t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
114
115       try {
116         con.setAutoCommit(true);
117       }
118       catch (Throwable e) {
119         logger.error("EntityImages.getImage resetting transaction mode failed: " + e.toString());
120         e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
121       }
122
123       try {
124         storageObject.freeConnection(con, stmt);
125       }
126       catch (Throwable e) {
127         logger.error("EntityImages.getImage freeing connection failed: " +e.toString());
128       }
129
130       throw new StorageObjectFailure(t);
131     }
132
133     return img_in;
134   }
135
136   public void setImage(InputStream in, String type) throws StorageObjectFailure {
137     // todo: failures should be treated in a better way: exception -> rollback instead
138     //  of commit
139     if (in != null) {
140
141       Connection con = null;
142       PreparedStatement pstmt = null;
143       File f = null;
144       try {
145         logger.debug("EntityImages.settimage :: making internal representation of image");
146
147         f = File.createTempFile("mir", ".tmp",
148                 new File(MirPropertiesConfiguration.instance().getString("TempDir")));
149         FileUtil.write(f, in);
150         ImageProcessor processor = new ImageProcessor(f);
151
152         con = storageObject.getPooledCon();
153         con.setAutoCommit(false);
154         LargeObjectManager lom;
155         java.sql.Connection connection;
156         connection = ((com.codestudio.sql.PoolManConnectionHandle)con).getNativeConnection();
157
158         lom = ((org.postgresql.Connection) connection).getLargeObjectAPI();
159
160         int oidImage = lom.create();
161         LargeObject lobImage = lom.open(oidImage);
162         processor.descaleImage(maxImageSize, minDescaleRatio, minDescaleReduction);
163         processor.writeScaledData(lobImage.getOutputStream(), type);
164         lobImage.close();
165         setFieldValue("img_height", new Integer(processor.getScaledHeight()).toString());
166         setFieldValue("img_width", new Integer(processor.getScaledWidth()).toString());
167
168         int oidIcon = lom.create();
169         LargeObject lobIcon = lom.open(oidIcon);
170         processor.descaleImage(maxIconSize, minDescaleRatio, minDescaleReduction);
171         processor.writeScaledData(lobIcon.getOutputStream(), type);
172         lobIcon.close();
173
174         setFieldValue("icon_height", new Integer(processor.getScaledHeight()).toString());
175         setFieldValue("icon_width", new Integer(processor.getScaledWidth()).toString());
176
177         setFieldValue("image_data", new Integer(oidImage).toString());
178         setFieldValue("icon_data", new Integer(oidIcon).toString());
179         update();
180       }
181       catch (Exception e) {
182         throw new StorageObjectFailure(e);
183       }
184       finally {
185         try {
186           if (con!=null)
187             con.setAutoCommit(true);
188           // get rid of the temp. file
189         }
190         catch (Throwable e) {
191           logger.error("EntityImages.setImage: unable to reset the connection to auto-commit:" + e.toString());
192         }
193         try {
194           f.delete();
195         }
196         catch (Throwable t) {
197           logger.error("EntityImages.setImage: unable to delete the temporary file:" + t.toString());
198         }
199
200         try {
201           if (con!=null)
202             storageObject.freeConnection(con,pstmt);
203         }
204         catch (Throwable t) {
205           logger.error("EntityImages.setImage: unable to free the connection:" + t.toString());
206         }
207       }
208     }
209   }
210
211   /**
212    * Takes an OutputStream as an argument and reads in the data
213    * from the DB and writes it to the OutputStream.
214    *
215    * It will also take care of closing the OutputStream.
216    */
217   public InputStream getIcon() throws StorageObjectFailure {
218     Connection con=null;
219     Statement stmt=null;
220     BlobInputStream in=null;
221     ImageInputStream img_in=null;
222
223     try {
224       con = storageObject.getPooledCon();
225       con.setAutoCommit(false);
226       LargeObjectManager lom;
227       java.sql.Connection jCon;
228       stmt = con.createStatement();
229       ResultSet rs = storageObject.executeSql(stmt, "select icon_data from images where id="+getId());
230       jCon = ((com.codestudio.sql.PoolManConnectionHandle)con)
231            .getNativeConnection();
232       lom = ((org.postgresql.Connection)jCon).getLargeObjectAPI();
233       if(rs!=null) {
234         if (rs.next()) {
235           LargeObject lob = lom.open(rs.getInt(1));
236           in = (BlobInputStream)lob.getInputStream();
237           img_in = new ImageInputStream( in, con ,stmt);
238           //img_data = rs.getBytes(1);
239         }
240         rs.close();
241       }
242     }
243     catch (Throwable t) {
244       logger.error("EntityImages.getIcon failed: "+t.toString());
245       t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
246
247       try {
248         con.setAutoCommit(true);
249       }
250       catch (SQLException e) {
251         logger.error("EntityImages.getIcon resetting transaction mode failed: " + e.toString());
252         e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
253       }
254       try {
255         storageObject.freeConnection(con, stmt);
256       }
257       catch (Throwable e) {
258        logger.error("EntityImages -- freeing connection failed: " + e.getMessage());
259       }
260
261       throw new StorageObjectFailure(t);
262     }
263
264     return img_in;
265   }
266
267   /**
268    * a small wrapper class that allows us to store the DB connection resources
269    * that the BlobInputStream is using and free them upon closing of the stream
270    */
271   private class ImageInputStream extends InputStream {
272
273     InputStream _in;
274     Connection _con;
275     Statement _stmt;
276
277     public ImageInputStream(BlobInputStream in, Connection con,
278                             Statement stmt ) {
279       _in = in;
280       _con = con;
281       _stmt = stmt;
282     }
283
284     public void close () throws IOException {
285       _in.close();
286       try {
287         _con.setAutoCommit(true);
288         storageObject.freeConnection(_con,_stmt);
289       }
290       catch (Exception e) {
291         throw new IOException("close(): "+e.toString());
292       }
293     }
294
295     public int read() throws IOException {
296       return _in.read();
297     }
298   }
299 }