PageRenderTime 19ms CodeModel.GetById 9ms app.highlight 7ms RepoModel.GetById 1ms app.codeStats 1ms

/ftr-gwt-library-file/src/main/java/eu/future/earth/gwt/server/file/FileUploadServlet.java

http://ftr-gwt-library.googlecode.com/
Java | 146 lines | 97 code | 23 blank | 26 comment | 8 complexity | 0d16e3f2ce54a2d4a187b9d5fe8568e7 MD5 | raw file
  1/*
  2 * Copyright 2007 Future Earth, info@future-earth.eu
  3 *
  4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5 * use this file except in compliance with the License. You may obtain a copy of
  6 * the License at
  7 *
  8 * http://www.apache.org/licenses/LICENSE-2.0
  9 *
 10 * Unless required by applicable law or agreed to in writing, software
 11 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 13 * License for the specific language governing permissions and limitations under
 14 * the License.
 15 */
 16
 17package eu.future.earth.gwt.server.file;
 18
 19import java.io.File;
 20import java.io.IOException;
 21import java.io.PrintWriter;
 22import java.util.List;
 23import java.util.logging.Level;
 24import java.util.logging.Logger;
 25
 26import javax.servlet.ServletException;
 27import javax.servlet.ServletOutputStream;
 28import javax.servlet.http.HttpServlet;
 29import javax.servlet.http.HttpServletRequest;
 30import javax.servlet.http.HttpServletResponse;
 31import javax.servlet.http.HttpSession;
 32
 33import org.apache.commons.fileupload.FileItem;
 34import org.apache.commons.fileupload.FileUploadException;
 35import org.apache.commons.fileupload.disk.DiskFileItemFactory;
 36import org.apache.commons.fileupload.servlet.ServletFileUpload;
 37import org.json.JSONException;
 38import org.json.JSONObject;
 39
 40import eu.future.earth.gwt.client.file.FileHolder;
 41
 42public abstract class FileUploadServlet extends HttpServlet {
 43
 44	/**
 45	 * 
 46	 */
 47	private static final long serialVersionUID = 1720563248457411214L;
 48
 49	private static final String CONTENT_TYPE = "text/html";
 50
 51	private final static Logger LOGGER = Logger.getLogger(FileUploadServlet.class.getName());
 52
 53	/**
 54	 * This method will try to display the image. Requested parameters are
 55	 */
 56	protected void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {
 57		// Get All the info for getting the temp file of the sored file
 58		String name = req.getParameter("name");
 59		String stored = req.getParameter("stored");
 60		final FileHolder holder = new FileHolder();
 61		holder.setName(name);
 62
 63		FileDataHolder file = null;
 64
 65		response.setHeader("Expires", "Sat, 6 May 1995 12:00:00 GMT");
 66		// Set standard HTTP/1.1 no-cache headers.
 67		response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
 68		// Set IE extended HTTP/1.1 no-cache headers (use addHeader).
 69		response.addHeader("Cache-Control", "post-check=0, pre-check=0");
 70		response.setHeader("Pragma", "no-cache");
 71		response.setContentType("image/jpeg");
 72		if ("true".equals(stored)) {
 73			file = getStoredFile(req, holder);
 74		} else {
 75			file = getTempFile(req.getSession(), holder);
 76		}
 77
 78		if (file != null) {
 79			response.setContentType(file.getType());
 80			// response.addHeader("Content-Disposition", "attachment;filename=" + name);
 81			ServletOutputStream out = response.getOutputStream();
 82			out.write(file.getData());
 83			out.close();
 84		} else {
 85			// Stream the default type
 86			response.sendError(HttpServletResponse.SC_FOUND, "Not found " + name + " " + stored);
 87		}
 88
 89	}
 90
 91	public abstract FileDataHolder getStoredFile(HttpServletRequest req, FileHolder holder);
 92
 93	public abstract int getFileThreshold();
 94
 95	public abstract File getTempDir();
 96
 97	public static FileDataHolder getTempFile(HttpSession session, FileHolder holder) {
 98		return (FileDataHolder) session.getAttribute(holder.getName());
 99	}
100
101	@SuppressWarnings("unchecked")
102	protected void doPost(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {
103		final JSONObject feedback = new JSONObject();
104		final PrintWriter out = response.getWriter();
105		try {
106			boolean isMultipart = ServletFileUpload.isMultipartContent(req);
107			if (isMultipart) {
108				final DiskFileItemFactory factory = new DiskFileItemFactory();
109				File tempDir = getTempDir();
110				if (!tempDir.exists()) {
111					tempDir.mkdirs();
112				}
113				factory.setRepository(tempDir);
114				factory.setSizeThreshold(getFileThreshold());
115				final ServletFileUpload upload = new ServletFileUpload(factory);
116				try {
117					final List<FileItem> items = (List<FileItem>) upload.parseRequest(req);
118					for (int i = 0; i < items.size(); i++) {
119						final FileItem current = items.get(i);
120						final HttpSession session = req.getSession();
121						final FileDataHolder holder = new FileDataHolder();
122						holder.setData(current.get());
123						holder.setFileName(current.getName());
124						holder.setType(current.getContentType());
125						session.setAttribute(holder.getFileName(), holder);
126						feedback.put("fileName", holder.getFileName());
127						feedback.put("fileType", holder.getType());
128						feedback.put("fileSize", String.valueOf(current.getSize()));
129					}
130
131					feedback.put("result", "succes");
132				} catch (FileUploadException e) {
133					LOGGER.log(Level.WARNING, e.getMessage());
134					feedback.put("result", "error");
135				}
136
137			}
138			response.setContentType(CONTENT_TYPE);
139
140		} catch (JSONException e) {
141			throw new ServletException(e);
142		}
143		out.write(feedback.toString());
144	}
145
146}