Java tutorial
/* Copyright 2006 - 2011 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 no.dusken.common.plugin.control.web; import no.dusken.common.exception.PageNotFoundException; import org.apache.commons.io.IOUtils; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import javax.servlet.http.HttpServletResponse; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.List; /** * @author Marvin B. Lillehaug <lillehau@underdusken.no> */ @Controller public class PluginResourceController { private List<String> allowedFileTypes = Arrays.asList(".css", ".png", ".jpg", ".jpeg", ".gif", ".js"); @RequestMapping(value = "/pluginresources.do", method = RequestMethod.GET) public void get(String path, HttpServletResponse response) throws PageNotFoundException { String name = "/no/dusken/plugin/content/" + path; String filetype = path.substring(path.lastIndexOf(".")); boolean isAllowedFiletype = allowedFileTypes.contains(filetype); if (!isAllowedFiletype) { throw new PageNotFoundException(filetype + " not allowed"); } InputStream inputStream = getClass().getResourceAsStream(name); if (inputStream != null) { try { ByteArrayOutputStream output = new ByteArrayOutputStream(); IOUtils.copy(inputStream, output); response.setContentLength(output.size()); response.setContentType(getContentType(filetype)); response.setHeader("Cache-Control", "public, max-age=2505600"); IOUtils.copy(new ByteArrayInputStream(output.toByteArray()), response.getOutputStream()); } catch (IOException e) { e.printStackTrace(); } } else { throw new PageNotFoundException(path); } } private String getContentType(String filetype) { String contentType = null; if (filetype.equals(".css")) { contentType = "text/css"; } else if (filetype.equals(".jpg") || filetype.equals(".jpeg")) { contentType = "image/jpeg"; } else if (filetype.equals(".png")) { contentType = "image/png"; } else if (filetype.contains(".gif")) { contentType = "image/gif"; } return contentType; } public void setAllowedFileTypes(List<String> allowedFileTypes) { this.allowedFileTypes = allowedFileTypes; } }