com.eryansky.modules.disk.web.FileKindEditorController.java Source code

Java tutorial

Introduction

Here is the source code for com.eryansky.modules.disk.web.FileKindEditorController.java

Source

/**
 * Copyright (c) 2005-2012 https://github.com/zhangkaitao
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.eryansky.modules.disk.web;

import com.eryansky.common.utils.mapper.JsonMapper;
import com.eryansky.common.web.springmvc.SimpleController;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.eryansky.core.security.LogUtils;
import com.eryansky.core.security.SecurityUtils;
import com.eryansky.core.security.SessionInfo;
import com.eryansky.core.web.upload.FileUploadUtils;
import com.eryansky.core.web.upload.exception.FileNameLengthLimitExceededException;
import com.eryansky.core.web.upload.exception.InvalidExtensionException;
import com.eryansky.modules.disk.entity.Folder;
import com.eryansky.modules.disk.utils.DiskUtils;
import com.eryansky.modules.disk.utils.FileUtils;
import com.eryansky.utils.AppConstants;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *  KindEditor??
 */
@Controller
@RequestMapping(value = "${adminPath}/disk/filekindeditor")
public class FileKindEditorController extends SimpleController {

    //mime
    private static final String[] IMAGE_EXTENSION = FileUploadUtils.IMAGE_EXTENSION;

    //mime
    private static final String[] ATTACHMENT_EXTENSION = FileUploadUtils.DEFAULT_ALLOWED_EXTENSION;

    //flash mime
    private static final String[] FLASH_EXTENSION = FileUploadUtils.FLASH_EXTENSION;

    //swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb
    private static final String[] MEDIA_EXTENSION = FileUploadUtils.MEDIA_EXTENSION;

    //? ??
    private long maxSize = FileUploadUtils.DEFAULT_MAX_SIZE;
    //
    private String baseDir = FileUploadUtils.getDefaultBaseDir();

    @Autowired
    private MessageSource messageSource;

    /**
     * ?
     * dir   file image flash media
     * <p/>
     * ??
     * 
     * {
     * error : 1
     * message : ?
     * }
     * <p/>
     * 
     * {
     * error:0
     * url:??
     * title:
     * }
     *
     * @param response
     * @param request
     * @param dir
     * @param file
     * @return
     */
    @RequestMapping(value = "upload", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> upload(HttpServletResponse response, HttpServletRequest request,
            @RequestParam(value = "dir", required = false) String dir,
            @RequestParam(value = "imgFile", required = false) MultipartFile multipartFile) {
        //        response.setContentType("text/html; charset=UTF-8");

        String[] allowedExtension = extractAllowedExtension(dir);

        try {
            SessionInfo sessionInfo = SecurityUtils.getCurrentSessionInfo();
            //            String basePath = DiskUtils.getKindEditorRelativePath(sessionInfo.getUserId());
            //            basePath +=  File.separator + FileUploadUtils.datePath();//
            //            String url = FileUploadUtils.upload(request, AppConstants.getDiskBaseDir() + File.separator + basePath, multipartFile, allowedExtension, maxSize, false, null);

            com.eryansky.modules.disk.entity.File file = DiskUtils.saveSystemFile(DiskUtils.FOLDER_KINDEDITOR,
                    sessionInfo, multipartFile);
            String filename = DiskUtils.getVirtualFilePath(file);

            return successResponse(request, file.getName(), filename);
        } catch (IOException e) {
            LogUtils.logError("file upload error", e);
            return errorResponse("?????");
        } catch (InvalidExtensionException.InvalidImageExtensionException e) {
            return errorResponse("???<br/>?("
                    + JsonMapper.getInstance().toJson(IMAGE_EXTENSION) + ")?");
        } catch (InvalidExtensionException.InvalidFlashExtensionException e) {
            return errorResponse("flash???<br/>?flash"
                    + JsonMapper.getInstance().toJson(FLASH_EXTENSION) + "?");
        } catch (InvalidExtensionException.InvalidMediaExtensionException e) {
            return errorResponse("???<br/>?"
                    + JsonMapper.getInstance().toJson(MEDIA_EXTENSION) + "?");
        } catch (InvalidExtensionException e) {
            return errorResponse("????????");
        } catch (FileUploadBase.FileSizeLimitExceededException e) {
            return errorResponse(
                    "????<br/>??"
                            + e.getPermittedSize() + "?");
        } catch (FileNameLengthLimitExceededException e) {
            return errorResponse("??" + e.getLength() + "");
        }

    }

    /**
     * ?
     * path ? ?..?
     * order ?  NAME SIZE TYPE
     * dir  file image flash media
     * <p/>
     * <p/>
     * ??
     * ????todo ? ????
     * ""
     * <p/>
     * 
     * {"current_url":???,
     * "current_dir_path":?,
     * "moveup_dir_path":????,
     * "file_list":[//
     * ??                  ?           ??    ?   ?        
     * {"filename":"My Pictures","filesize":0,"filetype":"","has_file":true,"is_dir":true,"is_photo":false,"datetime":"2013-03-09 11:41:17"}
     * ],
     * "total_count":?
     * }
     *
     * @return
     */
    @RequestMapping(value = "filemanager", method = RequestMethod.GET)
    @ResponseBody
    public Object fileManager(HttpServletRequest request,
            @RequestParam(value = "dir", required = false, defaultValue = "file") String dir,
            @RequestParam(value = "order", required = false, defaultValue = "NAME") String order) {
        List<String> fileSuffixs = Lists.newArrayList();
        if ("image".equalsIgnoreCase(dir)) {
            fileSuffixs = Arrays.<String>asList(FileUploadUtils.IMAGE_EXTENSION);
        } else if ("media".equalsIgnoreCase(dir)) {
            fileSuffixs = Arrays.<String>asList(FileUploadUtils.MEDIA_EXTENSION);
        } else if ("flash".equalsIgnoreCase(dir)) {
            fileSuffixs = Arrays.<String>asList(FileUploadUtils.FLASH_EXTENSION);
        } else {
            fileSuffixs = Arrays.<String>asList(FileUploadUtils.DEFAULT_ALLOWED_EXTENSION);
        }

        SessionInfo sessionInfo = SecurityUtils.getCurrentSessionInfo();
        String basePath = DiskUtils.getKindEditorRelativePath(sessionInfo.getUserId());

        //
        String moveupDirPath = "";

        //????
        List<Map<String, Object>> fileMetaInfoList = Lists.newArrayList();

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Folder folder = DiskUtils.getUserKindEditorFolder(sessionInfo.getUserId());
        List<com.eryansky.modules.disk.entity.File> files = FileUtils.getFolderFiles(folder.getId(), fileSuffixs);
        for (com.eryansky.modules.disk.entity.File file : files) {

            Map<String, Object> fileMetaInfo = Maps.newHashMap();
            File diskFile = file.getDiskFile();
            String fileName = file.getName();

            String fileExt = FilenameUtils.getExtension(fileName);
            fileMetaInfo.put("is_dir", false);
            fileMetaInfo.put("has_file", false);
            fileMetaInfo.put("filesize", diskFile.length());
            fileMetaInfo.put("is_photo", Arrays.<String>asList(FileUploadUtils.IMAGE_EXTENSION).contains(fileExt));
            fileMetaInfo.put("filetype", fileExt);

            fileMetaInfo.put("filename", DiskUtils.getVirtualFilePath(file));
            fileMetaInfo.put("name", file.getName());
            fileMetaInfo.put("datetime", df.format(diskFile.lastModified()));

            fileMetaInfoList.add(fileMetaInfo);
        }

        if ("size".equalsIgnoreCase(order)) {
            Collections.sort(fileMetaInfoList, new SizeComparator());
        } else if ("type".equalsIgnoreCase(order)) {
            Collections.sort(fileMetaInfoList, new TypeComparator());
        } else {
            Collections.sort(fileMetaInfoList, new NameComparator());
        }
        Map<String, Object> result = Maps.newHashMap();
        result.put("moveup_dir_path", moveupDirPath);
        result.put("current_dir_path", "");
        result.put("current_url", "");
        result.put("total_count", fileMetaInfoList.size());
        result.put("file_list", fileMetaInfoList);
        return result;
    }

    private Map<String, Object> successResponse(HttpServletRequest request, String filename, String url) {
        Map<String, Object> map = Maps.newHashMap();
        map.put("error", 0);
        map.put("url", request.getContextPath() + "/" + url);
        map.put("title", filename);
        return map;
    }

    private Map<String, Object> errorResponse(String errorCode) {
        //        String message = messageSource.getMessage(errorCode, null, null);
        String message = errorCode;
        if (message.contains("<br/>")) {
            message = message.replace("<br/>", "\\n");
        }
        Map<String, Object> map = Maps.newHashMap();
        map.put("error", 1);
        map.put("message", message);
        System.out.println(map);
        return map;
    }

    private String[] extractAllowedExtension(String dir) {
        if ("image".equals(dir)) {
            return IMAGE_EXTENSION;
        } else if ("flash".equals(dir)) {
            return FLASH_EXTENSION;
        } else if ("media".equals(dir)) {
            return MEDIA_EXTENSION;
        } else {
            return ATTACHMENT_EXTENSION;
        }

    }

    public class NameComparator implements Comparator {
        public int compare(Object a, Object b) {
            Map mapA = (Map) a;
            Map mapB = (Map) b;
            if (((Boolean) mapA.get("is_dir")) && !((Boolean) mapB.get("is_dir"))) {
                return -1;
            } else if (!((Boolean) mapA.get("is_dir")) && ((Boolean) mapB.get("is_dir"))) {
                return 1;
            } else {
                return ((String) mapA.get("filename")).compareTo((String) mapB.get("filename"));
            }
        }
    }

    public class SizeComparator implements Comparator {
        public int compare(Object a, Object b) {
            Map mapA = (Map) a;
            Map mapB = (Map) b;
            if (((Boolean) mapA.get("is_dir")) && !((Boolean) mapB.get("is_dir"))) {
                return -1;
            } else if (!((Boolean) mapA.get("is_dir")) && ((Boolean) mapB.get("is_dir"))) {
                return 1;
            } else {
                if (((Long) mapA.get("filesize")) > ((Long) mapB.get("filesize"))) {
                    return 1;
                } else if (((Long) mapA.get("filesize")) < ((Long) mapB.get("filesize"))) {
                    return -1;
                } else {
                    return 0;
                }
            }
        }
    }

    public class TypeComparator implements Comparator {
        public int compare(Object a, Object b) {
            Map mapA = (Map) a;
            Map mapB = (Map) b;
            if (((Boolean) mapA.get("is_dir")) && !((Boolean) mapB.get("is_dir"))) {
                return -1;
            } else if (!((Boolean) mapA.get("is_dir")) && ((Boolean) mapB.get("is_dir"))) {
                return 1;
            } else {
                return ((String) mapA.get("filetype")).compareTo((String) mapB.get("filetype"));
            }
        }
    }

}