PageRenderTime 53ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/branches/blojsom-2_07-final/blojsom-2.0/plugins/src/org/blojsom/plugin/admin/FileUploadPlugin.java

https://github.com/czarneckid/blojsom-sourceforge
Java | 282 lines | 174 code | 36 blank | 72 comment | 29 complexity | cf3408ab12f262b66e9d6188b3bf3271 MD5 | raw file
  1. /**
  2. * Copyright (c) 2003, David A. Czarnecki
  3. * All rights reserved.
  4. *
  5. * Portions Copyright (c) 2003 by Mark Lussier
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions are met:
  9. *
  10. * Redistributions of source code must retain the above copyright notice,
  11. * this list of conditions and the following disclaimer.
  12. * Redistributions in binary form must reproduce the above copyright notice,
  13. * this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  14. * Neither the name of the "David A. Czarnecki" and "blojsom" nor the names of
  15. * its contributors may be used to endorse or promote products derived from
  16. * this software without specific prior written permission.
  17. * Products derived from this software may not be called "blojsom",
  18. * nor may "blojsom" appear in their name, without prior written permission of
  19. * David A. Czarnecki.
  20. *
  21. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  22. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  23. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  24. * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
  25. * EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
  26. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  27. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  28. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  29. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
  30. * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  31. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  32. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  33. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  34. */
  35. package org.blojsom.plugin.admin;
  36. import org.apache.commons.logging.LogFactory;
  37. import org.apache.commons.logging.Log;
  38. import org.apache.commons.fileupload.DiskFileUpload;
  39. import org.apache.commons.fileupload.FileUploadException;
  40. import org.apache.commons.fileupload.FileItem;
  41. import org.blojsom.blog.BlojsomConfiguration;
  42. import org.blojsom.blog.BlogEntry;
  43. import org.blojsom.blog.BlogUser;
  44. import org.blojsom.plugin.BlojsomPluginException;
  45. import org.blojsom.util.BlojsomUtils;
  46. import org.blojsom.BlojsomException;
  47. import javax.servlet.ServletConfig;
  48. import javax.servlet.http.HttpServletRequest;
  49. import javax.servlet.http.HttpServletResponse;
  50. import java.util.*;
  51. import java.io.File;
  52. /**
  53. * FileUploadPlugin
  54. *
  55. * @author czarnecki
  56. * @version $Id: FileUploadPlugin.java,v 1.11 2003-12-30 23:24:08 czarneckid Exp $
  57. * @since blojsom 2.05
  58. */
  59. public class FileUploadPlugin extends BaseAdminPlugin {
  60. private Log _logger = LogFactory.getLog(FileUploadPlugin.class);
  61. private static final String PLUGIN_ADMIN_UPLOAD_IP = "plugin-admin-upload";
  62. private static final String TEMPORARY_DIRECTORY_IP = "temporary-directory";
  63. private static final String DEFAULT_TEMPORARY_DIRECTORY = "/tmp";
  64. private static final String MAXIMUM_UPLOAD_SIZE_IP = "maximum-upload-size";
  65. private static final long DEFAULT_MAXIMUM_UPLOAD_SIZE = 100000;
  66. private static final String MAXIMUM_MEMORY_SIZE_IP = "maximum-memory-size";
  67. private static final int DEFAULT_MAXIMUM_MEMORY_SIZE = 50000;
  68. private static final String ACCEPTED_FILE_TYPES_IP = "accepted-file-types";
  69. private static final String[] DEFAULT_ACCEPTED_FILE_TYPES = {"image/jpeg", "image/gif", "image/png"};
  70. private static final String RESOURCES_DIRECTORY_IP = "resources-directory";
  71. private static final String DEFAULT_RESOURCES_DIRECTORY = "/resources/";
  72. // Pages
  73. private static final String FILE_UPLOAD_PAGE = "/org/blojsom/plugin/admin/templates/admin-file-upload";
  74. // Constants
  75. private static final String PLUGIN_ADMIN_FILE_UPLOAD_FILES = "PLUGIN_ADMIN_FILE_UPLOAD_FILES";
  76. // Actions
  77. private static final String UPLOAD_FILE_ACTION = "upload-file";
  78. private static final String DELETE_UPLOAD_FILES = "delete-upload-files";
  79. // Form items
  80. private static final String FILE_TO_DELETE = "file-to-delete";
  81. private String _temporaryDirectory;
  82. private long _maximumUploadSize;
  83. private int _maximumMemorySize;
  84. private Map _acceptedFileTypes;
  85. private String _resourcesDirectory;
  86. /**
  87. * Default constructor.
  88. */
  89. public FileUploadPlugin() {
  90. }
  91. /**
  92. * Initialize this plugin. This method only called when the plugin is instantiated.
  93. *
  94. * @param servletConfig Servlet config object for the plugin to retrieve any initialization parameters
  95. * @param blojsomConfiguration {@link org.blojsom.blog.BlojsomConfiguration} information
  96. * @throws org.blojsom.plugin.BlojsomPluginException
  97. * If there is an error initializing the plugin
  98. */
  99. public void init(ServletConfig servletConfig, BlojsomConfiguration blojsomConfiguration) throws BlojsomPluginException {
  100. super.init(servletConfig, blojsomConfiguration);
  101. try {
  102. Properties configurationProperties = BlojsomUtils.loadProperties(servletConfig, PLUGIN_ADMIN_UPLOAD_IP, true);
  103. _temporaryDirectory = configurationProperties.getProperty(TEMPORARY_DIRECTORY_IP);
  104. if (BlojsomUtils.checkNullOrBlank(_temporaryDirectory)) {
  105. _temporaryDirectory = DEFAULT_TEMPORARY_DIRECTORY;
  106. }
  107. _logger.debug("Using temporary directory: " + _temporaryDirectory);
  108. try {
  109. _maximumUploadSize = Long.parseLong(configurationProperties.getProperty(MAXIMUM_UPLOAD_SIZE_IP));
  110. } catch (NumberFormatException e) {
  111. _maximumUploadSize = DEFAULT_MAXIMUM_UPLOAD_SIZE;
  112. }
  113. _logger.debug("Using maximum upload size: " + _maximumUploadSize);
  114. try {
  115. _maximumMemorySize = Integer.parseInt(configurationProperties.getProperty(MAXIMUM_MEMORY_SIZE_IP));
  116. } catch (NumberFormatException e) {
  117. _maximumMemorySize = DEFAULT_MAXIMUM_MEMORY_SIZE;
  118. }
  119. _logger.debug("Using maximum memory size: " + _maximumMemorySize);
  120. String acceptedFileTypes = configurationProperties.getProperty(ACCEPTED_FILE_TYPES_IP);
  121. String[] parsedListOfTypes;
  122. if (BlojsomUtils.checkNullOrBlank(acceptedFileTypes)) {
  123. parsedListOfTypes = DEFAULT_ACCEPTED_FILE_TYPES;
  124. } else {
  125. parsedListOfTypes = BlojsomUtils.parseCommaList(acceptedFileTypes);
  126. }
  127. _acceptedFileTypes = new HashMap(parsedListOfTypes.length);
  128. for (int i = 0; i < parsedListOfTypes.length; i++) {
  129. String type = parsedListOfTypes[i];
  130. _acceptedFileTypes.put(type, type);
  131. }
  132. _logger.debug("Using accepted file types: " + BlojsomUtils.arrayOfStringsToString(parsedListOfTypes));
  133. _resourcesDirectory = configurationProperties.getProperty(RESOURCES_DIRECTORY_IP);
  134. if (BlojsomUtils.checkNullOrBlank(_resourcesDirectory)) {
  135. _resourcesDirectory = DEFAULT_RESOURCES_DIRECTORY;
  136. }
  137. _resourcesDirectory = BlojsomUtils.checkStartingAndEndingSlash(_resourcesDirectory);
  138. _logger.debug("Using resources directory: " + _resourcesDirectory);
  139. } catch (BlojsomException e) {
  140. _logger.error(e);
  141. throw new BlojsomPluginException(e);
  142. }
  143. }
  144. /**
  145. * Process the blog entries
  146. *
  147. * @param httpServletRequest Request
  148. * @param httpServletResponse Response
  149. * @param user {@link org.blojsom.blog.BlogUser} instance
  150. * @param context Context
  151. * @param entries Blog entries retrieved for the particular request
  152. * @return Modified set of blog entries
  153. * @throws BlojsomPluginException If there is an error processing the blog entries
  154. */
  155. public BlogEntry[] process(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlogUser user, Map context, BlogEntry[] entries) throws BlojsomPluginException {
  156. if (!authenticateUser(httpServletRequest, httpServletResponse, context, user.getBlog())) {
  157. httpServletRequest.setAttribute(PAGE_PARAM, ADMIN_LOGIN_PAGE);
  158. return entries;
  159. }
  160. File resourceDirectory = new File(_blojsomConfiguration.getInstallationDirectory() + _resourcesDirectory + user.getId() + "/");
  161. String action = BlojsomUtils.getRequestValue(ACTION_PARAM, httpServletRequest);
  162. if (BlojsomUtils.checkNullOrBlank(action)) {
  163. _logger.debug("User did not request edit action");
  164. httpServletRequest.setAttribute(PAGE_PARAM, ADMIN_ADMINISTRATION_PAGE);
  165. } else if (PAGE_ACTION.equals(action)) {
  166. _logger.debug("User requested file upload page");
  167. httpServletRequest.setAttribute(PAGE_PARAM, FILE_UPLOAD_PAGE);
  168. } else if (UPLOAD_FILE_ACTION.equals(action)) {
  169. _logger.debug("User requested file upload action");
  170. // Create a new disk file upload and set its parameters
  171. DiskFileUpload diskFileUpload = new DiskFileUpload();
  172. diskFileUpload.setRepositoryPath(_temporaryDirectory);
  173. diskFileUpload.setSizeThreshold(_maximumMemorySize);
  174. diskFileUpload.setSizeMax(_maximumUploadSize);
  175. try {
  176. List items = diskFileUpload.parseRequest(httpServletRequest);
  177. Iterator itemsIterator = items.iterator();
  178. while (itemsIterator.hasNext()) {
  179. FileItem item = (FileItem) itemsIterator.next();
  180. // Check for the file upload form item
  181. if (!item.isFormField()) {
  182. _logger.debug("Found file item: " + item.getName() + " of type: " + item.getContentType());
  183. // Is it one of the accepted file types?
  184. String fileType = item.getContentType();
  185. boolean isAcceptedFileType = _acceptedFileTypes.containsKey(fileType);
  186. // If so, upload the file to the resources directory
  187. if (isAcceptedFileType) {
  188. if (!resourceDirectory.exists()) {
  189. if (!resourceDirectory.mkdirs()) {
  190. _logger.error("Unable to create resource directory for user: " + resourceDirectory.toString());
  191. addOperationResultMessage(context, "Unable to create resource directory");
  192. return entries;
  193. }
  194. }
  195. File resourceFile = new File(_blojsomConfiguration.getInstallationDirectory() +
  196. _resourcesDirectory + user.getId() + "/" + item.getName());
  197. try {
  198. item.write(resourceFile);
  199. } catch (Exception e) {
  200. _logger.error(e);
  201. }
  202. _logger.debug("Successfully uploaded resource file: " + resourceFile.toString());
  203. addOperationResultMessage(context, "Successfully upload resource file: " + item.getName());
  204. } else {
  205. _logger.error("Upload file is not an accepted type: " + item.getName() + " of type: " + item.getContentType());
  206. addOperationResultMessage(context, "Upload file is not an accepted type: " + item.getName() + " of type: " + item.getContentType());
  207. }
  208. }
  209. }
  210. } catch (FileUploadException e) {
  211. _logger.error(e);
  212. }
  213. httpServletRequest.setAttribute(PAGE_PARAM, FILE_UPLOAD_PAGE);
  214. } else if (DELETE_UPLOAD_FILES.equals(action)) {
  215. String[] filesToDelete = httpServletRequest.getParameterValues(FILE_TO_DELETE);
  216. if (filesToDelete != null && filesToDelete.length > 0) {
  217. File deletedFile;
  218. for (int i = 0; i < filesToDelete.length; i++) {
  219. String fileToDelete = filesToDelete[i];
  220. deletedFile = new File(resourceDirectory, fileToDelete);
  221. if (!deletedFile.delete()) {
  222. _logger.debug("Unable to delete resource file: " + deletedFile.toString());
  223. }
  224. }
  225. addOperationResultMessage(context, "Deleted " + filesToDelete.length + " file(s) from resources directory");
  226. }
  227. httpServletRequest.setAttribute(PAGE_PARAM, FILE_UPLOAD_PAGE);
  228. }
  229. // Create a list of files in the user's resource directory
  230. Map resourceFilesMap = new HashMap();
  231. if (resourceDirectory.exists()) {
  232. File[] resourceFiles = resourceDirectory.listFiles();
  233. if (resourceFiles != null) {
  234. resourceFilesMap = new HashMap(resourceFiles.length);
  235. for (int i = 0; i < resourceFiles.length; i++) {
  236. File resourceFile = resourceFiles[i];
  237. resourceFilesMap.put(resourceFile.getName(), resourceFile.getName());
  238. }
  239. }
  240. } else {
  241. resourceFilesMap = new HashMap();
  242. }
  243. context.put(PLUGIN_ADMIN_FILE_UPLOAD_FILES, resourceFilesMap);
  244. return entries;
  245. }
  246. }