/* Copyright 2006 - 2009 Under Dusken Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.pegadi.webapp.view; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.servlet.view.AbstractView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.util.Map; public class FileView extends AbstractView { private final Logger log = LoggerFactory.getLogger(getClass()); protected void renderMergedOutputModel(Map map, HttpServletRequest request, HttpServletResponse response) throws IOException { // get the file from the map File file = (File) map.get("file"); // check if it exists if (file == null || !file.exists() || !file.canRead()) { log.warn("Error reading: " + file); try { response.sendError(404); } catch (IOException e) { log.error("Could not write to response", e); } return; } // give some info in the response response.setContentType(getServletContext().getMimeType( file.getAbsolutePath())); // files does not change so often, allow three days caching response.setHeader("Cache-Control", "max-age=259200"); response.setContentLength((int) file.length()); // start writing to the response BufferedOutputStream out = null; BufferedInputStream in = null; try { out = new BufferedOutputStream(response.getOutputStream()); in = new BufferedInputStream(new FileInputStream(file)); int c = in.read(); while (c != -1) { out.write(c); c = in.read(); } } finally { if (in != null) { in.close(); } if (out != null) { out.flush(); out.close(); } } } }