FileDownloadServlet.java 7.25 KB
/*
 * Copyright Codecrew Ry
 * 
 * All rights reserved.
 * 
 * This license applies to any software containing a notice placed by the 
 * copyright holder. Such software is herein referred to as the Software. 
 * This license covers modification, distribution and use of the Software. 
 * 
 * Any distribution and use in source and binary forms, with or without 
 * modification is not permitted without explicit written permission from the 
 * copyright owner. 
 * 
 * A non-exclusive royalty-free right is granted to the copyright owner of the 
 * Software to use, modify and distribute all modifications to the Software in 
 * future versions of the Software. 
 * 
 */
package fi.codecrew.moya.servlet;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.ejb.EJB;
import javax.imageio.ImageIO;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import fi.codecrew.moya.beans.CardPrintBeanLocal;
import fi.codecrew.moya.beans.CardTemplateBeanLocal;
import fi.codecrew.moya.beans.EventBeanLocal;
import fi.codecrew.moya.beans.PermissionBeanLocal;
import fi.codecrew.moya.beans.UserBeanLocal;
import fi.codecrew.moya.enums.apps.UserPermission;
import fi.codecrew.moya.model.CardTemplate;
import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.LanEventProperty;
import fi.codecrew.moya.model.LanEventPropertyKey;
import fi.codecrew.moya.model.PrintedCard;
import fi.codecrew.moya.model.UserImage;

/**
 * Servlet implementation class UploadServlet
 */
@WebServlet(urlPatterns = {"/dydata/*"})
public class FileDownloadServlet extends GenericImageServlet {

	/**
	 *
	 */
	private static final long serialVersionUID = -3359999630873773508L;
	@EJB
	private CardTemplateBeanLocal ctbean;

	@EJB
	private UserBeanLocal userbean;

	@EJB
	private CardTemplateBeanLocal cardbean;

	@EJB
	private CardPrintBeanLocal cardprint;

	@EJB
	private PermissionBeanLocal permbean;

	@EJB
	private EventBeanLocal orgbean;

	private static final Logger logger = LoggerFactory.getLogger(FileDownloadServlet.class);

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 * response)
	 */

	private static final Pattern URLPATTERN = Pattern.compile("([^./]+)");

	/**
	 * Usage MoyaWeb/dydata/format/ possible formats logo
	 * userimage/<eventuserid>.jpg cardtemplate/<cardtemplateid>.png usercard/
	 */
	@Override
	protected ImageMover getImagedata(HttpServletRequest request) {
		ImageMover ret = new ImageMover();
		Matcher matcher = URLPATTERN.matcher(request.getPathInfo());
		List<String> urlparts = new ArrayList<String>();

		while (matcher.find()) {
			urlparts.add(matcher.group());
		}
		logger.debug("filedownload urlparts {}", urlparts);

		if (urlparts.isEmpty()) {
			ret.setResponse(HttpServletResponse.SC_NOT_FOUND);
		} else if (urlparts.get(0).equals("logo")) {
			// Urlparts.get(1) == event.id. But no need to check, Just return the logo for this event
			LanEventProperty logo = orgbean.getProperty(LanEventPropertyKey.EVENT_LOGO);
			if (logo != null) {
				String mime = logo.getByteMime();
				byte[] data = logo.getByteValue();
				if (mime == null || data == null || data.length == 0) {
					try {
						mime = "image/png";
						data = makeImage(logo.getTextvalue()).toByteArray();
					} catch (IOException e) {
						mime = null;
						data = null;
						logger.warn("Error creating image from logo " + logo, e);
					}
				}
				if (mime != null || data != null) {
					ret.setData(data);
					ret.setImagetype(mime);
				}

			}
		} else if (urlparts.get(0).equals("cardtemplate") && urlparts.size() > 2) {
			int imageid = Integer.parseInt(urlparts.get(1));
			CardTemplate templ = ctbean.find(imageid);
			logger.info("Cardtemplate {}, {}", imageid, templ);
			if (templ != null && templ.getImage().length > 0) {
				ret.setData(templ.getImage());
				ret.setImagetype("image/jpeg");
			}
		} else if (urlparts.get(0).equals("userimage") && urlparts.size() > 2) {

			int imageid = Integer.parseInt(urlparts.get(1));
			UserImage image = userbean.findUserimageFORCE(imageid);
			if (image != null) {

				if (!permbean.isCurrentUser(image.getUser())
					&& !permbean.hasPermission(UserPermission.VIEW_ALL)) {
					ret.setResponse(HttpServletResponse.SC_FORBIDDEN);
					return ret;
				}

				ret.setData(image.getImageData());
				ret.setImagetype(image.getMimeType());

				// Create image on file for cropper to work...
				// Check
				// http://code.google.com/p/primefaces/issues/detail?id=3751
				String dydataRoot = this.getServletContext().getRealPath("/dydata/");

				File imagefile = null;
				if (dydataRoot != null) {
					imagefile = new File(dydataRoot + request.getPathInfo());
				}
				if (imagefile != null && !imagefile.exists()) {
					File parentPath = new File(imagefile.getParent());
					if (!parentPath.isDirectory() && !parentPath.mkdirs()) {
						logger.warn("Error creating directory {}", parentPath.getAbsolutePath());
					}
					try {
						FileOutputStream writer = null;
						try {
							writer = new FileOutputStream(imagefile);
							writer.write(image.getImageData());
						} finally {
							if (writer != null) {
								writer.close();
							}
						}
						logger.info("Created image on file: {}", imagefile.getAbsolutePath());
					} catch (IOException e) {
						logger.warn("error creating image on file {}", e);
					}

				}

			}

		} else if (urlparts.get(0).equals("usercard") && urlparts.size() > 2) {
			int userid = Integer.parseInt(urlparts.get(1));

			EventUser usr = userbean.findByUserId(userid, false);
			logger.info("Trying to print usercard for user {}", usr);
			if (usr != null) {
				if (!permbean.isCurrentUser(usr.getUser())
					&& !permbean.hasPermission(UserPermission.VIEW_ALL)) {
					ret.setResponse(HttpServletResponse.SC_FORBIDDEN);
					return ret;
				}
				PrintedCard card = cardbean.checkPrintedCard(usr);
				try {
					byte[] img = cardprint.constructPNG(card);
					if (img != null && img.length > 0) {
						ret.setData(img);
						ret.setImagetype("image/png");
					}
				} catch (Exception e) {
					logger.warn("Error generating image", e);
				}

			}
		}

		if (ret.getImagetype() == null) {
			ret.setResponse(HttpServletResponse.SC_NOT_FOUND);
		}
		return ret;

	}

	private ByteArrayOutputStream makeImage(String textvalue) throws IOException {
		logger.info("Trying to create image from text {}", textvalue);
		int w = 400;
		int h = 45;

		BufferedImage bufferedImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
		Graphics2D graphics = bufferedImage.createGraphics();

		//		graphics.setComposite(AlphaComposite.Clear);
		graphics.setColor(new Color(0, 0, 0, 0));
		graphics.fillRect(0, 0, w, h);

		graphics.setColor(Color.WHITE);
		graphics.setFont(new Font("Arial Black", Font.BOLD, 45));
		graphics.drawString(textvalue, 10, h);

		ByteArrayOutputStream ostr = new ByteArrayOutputStream();
		ImageIO.write(bufferedImage, "png", ostr);
		return ostr;
	}
}