lk.studysmart.apps.BrainTeaserFileUpload.java Source code

Java tutorial

Introduction

Here is the source code for lk.studysmart.apps.BrainTeaserFileUpload.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 lk.studysmart.apps;

import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceUnit;
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 javax.transaction.HeuristicMixedException;
import javax.transaction.HeuristicRollbackException;
import javax.transaction.NotSupportedException;
import javax.transaction.RollbackException;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;
import lk.studysmart.apps.models.Internalresources;
import lk.studysmart.apps.models.Subject;
import lk.studysmart.apps.models.User;
import org.apache.commons.io.IOUtils;

/**
 *
 * @author Kaveesh
 */
@WebServlet(name = "FileUploadServlet", urlPatterns = { "/brainTeaseFileUpload" })
@MultipartConfig
public class BrainTeaserFileUpload extends HttpServlet {

    @PersistenceUnit(unitName = "lk.studysmart_StudySmart-web_war_1.0-SNAPSHOTPU")
    private final EntityManagerFactory emf = Persistence
            .createEntityManagerFactory("lk.studysmart_StudySmart-web_war_1.0-SNAPSHOTPU");

    @Resource
    UserTransaction utx;

    @PersistenceContext
    EntityManager em;

    User user;

    /**
     * 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");

        user = (User) request.getSession().getAttribute("user");
        //Get information from tha frontend of file upload
        final Part filePart = request.getPart("file");
        final String fileName = request.getParameter("filename");
        final String description = request.getParameter("description");

        InputStream filecontent = filePart.getInputStream();

        byte[] bytes = IOUtils.readFully(filecontent, Integer.valueOf(Long.toString(filePart.getSize())));

        Subject subject = em.find(Subject.class, request.getParameter("subject"));

        //Set attribute values to object 
        Internalresources resource = new Internalresources();
        resource.setUser(user);
        resource.setSubject(subject);
        resource.setFilename(fileName);
        resource.setDescription(description);
        resource.setBlob(bytes);

        try {
            utx.begin();
            em.persist(resource);
            utx.commit();
        } catch (NotSupportedException | SystemException | RollbackException | HeuristicMixedException
                | HeuristicRollbackException | SecurityException | IllegalStateException ex) {
            Logger.getLogger(BrainTeaserFileUpload.class.getName()).log(Level.SEVERE, null, ex);
            response.getWriter().write("Error: " + ex.getLocalizedMessage());
        }
        //Redirect page to the teacher's VLE main interface
        response.sendRedirect("teachVLEMUI.jsp?msg=File Uploaded");
    }

    private String getFileName(final Part part) {
        final String partHeader = part.getHeader("content-disposition");
        for (String content : part.getHeader("content-disposition").split(";")) {
            if (content.trim().startsWith("filename")) {
                return content.substring(content.indexOf('=') + 1).trim().replace("\"", "");
            }
        }
        return null;
    }

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

}