/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Java;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import org.imgscalr.Scalr;
/**
*
* @author Geert
*/
@WebServlet(name = "ServletUploadPhoto", urlPatterns = {"/ServletUploadPhoto"})
@MultipartConfig()
public class ServletUploadPhoto extends HttpServlet {
private boolean publicPhoto = false;
/**
* Processes requests for both HTTP
* <code>GET</code> and
* <code>POST</code> methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Enumeration<String> params = request.getParameterNames();
while (params.hasMoreElements())
System.out.println(params.nextElement());
RequestDispatcher rd;
File preview;
String publicphoto = request.getParameter("publicPhoto");
if(publicphoto != null) { publicPhoto = (publicphoto.equals("on")); }
if (request.getParameter("btnUploadPhoto") != null || request.getParameter("btnUploadPhoto.x") != null) {
String username = (String)request.getSession().getAttribute("username");
String category = request.getParameter("category");
if (!DatabaseKoppeling.categoryExists(category, username)) {
request.setAttribute("uploadPhotoMessage", "Categorie is niet bekend.");
request.setAttribute("messageColor", "red");
rd = request.getRequestDispatcher("P-Upload.jsp");
rd.forward(request, response);
return;
}
Part filePart = request.getPart("btnSelectFile");
if (!this.checkImageExtension(filePart)) {
request.setAttribute("uploadPhotoMessage", "Alleen foto's met een jpg/jpeg of png extensie mogen worden geüpload.");
request.setAttribute("messageColor", "red");
rd = request.getRequestDispatcher("P-Upload.jsp");
rd.forward(request, response);
return;
}
String fileExtension = filePart.getContentType().split("/")[1].toLowerCase();
Integer filename = DatabaseKoppeling.getNextPhotoName();
if (filename != null) {
String location = String.format("%s%s.%s", getServletContext().getInitParameter("PhotoLocation"), filename, fileExtension);
File photo = new File(String.format("%s%s.%s", getServletContext().getInitParameter("PhotoLocation"), filename, fileExtension));
BufferedInputStream input = null;
OutputStream output = null;
try {
long processedBytes = 0;
int lastProgress = 0;
input = new BufferedInputStream(filePart.getInputStream());
output = new FileOutputStream(new File(location));
while (input.available() > 0) {
output.write(input.read());
processedBytes++;
int progress = (int)(100 * ((double)processedBytes / (double)filePart.getSize()));
if (lastProgress != progress) {
lastProgress = progress;
System.out.println(progress);
}
}
} finally {
if (output != null) try { output.flush(); output.close(); } catch (IOException ex) {}
if (input != null) try { input.close(); } catch (IOException ex) {}
}
// Create preview.
BufferedImage img = ImageIO.read(photo);
double pixelFactor = Double.valueOf(getServletContext().getInitParameter("PreviewPixelFactor"));
img = Scalr.resize(img, (int)(800 * pixelFactor), (int)(600 * pixelFactor));
img = Scalr.resize(img, 800, 600);
preview = new File(String.format("%s%s.%s", getServletContext().getInitParameter("PreviewLocation"), filename, fileExtension));
ImageIO.write(img, fileExtension, preview);
String relativePathPreview = preview.getPath().replace("\\", "/");
relativePathPreview = relativePathPreview.substring(0, relativePathPreview.lastIndexOf("/") + 1);
String relativePathPhoto = photo.getPath().replace("\\", "/");
relativePathPhoto = relativePathPhoto.substring(0, relativePathPhoto.lastIndexOf("/") + 1);
if (!DatabaseKoppeling.processPhoto(username, category, relativePathPreview, relativePathPhoto, filename, fileExtension, publicPhoto)) {
photo.delete();
preview.delete();
request.setAttribute("uploadPhotoMessage", "Het uploaden van de foto heeft gefaald.");
request.setAttribute("messageColor", "red");
rd = request.getRequestDispatcher("P-Upload.jsp");
rd.forward(request, response);
return;
}
} else {
request.setAttribute("uploadPhotoMessage", "Fout bij het toevoegen aan de database.");
request.setAttribute("messageColor", "red");
rd = request.getRequestDispatcher("P-Upload.jsp");
rd.forward(request, response);
return;
}
try { Thread.sleep(1750); } catch (InterruptedException ex) { }
if(UserType.B_Photographer == request.getSession().getAttribute("usertype")) {
rd = request.getRequestDispatcher("P-Upload.jsp");
} else {
request.getSession().setAttribute("photo", filename);
rd = request.getRequestDispatcher("P-Photo.jsp");
}
rd.forward(request, response);
return;
}
rd = request.getRequestDispatcher("P-Upload.jsp");
rd.forward(request, response);
}
private boolean checkImageExtension(Part part) {
String fileExtension = part.getContentType().split("/")[1].toLowerCase();
if (fileExtension.equals("jpg") || fileExtension.equals("jpeg") || fileExtension.equals("png"))
return true;
return false;
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP
* <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP
* <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}