fixed the handling of GIF images now also for the classic image handlers
[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 org.postgresql.largeobject.BlobInputStream;
43 import org.postgresql.largeobject.LargeObject;
44 import org.postgresql.largeobject.LargeObjectManager;
45
46 import mir.config.MirPropertiesConfiguration;
47 import mir.log.LoggerWrapper;
48 import mir.misc.FileUtil;
49 import mir.storage.StorageObject;
50 import mir.storage.StorageObjectFailure;
51 import mircoders.media.ImageProcessor;
52
53 /**
54  * Diese Klasse enth?lt die Daten eines MetaObjekts
55  *
56  * @author RK, mh, mir-coders
57  * @version $Id: EntityImages.java,v 1.21 2003/04/30 00:37:27 zapata Exp $
58  */
59
60
61 public class EntityImages extends EntityUploadedMedia
62 {
63   private int maxImageSize = configuration.getInt("Producer.Image.MaxSize");
64   private int maxIconSize = configuration.getInt("Producer.Image.MaxIconSize");
65   private float minDescaleRatio = configuration.getFloat("Producer.Image.MinDescalePercentage")/100;
66   private int minDescaleReduction = configuration.getInt("Producer.Image.MinDescaleReduction");
67
68
69   public EntityImages()
70   {
71     super();
72
73     logger = new LoggerWrapper("Entity.UploadedMedia.Images");
74   }
75
76   public EntityImages(StorageObject theStorage) {
77     this();
78     setStorage(theStorage);
79   }
80
81   //
82   // methods
83
84
85   public InputStream getImage() throws StorageObjectFailure {
86     logger.debug("EntityImages.getimage started");
87     java.sql.Connection con=null;
88     Statement stmt=null;
89     BlobInputStream in;
90     InputStream img_in = null;
91     try {
92       con = theStorageObject.getPooledCon();
93       con.setAutoCommit(false);
94       LargeObjectManager lom;
95       java.sql.Connection jCon;
96       stmt = con.createStatement();
97       ResultSet rs = theStorageObject.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         theStorageObject.freeConnection(con, stmt);
125       }
126       catch (Throwable e) {
127         logger.error("EntityImages.getImage freeing connection failed: " +e.toString());
128       }
129
130       throwStorageObjectFailure(t, "EntityImages -- getImage failed: ");
131     }
132     return img_in;
133   }
134
135   public void setImage(InputStream in, String type) throws StorageObjectFailure {
136
137     if (in != null) {
138
139       Connection con = null;
140       PreparedStatement pstmt = null;
141       File f = null;
142       try {
143         logger.debug("EntityImages.settimage :: making internal representation of image");
144
145         f = File.createTempFile("mir", ".tmp",
146                 new File(MirPropertiesConfiguration.instance().getString("TempDir")));
147         FileUtil.write(f, in);
148         ImageProcessor processor = new ImageProcessor(f);
149
150         con = theStorageObject.getPooledCon();
151         con.setAutoCommit(false);
152         LargeObjectManager lom;
153         java.sql.Connection connection;
154         connection = ((com.codestudio.sql.PoolManConnectionHandle)con).getNativeConnection();
155
156         lom = ((org.postgresql.Connection) connection).getLargeObjectAPI();
157
158         int oidImage = lom.create();
159         LargeObject lobImage = lom.open(oidImage);
160         processor.descaleImage(maxImageSize, minDescaleRatio, minDescaleReduction);
161         processor.writeScaledData(lobImage.getOutputStream(), type);
162         lobImage.close();
163         setValueForProperty("img_height", new Integer(processor.getScaledHeight()).toString());
164         setValueForProperty("img_width", new Integer(processor.getScaledWidth()).toString());
165
166         int oidIcon = lom.create();
167         LargeObject lobIcon = lom.open(oidIcon);
168         processor.descaleImage(maxIconSize, minDescaleRatio, minDescaleReduction);
169         processor.writeScaledData(lobIcon.getOutputStream(), type);
170         lobIcon.close();
171
172         setValueForProperty("icon_height", new Integer(processor.getScaledHeight()).toString());
173         setValueForProperty("icon_width", new Integer(processor.getScaledWidth()).toString());
174
175         setValueForProperty("image_data", new Integer(oidImage).toString());
176         setValueForProperty("icon_data", new Integer(oidIcon).toString());
177         update();
178       }
179       catch (Exception e) {
180         throwStorageObjectFailure(e, "settimage :: setImage gescheitert: ");
181       }
182       finally {
183         try {
184           if (con!=null)
185             con.setAutoCommit(true);
186           // get rid of the temp. file
187           f.delete();
188         } catch (SQLException e) {
189           throwStorageObjectFailure(e,"Resetting transaction-mode failed");
190         }
191         if (con!=null)
192           theStorageObject.freeConnection(con,pstmt);
193       }
194     }
195   }
196
197   /**
198    * Takes an OutputStream as an argument and reads in the data
199    * from the DB and writes it to the OutputStream.
200    *
201    * It will also take care of closing the OutputStream.
202    */
203   public InputStream getIcon() throws StorageObjectFailure {
204     Connection con=null;
205     Statement stmt=null;
206     BlobInputStream in=null;
207     ImageInputStream img_in=null;
208
209     try {
210       con = theStorageObject.getPooledCon();
211       con.setAutoCommit(false);
212       LargeObjectManager lom;
213       java.sql.Connection jCon;
214       stmt = con.createStatement();
215       ResultSet rs = theStorageObject.executeSql(stmt, "select icon_data from images where id="+getId());
216       jCon = ((com.codestudio.sql.PoolManConnectionHandle)con)
217            .getNativeConnection();
218       lom = ((org.postgresql.Connection)jCon).getLargeObjectAPI();
219       if(rs!=null) {
220         if (rs.next()) {
221           LargeObject lob = lom.open(rs.getInt(1));
222           in = (BlobInputStream)lob.getInputStream();
223           img_in = new ImageInputStream( in, con ,stmt);
224           //img_data = rs.getBytes(1);
225         }
226         rs.close();
227       }
228     }
229     catch (Throwable t) {
230       logger.error("EntityImages.getIcon failed: "+t.toString());
231       t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
232
233       try {
234         con.setAutoCommit(true);
235       }
236       catch (SQLException e) {
237         logger.error("EntityImages.getIcon resetting transaction mode failed: " + e.toString());
238         e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
239       }
240       try {
241         theStorageObject.freeConnection(con, stmt);
242       }
243       catch (Throwable e) {
244        logger.error("EntityImages -- freeing connection failed: " + e.getMessage());
245       }
246
247       throwStorageObjectFailure(t, "EntityImages -- getIcon failed:");
248     }
249
250     return img_in;
251   }
252
253   /**
254    * a small wrapper class that allows us to store the DB connection resources
255    * that the BlobInputStream is using and free them upon closing of the stream
256    */
257   private class ImageInputStream extends InputStream {
258
259     InputStream _in;
260     Connection _con;
261     Statement _stmt;
262
263     public ImageInputStream(BlobInputStream in, Connection con,
264                             Statement stmt ) {
265       _in = in;
266       _con = con;
267       _stmt = stmt;
268     }
269
270     public void close () throws IOException {
271       _in.close();
272       try {
273         _con.setAutoCommit(true);
274         theStorageObject.freeConnection(_con,_stmt);
275       } catch (Exception e) {
276         throw new IOException("close(): "+e.toString());
277       }
278     }
279
280     public int read() throws IOException {
281       return _in.read();
282     }
283   }
284 }