Java tutorial
/******************************************************************************* * This file is part of Termitaria, a project management tool * Copyright (C) 2008-2013 CodeSphere S.R.L., www.codesphere.ro * * Termitaria is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Termitaria. If not, see <http://www.gnu.org/licenses/> . ******************************************************************************/ package ro.cs.om.web.servlet; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.OutputStream; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.security.core.context.SecurityContextHolder; import ro.cs.om.business.BLPicture; import ro.cs.om.entity.Picture; import ro.cs.om.utils.file.FileUtils; import ro.cs.om.web.security.UserAuth; /** * @author dd * */ public class ImageServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected Log logger = LogFactory.getLog(this.getClass()); private static String PICTURE = "picture"; private static String REPLACE_THEME = "replaceTheme"; private static String ONE_PIXEL_PIC_LOCATION = "themes".concat(File.separator).concat(REPLACE_THEME) .concat(File.separator).concat("images").concat(File.separator).concat("onePixel.jpg"); private static String ONE_PIXEL_PIC_EXTENSION = "jpg"; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //Picture's Id int pictureId = -1; //Picture's name String pictureName = null; //Picture ID as a request parameter if (req.getParameter(PICTURE) != null) { try { pictureId = Integer.parseInt(req.getParameter(PICTURE)); } catch (NumberFormatException nfex) { } if (pictureId == -1) { pictureName = req.getParameter(PICTURE); } } ServletOutputStream sos = null; try { //Servlet's OutputStream sos = resp.getOutputStream(); Picture picture = null; if (pictureId > 0) { //Getting picture from database picture = getPicture(pictureId); } else if (pictureName != null) { picture = getPicture(pictureName); logger.debug("picture = " + picture); if (picture == null) { picture = new Picture(); //Setting the One Pixel Picture extension picture.setExtension(ONE_PIXEL_PIC_EXTENSION); //Setting the One Pixel Picture as the picture of this logo String themeCode = ((UserAuth) SecurityContextHolder.getContext().getAuthentication() .getPrincipal()).getThemeCode(); String onePixelPicLocation = ONE_PIXEL_PIC_LOCATION.replace(REPLACE_THEME, themeCode); onePixelPicLocation = FileUtils.getInstance().getRealPathForResource(onePixelPicLocation); picture.setPicture(FileUtils.getInstance().getBytesFromFile(new File(onePixelPicLocation))); } } if (picture != null) { //Setting response's content type after picture's extension resp.setContentType(getMime(picture.getExtension())); logger.debug("extenstion = " + picture.getExtension()); logger.debug("mime = " + getMime(picture.getExtension())); //Setting response's length (in bytes) resp.setContentLength(picture.getPicture().length); logger.debug("length = " + picture.getPicture().length); //Writing the picture dumpFile(picture, sos); } } catch (Exception ex) { logger.error("", ex); } finally { //Flushing and Closing OutputStream sos.flush(); sos.close(); } } /** * Abstract function to be implemented by each concrete implementation of this ImageServlet. * */ public Picture getPicture(int pictureId) throws Exception { logger.debug("picture id: " + pictureId); return BLPicture.getInstance().get(pictureId); } public Picture getPicture(String pictureName) throws Exception { logger.debug("picture name: " + pictureName); return BLPicture.getInstance().getByName(pictureName); } /** * Dumps Picture's content in an OutputStream */ private void dumpFile(Picture picture, OutputStream outputstream) throws IOException { byte buffer[] = new byte[4096]; BufferedInputStream bufferedinputstream = new BufferedInputStream( new ByteArrayInputStream(picture.getPicture())); int i; while ((i = bufferedinputstream.read(buffer, 0, 4096)) != -1) outputstream.write(buffer, 0, i); bufferedinputstream.close(); } /** * Returns the mime type according to an extension */ private String getMime(String extension) { String s1 = extension.toUpperCase(); if (s1.equals("GIF")) return "image/gif"; if (s1.equals("JPG") || s1.equals("JPEG") || s1.equals("JPE")) return "image/jpeg"; if (s1.startsWith("TIF")) return "image/tiff"; if (s1.startsWith("PNG")) return "image/png"; if (s1.equals("IEF")) return "image/ief"; if (s1.equals("BMP")) return "image/bmp"; if (s1.equals("RAS")) return "image/x-cmu-raster"; if (s1.equals("PNM")) return "image/x-portable-anymap"; if (s1.equals("PBM")) return "image/x-portable-bitmap"; if (s1.equals("PGM")) return "image/x-portable-graymap"; if (s1.equals("PPM")) return "image/x-portable-pixmap"; if (s1.equals("RGB")) return "image/x-rgb"; if (s1.equals("XBM")) return "image/x-xbitmap"; if (s1.equals("XPM")) return "image/x-xpixmap"; if (s1.equals("XWD")) return "image/x-xwindowdump"; else return "application/octet-stream"; } }