com.anritsu.mcreleaseportal.utils.FileUpload.java Source code

Java tutorial

Introduction

Here is the source code for com.anritsu.mcreleaseportal.utils.FileUpload.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 com.anritsu.mcreleaseportal.utils;

import com.anritsu.mcreleaseportal.dbController.DBController;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.logging.Level;
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 javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author ro100051
 */
public class FileUpload extends HttpServlet {

    private static final Logger LOGGER = Logger.getLogger(FileUpload.class.getName());

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

        HttpSession session = request.getSession();
        session.setAttribute("mcPackage", null);
        PrintWriter pw = response.getWriter();
        response.setContentType("text/plain");
        ServletFileUpload upload = new ServletFileUpload();
        try {
            FileItemIterator iter = upload.getItemIterator(request);

            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                InputStream stream = item.openStream();

                // Save input stream file for later use
                File dir = new File(Configuration.getInstance().getSavePath());
                if (!dir.exists() && !dir.isDirectory()) {
                    dir.mkdir();
                    LOGGER.log(Level.INFO, "Changes.xml archive directory was created at " + dir.getAbsolutePath());
                }
                String fileName = request.getSession().getId() + "_" + System.currentTimeMillis();
                File file = new File(dir, fileName);
                file.createNewFile();
                Path path = file.toPath();
                Files.copy(stream, path, StandardCopyOption.REPLACE_EXISTING);
                LOGGER.log(Level.INFO, "changes.xml saved on disk as: " + file.getAbsolutePath());

                // Save filename to session for next calls
                session.setAttribute("xmlFileLocation", file.getAbsolutePath());
                LOGGER.log(Level.INFO, "changes.xml saved on session as: fileName:" + file.getAbsolutePath());

                // Cleanup
                stream.close();

            }

        } catch (FileUploadException | IOException | RuntimeException e) {
            pw.println(
                    "An error occurred when trying to process uploaded file! \n Please check the file consistency and try to re-submit. \n If the error persist pleace contact system administrator!");
        }
    }

    // <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 {
        response.setContentType("text/html;charset=UTF-8");
        if (request.getParameter("xmlSchemaLocation") != null
                && request.getParameter("xmlSchemaLocation").equals("1")) {
            PrintWriter out = response.getWriter();
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>MasterClaw&#0153; Release Portal</title>");
            out.println("</head>");
            out.println("<body>");
            out.println(Configuration.getInstance().getXmlSchemaLocation());
            out.println("</body>");
            out.println("</html>");
        } else {
            System.out.println("Schema location: " + request.getParameter("xmlSchemaLocation"));
            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>

}