sd.code.stagent.fileservices.BackupFiles.java Source code

Java tutorial

Introduction

Here is the source code for sd.code.stagent.fileservices.BackupFiles.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 sd.code.stagent.fileservices;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import sd.code.stagent.common.Web;

/**
 *
 * @author motaz
 */
@WebServlet(name = "BackupFiles", urlPatterns = { "/BackupFiles" })
public class BackupFiles extends HttpServlet {

    String lastError;

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

        String requestText = Web.readClient(request);
        try {

            JSONParser parser = new JSONParser();
            JSONObject obj = (JSONObject) parser.parse(requestText);
            String dir = obj.get("directory").toString();
            String ext = obj.get("ext").toString();
            String backupName = obj.get("name").toString();

            String compressedFileName = "/tmp/pbx-" + Math.random() + ".zip";

            boolean success = compressFiles(dir, compressedFileName, ext);

            JSONObject result = new JSONObject();
            if (!success) {
                result.put("success", false);
                result.put("errorcode", 1);
                result.put("message", lastError);
                PrintWriter out = response.getWriter();
                out.println(result.toJSONString());
            }

            OutputStream servletOut = response.getOutputStream();
            response.setContentType("application/zip");
            response.setHeader("Content-Disposition", "attachment;filename=" + backupName + ".zip");

            FileInputStream stream = new FileInputStream(compressedFileName);
            BufferedInputStream bufferedInputStream = new BufferedInputStream(stream);
            response.setContentLength(stream.available());

            byte data[] = new byte[10024];
            int len;
            while ((len = bufferedInputStream.read(data)) != -1) {
                servletOut.write(data, 0, len);
            }

            bufferedInputStream.close();
            stream.close();

        } catch (Exception ex) {
            PrintWriter out = response.getWriter();
            JSONObject result = new JSONObject();
            result.put("success", false);
            result.put("errorcode", 5);
            result.put("message", ex.toString());

            out.println(result.toJSONString());
        }

    }

    private ArrayList<String> getFiles(String dir, String ext) {
        ArrayList<String> files = new ArrayList<>();
        try {
            // create new file
            File f = new File(dir);

            // returns pathnames for files and directory
            File[] paths = f.listFiles();

            // for each pathname in pathname array
            for (File path : paths) {
                // prints file and directory paths
                if ((path.isFile()) && (path.getPath().endsWith(ext))) {
                    files.add(path.getPath());
                }
            }

        } catch (Exception e) {
            // if any error occurs
            System.out.println("Error in getFiles: " + e.toString());
            lastError = e.toString();
        }

        return files;

    }

    public boolean compressFiles(String sourceDir, String zipFile, String ext) {

        byte[] buffer = new byte[1024];

        try {
            ArrayList<String> files = getFiles(sourceDir, ext);

            FileOutputStream fos = new FileOutputStream(zipFile);
            ZipOutputStream zos = new ZipOutputStream(fos);

            for (String aFile : files) {
                File output = new File(aFile);

                ZipEntry ze = new ZipEntry(output.getName());
                zos.putNextEntry(ze);

                FileInputStream in = new FileInputStream(aFile);

                int len;
                while ((len = in.read(buffer)) > 0) {
                    zos.write(buffer, 0, len);
                }

                in.close();

                zos.closeEntry();
            }

            zos.close();
            return true;

        } catch (Exception ex) {
            System.out.println("Error in compressFile: " + ex.toString());
            lastError = ex.toString();
            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>

}