KickJava   Java API By Example, From Geeks To Geeks.

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


1 /*
2  * $Id: ImportBlogThemeAction.java,v 1.3 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.io.File JavaDoc;
29 import java.io.IOException JavaDoc;
30 import java.io.InputStream JavaDoc;
31 import java.util.Iterator JavaDoc;
32 import java.util.List JavaDoc;
33 import java.util.zip.ZipInputStream JavaDoc;
34
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.BlogDAO;
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.Blog;
52 import com.j2biz.blogunity.pojo.SystemConfiguration;
53 import com.j2biz.blogunity.util.ResourceUtils;
54 import com.j2biz.blogunity.web.ActionResultFactory;
55 import com.j2biz.blogunity.web.FormError;
56 import com.j2biz.blogunity.web.FormErrorList;
57 import com.j2biz.blogunity.web.IActionResult;
58
59 /**
60  * @author michelson
61  * @version $$
62  * @since 0.1
63  *
64  *
65  */

66 public class ImportBlogThemeAction extends MyAbstractAction {
67     /**
68      * Logger for this class
69      */

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

81     public IActionResult execute(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response)
82             throws BlogunityException {
83
84         boolean isMultipart = FileUpload.isMultipartContent(request);
85
86         if (!isMultipart) {
87
88         throw new BlogunityException(I18NStatusFactory.create(I18N.ERRORS.NOT_MULTIPART));
89
90         }
91
92         FormErrorList errors = new FormErrorList();
93         DiskFileUpload upload = new DiskFileUpload();
94
95         // TODO this parameters should be specified in global
96
// configuration-settings
97
// upload.setSizeThreshold(yourMaxMemorySize);
98
// upload.setSizeMax(yourMaxRequestSize);
99
upload.setRepositoryPath(BlogunityManager.getSystemConfiguration().getTempDir());
100
101         List JavaDoc /* FileItem */items;
102         try {
103             items = upload.parseRequest(request);
104         } catch (FileUploadException e) {
105             throw new BlogunityException(I18NStatusFactory.create(
106                     I18N.ERRORS.UNABLE_TO_PARSE_UPLOAD, e));
107         }
108
109         // Process the uploaded items
110
Blog blog = null;
111         String JavaDoc fieldName = null;
112         String JavaDoc fileName = null;
113         String JavaDoc contentType = null;
114         boolean isInMemory = false;
115         long sizeInBytes = 0;
116         InputStream JavaDoc uploadedStream = null;
117
118         Iterator JavaDoc iter = items.iterator();
119         while (iter.hasNext()) {
120             FileItem item = (FileItem) iter.next();
121
122             if (item.isFormField()) {
123                 String JavaDoc name = item.getFieldName();
124                 String JavaDoc value = item.getString();
125  
126                 if (name.equals("blogId") && StringUtils.isNotEmpty(value)) {
127                     try {
128                         blog = (new BlogDAO()).getBlogByID(Long.parseLong(value));
129                     } catch (Exception JavaDoc e1) {
130                         blog = null;
131                     }
132                 }
133
134             } else {
135                 fieldName = item.getFieldName();
136                 fileName = item.getName();
137                 contentType = item.getContentType();
138                 isInMemory = item.isInMemory();
139                 sizeInBytes = item.getSize();
140                 try {
141                     uploadedStream = item.getInputStream();
142                 } catch (IOException JavaDoc e1) {
143                     uploadedStream = null;
144                 }
145             }
146         }
147
148         if (blog == null) { throw new BlogunityException(I18NStatusFactory.create(
149                 I18N.ERRORS.NOT_FOUND, "Blog")); }
150         if (blog.getFounder().getId().longValue() != user.getId().longValue()
151                 && !user.isAdministrator())
152                 throw new BlogunityException(I18NStatusFactory
153                         .create(I18N.ERRORS.USER_NOT_AUTHORIZED_FOR_EXECUTION));
154
155         if (StringUtils.isEmpty(fileName)) {
156             errors.add(new FormError("themeFile", "Theme-File is not specified!"));
157         }
158
159         if (errors.size() == 0) {
160
161             if (fieldName.equals("themeFile")) {
162                 if (log.isDebugEnabled()) {
163                     log.debug("Parsing uploaded file: name=" + fileName + ", contentType="
164                             + contentType + ", size=" + sizeInBytes);
165                 }
166
167                 File JavaDoc unzipDir = new File JavaDoc(BlogunityManager.getSystemConfiguration().getTempDir(),
168                         "theme-upload" + System.currentTimeMillis());
169                 boolean result = unzipDir.mkdir();
170                 if (!result)
171                         throw new BlogunityException(I18NStatusFactory.create(
172                                 I18N.ERRORS.CREATE_DIRECTORY, unzipDir.getAbsolutePath()));
173
174                 try {
175                     ZipInputStream JavaDoc zin = new ZipInputStream JavaDoc(uploadedStream);
176                     ResourceUtils.unzipFile(zin, unzipDir);
177
178                     File JavaDoc realThemeDir = checkUploadedTheme(unzipDir);
179
180                     // now overwrite old blog's
181
SystemConfiguration config = BlogunityManager.getSystemConfiguration();
182                     File JavaDoc blogsDir = config.getBlogsDirectory();
183                     // 1. first remove existing theme-directory
184
File JavaDoc oldThemeDir = new File JavaDoc(blogsDir, blog.getUrlName() + "/theme");
185                     ResourceUtils.removeDirectory(oldThemeDir);
186
187                     // 2. now create empty theme-directory
188
boolean r = oldThemeDir.mkdir();
189                     if (!r) { throw new BlogunityException(I18NStatusFactory.create(
190                             I18N.ERRORS.READ_DIRECTORY, oldThemeDir.getAbsolutePath())); }
191
192                     // 3. and copy theme-files...
193
ResourceUtils.copyDirectory(realThemeDir, oldThemeDir);
194
195                     // and delete uploadedTheme
196
ResourceUtils.removeDirectory(unzipDir);
197
198                 } catch (BlogunityException e) {
199                     throw e;
200                 } finally {
201                     try {
202                         if (uploadedStream != null) uploadedStream.close();
203                     } catch (IOException JavaDoc e1) {
204                         ;
205                     }
206                 }
207
208             }
209
210         } else {
211             request.setAttribute("errors", errors);
212             request.setAttribute("blog", blog);
213             return THEME_FORM_FORWARD;
214         }
215
216         return navigationStack.peek();
217     }
218
219     /**
220      * @param unzipDir
221      * @throws BlogunityException
222      */

223     private File JavaDoc checkUploadedTheme(File JavaDoc uploadedTempDir) throws BlogunityException {
224
225         File JavaDoc[] files = uploadedTempDir.listFiles();
226         if (files.length != 1 || !files[0].isDirectory()) {
227             ResourceUtils.removeDirectory(uploadedTempDir);
228             throw new BlogunityException(I18NStatusFactory
229                     .create(I18N.ERRORS.THEME_PACKAGE_NOT_VALID));
230         }
231
232         File JavaDoc realtThemeDir = files[0];
233         File JavaDoc[] themeFiles = realtThemeDir.listFiles();
234
235         //clean uploaded theme
236
//FIXME we allow at the moment only flat theme-structure
237
// (whithout sub-directories) and only files with extension
238
// vm/css/jpg/jpeg/gif/png
239
for (int i = 0; i < themeFiles.length; i++) {
240             if (themeFiles[i].isDirectory()) ResourceUtils.removeDirectory(themeFiles[i]);
241
242             if (themeFiles[i].isFile()) {
243                 if (!(themeFiles[i].getName().endsWith(".vm")
244                         || themeFiles[i].getName().endsWith(".css")
245                         || themeFiles[i].getName().endsWith(".jpg")
246                         || themeFiles[i].getName().endsWith(".jpeg")
247                         || themeFiles[i].getName().endsWith(".gif") || themeFiles[i].getName()
248                         .endsWith(".png"))) {
249                     themeFiles[i].delete();
250                 }
251             }
252         }
253
254         return realtThemeDir;
255
256     }
257
258 }
Popular Tags