BaseController.java 7.54 KB
package com.huaheng.framework.web.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.huaheng.common.utils.StringUtils;
import com.huaheng.common.utils.security.ShiroUtils;
import com.huaheng.framework.web.domain.AjaxResult;
import com.huaheng.framework.web.page.PageDomain;
import com.huaheng.framework.web.page.TableDataInfo;
import com.huaheng.framework.web.page.TableSupport;
import com.huaheng.pc.system.user.domain.User;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Semaphore;

/**
 * web层通用数据处理
 *
 * @author huaheng
 */
public class BaseController {
    /**
     * 将前台传递过来的日期格式的字符串,自动转化为Date类型
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));

//        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//        LocalDateTime time = LocalDateTime.now();
//        String localTime = df.format(time);
//        将LocalDateTime转为String
    }

    /**
     * 设置请求分页数据
     */
    protected void startPage() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            String orderBy = pageDomain.getOrderBy();
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }
    }

    protected void startPages() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize() / 2;
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            String orderBy = pageDomain.getOrderBy();
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }
    }

    /**
     * 设置请求分页数据
     */
    protected void startPage(Integer pageNum, Integer pageSize, String orderBy) {
        PageHelper.startPage(pageNum, pageSize, orderBy);
    }

    /**
     * 响应请求分页数据
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    protected TableDataInfo getDataTable(List<?> list) {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(200);
        rspData.setData(list);
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }

    /**
     * 响应返回结果
     *
     * @param rows 影响行数
     * @return 操作结果
     */
    protected AjaxResult toAjax(int rows) {
        return rows > 0 ? success() : error();
    }

    /**
     * 响应返回结果
     *
     * @param succeed 是否成功
     * @return 操作结果
     */
    protected AjaxResult toAjax(boolean succeed) {
        return succeed ? success() : error();
    }

    /**
     * 返回成功
     */
    public AjaxResult success() {
        return AjaxResult.success("操作成功!");
    }

    /**
     * 返回失败消息
     */
    public AjaxResult error() {
        return AjaxResult.error("操作失败!");
    }

    /**
     * 返回成功消息
     */
    public AjaxResult success(String message) {
        return AjaxResult.success(message);
    }

    /**
     * 返回失败消息
     */
    public AjaxResult error(String message) {
        return AjaxResult.error(message);
    }

//    /**
//     * 返回错误码消息
//     */
//    public AjaxResult error(int code, String message)
//    {
//        return AjaxResult.error(code, message);
//    }

    /**
     * 页面跳转
     */
    public String redirect(String url) {
        return StringUtils.format("redirect:{}", url);
    }

    public User getUser() {
        return ShiroUtils.getUser();
    }

    public void setUser(User user) {
        ShiroUtils.setUser(user);
    }

    public Integer getUserId() {
        return getUser().getId();
    }

    public String getLoginName() {
        return getUser().getLoginName();
    }

    /**
     * mybatis-plus响应请求分页数据
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    protected TableDataInfo getMpDataTable(List<?> list, Long total) {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(200);
        rspData.setData(list);
        rspData.setTotal(total);
        return rspData;
    }

    Semaphore semaphore = new Semaphore(1);

    public AjaxResult handleMultiProcess(MultiProcessListener multiProcessListener) {
        AjaxResult ajaxResult = null;
        int max_time = 30 * 1000;
        int now = 0;
        boolean avail = true;
        while (avail) {
            int availablePermits = semaphore.availablePermits();
            if (availablePermits > 0) {
                avail = false;
                try {
                    semaphore.acquire(1);
                    ajaxResult = multiProcessListener.doProcess();
                } catch (Exception e) {
                    e.printStackTrace();
                    ajaxResult = AjaxResult.error(e.getMessage());
                } finally {
                    semaphore.release(1);
                }
            } else {
                ajaxResult = AjaxResult.error("多线程处理异常");
                try {
                    now = now + 200;
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (now >= max_time) {
                    avail = false;
                }
            }
        }
        return ajaxResult;
    }

    public interface MultiProcessListener {
        AjaxResult doProcess();
    }

    // 下发任务并发控制
    Map<String, Boolean> multiProcessMap = new HashMap<>();

    public AjaxResult handleMultiProcessV1(String taskKey, MultiProcessListener multiProcessListener) {
        AjaxResult ajaxResult = null;
        int max_time = 30 * 1000;
        int now = 0;
        boolean avail = true;
        while (avail) {
            boolean availablePermits = MapUtils.getBoolean(multiProcessMap, taskKey, false);
            if (!availablePermits) {
                avail = false;
                try {
                    multiProcessMap.put(taskKey, true);
                    ajaxResult = multiProcessListener.doProcess();
                } catch (Exception e) {
                    e.printStackTrace();
//                    throw new RuntimeException(e);
                    ajaxResult = AjaxResult.error(e.getMessage());
                } finally {
                    multiProcessMap.put(taskKey, false);
                }
            } else {
                ajaxResult = AjaxResult.error("多线程处理异常, 待处理现场太多,等待时间超出30秒");
                try {
                    now = now + 200;
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (now >= max_time) {
                    avail = false;
                }
            }
        }
        return ajaxResult;
    }

}