servlet.MatrialRequest.java Source code

Java tutorial

Introduction

Here is the source code for servlet.MatrialRequest.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 servlet;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import entity.ItemDescription;
import entity.ItemDescriptionType;
import entity.MaterialRequest;
import entity.MaterialType;
import entity.Units;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import jpa.ItemDescriptionJpaController;
import jpa.ItemDescriptionTypeJpaController;
import jpa.MaterialRequestJpaController;
import jpa.MaterialTypeJpaController;
import jpa.UnitsJpaController;
import model.cons;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import sun.misc.BASE64Encoder;

/**
 *
 * @author Kareem Moustafa
 */
public class MatrialRequest extends HttpServlet {

    private static final String FILES_DIRECTORY = "E://";
    private static final String PICS_DIRECTORY = "E://";

    /**
     * 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 {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet MatrialRequest</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet MatrialRequest at " + request.getContextPath() + "</h1>");
            out.println("</body>");
            out.println("</html>");
        } finally {
            out.close();
        }
    }

    // <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 {

        String requestType = request.getParameter("requestType");
        EntityManagerFactory emf = null;
        Gson gson = new Gson();
        emf = Persistence.createEntityManagerFactory(cons.entityName);
        EntityManager em = emf.createEntityManager();
        if (requestType.equalsIgnoreCase("load")) {

            MaterialRequestJpaController controller = new MaterialRequestJpaController(emf);
            MaterialTypeJpaController materialTypeJpaController = new MaterialTypeJpaController(emf);
            response.setContentType("application/json");
            em.getTransaction().begin();
            int nextId = controller.getNextId();
            List<MaterialType> allMaterials = materialTypeJpaController.getMaterialsByItemTypeDesc();
            em.getTransaction().commit();

            JsonObject jsonObject = new JsonObject();

            jsonObject.addProperty("nextId", nextId);

            jsonObject.addProperty("allTypes", gson.toJson(allMaterials));
            PrintWriter writer = response.getWriter();
            writer.write(gson.toJson(jsonObject));
            writer.close();
            em.close();
            emf.close();
        } else if (requestType.equalsIgnoreCase("getItemDescs")) {
            Integer mrid = Integer.valueOf(request.getParameter("mrid"));
            ItemDescriptionTypeJpaController itemDescriptionTypeJpaController = new ItemDescriptionTypeJpaController(
                    emf);
            em.getTransaction().begin();
            List<ItemDescriptionType> idts = itemDescriptionTypeJpaController.findItemDescriptionTypeByMRId(mrid);
            List<Integer> ids = new ArrayList<>();
            for (ItemDescriptionType descriptionType : idts) {
                ids.add(descriptionType.getItemTypeId());
            }
            ItemDescriptionJpaController descriptionJpaController = new ItemDescriptionJpaController(emf);
            List<ItemDescription> descriptions = descriptionJpaController.findItemsDescriptionsByItemTypeIds(ids);
            em.getTransaction().commit();
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("allDescs", gson.toJson(descriptions));
            PrintWriter writer = response.getWriter();
            writer.write(gson.toJson(jsonObject));
            writer.close();
            em.close();
            emf.close();

        } else if (requestType.equalsIgnoreCase("getItemFileds")) {
            Integer itemId = Integer.valueOf(request.getParameter("itemid"));

            ItemDescriptionTypeJpaController itemDescriptionTypeJpaController = new ItemDescriptionTypeJpaController(
                    emf);
            em.getTransaction().begin();
            ItemDescriptionJpaController descriptionJpaController = new ItemDescriptionJpaController(emf);
            ItemDescription itemDescription = descriptionJpaController.findItemDescription(itemId);
            JsonObject jsonObject = new JsonObject();
            UnitsJpaController unitsJpaController = new UnitsJpaController(emf);
            Units findUnits = unitsJpaController.findUnits(itemDescription.getUnitId());
            jsonObject.addProperty("unitId", findUnits.getUnitId());
            jsonObject.addProperty("unitDesc", findUnits.getUnitDesc());
            String image = "";
            try {
                String extension = FilenameUtils.getExtension(itemDescription.getUploadFileName());
                BufferedImage img = ImageIO.read(new File(PICS_DIRECTORY + itemDescription.getUploadFileName()));
                image = encodeToString(img, extension);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
            jsonObject.addProperty("thumb", image);
            PrintWriter writer = response.getWriter();
            writer.write(gson.toJson(jsonObject));

            writer.close();
            em.close();
            emf.close();
        }

    }

    /**
     * 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);
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        MaterialRequest materialRequest = new MaterialRequest();

        if (!isMultipart) {
        } else {

            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            MatrialRequest matrialRequest = new MatrialRequest();
            List items = null;
            try {
                items = upload.parseRequest(request);
            } catch (FileUploadException e) {
                e.printStackTrace();
            }
            Iterator itr = items.iterator();
            while (itr.hasNext()) {
                FileItem item = (FileItem) itr.next();

                if (item.isFormField()) {
                    switch (item.getFieldName()) {
                    case "typeId":
                        materialRequest.setMrId(Integer.valueOf(getStringFromInputStream(item.getInputStream())));
                        break;
                    case "typeDate":
                        SimpleDateFormat formatter = new SimpleDateFormat("MM-dd-yyyy");

                        String d = getStringFromInputStream(item.getInputStream()); {
                        try {
                            materialRequest.setMrDate(formatter.parse(d));
                        } catch (ParseException ex) {
                            Logger.getLogger(MatrialRequest.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                        break;
                    case "typeDesc":
                        materialRequest.setMaterialTypeId(
                                Integer.valueOf(getStringFromInputStream(item.getInputStream())));
                        break;
                    case "itemProjCode":
                        materialRequest.setProjectItemCode(getStringFromInputStream(item.getInputStream()));
                        break;
                    case "itemDesc":
                        materialRequest
                                .setItemDescId(Integer.valueOf(getStringFromInputStream(item.getInputStream())));
                        break;
                    case "itemQty":
                        materialRequest
                                .setMrQuantity(Integer.valueOf(getStringFromInputStream(item.getInputStream())));
                        break;
                    case "typeunit":
                        materialRequest.setUnitId(Integer.valueOf(getStringFromInputStream(item.getInputStream())));
                        break;
                    case "typeRemarks":
                        materialRequest.setRemark(getStringFromInputStream(item.getInputStream()));
                        break;
                    case "endRow":
                        //Will save MR type;
                        try {
                            EntityManagerFactory emf = Persistence.createEntityManagerFactory(cons.entityName);
                            EntityManager em = emf.createEntityManager();
                            MaterialRequestJpaController controller = new MaterialRequestJpaController(emf);
                            controller.create(materialRequest);
                            em.getTransaction().commit();
                            materialRequest = new MaterialRequest();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;
                    }

                } else {
                    try {
                        String itemName = item.getName();
                        File savedFile = new File(FILES_DIRECTORY + itemName);
                        item.write(savedFile);
                        System.out.println("Your file has been saved at the loaction: "
                                + getServletContext().getRealPath("/") + "uploadedFiles" + "\\" + itemName);
                        materialRequest.setAttachFile(itemName);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            response.sendRedirect("/insider360_dev/cNewMR.jsp");
            // Before save, make sure there is attched file
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    public static String encodeToString(BufferedImage image, String type) {
        String imageString = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        try {
            ImageIO.write(image, type, bos);
            byte[] imageBytes = bos.toByteArray();

            BASE64Encoder encoder = new BASE64Encoder();
            imageString = encoder.encode(imageBytes);

            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return imageString;
    }

    private static String getStringFromInputStream(InputStream is) {

        BufferedReader br = null;
        StringBuilder sb = new StringBuilder();

        String line;
        try {

            br = new BufferedReader(new InputStreamReader(is));
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return sb.toString();

    }

}