com.glaf.core.web.springmvc.MxDiskFileManagerJsonController.java Source code

Java tutorial

Introduction

Here is the source code for com.glaf.core.web.springmvc.MxDiskFileManagerJsonController.java

Source

/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.glaf.core.web.springmvc;

import java.io.File;
import java.text.SimpleDateFormat;
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.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.glaf.core.config.SystemProperties;
import com.glaf.core.security.LoginContext;
import com.glaf.core.util.RequestUtils;

@Controller("/diskFileManagerJson")
@RequestMapping("/diskFileManagerJson")
public class MxDiskFileManagerJsonController {

    private static class NameComparator implements Comparator<Object>, java.io.Serializable {
        private static final long serialVersionUID = 1L;

        public int compare(Object a, Object b) {
            Hashtable<?, ?> hashA = (Hashtable<?, ?>) a;
            Hashtable<?, ?> hashB = (Hashtable<?, ?>) 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"));
            }
        }
    }

    private static class SizeComparator implements Comparator<Object>, java.io.Serializable {
        private static final long serialVersionUID = 1L;

        public int compare(Object a, Object b) {
            Hashtable<?, ?> hashA = (Hashtable<?, ?>) a;
            Hashtable<?, ?> hashB = (Hashtable<?, ?>) 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;
                }
            }
        }
    }

    private static class TypeComparator implements Comparator<Object>, java.io.Serializable {

        private static final long serialVersionUID = 1L;

        public int compare(Object a, Object b) {
            Hashtable<?, ?> hashA = (Hashtable<?, ?>) a;
            Hashtable<?, ?> hashB = (Hashtable<?, ?>) 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"));
            }
        }
    }

    private String getError(String message) throws Exception {
        JSONObject object = new JSONObject();
        object.put("error", 1);
        object.put("message", message);
        return object.toString();
    }

    @RequestMapping
    public void show(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setContentType("text/html; charset=UTF-8");
        String serviceKey = request.getParameter("serviceKey");
        LoginContext loginContext = RequestUtils.getLoginContext(request);
        // ?? /var/www/upload/
        String rootPath = SystemProperties.getAppPath() + "/upload/" + loginContext.getUser().getId() + "/";
        // URL?? http://www.yoursite.com/upload/
        String rootUrl = request.getContextPath() + "/upload/" + loginContext.getUser().getId() + "/";
        if (StringUtils.isNotEmpty(serviceKey)) {
            rootPath = rootPath + serviceKey + "/";
            rootUrl = rootUrl + serviceKey + "/";
        }
        // ??
        String[] fileTypes = new String[] { "gif", "jpg", "jpeg", "png", "bmp", "swf" };

        // ?path??URL
        String path = request.getParameter("path") != null ? request.getParameter("path") : "";
        String currentPath = rootPath + path;
        String currentUrl = rootUrl + 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) : "";
        }

        // ??name or size or type
        String order = request.getParameter("order") != null ? request.getParameter("order").toLowerCase() : "name";

        // ??..
        if (path.indexOf("..") >= 0) {
            response.getWriter().write(getError("Access is not allowed."));
            return;
        }

        // ??/
        if (!"".equals(path) && !path.endsWith("/")) {
            response.getWriter().write(getError("Parameter is not valid."));
            return;
        }

        // ??
        File currentPathFile = new File(currentPath);
        if (!currentPathFile.isDirectory()) {
            response.getWriter().write(getError("Directory does not exist."));
            return;
        }

        // ????
        List<Hashtable<String, Object>> fileList = new java.util.ArrayList<Hashtable<String, Object>>();
        if (currentPathFile != null && currentPathFile.listFiles() != null) {
            File[] filelist = currentPathFile.listFiles();
            if (filelist != null) {
                for (int i = 0, len = filelist.length; i < len; i++) {
                    File file = filelist[i];
                    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 = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                        hash.put("is_dir", false);
                        hash.put("has_file", false);
                        hash.put("filesize", file.length());
                        hash.put("is_photo", Arrays.<String>asList(fileTypes).contains(fileExt));
                        hash.put("filetype", fileExt);
                    }
                    hash.put("filename", fileName);
                    hash.put("datetime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(file.lastModified()));
                    fileList.add(hash);
                }
            }
        }

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

        JSONObject result = new JSONObject();
        result.put("moveup_dir_path", moveupDirPath);
        result.put("current_dir_path", currentDirPath);
        result.put("current_url", currentUrl);
        result.put("total_count", fileList.size());
        result.put("file_list", fileList);

        response.setContentType("application/json; charset=UTF-8");
        response.getWriter().write(result.toString());
    }

}