hu.jozsef.vesza.so.servlets.MealImageService.java Source code

Java tutorial

Introduction

Here is the source code for hu.jozsef.vesza.so.servlets.MealImageService.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package hu.jozsef.vesza.so.servlets;

import com.google.appengine.api.datastore.Blob;
import com.googlecode.objectify.Objectify;
import hu.jozsef.vesza.so.model.Meal;
import hu.jozsef.vesza.so.utils.OfyService;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;

/**
 *
 * @author Jzsef
 */
public class MealImageService extends HttpServlet {

    private static final Logger log = Logger.getLogger(EventManagerServlet.class.getName());
    Objectify objectify = OfyService.ofy();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Long mealId = new Long(request.getParameter("identifier"));
        Meal fetchedMeal = objectify.load().type(Meal.class).id(mealId).now();

        if (fetchedMeal.getImage() != null) {
            String imageUrl = "/WEB-INF/" + fetchedMeal.getImage();
            String imageRealPath = this.getServletContext().getRealPath(imageUrl);
            InputStream imgStream = new FileInputStream(new File(imageRealPath));

            Blob image = new Blob(IOUtils.toByteArray(imgStream));
            response.setContentType("image/jpeg");
            response.getOutputStream().write(image.getBytes());
        } else {
            response.getWriter().print("No image");
        }
    }

}