com.us.servlet.FileManager.java Source code

Java tutorial

Introduction

Here is the source code for com.us.servlet.FileManager.java

Source

/*
 * @(#)FileManager.java 2011-10-12
 * ?us??  2008-2011, Inc. All rights reserved.
 * s.server. Use is subject to license terms.
 */

package com.us.servlet;

import java.io.File;
import java.io.FilenameFilter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Hashtable;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FilenameUtils;

import com.us.config.AppHelper;
import com.us.i118.I118Helper;
import com.us.model.KindFileMgr;
import com.us.util.DateUtil;
import com.us.util.FileHelper;
import com.us.util.JSONHelper;

/**
 * KindEditor?
 * 
 * @author <a href="mailto:monlyu.hong@gmail.com">monlyu</a>
 * @version --0.0.1--, 2011-10-12
 * @since JDK6.0
 */
public class FileManager implements Servlet {

    private static final String FILE_MGR_ROOT = "fileMgrRoot";
    private static final String FILE_IMAGE_TYPE = "image";

    @Override
    public void execute(HttpServletRequest req, HttpServletResponse resp) throws Exception {

        // 
        final String fileRoot = AppHelper.KIND_CONFIG.get(FILE_MGR_ROOT).toString();
        File root = FileHelper.getFile(AppHelper.APPSET.getFilePath(), fileRoot);

        PrintWriter out = resp.getWriter();
        final String path = req.getParameter("path") != null ? req.getParameter("path") : "";
        final String dirType = req.getParameter("dir").toLowerCase();// ??name or size or type
        String order = req.getParameter("order") != null ? req.getParameter("order").toLowerCase() : "name";
        if (!root.exists()) {
            root.mkdirs();
        }

        String currentUrl = AppHelper.APPSET.getWebPath() + fileRoot + path;
        String currentDirPath = path;
        String moveupDirPath = "";
        if (!"".equals(path)) {
            String str = currentDirPath.substring(0, currentDirPath.length() - 1);
            moveupDirPath = str.lastIndexOf("/") >= 0 ? str.substring(0, str.lastIndexOf("/") + 1) : "";
        }

        String[] imageType = AppHelper.KIND_CONFIG.get(FILE_IMAGE_TYPE).toString().split(",");

        // ??..
        if (path.indexOf("..") >= 0) {
            out.println(I118Helper.i118Value("${fileMgr.accessFail}", req));
            return;
        }
        // ??/
        if (!"".equals(path) && !path.endsWith("/")) {
            out.println(I118Helper.i118Value("${fileMgr.badArgs}", req));
            return;
        }

        File showDir = FileHelper.getFile(root, currentDirPath);
        if (!showDir.isDirectory()) {
            out.println(I118Helper.i118Value("${fileMgr.rootNotExist}", req));
            return;
        }

        List<Hashtable<String, Object>> fileList = new ArrayList<Hashtable<String, Object>>();
        final File[] listFiles = showDir.listFiles(new FilenameFilter() {

            @Override
            public boolean accept(File dir, String name) {
                if (FileHelper.getFile(dir, name).isDirectory()) {
                    return true;
                }
                final List<String> fileTypeList = Arrays
                        .<String>asList(AppHelper.KIND_CONFIG.get(dirType).toString().split(","));
                return fileTypeList.contains(FilenameUtils.getExtension(name));
            }
        });
        if (listFiles != null) {
            for (File file : listFiles) {
                Hashtable<String, Object> hash = new Hashtable<String, Object>();
                String fileName = file.getName();
                if (file.isDirectory()) {
                    hash.put("is_dir", true);
                    hash.put("has_file", (file.listFiles() != null));
                    hash.put("filesize", 0L);
                    hash.put("is_photo", false);
                    hash.put("filetype", "");
                } else if (file.isFile()) {
                    String fileExt = FilenameUtils.getExtension(fileName).toLowerCase();
                    hash.put("is_dir", false);
                    hash.put("has_file", false);
                    hash.put("filesize", file.length());
                    hash.put("is_photo", Arrays.<String>asList(imageType).contains(fileExt));
                    hash.put("filetype", fileExt);
                }
                hash.put("filename", fileName);
                hash.put("datetime", DateUtil.format(file.lastModified(), DateUtil.DATETIME_PATTERN));
                fileList.add(hash);
            }
        }

        if ("size".equals(order)) {
            Collections.sort(fileList, new SizeComparator<Hashtable<String, Object>>());
        } else if ("type".equals(order)) {
            Collections.sort(fileList, new TypeComparator<Hashtable<String, Object>>());
        } else {
            Collections.sort(fileList, new NameComparator<Hashtable<String, Object>>());
        }

        KindFileMgr mgr = new KindFileMgr();
        mgr.setMoveup_dir_path(moveupDirPath);
        mgr.setCurrent_dir_path(currentDirPath);
        mgr.setCurrent_url(currentUrl);
        mgr.setTotal_count(fileList.size());
        mgr.setFile_list(fileList);
        resp.setContentType("application/json; charset=UTF-8");
        out.println(JSONHelper.obj2Json(mgr));
    }

    /**
     * ??
     * 
     * @param <T>
     */
    public class NameComparator<T> implements Comparator<T> {

        @Override
        @SuppressWarnings("unchecked")
        public int compare(Object a, Object b) {
            Hashtable<String, Object> hashA = (Hashtable<String, Object>) a;
            Hashtable<String, Object> hashB = (Hashtable<String, Object>) b;
            if (((Boolean) hashA.get("is_dir")) && !((Boolean) hashB.get("is_dir"))) {
                return -1;
            } else if (!((Boolean) hashA.get("is_dir")) && ((Boolean) hashB.get("is_dir"))) {
                return 1;
            } else {
                return ((String) hashA.get("filename")).compareTo((String) hashB.get("filename"));
            }
        }
    }

    /**
     * ??
     * 
     * @param <T>
     */
    public class SizeComparator<T> implements Comparator<T> {

        @Override
        @SuppressWarnings("unchecked")
        public int compare(Object a, Object b) {
            Hashtable<String, Object> hashA = (Hashtable<String, Object>) a;
            Hashtable<String, Object> hashB = (Hashtable<String, Object>) b;
            if (((Boolean) hashA.get("is_dir")) && !((Boolean) hashB.get("is_dir"))) {
                return -1;
            } else if (!((Boolean) hashA.get("is_dir")) && ((Boolean) hashB.get("is_dir"))) {
                return 1;
            } else {
                if (((Long) hashA.get("filesize")) > ((Long) hashB.get("filesize"))) {
                    return 1;
                } else if (((Long) hashA.get("filesize")) < ((Long) hashB.get("filesize"))) {
                    return -1;
                } else {
                    return 0;
                }
            }
        }
    }

    /**
     * 
     * 
     * @param <T>
     */
    public class TypeComparator<T> implements Comparator<T> {

        @Override
        @SuppressWarnings("unchecked")
        public int compare(Object a, Object b) {
            Hashtable<String, Object> hashA = (Hashtable<String, Object>) a;
            Hashtable<String, Object> hashB = (Hashtable<String, Object>) b;
            if (((Boolean) hashA.get("is_dir")) && !((Boolean) hashB.get("is_dir"))) {
                return -1;
            } else if (!((Boolean) hashA.get("is_dir")) && ((Boolean) hashB.get("is_dir"))) {
                return 1;
            } else {
                return ((String) hashA.get("filetype")).compareTo((String) hashB.get("filetype"));
            }
        }
    }
}