fixing scaling images -> nullpointer, patch by yossarian
[mir.git] / source / mircoders / media / MediaHandlerImagesExternScaling.java
index 5b48ec2..1afa019 100644 (file)
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two.  You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries.  If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mircoders.media;
-
-
-import java.io.BufferedInputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-
-import mir.entity.Entity;
-import mir.log.LoggerWrapper;
-import mir.media.MediaExc;
-import mir.media.MediaFailure;
-import mir.media.image.ImageMagickImageProcessor;
-import mir.media.image.ImageProcessor;
-import mir.misc.StringUtil;
-import mir.util.FileRoutines;
-
-/**
- * Image handler that stores images outside of the database.
- * 
- * @author Zapata
- * @version 1.0
- */
-
-public class MediaHandlerImagesExternScaling extends MediaHandlerGeneric
-{
-  private int maxSize;
-  private int maxIconSize;
-  private float minDescaleRatio;
-  private int minDescaleReduction;
-  public MediaHandlerImagesExternScaling() {
-    logger = new LoggerWrapper("Media.Images.Extern");
-    maxSize = configuration.getInt("Producer.Image.MaxSize");
-    maxIconSize = configuration.getInt("Producer.Image.MaxIconSize");
-    minDescaleRatio = configuration.getFloat("Producer.Image.MinDescalePercentage")/100;
-    minDescaleReduction = configuration.getInt("Producer.Image.MinDescaleReduction");
-  }
-  
-
-  
-  public void produce(Entity anImageEntity, Entity mediaTypeEnt) throws MediaExc, MediaFailure {
-    try {
-      String date = anImageEntity.getFieldValue("date");
-      String datePath = StringUtil.webdbDate2path(date);
-      String ext = "." + mediaTypeEnt.getFieldValue("name");
-      String fileBasePath = datePath + anImageEntity.getId();
-      String filePath = fileBasePath + ext;
-
-      String imageFilePath = getBaseStoragePath() + File.separator + filePath;
-      File imageFile = new File(imageFilePath);
-      
-      if (!imageFile.exists()) {
-        throw new MediaExc("error in MediaHandlerImagesExtern.execute(): "
-            + filePath + " does not exist!");
-      } else {
-        ImageProcessor processor = new ImageMagickImageProcessor(imageFile);
-        String iconPath = getBaseIconStoragePath() + fileBasePath + ".jpg";
-        String iconStoragePath = doIconScaling(processor, iconPath);
-        anImageEntity.setFieldValue("icon_height", new Integer(processor.getScaledHeight()).toString());
-        anImageEntity.setFieldValue("icon_width", new Integer(processor.getScaledWidth()).toString());
-        anImageEntity.setFieldValue("icon_path", iconPath);
-        
-        String imageOriginalRelPath = doImageScaling(filePath, imageFile, processor);
-        anImageEntity.setFieldValue("original_file_path", imageOriginalRelPath);
-        anImageEntity.setFieldValue("img_height", Integer.toString(processor.getScaledHeight()));
-        anImageEntity.setFieldValue("img_width", Integer.toString(processor.getScaledWidth()));
-
-        processor.cleanup();
-        anImageEntity.setFieldValue("publish_path", filePath);
-        anImageEntity.update();
-        reportChange(iconStoragePath);
-        reportChange(imageFilePath);
-      }
-    }
-    catch(Throwable t) {
-      logger.error("MediaHandlerImagesExtern.execute: " + t.getMessage(), t);
-      throw new MediaFailure(t.getMessage(), t);
-    }
-  }
-
-    /**
-     * Scale an icon image and write it to the file system.
-     * @param processor
-     * @param iconPath
-     * @return
-     * @throws MediaExc
-     */
-    private String doIconScaling(ImageProcessor processor, String iconPath) throws MediaExc {
-        String iconStoragePath = configuration.getString("Producer.StorageRoot") + iconPath;
-        File iconFile = new File(iconStoragePath);
-        processor.descaleImage(maxIconSize, minDescaleRatio, minDescaleReduction);
-        File dir = new File(iconFile.getParent());
-        if (dir != null && !dir.exists()) {
-          dir.mkdirs();
-        }
-        processor.writeScaledData(iconFile, "JPEG");
-        return iconStoragePath;
-    }
-
-    /**
-     * Make the resized file.
-     * @param filePath
-     * @param imageFile
-     * @param processor
-     * @return
-     * @throws MediaExc
-     * @throws IOException
-     */
-    private String doImageScaling(String filePath, File imageFile, ImageProcessor processor) throws MediaExc, IOException {
-        // get a file path where the the original image should be saved if image resizing is turned on
-          String imagesOriginalDir = configuration.getString("Producer.ImagesOriginalDir.Path");
-          String imagesOriginalDirRelPath = configuration.getString("Producer.ImagesOriginalDir.RelPath");
-          String imageOriginalFilePath = imagesOriginalDir + filePath;
-          String imageOriginalRelPath = imagesOriginalDirRelPath +  filePath;
-          File originalFile = new File(imageOriginalFilePath);   
-          processor.descaleImage(maxSize, minDescaleRatio, minDescaleReduction);
-          File originalDir = new File(originalFile.getParent());
-          if (originalDir != null && !originalDir.exists()) {
-            originalDir.mkdirs();
-          }
-          if (!originalFile.exists()) {
-            FileRoutines.copy(imageFile, originalFile);
-            reportChange(originalFile.getAbsolutePath());
-          }
-          // yoss: don't write the scaled data again if it's the same size as
-          // the file that's there right now. Image producer runs are 4 times
-          // faster this way.
-          if (processor.getScaledFileSize() != imageFile.length()) {
-              processor.writeScaledData(imageFile, "JPEG");
-          }
-        return imageOriginalRelPath;
-    }
-
-/** {@inheritDoc} */
-  public InputStream getThumbnail(Entity anImageEntity) throws MediaExc, MediaFailure {
-    try {
-      File file = new File(configuration.getString("Producer.StorageRoot") + anImageEntity.getFieldValue("icon_path"));
-
-      if (!file.exists()) {
-        // hackish
-        file = new File(configuration.getHome(), "../img/photo_big.gif");
-      }
-
-      return new BufferedInputStream(
-        new FileInputStream(file),8192);
-    }
-    catch (Throwable t) {
-      return null;
-    }
-  }
-
-  public String getIconMimeType(Entity anImageEntity, Entity aMediaType) {
-    return "image/jpeg";
-  }
-
-  public String getBaseStoragePath()
-  {
-    return configuration.getString("Producer.Image.Path");
-  }
-
-  public String getBaseIconStoragePath()
-  {
-    return configuration.getString("Producer.Image.IconPath");
-  }
-
-  public String getPublishHost()
-  {
-    return StringUtil.removeSlash(configuration.getString("Producer.Image.Host"));
-  }
-
-  public String getTinyIconName()
-  {
-    return configuration.getString("Producer.Icon.TinyImage");
-  }
-
-  public String getBigIconName()
-  {
-    return configuration.getString("Producer.Icon.BigImage");
-  }
-
-  public String getIconAltName()
-  {
-    return "Image";
-  }
-
-  public String getDescr(Entity mediaType)
-  {
-     return "image/jpeg";
-  }
-}
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with  any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two.  You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries.  If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package mircoders.media;\r
+\r
+\r
+import java.io.BufferedInputStream;\r
+import java.io.File;\r
+import java.io.FileInputStream;\r
+import java.io.FileNotFoundException;\r
+import java.io.IOException;\r
+import java.io.InputStream;\r
+\r
+import mir.entity.Entity;\r
+import mir.log.LoggerWrapper;\r
+import mir.media.MediaExc;\r
+import mir.media.MediaFailure;\r
+import mir.media.image.ImageMagickImageProcessor;\r
+import mir.media.image.ImageProcessor;\r
+import mir.misc.StringUtil;\r
+import mir.util.FileRoutines;\r
+\r
+/**\r
+ * Image handler that stores images outside of the database.\r
+ * \r
+ * @author Zapata\r
+ * @version 1.0\r
+ */\r
+\r
+public class MediaHandlerImagesExternScaling extends MediaHandlerGeneric\r
+{\r
+  private int maxSize;\r
+  private int maxIconSize;\r
+  private float minDescaleRatio;\r
+  private int minDescaleReduction;\r
+  public MediaHandlerImagesExternScaling() {\r
+    logger = new LoggerWrapper("Media.Images.Extern");\r
+    maxSize = configuration.getInt("Producer.Image.MaxSize");\r
+    maxIconSize = configuration.getInt("Producer.Image.MaxIconSize");\r
+    minDescaleRatio = configuration.getFloat("Producer.Image.MinDescalePercentage")/100;\r
+    minDescaleReduction = configuration.getInt("Producer.Image.MinDescaleReduction");\r
+  }\r
+  \r
+\r
+  \r
+  public void produce(Entity anImageEntity, Entity mediaTypeEnt) throws MediaExc, MediaFailure {\r
+    try {\r
+      String date = anImageEntity.getFieldValue("date");\r
+      String datePath = StringUtil.webdbDate2path(date);\r
+      String ext = "." + mediaTypeEnt.getFieldValue("name");\r
+      String fileBasePath = datePath + anImageEntity.getId();\r
+      String filePath = fileBasePath + ext;\r
+\r
+      String imageFilePath = getBaseStoragePath() + File.separator + filePath;\r
+      File imageFile = new File(imageFilePath);\r
+      \r
+      if (!imageFile.exists()) {\r
+        throw new MediaExc("error in MediaHandlerImagesExtern.execute(): "\r
+            + filePath + " does not exist!");\r
+      } else {\r
+        ImageProcessor processor = new ImageMagickImageProcessor(imageFile);\r
+        String iconPath = getBaseIconStoragePath() + fileBasePath + ".jpg";\r
+        String iconStoragePath = doIconScaling(processor, iconPath);\r
+        anImageEntity.setFieldValue("icon_height", new Integer(processor.getScaledHeight()).toString());\r
+        anImageEntity.setFieldValue("icon_width", new Integer(processor.getScaledWidth()).toString());\r
+        anImageEntity.setFieldValue("icon_path", iconPath);\r
+        \r
+        String imageOriginalRelPath = doImageScaling(filePath, imageFile, processor);\r
+        anImageEntity.setFieldValue("original_file_path", imageOriginalRelPath);\r
+        anImageEntity.setFieldValue("img_height", Integer.toString(processor.getScaledHeight()));\r
+        anImageEntity.setFieldValue("img_width", Integer.toString(processor.getScaledWidth()));\r
+\r
+        processor.cleanup();\r
+        anImageEntity.setFieldValue("publish_path", filePath);\r
+        anImageEntity.update();\r
+        reportChange(iconStoragePath);\r
+        reportChange(imageFilePath);\r
+      }\r
+    }\r
+    catch(Throwable t) {\r
+      logger.error("MediaHandlerImagesExtern.execute: " + t.getMessage(), t);\r
+      throw new MediaFailure(t.getMessage(), t);\r
+    }\r
+  }\r
+\r
+    /**\r
+     * Scale an icon image and write it to the file system.\r
+     * @param processor\r
+     * @param iconPath\r
+     * @return\r
+     * @throws MediaExc\r
+     */\r
+    private String doIconScaling(ImageProcessor processor, String iconPath) throws MediaExc {\r
+        String iconStoragePath = configuration.getString("Producer.StorageRoot") + iconPath;\r
+        File iconFile = new File(iconStoragePath);\r
+        processor.descaleImage(maxIconSize, minDescaleRatio, minDescaleReduction);\r
+        File dir = new File(iconFile.getParent());\r
+        if (dir != null && !dir.exists()) {\r
+          dir.mkdirs();\r
+        }\r
+               try {\r
+                       processor.writeScaledData(iconFile, "JPEG");\r
+               } catch (FileNotFoundException e) {\r
+                       // TODO Auto-generated catch block\r
+                       e.printStackTrace();\r
+               } catch (IOException e) {\r
+                       // TODO Auto-generated catch block\r
+                       e.printStackTrace();\r
+               }\r
+        return iconStoragePath;\r
+    }\r
+\r
+    /**\r
+     * Make the resized file.\r
+     * @param filePath\r
+     * @param imageFile\r
+     * @param processor\r
+     * @return\r
+     * @throws MediaExc\r
+     * @throws IOException\r
+     */\r
+    private String doImageScaling(String filePath, File imageFile, ImageProcessor processor) throws MediaExc, IOException {\r
+        // get a file path where the the original image should be saved if image resizing is turned on\r
+          String imagesOriginalDir = configuration.getString("Producer.ImagesOriginalDir.Path");\r
+          String imagesOriginalDirRelPath = configuration.getString("Producer.ImagesOriginalDir.RelPath");\r
+          String imageOriginalFilePath = imagesOriginalDir + filePath;\r
+          String imageOriginalRelPath = imagesOriginalDirRelPath +  filePath;\r
+          File originalFile = new File(imageOriginalFilePath);   \r
+          processor.descaleImage(maxSize, minDescaleRatio, minDescaleReduction);\r
+          File originalDir = new File(originalFile.getParent());\r
+          if (originalDir != null && !originalDir.exists()) {\r
+            originalDir.mkdirs();\r
+          }\r
+          if (!originalFile.exists()) {\r
+            FileRoutines.copy(imageFile, originalFile);\r
+            reportChange(originalFile.getAbsolutePath());\r
+          }\r
+          // yoss: don't write the scaled data again if it's the same size as\r
+          // the file that's there right now. Image producer runs are 4 times\r
+          // faster this way.\r
+          if (processor.getScaledFileSize() != imageFile.length()) {\r
+              processor.writeScaledData(imageFile, "JPEG");\r
+          }\r
+        return imageOriginalRelPath;\r
+    }\r
+\r
+/** {@inheritDoc} */\r
+  public InputStream getThumbnail(Entity anImageEntity) throws MediaExc, MediaFailure {\r
+    try {\r
+      File file = new File(configuration.getString("Producer.StorageRoot") + anImageEntity.getFieldValue("icon_path"));\r
+\r
+      if (!file.exists()) {\r
+        // hackish\r
+        file = new File(configuration.getHome(), "../img/photo_big.gif");\r
+      }\r
+\r
+      return new BufferedInputStream(\r
+        new FileInputStream(file),8192);\r
+    }\r
+    catch (Throwable t) {\r
+      return null;\r
+    }\r
+  }\r
+\r
+  public String getIconMimeType(Entity anImageEntity, Entity aMediaType) {\r
+    return "image/jpeg";\r
+  }\r
+\r
+  public String getBaseStoragePath()\r
+  {\r
+    return configuration.getString("Producer.Image.Path");\r
+  }\r
+\r
+  public String getBaseIconStoragePath()\r
+  {\r
+    return configuration.getString("Producer.Image.IconPath");\r
+  }\r
+\r
+  public String getPublishHost()\r
+  {\r
+    return StringUtil.removeSlash(configuration.getString("Producer.Image.Host"));\r
+  }\r
+\r
+  public String getTinyIconName()\r
+  {\r
+    return configuration.getString("Producer.Icon.TinyImage");\r
+  }\r
+\r
+  public String getBigIconName()\r
+  {\r
+    return configuration.getString("Producer.Icon.BigImage");\r
+  }\r
+\r
+  public String getIconAltName()\r
+  {\r
+    return "Image";\r
+  }\r
+\r
+  public String getDescr(Entity mediaType)\r
+  {\r
+     return "image/jpeg";\r
+  }\r
+}\r