KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > j2biz > blogunity > web > actions > my > UploadUserpicAction


1 /*
2  * $Id: UploadUserpicAction.java,v 1.2 2005/01/17 21:35:45 michelson Exp $
3  *
4  * Copyright (c) 2004 j2biz Group, http://www.j2biz.com
5  * Koeln / Duesseldorf , Germany
6  *
7  * @author Max Kalina
8  *
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23  *
24  */

25
26 package com.j2biz.blogunity.web.actions.my;
27
28 import java.awt.Image JavaDoc;
29 import java.io.File JavaDoc;
30 import java.io.FileInputStream JavaDoc;
31 import java.util.Iterator JavaDoc;
32 import java.util.List JavaDoc;
33
34 import javax.imageio.ImageIO JavaDoc;
35 import javax.servlet.http.HttpServletRequest JavaDoc;
36 import javax.servlet.http.HttpServletResponse JavaDoc;
37
38 import org.apache.commons.fileupload.DiskFileUpload;
39 import org.apache.commons.fileupload.FileItem;
40 import org.apache.commons.fileupload.FileUpload;
41 import org.apache.commons.fileupload.FileUploadException;
42 import org.apache.commons.lang.StringUtils;
43 import org.apache.commons.logging.Log;
44 import org.apache.commons.logging.LogFactory;
45
46 import com.j2biz.blogunity.BlogunityManager;
47 import com.j2biz.blogunity.dao.UserpicDAO;
48 import com.j2biz.blogunity.exception.BlogunityException;
49 import com.j2biz.blogunity.i18n.I18N;
50 import com.j2biz.blogunity.i18n.I18NStatusFactory;
51 import com.j2biz.blogunity.pojo.SystemConfiguration;
52 import com.j2biz.blogunity.pojo.Userpic;
53 import com.j2biz.blogunity.util.HibernateUtil;
54 import com.j2biz.blogunity.util.ResourceUtils;
55 import com.j2biz.blogunity.web.ActionResultFactory;
56 import com.j2biz.blogunity.web.FormError;
57 import com.j2biz.blogunity.web.FormErrorList;
58 import com.j2biz.blogunity.web.IActionResult;
59
60 /**
61  * @author michelson
62  * @version $$
63  * @since 0.1
64  *
65  *
66  */

67 public class UploadUserpicAction extends MyAbstractAction {
68     /**
69      * Logger for this class
70      */

71     private static final Log log = LogFactory.getLog(UploadUserpicAction.class);
72
73     private static final IActionResult USERPICS_FORM_FORWARD = ActionResultFactory
74             .buildForward("/jsp/my/userpicsForm.jsp");
75
76     /*
77      * (non-Javadoc)
78      *
79      * @see com.j2biz.blogunity.web.actions.AbstractAction#execute(javax.servlet.http.HttpServletRequest,
80      * javax.servlet.http.HttpServletResponse)
81      */

82     public IActionResult execute(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response)
83             throws BlogunityException {
84
85         FormErrorList errors = new FormErrorList();
86
87         int userpicsPerUser = com.j2biz.blogunity.BlogunityManager.getSystemConfiguration()
88                 .getUserpicsPerUser();
89         int hasAlreadyUserpics = user.getUserpics().size();
90         if (hasAlreadyUserpics >= userpicsPerUser && userpicsPerUser != -1) {
91             errors.add(new FormError("name", "You have already defined maximal number("
92                     + hasAlreadyUserpics + ") of userpics!"));
93
94             request.setAttribute("errors", errors);
95             request.setAttribute("avatars", EditUserpicsFormAction.getAvatars(user));
96             return USERPICS_FORM_FORWARD;
97
98         }
99
100         boolean isMultipart = FileUpload.isMultipartContent(request);
101
102         if (!isMultipart) { throw new BlogunityException(I18NStatusFactory
103                 .create(I18N.ERRORS.NOT_MULTIPART)); }
104
105         DiskFileUpload upload = new DiskFileUpload();
106
107         SystemConfiguration config = BlogunityManager.getSystemConfiguration();
108
109         // TODO this parameters should be specified in global
110
// configuration-settings
111
// upload.setSizeThreshold(yourMaxMemorySize);
112
upload.setSizeMax(config.getMaxUserpicSize());
113         upload.setRepositoryPath(config.getTempDir());
114
115         List JavaDoc /* FileItem */items;
116         try {
117             items = upload.parseRequest(request);
118         } catch (FileUploadException e) {
119             throw new BlogunityException(I18NStatusFactory.create(
120                     I18N.ERRORS.UNABLE_TO_PARSE_UPLOAD, e));
121         }
122
123         // Process the uploaded items
124
String JavaDoc userpicName = null;
125         String JavaDoc extension = null;
126         File JavaDoc uploadedFile = null;
127
128         Iterator JavaDoc iter = items.iterator();
129         while (iter.hasNext()) {
130             FileItem item = (FileItem) iter.next();
131
132             if (item.isFormField()) {
133
134                 String JavaDoc name = item.getFieldName();
135                 String JavaDoc value = item.getString();
136
137                 if (name.equals("uploadname") && StringUtils.isNotEmpty(value)) {
138                     userpicName = value;
139
140                     if (user.containsUserpicWithName(userpicName)) {
141                         errors.add(new FormError("uploadname", "Userpic with name '" + userpicName
142                                 + "' already exists!"));
143                     }
144                 }
145
146             } else {
147
148                 String JavaDoc fieldName = item.getFieldName();
149                 String JavaDoc fileName = item.getName();
150                 extension = fileName.substring(fileName.lastIndexOf('.') + 1);
151
152                 if (fieldName.equals("userpic")) {
153
154                     try {
155                         uploadedFile = parseUploadedUserpic(item, errors);
156                     } catch (Exception JavaDoc e) {
157                         throw new BlogunityException(I18NStatusFactory.create(I18N.ERRORS.UNKNOWN,
158                                 e));
159                     }
160
161                 }
162             }
163         }
164
165         if (uploadedFile == null || extension == null) {
166             errors.add(new FormError("userpic", "Uploaded file is not valid image file!"));
167         }
168
169         if (StringUtils.isEmpty(userpicName)) {
170             errors.add(new FormError("uploadname", "Userpic name is not specified!"));
171         }
172
173         // return, if there is errors
174
if (errors.size() > 0) {
175             request.setAttribute("errors", errors);
176             request.setAttribute("avatars", EditUserpicsFormAction.getAvatars(user));
177             if (uploadedFile != null) uploadedFile.delete();
178             return USERPICS_FORM_FORWARD;
179         }
180
181         Userpic pic = new Userpic(userpicName, "/users/" + user.getNickname() + "/userpics/"
182                 + System.currentTimeMillis() + "." + extension, false, user);
183
184         if (!user.containsUserpicWithUrl(pic.getUrl())) {
185             (new UserpicDAO()).createUserpic(pic);
186
187             try {
188                 copyUserpic(pic, uploadedFile);
189             } catch (BlogunityException e1) {
190                 log.error("Error copying userpic!", e1);
191                 HibernateUtil.rollbackTransaction();
192                 throw new BlogunityException(I18NStatusFactory.create(I18N.ERRORS.CREATE_FILE, e1));
193             }
194
195         }
196
197         return navigationStack.peek();
198     }
199
200     private File JavaDoc parseUploadedUserpic(FileItem item, FormErrorList errors) throws Exception JavaDoc {
201         String JavaDoc fieldName = item.getFieldName();
202         String JavaDoc fileName = item.getName();
203         String JavaDoc extension = fileName.substring(fileName.lastIndexOf('.') + 1);
204         String JavaDoc contentType = item.getContentType();
205         boolean isInMemory = item.isInMemory();
206         long sizeInBytes = item.getSize();
207         SystemConfiguration config = BlogunityManager.getSystemConfiguration();
208
209         if (log.isDebugEnabled()) {
210             log.debug("Parsing uploaded file: name=" + fileName + ", contentType=" + contentType
211                     + ", size=" + sizeInBytes);
212         }
213
214         if (StringUtils.isEmpty(fileName)) {
215             errors.add(new FormError("userpic", "Userpic is not specified!"));
216             return null;
217         }
218
219         if (!canReadMimeType(contentType)) {
220             errors.add(new FormError("userpic", "Uploaded file is not valid image file!"));
221             return null;
222         }
223
224         File JavaDoc uploadedFile = new File JavaDoc(BlogunityManager.getSystemConfiguration().getTempDir(), System
225                 .currentTimeMillis()
226                 + fileName);
227
228         if (uploadedFile.exists()) uploadedFile.delete();
229         uploadedFile.createNewFile();
230         item.write(uploadedFile);
231
232         if (uploadedFile.length() > config.getMaxUserpicSize()) {
233             errors.add(new FormError("userpic",
234                     "Uploaded userpic has wrong size. Size of the uploaded userpics can be maximal "
235                             + ResourceUtils.getPreformattedFilesize(config.getMaxUserpicSize())
236                             + "!"));
237             return null;
238
239         }
240
241         if (uploadedFile.exists() && uploadedFile.length() > 0) {
242             Image JavaDoc image = ImageIO.read(new FileInputStream JavaDoc(uploadedFile));
243             if (image != null) {
244                 int width = image.getWidth(null);
245                 int height = image.getHeight(null);
246
247                 if (width > config.getMaxUserpicWidth() || height > config.getMaxUserpicHeight()) {
248                     errors.add(new FormError("userpic",
249                             "Uploaded userpic has wrong insets. Size of the uploaded userpics can be maximal "
250                                     + config.getMaxUserpicWidth() + "x"
251                                     + config.getMaxUserpicHeight() + " pixels!"));
252                     return null;
253                 }
254             } else {
255                 errors.add(new FormError("userpic", "Userpic is not specified!!"));
256                 return null;
257             }
258         }
259
260         return uploadedFile;
261     }
262
263     /**
264      * Copy uploaded userpic into user's "userpics"-directory.
265      *
266      * @param pic
267      * @param in
268      * @throws BlogunityException
269      */

270     private void copyUserpic(Userpic pic, File JavaDoc source) throws BlogunityException {
271
272         SystemConfiguration config = BlogunityManager.getSystemConfiguration();
273         File JavaDoc userpicDir = new File JavaDoc(config.getUsersDirectory(), user.getNickname() + "/userpics");
274         if (!userpicDir.exists()) {
275             boolean result = userpicDir.mkdirs();
276             if (!result)
277                     throw new BlogunityException(I18NStatusFactory.create(
278                             I18N.ERRORS.CREATE_DIRECTORY, userpicDir.getAbsolutePath()));
279         }
280
281         File JavaDoc destination = new File JavaDoc(config.getDataDir(), pic.getUrl());
282
283         ResourceUtils.copyFile(source, destination);
284         source.delete();
285     }
286
287     /**
288      * Returns true if the specified mime type can be read
289      *
290      * @param mimeType
291      * @return
292      */

293     private static boolean canReadMimeType(String JavaDoc mimeType) {
294         Iterator JavaDoc iter = ImageIO.getImageReadersByMIMEType(mimeType);
295         return iter.hasNext();
296     }
297
298 }
Popular Tags