com.eryansky.modules.sys.web.BugController.java Source code

Java tutorial

Introduction

Here is the source code for com.eryansky.modules.sys.web.BugController.java

Source

/**
 *  Copyright (c) 2012-2014 http://www.eryansky.com
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.eryansky.modules.sys.web;

import com.eryansky.common.excel.ExcelUtil;
import com.eryansky.common.excel.ExportExcel;
import com.eryansky.common.model.Datagrid;
import com.eryansky.common.model.Result;
import com.eryansky.common.orm.Page;
import com.eryansky.common.orm.PropertyFilter;
import com.eryansky.common.orm.hibernate.EntityManager;
import com.eryansky.common.orm.hibernate.HibernateWebUtils;
import com.eryansky.common.utils.DateUtils;
import com.eryansky.common.utils.StringUtils;
import com.eryansky.common.web.springmvc.BaseController;
import com.eryansky.common.web.springmvc.SpringMVCHolder;
import com.eryansky.common.web.utils.WebUtils;
import com.eryansky.modules.sys.entity.Bug;
import com.eryansky.modules.sys.entity.Dictionary;
import com.eryansky.modules.sys.service.BugManager;
import com.eryansky.modules.sys.service.DictionaryManager;
import com.eryansky.modules.sys.utils.DictionaryUtils;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.google.common.collect.Lists;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.beans.PropertyEditorSupport;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

/**
 * bug?Controller.
 *
 * @author &Eryan eryanwcp@gmail.com
 * @date 2013-3-27 ?8:02:39
 */
@SuppressWarnings("serial")
@Controller
@RequestMapping(value = "${adminPath}/sys/bug")
public class BugController extends BaseController<Bug, Long> {

    public final static String SSSION_SEARCH = "BUG_SEARCH";

    @Autowired
    private BugManager bugManager;
    @Autowired
    private DictionaryManager dictionaryManager;

    @Override
    public EntityManager<Bug, Long> getEntityManager() {
        return bugManager;
    }

    @RequestMapping(value = { "" })
    public String list() {
        return "modules/sys/bug";
    }

    @RequestMapping(value = { "input" })
    public String input() {
        return "modules/sys/bug-input";
    }

    @RequestMapping(value = { "view" })
    public String view(@ModelAttribute("model") Bug bug) {
        return "modules/sys/bug-view";
    }

    /**
     * ??
     * @param binder
     */
    @Override
    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        Object annotationValue = AnnotationUtils
                .getValue(AnnotationUtils.findAnnotation(entityClass, JsonIgnoreProperties.class));
        if (annotationValue != null) {
            String[] jsonIgnoreProperties = (String[]) annotationValue;
            binder.setDisallowedFields(jsonIgnoreProperties);
        }

        // Date ?
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                setValue(DateUtils.parseDate(text));
            }
        });
    }

    @RequestMapping(value = { "_save" })
    @ResponseBody
    public Result save(@ModelAttribute("model") Bug bug) {
        Result result;
        // ????
        Bug checkBug = bugManager.findUniqueBy("title", bug.getTitle());
        if (checkBug != null && !checkBug.getId().equals(bug.getId())) {
            result = new Result(Result.WARN, "[" + bug.getTitle() + "],!", "title");
            return result;
        }

        bugManager.saveEntity(bug);
        result = Result.successResult();
        return result;
    }

    @Override
    @RequestMapping(value = { "datagrid" })
    @ResponseBody
    public Datagrid datagrid() {
        // 
        List<PropertyFilter> filters = HibernateWebUtils.buildPropertyFilters(SpringMVCHolder.getRequest());
        Page<Bug> p = new Page<Bug>(SpringMVCHolder.getRequest());
        p = getEntityManager().findPage(p, filters);

        //?bug??
        if (p.getResult() != null) {
            for (Bug bug : p.getResult()) {
                //                Dictionary dictionary = dictionaryManager.getByCode(bug.getType());
                Dictionary dictionary = dictionaryManager.getDictionaryByDV(DictionaryUtils.DIC_BUG, bug.getType());
                if (dictionary != null) {
                    bug.setTypeName(dictionary.getName());
                } else {
                    logger.warn("[{}].", bug.getTitle());
                }
            }
        }
        Datagrid<Bug> dg = new Datagrid<Bug>(p.getTotalCount(), p.getResult());
        return dg;
    }

    @RequestMapping(value = { "import" })
    public String _import() {
        return "modules/sys/bug-import";
    }

    /**
     * Excel
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = { "importExcel" })
    @ResponseBody
    public Result importExcel(@RequestParam(value = "filedata") MultipartFile file) {
        Result result = null;
        List<Bug> bugs = null;
        List<Bug> bugs_new = Lists.newArrayList();
        try {
            if (file != null) {
                bugs = (List<Bug>) ExcelUtil.importExcelByIs(file.getInputStream(), Bug.class);
                if (bugs != null && bugs.size() > 0) {
                    for (Bug bug : bugs) {
                        //???
                        Bug checkBug = bugManager.findUniqueBy("title", bug.getTitle());
                        if (checkBug == null) {
                            bug.setVersion(0);
                            //                            bug.setContent(ClobUtil.getClob(bug.getContentView()));
                            Dictionary dictionary = dictionaryManager.findUniqueBy("name", bug.getTypeName());
                            if (dictionary != null) {
                                bug.setType(dictionary.getCode());
                            } else {
                                logger.warn("[{}].", bug.getTypeName());
                            }
                            bugs_new.add(bug);
                        } else {
                            logger.warn("[{}].", bug.getTitle());
                        }
                    }
                }
                bugManager.saveOrUpdate(bugs_new);
                result = new Result(Result.SUCCESS, "" + bugs_new.size() + "??.", null);

            } else {
                result = new Result(Result.WARN, ".", null);
            }

        } catch (IOException e) {
            logger.error(" " + e.getMessage(), e);
            result = new Result(Result.ERROR, "", null);
        } catch (Exception e) {
            logger.error("?? " + e.getMessage(), e);
            result = new Result(Result.ERROR, "??", null);
        } finally {
            return result;
        }
    }

    /**
     * Excel
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = { "exportExcel" })
    public void exportExcel(HttpServletRequest request, HttpServletResponse response, HttpSession session)
            throws Exception {
        // ????
        final String fileName = "?.xls";
        OutputStream outStream = null;
        try {
            //
            response.setContentType(WebUtils.EXCEL_TYPE);
            //?
            WebUtils.setDownloadableHeader(request, response, fileName);
            //session??
            List<PropertyFilter> sessionFilters = (List<PropertyFilter>) session.getAttribute(SSSION_SEARCH);
            List<Bug> bugs = null;
            if (sessionFilters != null) {
                bugs = bugManager.find(sessionFilters, "orderNo", Page.ASC);
            } else {
                bugs = bugManager.getAll("id", Page.ASC);
            }
            //bugBug?Dictionary??
            for (Bug bug : bugs) {
                String dicStringName = "";
                if (StringUtils.isNotBlank(bug.getType())) {
                    dicStringName = DictionaryUtils.getDictionaryNameByDV(DictionaryUtils.DIC_BUG, bug.getType(),
                            null);
                    bug.setTypeName(dicStringName);
                }

            }
            HSSFWorkbook workbook = new ExportExcel<Bug>().exportExcel("?", Bug.class, bugs);
            outStream = response.getOutputStream();
            workbook.write(outStream);
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                outStream.flush();
                outStream.close();
            } catch (IOException e) {

            }
        }
    }
}