com.school.exam.web.student.StudentController.java Source code

Java tutorial

Introduction

Here is the source code for com.school.exam.web.student.StudentController.java

Source

/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.school.exam.web.student;

import com.google.common.collect.Lists;
import com.school.exam.entity.*;
import com.school.exam.repository.Token;
import com.school.exam.service.account.ShiroDbRealm;
import com.school.exam.service.exam.ExamPaperResultService;
import com.school.exam.service.exam.ExamQuestionService;
import com.school.exam.service.project.ProjectService;
import com.school.exam.service.question.AnswerService;
import com.school.exam.service.question.WordsService;
import com.school.exam.utils.ExcelUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springside.modules.web.MediaTypes;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.sql.Date;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Student?Controller, RestfulUrls:
 * 
 * List page : GET /student/
 * Create page : GET /student/create
 * Create action : POST /student/create
 * Update page : GET /student/update/{id}
 * Update action : POST /student/update
 * Delete action : GET /student/delete/{id}
 * 
 * @author baiqw
 */
@Controller
@RequestMapping(value = "/student")
public class StudentController {
    private Logger logger = LoggerFactory.getLogger(StudentController.class);

    public static Map<String, String> NAV_MAP = new LinkedHashMap<String, String>();
    public static Map<String, Course> COURSE_MAP = new LinkedHashMap<String, Course>();
    public static List<List<String>> RESOURCES = new ArrayList<List<String>>();
    public static List<List<String>> IMAGES = new ArrayList<List<String>>();
    public static final String COURSE_NAME = "???";

    static {
        NAV_MAP.put("", "student/");
        NAV_MAP.put("", "student/classes/index");
        NAV_MAP.put("", "student/classes/study");
        //        NAV_MAP.put("", "student/testroom");
        NAV_MAP.put("", "student/examlist");
        //        NAV_MAP.put("", "examlist");
        NAV_MAP.put("?", "student/classes/books");
        NAV_MAP.put("???", "student/words");
        NAV_MAP.put("", "student/classes/moves");
        NAV_MAP.put("", "student/classes/flash");
        NAV_MAP.put("", "student/classes/images");

        InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("classes.xls");
        InputStream inputStreamImages = Thread.currentThread().getContextClassLoader()
                .getResourceAsStream("images.xls");

        IMAGES.addAll(ExcelUtils.toList(inputStreamImages));
        RESOURCES.addAll(ExcelUtils.toList(inputStream));
        COURSE_MAP.putAll(ExcelUtils.toCourse(RESOURCES));

    }

    @Autowired
    private ExamQuestionService questionService;
    @Autowired
    private ExamPaperResultService resultService;
    @Autowired
    private ProjectService projectService;
    @Autowired
    private WordsService wordsService;

    @Autowired
    private AnswerService answerService;

    @RequestMapping(method = RequestMethod.GET)
    public String index(Model model) {
        model.addAttribute("nav", NAV_MAP);
        model.addAttribute("curent", "");
        ShiroDbRealm.ShiroUser user = (ShiroDbRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal();
        logger.debug("className:{}", user.getClassName());
        return "student" + "/index";
    }

    public List<List<String>> getResourceByTaskName(String taskName, String type, List<List<String>> res) {
        List<List<String>> resource = new ArrayList<List<String>>();

        for (List<String> r : res) {
            //            logger.debug("resource:{}", r);
            if (taskName.equals(r.get(1)) && type.equals(r.get(5))) {
                resource.add(r);
            }
        }

        logger.debug("taskName:{}, type:{}, resource :{} ", taskName, type, resource);

        return resource;
    }

    @RequestMapping(value = "classes/images", method = RequestMethod.GET)
    public String images(Model model, @RequestParam(value = "type", defaultValue = "") String taskName) {
        String className = getCurrentClassName();
        if (!"ysfx".equals(className)) {
            model.addAttribute("resourcePath", "pmfj");
            if ("".equals(taskName)) {
                taskName = "PM2.5?";
            }
        } else {
            model.addAttribute("resourcePath", "ysfx");
            if ("".equals(taskName)) {
                taskName = "?PM2.5?";
            }

        }

        model.addAttribute("nav", NAV_MAP);
        model.addAttribute("curent", "");

        model.addAttribute("resources", getResourceByTaskName(taskName, "IMG", IMAGES));

        return NAV_MAP.get("");
    }

    @RequestMapping(value = "classes/flash", method = RequestMethod.GET)
    public String flash(Model model,
            @RequestParam(value = "type", defaultValue = "PM2.5?") String taskName) {
        String className = getCurrentClassName();
        if (!"ysfx".equals(className)) {
            model.addAttribute("resourcePath", "pmfj");
            taskName = "PM2.5?";
        } else {
            model.addAttribute("resourcePath", "ysfx");
            taskName = "?PM2.5?";
        }
        model.addAttribute("nav", NAV_MAP);
        model.addAttribute("curent", "");
        model.addAttribute("resources", getResourceByTaskName(taskName, "FLASH", IMAGES));

        return NAV_MAP.get("");
    }

    @RequestMapping(value = "classes/moves", method = RequestMethod.GET)
    public String moves(Model model,
            @RequestParam(value = "type", defaultValue = "PM2.5?") String taskName) {
        String className = getCurrentClassName();
        if (!"ysfx".equals(className)) {
            model.addAttribute("resourcePath", "pmfj");
            taskName = "PM2.5?";
        } else {
            model.addAttribute("resourcePath", "ysfx");
            taskName = "?PM2.5?";
        }
        model.addAttribute("nav", NAV_MAP);
        model.addAttribute("curent", "");
        model.addAttribute("resources", getResourceByTaskName(taskName, "MOVIE", IMAGES));

        return NAV_MAP.get("");
    }

    @RequestMapping(value = "classes/books", method = RequestMethod.GET)
    public String books(Model model,
            @RequestParam(value = "type", defaultValue = "PM2.5?") String taskName) {
        String className = getCurrentClassName();
        if (!"ysfx".equals(className)) {
            model.addAttribute("resourcePath", "pmfj");
            taskName = "PM2.5?";
        } else {
            model.addAttribute("resourcePath", "ysfx");
            taskName = "?PM2.5?";
        }

        model.addAttribute("nav", NAV_MAP);
        model.addAttribute("curent", "?");
        model.addAttribute("course", COURSE_MAP);
        model.addAttribute("resources", getResourceByTaskName(taskName, "CKZL", IMAGES));
        return NAV_MAP.get("?");
    }

    @RequestMapping(value = "testroom", method = RequestMethod.GET)
    public String testroom(Model model) {

        model.addAttribute("nav", NAV_MAP);
        model.addAttribute("curent", "");
        model.addAttribute("course", COURSE_MAP);

        return NAV_MAP.get("");
    }

    @RequestMapping(value = "classes/study", method = RequestMethod.GET)
    public String classes(Model model) {

        model.addAttribute("nav", NAV_MAP);
        model.addAttribute("curent", "");
        model.addAttribute("courseName", getCurrentCourseName());
        model.addAttribute("course", COURSE_MAP);

        return NAV_MAP.get("");
    }

    private String getCurrentCourseName() {
        if ("ysfx".equals(getCurrentClassName())) {
            return "???";
        }
        return COURSE_NAME;
    }

    @RequestMapping(value = "classes/index", method = RequestMethod.GET)
    public String classIndex(Model model) {
        model.addAttribute("nav", NAV_MAP);
        model.addAttribute("curent", "");
        return NAV_MAP.get("");
    }

    @RequestMapping(value = "project", method = RequestMethod.GET)
    public String project(Model model, @RequestParam("course_name") String courseName,
            @RequestParam("project_title") String projectTitle, @RequestParam("task_title") String taskTitle) {

        model.addAttribute("nav", NAV_MAP);
        model.addAttribute("curent", "");
        model.addAttribute("course", COURSE_MAP.get(courseName).getSubEntitys().get(projectTitle));
        model.addAttribute("currentProject", projectTitle);
        model.addAttribute("courseName", courseName);
        model.addAttribute("currentTask", taskTitle);

        if (COURSE_NAME.equals(courseName)) {
            model.addAttribute("resourcePath", "pmfj");
        } else {
            model.addAttribute("resourcePath", "ysfx");
        }

        return "student/classes/project";
    }

    @RequestMapping(value = "words", method = RequestMethod.GET)
    public String project(Model model,
            @RequestParam(defaultValue = "PM2.5?") String type) {

        model.addAttribute("nav", NAV_MAP);
        model.addAttribute("curent", "???");
        model.addAttribute("words", wordsService.findAll());

        return NAV_MAP.get("???");
    }

    @RequestMapping(value = "examlist", method = RequestMethod.GET)
    @Token(save = true)
    public String examlist(@RequestParam(defaultValue = "") String project, Model model) {
        String className = getCurrentClassName();
        if (!"ysfx".equals(className)) {
            model.addAttribute("resourcePath", "pmfj");
            if (org.apache.commons.lang3.StringUtils.isEmpty(project)) {
                project = "PM2.5?";
            }
        } else {
            model.addAttribute("resourcePath", "ysfx");
            if (org.apache.commons.lang3.StringUtils.isEmpty(project)) {
                project = "?PM2.5?";
            }

        }

        //        TeProjectVO projectVO =projectService.findByProjectName(project);

        model.addAttribute("nav", NAV_MAP);
        model.addAttribute("curent", "");
        model.addAttribute("course", COURSE_MAP);
        model.addAttribute("project", project);

        ShiroDbRealm.ShiroUser user = getCurrentUser();
        List<TeMakeExamVO> examlist = questionService.findByExamName(project);
        TeMakeExamVO teMakeExamVO = null;
        if (null == examlist || examlist.size() == 0) {
            model.addAttribute("message", "??!");
            return NAV_MAP.get("");
        } else {

            teMakeExamVO = examlist.get(0);
            logger.debug("teMakeExamVO:{}", teMakeExamVO.getExamName());

            if (!resultService.isHasExamByCurrentUserId(user.id, teMakeExamVO.getId())) {
                TeMakeExamVO examvo = questionService.findExamQuestions(teMakeExamVO.getId());
                examvo = addRemark(examvo, teMakeExamVO.getId());
                model.addAttribute("examvo", examvo);
                model.addAttribute("examName", project);

                return NAV_MAP.get("");
            } else {
                TeMakeExamVO examvo = questionService.findExamQuestions(teMakeExamVO.getId());
                List<TeExamQuestionVO> list = examvo.getQuestionList();

                List<TeExamPaperResultVO> eprlist = resultService.getExamPaperByPersonId(user.id,
                        teMakeExamVO.getId());
                model.addAttribute("sumScore", null == eprlist ? 0 : eprlist.get(0).getSumScore());
                model.addAttribute("examvo", examvo);
                model.addAttribute("resultlist",
                        questionService.findByDepdIdAndPersonId(teMakeExamVO.getId(), user.id));

                return "student/resultlist";
            }

        }

    }

    private TeMakeExamVO addRemark(TeMakeExamVO examvo, Long id) {
        List<TeExamQuestionVO> list = examvo.getQuestionList();
        long singleChoolse = questionService.getTypeNumber(1, id);
        long multChoolse = questionService.getTypeNumber(2, id);
        int s = 0;
        int m = 0;
        for (TeExamQuestionVO vo : list) {
            if (vo.getType().equals(1) && s == 0) {
                vo.setTypeRemark("?(" + singleChoolse + "? " + (vo.getQuestionScore() * singleChoolse)
                        + "?" + vo.getQuestionScore() + ")");
                ++s;
                continue;
            }
            if (vo.getType().equals(2) && m == 0) {
                vo.setTypeRemark("(" + multChoolse + "? " + (vo.getQuestionScore() * multChoolse)
                        + "?" + vo.getQuestionScore() + ")");
                ++m;
                continue;
            }
        }
        examvo.setQuestionList(list);
        return examvo;
    }

    @RequestMapping(value = "submitpaper", method = RequestMethod.POST)
    @Token(remove = true)
    public String submitPaper(Model model, ServletRequest request) {
        ShiroDbRealm.ShiroUser user = getCurrentUser();
        Map<String, String[]> param = request.getParameterMap();
        Long examId = Long.valueOf(param.get("id")[0]);
        //?????
        Integer isNothas = resultService.hasExamPaperByPersonId(user.id, examId);
        if (isNothas > 0) {
            //model.addAttribute("message", "??,?????!");
            return "redirect:examlist";
        } else {
            TeMakeExamVO examvo = questionService.findExamQuestions(examId);
            examvo = addRemark(examvo, examId);
            List<TeExamResultVO> resultList = Lists.newArrayList();
            Double sumScore = 0.0;
            List<TeExamQuestionVO> eqlist = examvo.getQuestionList();
            for (TeExamQuestionVO vo : eqlist) {
                String[] selectval = param.get(vo.getId().toString());
                //
                TeExamResultVO rvo = new TeExamResultVO();
                rvo.setPersonId(user.id);
                rvo.setPersonName(user.getName());
                rvo.setDepdId(examvo.getId());
                rvo.setExamQuestionId(vo.getId());
                rvo.setQuestionAnswer(vo.getQuestionAnswerId());
                rvo.setState(1);
                if (null != selectval) {
                    if (vo.getType().equals(1)) {
                        if (vo.getQuestionAnswerId().equals(selectval[0])) {
                            rvo.setQuestionScore(vo.getQuestionScore());
                        } else {
                            rvo.setQuestionScore(0.0);
                        }
                        rvo.setChooseQuestionId(selectval[0]);
                    }
                    if (vo.getType().equals(2)) {
                        if (vo.getQuestionAnswerId().contentEquals(StringUtils.toDelimitedString(selectval, ","))) {
                            rvo.setQuestionScore(vo.getQuestionScore());
                        } else {
                            rvo.setQuestionScore(0.0);
                        }
                        rvo.setChooseQuestionId(StringUtils.toDelimitedString(selectval, ","));
                    }
                }
                if (null != rvo.getQuestionScore()) {
                    BigDecimal bd = BigDecimal.valueOf(rvo.getQuestionScore());
                    BigDecimal sum = BigDecimal.valueOf(sumScore).add(bd);
                    sumScore = sum.doubleValue();
                }
                resultList.add(rvo);
            }
            //?
            questionService.saveExamResult(resultList);
            TeExamPaperResultVO resultvo = new TeExamPaperResultVO();
            resultvo.setExamId(examId);
            resultvo.setExamName(examvo.getExamName());
            resultvo.setExamRemark(examvo.getExamRemark());
            resultvo.setSumScore(sumScore);
            resultvo.setState(1);
            resultvo.setPersonId(user.id);
            resultvo.setPersonName(user.getName());
            //?
            resultService.saveExamPaperResult(resultvo);

            model.addAttribute("sumScore", sumScore);
            model.addAttribute("examvo", examvo);
            model.addAttribute("resultlist", resultList);
            model.addAttribute("nav", NAV_MAP);
            model.addAttribute("project", examvo.getProject().getProjectName());

            return "student/resultlist";
        }
    }

    /**
     * ?Shiro?
     */
    private ShiroDbRealm.ShiroUser getCurrentUser() {
        ShiroDbRealm.ShiroUser user = (ShiroDbRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal();
        return user;
    }

    @RequestMapping(value = "answer", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
    @ResponseBody
    public String answerFile(AnswerVO answerVO, HttpServletRequest request) {

        logger.debug("upload path:{}->file:{}", request.getRealPath("/"), answerVO.getFile().getName());

        String logoRealPathDir = request.getSession().getServletContext().getRealPath("/static/temp");

        /**?**/
        File logoSaveFile = new File(logoRealPathDir);
        if (!logoSaveFile.exists())
            logoSaveFile.mkdirs();

        Long currentMillis = System.currentTimeMillis();

        String suffix = answerVO.getFile().getOriginalFilename()
                .substring(answerVO.getFile().getOriginalFilename().lastIndexOf("."));

        Answer answerObj = new Answer();

        String course = answerVO.getCourse();
        if (null != course) {
            course = org.apache.commons.lang3.StringUtils.replace(course, "<br/>", "");
            course = org.apache.commons.lang3.StringUtils.replace(course, " ", "");
        }

        answerObj.setTitle(answerVO.getTitle());
        answerObj.setCourse(course);
        answerObj.setAnswer(answerVO.getFile().getOriginalFilename());
        answerObj.setType(suffix);
        answerObj.setAnswerDate(new Date(currentMillis));

        User user = new User();
        user.setId(getCurrentUserId());

        answerObj.setUser(user);

        answerService.save(answerObj);

        String fileName = logoRealPathDir + File.separator + answerObj.getUser().getId() + "-"
                + answerObj.getAnswer();
        File file = new File(fileName);

        try {
            answerVO.getFile().transferTo(file);
        } catch (IOException e) {
            logger.warn("save file error!", e);
        }
        return "true";
    }

    /**
     * ?Shiro?Id.
     */
    private Long getCurrentUserId() {
        ShiroDbRealm.ShiroUser user = (ShiroDbRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal();
        return user.id;
    }

    /**
     * ?Shiro?Id.
     */
    private String getCurrentClassName() {
        ShiroDbRealm.ShiroUser user = (ShiroDbRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal();
        return user.className;
    }

}