KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > snipsnap > net > FileUploadServlet


1 /*
2  * This file is part of "SnipSnap Wiki/Weblog".
3  *
4  * Copyright (c) 2002 Stephan J. Schmidt, Matthias L. Jugel
5  * All Rights Reserved.
6  *
7  * Please visit http://snipsnap.org/ for updates and contact.
8  *
9  * --LICENSE NOTICE--
10  * This program is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU General Public License
12  * as published by the Free Software Foundation; either version 2
13  * of the License, or (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., 675 Mass Ave, Cambridge, MA 02139, USA.
23  * --LICENSE NOTICE--
24  */

25 package org.snipsnap.net;
26
27 import org.radeox.util.logging.Logger;
28 import org.snipsnap.app.Application;
29 import org.snipsnap.config.Configuration;
30 import org.snipsnap.net.filter.MultipartWrapper;
31 import org.snipsnap.snip.Snip;
32 import org.snipsnap.snip.SnipSpace;
33 import org.snipsnap.snip.SnipSpaceFactory;
34 import org.snipsnap.snip.attachment.Attachment;
35 import org.snipsnap.snip.attachment.Attachments;
36 import org.snipsnap.snip.attachment.storage.AttachmentStorage;
37 import org.snipsnap.snip.storage.XMLFileSnipStorage;
38 import org.snipsnap.user.Permissions;
39 import org.snipsnap.user.Roles;
40 import org.snipsnap.user.Security;
41 import org.snipsnap.user.User;
42 import org.snipsnap.container.Components;
43
44 import javax.servlet.RequestDispatcher JavaDoc;
45 import javax.servlet.ServletConfig JavaDoc;
46 import javax.servlet.ServletException JavaDoc;
47 import javax.servlet.http.HttpServlet JavaDoc;
48 import javax.servlet.http.HttpServletRequest JavaDoc;
49 import javax.servlet.http.HttpServletResponse JavaDoc;
50 import java.io.*;
51 import java.util.Date JavaDoc;
52
53 /**
54  * Servlet to store attachments to snips.
55  * @author Matthias L. Jugel
56  * @version $Id: FileUploadServlet.java 1614 2004-05-25 10:18:11Z stephan $
57  */

58 public class FileUploadServlet extends HttpServlet JavaDoc {
59
60   private Roles roles = new Roles();
61
62   public void init(ServletConfig JavaDoc servletConfig) throws ServletException JavaDoc {
63     super.init(servletConfig);
64     roles.add("Editor");
65     roles.add("Admin");
66   }
67
68   public void doGet(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response)
69     throws ServletException JavaDoc, IOException {
70     doPost(request, response);
71   }
72
73   public void doPost(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response)
74     throws ServletException JavaDoc, IOException {
75     Configuration config = Application.get().getConfiguration();
76
77     // If this is not a multipart/form-data request continue
78
String JavaDoc type = request.getHeader("Content-Type");
79     if (type != null && type.startsWith("multipart/form-data")) {
80       try {
81         request = new MultipartWrapper(request, config.getEncoding() != null ? config.getEncoding() : "UTF-8");
82       } catch (IllegalArgumentException JavaDoc e) {
83         Logger.warn("FileUploadServlet: multipart/form-data wrapper:" + e.getMessage());
84       }
85     }
86
87     String JavaDoc snipName = request.getParameter("name");
88
89     if (null == snipName) {
90       response.sendRedirect(config.getUrl());
91       return;
92     }
93
94     SnipSpace space = SnipSpaceFactory.getInstance();
95     Snip snip = space.load(snipName);
96
97     if (request.getParameter("cancel") != null) {
98       response.sendRedirect(config.getUrl("/space/" + snip.getNameEncoded()));
99       return;
100     }
101
102     AttachmentStorage attachmentStorage = (AttachmentStorage) Components.getComponent(AttachmentStorage.class);
103
104     User user = Application.get().getUser();
105     if (Security.checkPermission(Permissions.ATTACH_TO_SNIP, user, snip)) {
106       if (request.getParameter("upload") != null) {
107         try {
108           uploadFile(request, snip);
109         } catch (IOException e) {
110           request.setAttribute("error", "I/O Error while uploading.");
111           e.printStackTrace();
112         }
113       } else if (request.getParameter("delete") != null) {
114         String JavaDoc files[] = request.getParameterValues("attfile");
115
116         if (files != null && files.length > 0) {
117           Attachments attachments = snip.getAttachments();
118           for (int fileNo = 0; fileNo < files.length; fileNo++) {
119             Attachment attachment = attachments.getAttachment(files[fileNo]);
120             if (null != attachment) {
121               attachmentStorage.delete(attachment);
122               attachments.removeAttachment(attachment);
123             }
124           }
125           // make sure to store the changed snip
126
SnipSpaceFactory.getInstance().store(snip);
127         } else {
128           request.setAttribute("error", "Please select files to delete.");
129         }
130       }
131     } else {
132       request.setAttribute("error", "You don't have permission to upload or delete files.");
133     }
134
135     request.setAttribute("snip", snip);
136     request.setAttribute("snip_name", snipName);
137     RequestDispatcher JavaDoc dispatcher = request.getRequestDispatcher("/exec/upload.jsp");
138     dispatcher.forward(request, response);
139   }
140
141   public String JavaDoc uploadFile(HttpServletRequest JavaDoc request, Snip snip) throws IOException {
142     AttachmentStorage attachmentStorage = (AttachmentStorage) Components.getComponent(AttachmentStorage.class);
143
144     MultipartWrapper wrapper = (MultipartWrapper) request;
145     String JavaDoc fileName = wrapper.getParameter("filename");
146     String JavaDoc contentType = wrapper.getParameter("mimetype");
147     if (null == contentType || contentType.length() == 0) {
148       contentType = wrapper.getFileContentType("file");
149     }
150     // make sure the file name does not contain slashes or backslashes
151
if (null == fileName || fileName.length() == 0) {
152       fileName = getCanonicalFileName(wrapper.getFileName("file"));
153     } else {
154       fileName = getCanonicalFileName(fileName);
155     }
156
157     InputStream fileInputStream = wrapper.getFileInputStream("file");
158
159     if (fileInputStream != null && fileName != null && fileName.length() > 0 && contentType != null) {
160
161       // Logger.log(Logger.DEBUG, "Uploading '" + relativeFileLocation.getName() + "' to '" + file.getCanonicalPath() + "'");
162

163       File relativeFileLocation = new File(snip.getName(), fileName);
164       Attachment attachment = new Attachment(relativeFileLocation.getName(), contentType, 0, new Date JavaDoc(), relativeFileLocation.getPath());
165       OutputStream out = attachmentStorage.getOutputStream(attachment);
166       int size = storeAttachment(out, fileInputStream);
167       attachment.setSize(size);
168       out.close();
169       fileInputStream.close();
170
171       snip.getAttachments().addAttachment(attachment);
172
173       SnipSpaceFactory.getInstance().store(snip);
174       return fileName;
175     }
176     return null;
177   }
178
179   // make file name pure without the path
180
public static String JavaDoc getCanonicalFileName(String JavaDoc fileName) throws IOException {
181     int slashIndex = fileName.lastIndexOf('\\');
182     if (slashIndex >= 0) {
183       Logger.log(Logger.WARN, "Windows path detected, cutting off: " + fileName);
184       fileName = fileName.substring(slashIndex + 1);
185     }
186
187     slashIndex = fileName.lastIndexOf('/');
188     if (slashIndex != -1) {
189       Logger.log(Logger.WARN, "UNIX path detected, cutting off: " + fileName);
190       fileName = fileName.substring(slashIndex + 1);
191     }
192
193     if (fileName.equals(XMLFileSnipStorage.SNIP_XML)) {
194       throw new IOException("illegal file name");
195     }
196
197     return fileName;
198   }
199
200   // store file from input stream into a file
201
public int storeAttachment(OutputStream out, InputStream in) throws IOException {
202     byte[] buf = new byte[4096];
203     int length = 0, size = 0;
204     while ((length = in.read(buf)) != -1) {
205       out.write(buf, 0, length);
206       size += length;
207     }
208     return size;
209   }
210 }
211
Popular Tags