package com.ejie.aa94a.servlet;

import java.io.BufferedInputStream;
import java.io.File;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;

public class ImagenServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		ServletOutputStream out = null;
		BufferedInputStream in = null;
		try {
			out = response.getOutputStream();
			String ruta = request.getParameter("ruta");
			// Imagen img = ServicesImagenes.getInstance().getImagen(request);
			// if (img == null) {
			// return;
			// }
			response.setHeader("Expires", "0");
			response.setContentType("image/png");
			File file = new File(ruta);
			java.io.ByteArrayInputStream byteArray = new java.io.ByteArrayInputStream(
					FileUtils.readFileToByteArray(file));
			in = new BufferedInputStream(byteArray);
			int value = -1;
			while ((value = in.read()) != -1) {
				out.write(value);
			}
		} catch (Exception e) {
			;// do nothing
		} finally {
			// pase lo que pase intentamos cerrar todo
			try {
				if (out != null) {
					out.flush();
				}
			} catch (Exception ex) {
				;// do nothing
			}
			try {
				if (out != null) {
					out.close();
				}
			} catch (Exception ex) {
				;// do nothing
			}
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception ex) {
				;// do nothing
			}
		}
	}

	/**
	 * 
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		this.doGet(request, response);
	}
}
