vn.webapp.controller.cp.RegularTimetableController.java Source code

Java tutorial

Introduction

Here is the source code for vn.webapp.controller.cp.RegularTimetableController.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package vn.webapp.controller.cp;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
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 org.springframework.web.servlet.ModelAndView;

/**
 * Customize
 */
import vn.webapp.controller.BaseWeb;
import vn.webapp.dto.DataPage;
import vn.webapp.model.AcademicYear;
import vn.webapp.model.RegularCourse.*;
import vn.webapp.model.Rooms;
import vn.webapp.model.User;
import vn.webapp.service.AcademicYearService;
import vn.webapp.service.RegularCourse.*;
import vn.webapp.utilities.Normalization;
import vn.webapp.utilities.StringConvert;
import vn.webapp.service.RoomsService;
import vn.webapp.service.RoomClusterService;
import vn.webapp.service.UserService;
import vn.webapp.validation.FileValidation;
import vn.webapp.validation.RegularTimetableAddValidation;
import vn.webapp.validation.RegularTimetableEditValidation;
import vn.webapp.validation.RegularTimetableFromSISValidation;
import vn.webapp.validation.RegularTimetableValidation;
import java.util.ArrayList;
import java.util.Iterator;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

@Controller("cpRegularTimetable")
@RequestMapping(value = { "/cp" })
public class RegularTimetableController extends BaseWeb {

    @Autowired
    private UserService userService;

    @Autowired
    private AcademicYearService academicYearService;

    @Autowired
    private RoomsService roomsService;

    @Autowired
    private RoomClusterService roomClusterService;

    @Autowired
    private RegularCourseTimetableEntryService regularCourseTimetableEntryService;

    @Autowired
    private RegularCourseTimetableService regularCourseTimetableService;

    @Autowired
    private RegularCourseTimetableStatusService regularCourseTimetableStatusService;

    @Autowired
    private RegularCourseService regularCourseService;

    @Autowired
    private RegularCourseTimetableInterfaceService regularCourseTimetableInterfaceService;

    /**
     *
     * @param model
     * @return
     */

    @RequestMapping(value = "/RegularTimetables", method = RequestMethod.GET)
    public String RegularTimetables(ModelMap model, HttpSession session) {

        /*
         * Get current user name and role
         */
        String currentUserName = session.getAttribute("currentUserName").toString();
        String userRole = session.getAttribute("currentUserRole").toString();

        // Get list regulartimetables
        List<RegularCourseTimetableStatus> regularCourseTimetableStatusList = regularCourseTimetableStatusService
                .loadRCTTSList();

        /*
         * Put data back to view
         */
        model.put("regularCourseTimetableStatusList", regularCourseTimetableStatusList);
        return "cp.regularTimetables";
    }

    @RequestMapping(value = "/RegularTimetableDetail/{id}", method = RequestMethod.GET)
    public String RegularTimetableDetail(ModelMap model, @PathVariable("id") int Id, HttpSession session) {

        RegularCourseTimetableStatus RCTTS = regularCourseTimetableStatusService.loadByID(Id);
        List<RegularCourseTimetableInterface> RCTTI_List = regularCourseTimetableInterfaceService
                .loadRCTTIList(RCTTS.getRCTTS_AcaYear_Code(), RCTTS.getRCTTS_Semester());
        model.put("RCTTS_ID", Id);
        model.put("regularCourseTimetableInterfaceList", RCTTI_List);
        model.put("regularCourseTimetableStatus", RCTTS);

        return "cp.regularTimetableDetail";
    }

    @RequestMapping(value = "/AddARegularTimetable/{RCTTS_id}", method = RequestMethod.GET)
    public String RegularTimetableAddOne(ModelMap model, @PathVariable("RCTTS_id") int RCTTS_id,
            HttpSession session) {

        model.put("RCTTS_ID", RCTTS_id);
        model.put("RegularTimetableAddForm", new RegularTimetableAddValidation());
        model.put("regularCourseList", regularCourseService.listRegularCourse());
        model.put("roomsList", roomsService.listRooms());

        return "cp.addARegularTimetable";
    }

    @RequestMapping(value = "add-a-regulartimetable", method = RequestMethod.POST)
    public String saveARegularTimetable(HttpServletRequest request,
            @Valid @ModelAttribute("RegularTimetableAddForm") RegularTimetableAddValidation regularTimetableAddValidation,
            BindingResult result, Map model, HttpSession session) {

        if (result.hasErrors()) {
            model.put("RCTTS_ID", regularTimetableAddValidation.getRCTTS_ID());
            model.put("regularCourseList", regularCourseService.listRegularCourse());
            model.put("roomsList", roomsService.listRooms());
            return "cp.addARegularTimetable";
        } else {
            RegularCourseTimetableStatus RCTTS = regularCourseTimetableStatusService
                    .loadByID(regularTimetableAddValidation.getRCTTS_ID());
            RegularCourse RC = regularCourseService.loadByCode(regularTimetableAddValidation.getRC_Code());
            String RCTTE_Code = RCTTS.getRCTTS_AcaYear_Code() + "-" + RCTTS.getRCTTS_Semester() + "-"
                    + regularTimetableAddValidation.getClassCode();
            String RCTT_Code = RCTTE_Code + "-" + regularTimetableAddValidation.getDay();
            List<Integer> check = regularCourseTimetableService.CheckOK(RCTT_Code,
                    regularTimetableAddValidation.getDay(), regularTimetableAddValidation.getSlot(),
                    regularTimetableAddValidation.getSemesterType(), regularTimetableAddValidation.getRoomCode());
            int RCTT_ID = -1;
            if (check.isEmpty()) {//Khong co tiet trung            

                RegularCourseTimetableEntry RCTTE = regularCourseTimetableEntryService.loadRCTTEByCode(RCTTE_Code);
                if (RCTTE == null) {
                    int RCTTE_ID = regularCourseTimetableEntryService.save(RCTTS.getRCTTS_Semester(),
                            regularTimetableAddValidation.getClassCode(), RC, RCTTE_Code,
                            RCTTS.getRCTTS_AcaYear_Code(), regularTimetableAddValidation.getClassType(),
                            regularTimetableAddValidation.getSemesterType(),
                            regularTimetableAddValidation.getCheckSlots(),
                            regularTimetableAddValidation.getClassInfo(),
                            regularTimetableAddValidation.getCourseInfo(),
                            regularTimetableAddValidation.getClassStatus());
                    RCTTE = regularCourseTimetableEntryService.loadRCTTEByCode(RCTTE_Code);
                }
                model.put("regularCourseTimetableEntry", RCTTE);
                RCTT_ID = regularCourseTimetableService.save(regularTimetableAddValidation.getDay(),
                        regularTimetableAddValidation.getSlot(), regularTimetableAddValidation.getWeek(),
                        regularTimetableAddValidation.getRoomCode(), RCTTE);
                RegularCourseTimetable RCTT = regularCourseTimetableService.loadByID(RCTT_ID);
                model.put("regularCourseTimetable", RCTT);
                model.put("status", "Bn  thm thnh cng thng tin th?i kha biu");
                model.put("statusType", "success");
            } else if (check.contains(-1)) {
                model.put("status", "Lu khng thnh cng, c li xy ra");
                model.put("statusType", "danger");
            } else {
                String resultstatus = "Lu khng thnh cng, phng "
                        + regularTimetableAddValidation.getRoomCode() + " th "
                        + regularTimetableAddValidation.getDay() + " k "
                        + regularTimetableAddValidation.getSemesterType() + " b trng tit: ";
                for (int i : check) {
                    resultstatus += " " + i;
                }
                model.put("status", resultstatus);
                model.put("statusType", "danger");
            }

            model.put("RCTTS_ID", regularTimetableAddValidation.getRCTTS_ID());
            model.put("regularCourse", RC);
            model.put("regularCourseList", regularCourseService.listRegularCourse());
            model.put("roomsList", roomsService.listRooms());
            return "cp.addARegularTimetable";

        }
    }

    @RequestMapping(value = "/DeleteRegularCourseTimetable/{id}", method = RequestMethod.GET)
    public String DeleteRegularCourseTimetable(ModelMap model, @PathVariable("id") int Id, HttpSession session) {
        RegularCourseTimetableStatus rCTTS = regularCourseTimetableStatusService.loadByID(Id);
        String AcaYear = rCTTS.getRCTTS_AcaYear_Code();
        int semester = rCTTS.getRCTTS_Semester();
        regularCourseTimetableStatusService.remove(Id);
        List<RegularCourseTimetableStatus> rCTTSList = regularCourseTimetableStatusService.loadRCTTSList();
        model.put("regularCourseTimetableStatusList", rCTTSList);
        model.put("status", "? xa thnh cng th?i kha biu" + " h?c k "
                + Integer.toString(semester) + " nm h?c " + AcaYear);
        return "cp.regularTimetables";
    }

    @RequestMapping(value = "/RegularTimetableDelete/{RCTTS_id}/{id}", method = RequestMethod.GET)
    public String RegularTimetableDelete(ModelMap model, @PathVariable("RCTTS_id") int RCTTS_id,
            @PathVariable("id") int Id, HttpSession session) {
        RegularCourseTimetable RCTT = regularCourseTimetableService.loadByID(Id);
        int RCTTE_ID = RCTT.getRegularCourseTimetableEntry().getRCTTE_ID();
        String RCTTE_Code = RCTT.getRegularCourseTimetableEntry().getRCTTE_Code();
        regularCourseTimetableService.remove(Id);
        List<RegularCourseTimetable> listRCTT = new ArrayList<RegularCourseTimetable>();
        listRCTT = regularCourseTimetableService.loadByRCTTE(RCTTE_Code);
        if (listRCTT.isEmpty()) {
            regularCourseTimetableEntryService.remove(RCTTE_ID);
        }

        RegularCourseTimetableStatus RCTTS = regularCourseTimetableStatusService.loadByID(RCTTS_id);
        List<RegularCourseTimetableInterface> RCTTI_List = regularCourseTimetableInterfaceService
                .loadRCTTIList(RCTTS.getRCTTS_AcaYear_Code(), RCTTS.getRCTTS_Semester());
        model.put("RCTTS_ID", Id);
        model.put("regularCourseTimetableInterfaceList", RCTTI_List);
        model.put("regularCourseTimetableStatus", RCTTS);

        return "cp.regularTimetableDetail";
    }

    @RequestMapping(value = "/RegularTimetableEdit/{RCTTS_id}/{id}", method = RequestMethod.GET)
    public String RegularTimetableEdit(ModelMap model, @PathVariable("RCTTS_id") int RCTTS_id,
            @PathVariable("id") int Id, HttpSession session) {

        RegularCourseTimetable RCTT = regularCourseTimetableService.loadByID(Id);
        String[] tokens = RCTT.getRCTT_Code().split("-");
        String RCTTE_Code = tokens[0] + "-" + tokens[1] + "-" + tokens[2] + "-" + tokens[3];
        System.out.println(RCTTE_Code);
        RegularCourseTimetableEntry RCTTE = RCTT.getRegularCourseTimetableEntry();
        RegularCourse RC = RCTTE.getRegularCourse();

        model.put("RCTTS_ID", RCTTS_id);
        model.put("regularCourse", RC);
        model.put("regularCourseTimetableEntry", RCTTE);
        model.put("regularCourseTimetable", RCTT);
        model.put("RegularTimetableEditForm", new RegularTimetableEditValidation());
        model.put("roomsList", roomsService.listRooms());

        return "cp.regularTimetableEdit";
    }

    @RequestMapping(value = "/ListRegularTimetableInvalid/{RCTTS_id}", method = RequestMethod.GET)
    public String ListRegularTimetableInvalid(ModelMap model, @PathVariable("RCTTS_id") int RCTTS_id,
            HttpSession session) {

        RegularCourseTimetableStatus RCTTS = regularCourseTimetableStatusService.loadByID(RCTTS_id);
        List<RegularCourseTimetableInterface> RCTTI_List_temp = regularCourseTimetableInterfaceService
                .loadRCTTIList(RCTTS.getRCTTS_AcaYear_Code(), RCTTS.getRCTTS_Semester());
        List<RegularCourseTimetableInterface> RCTTI_List = new ArrayList<RegularCourseTimetableInterface>();
        for (RegularCourseTimetableInterface RCTTI : RCTTI_List_temp) {
            RegularCourseTimetable RCTT = regularCourseTimetableService.loadByID(RCTTI.getId());
            List<Integer> check = regularCourseTimetableService.CheckOK(RCTT.getRCTT_Code(), RCTT.getRCTT_Day(),
                    RCTT.getRCTT_Slots(), RCTT.getRegularCourseTimetableEntry().getRCTTE_Semester_Type(),
                    RCTT.getRCTT_Room_Code());
            int RCTT_ID = -1;
            if (!check.isEmpty()) {
                if (check.contains(-1)) {
                    RCTTI.setStatus("C li v? d liu");
                    RCTTI_List.add(RCTTI);
                } else {
                    String resultstatus = "Phng " + RCTT.getRCTT_Room_Code() + " th " + RCTT.getRCTT_Day()
                            + " k " + RCTT.getRegularCourseTimetableEntry().getRCTTE_Semester_Type()
                            + " b trng tit: ";
                    for (int i : check) {
                        resultstatus += " " + i;
                    }
                    RCTTI.setStatus(resultstatus);
                    RCTTI_List.add(RCTTI);
                }
            }
        }

        model.put("RCTTS_ID", RCTTS_id);
        model.put("regularCourseTimetableInterfaceList", RCTTI_List);
        model.put("regularCourseTimetableStatus", RCTTS);

        return "cp.regularTimetableInvalidList";
    }

    @RequestMapping(value = "/OverlapRoomList", method = RequestMethod.POST)
    public String OverlapRoomList(HttpServletRequest request,
            @Valid @ModelAttribute("checkOverLapFromExcel") FileValidation fileValidation, BindingResult result,
            Map model, HttpSession session) {
        /*
         * Get list of paper category and journalList
         */
        List<AcademicYear> academicYearList = academicYearService.list();
        model.put("academicYearList", academicYearList);

        /*
         * Put data back to view
         */
        if (result.hasErrors()) {
            return "cp.checkOverlapRoomFromExcel";
        } else {
            /*
             * Prepare data for inserting DB
             */

            /**
             * Uploading file
             */
            MultipartFile sourceUploadFile = fileValidation.getFileUpload();
            String fileName = sourceUploadFile.getOriginalFilename();
            String sourceUploadFileSrc = "";
            try {
                //Creating Date in java with today's date.
                Date currentDate = new Date();
                //change date into string yyyyMMdd format example "20110914"
                SimpleDateFormat dateformatyyyyMMdd = new SimpleDateFormat("HHmmssddMMyyyy");
                String sCurrentDate = dateformatyyyyMMdd.format(currentDate);

                byte[] bytes = sourceUploadFile.getBytes();
                String path = request.getServletContext().getRealPath("uploads");
                File dir = new File(path + "/regularTimetables");
                if (!dir.exists()) {
                    dir.mkdirs();
                }

                // Create a file
                String currentUserName = session.getAttribute("currentUserName").toString();
                fileName = currentUserName + "_" + sCurrentDate + "_" + fileName;
                File serverFile = new File(dir.getAbsolutePath() + File.separator + fileName);
                if (serverFile.exists()) {
                    sourceUploadFileSrc = dir.getAbsolutePath() + File.separator + fileName;
                }
                // Save data into file
                BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
                stream.write(bytes);
                stream.close();
                boolean isToAdd = true;
                ArrayList<OverlapRoom> overlapRooms = ReadTimeTableExcelFormat2
                        .CheckOverlap(dir.getAbsolutePath() + File.separator + fileName);
                System.out.println(overlapRooms);
                model.put("overlapRoomList", overlapRooms);
            } catch (Exception e) {
                e.printStackTrace();
                model.put("status", "You failed to upload " + fileName + " => " + e.getMessage());
            }

            return "cp.overlapRoomList";
        }
    }

    @RequestMapping(value = "edit-a-regulartimetable", method = RequestMethod.POST)
    public String saveRegularTimetable(HttpServletRequest request,
            @Valid @ModelAttribute("RegularTimetableEditForm") RegularTimetableEditValidation regularTimetableEditValidation,
            BindingResult result, Map model, HttpSession session) {

        if (result.hasErrors()) {
            return "cp.regularTimetableEdit";
        } else {
            RegularCourseTimetable RCTTtemp = regularCourseTimetableService
                    .loadByID(regularTimetableEditValidation.getRCTT_ID());
            RegularCourseTimetableEntry RCTTEtemp = RCTTtemp.getRegularCourseTimetableEntry();
            RegularCourse RC = RCTTEtemp.getRegularCourse();
            int RCTTE_ID = RCTTEtemp.getRCTTE_ID();
            List<Integer> check = regularCourseTimetableService.CheckOK(RCTTtemp.getRCTT_Code(),
                    regularTimetableEditValidation.getDay(), regularTimetableEditValidation.getSlot(),
                    RCTTEtemp.getRCTTE_Semester_Type(), regularTimetableEditValidation.getRoomCode());
            if (check.isEmpty()) {
                regularCourseTimetableEntryService.edit(RCTTE_ID, RCTTEtemp.getRCTTE_Semester(),
                        RCTTEtemp.getRCTTE_Class_Code(), RC, RCTTEtemp.getRCTTE_Code(),
                        RCTTEtemp.getRCTTE_AcaYear_Code(), RCTTEtemp.getRCTTE_Class_Type(),
                        regularTimetableEditValidation.getSemesterType(), "",
                        regularTimetableEditValidation.getClassInfo(),
                        regularTimetableEditValidation.getCourseInfo(),
                        regularTimetableEditValidation.getClassStatus());
                RegularCourseTimetableEntry RCTTE = regularCourseTimetableEntryService.loadByID(RCTTE_ID);
                regularCourseTimetableService.edit(RCTTtemp.getRCTT_ID(), regularTimetableEditValidation.getDay(),
                        regularTimetableEditValidation.getSlot(), regularTimetableEditValidation.getWeek(),
                        regularTimetableEditValidation.getRoomCode(), RCTTE);
                model.put("status", "Bn  sa i thnh cng thng tin th?i kha biu");
                model.put("statusType", "success");
            } else if (check.contains(-1)) {
                model.put("status", "Lu khng thnh cng, c li xy ra");
                model.put("statusType", "danger");
            } else {
                String resultstatus = "Lu khng thnh cng, phng "
                        + regularTimetableEditValidation.getRoomCode() + " th "
                        + regularTimetableEditValidation.getDay() + " k " + RCTTEtemp.getRCTTE_Semester()
                        + " b trng tit: ";
                for (int i : check) {
                    resultstatus += " " + i;
                }
                model.put("status", resultstatus);
            }

            RegularCourseTimetable RCTT = regularCourseTimetableService
                    .loadByID(regularTimetableEditValidation.getRCTT_ID());
            RegularCourseTimetableEntry RCTTE = regularCourseTimetableEntryService.loadByID(RCTTE_ID);

            model.put("RCTTS_ID", regularTimetableEditValidation.getRCTTS_ID());
            model.put("regularCourse", RC);
            model.put("regularCourseTimetableEntry", RCTTE);
            model.put("regularCourseTimetable", RCTT);
            model.put("roomsList", roomsService.listRooms());

            return "cp.regularTimetableEdit";

        }
    }

    @RequestMapping(value = "/CheckSlotNum/{id}", method = RequestMethod.GET)
    public String CheckSlotNum(ModelMap model, @PathVariable("id") int Id, HttpSession session) {

        RegularCourseTimetableStatus RCTTS = regularCourseTimetableStatusService.loadByID(Id);
        List<RegularCourseTimetableInterface> RCTTI_List = regularCourseTimetableInterfaceService
                .loadRCTTIList(RCTTS.getRCTTS_AcaYear_Code(), RCTTS.getRCTTS_Semester());

        List<RegularCourseTimetableEntry> RCTTE_List = regularCourseTimetableEntryService
                .loadRCTTEList(RCTTS.getRCTTS_AcaYear_Code(), RCTTS.getRCTTS_Semester());

        List<RegularCourseTimetableEntryWrapper> failed_RCTTEW_List = new ArrayList<RegularCourseTimetableEntryWrapper>();

        StringConvert strConv = new StringConvert();
        Normalization norm = new Normalization();

        for (RegularCourseTimetableEntry RCTTE : RCTTE_List) {
            System.out.println(RCTTE.getRCTTE_Class_Code());
            String creditHourStr = RCTTE.regularCourse.getRC_CreditHour();
            System.out.println(creditHourStr);
            creditHourStr = creditHourStr.replace(",", ".");
            String[] tokens = creditHourStr.split("[(-]");
            int creditHour = 0;
            int experHour = 0;
            try {
                if (Integer.parseInt(tokens[0]) == 0)
                    continue;
            } catch (NumberFormatException e) {
                System.out.println(
                        "Lp " + RCTTE.getRCTTE_Class_Code() + " khng c thng tin v? khi lng");
            }
            try {
                switch (RCTTE.getRCTTE_Class_Type()) {
                case "LT":
                    creditHour = Integer.parseInt(tokens[1]);
                    experHour = Integer.parseInt(tokens[3]);
                    break;
                case "BT":
                    creditHour = Integer.parseInt(tokens[2]);
                    experHour = Integer.parseInt(tokens[3]);
                    break;
                default:
                    creditHour = Integer.parseInt(tokens[1]) + Integer.parseInt(tokens[2]);
                    experHour = Integer.parseInt(tokens[3]);
                    break;
                }
            } catch (NumberFormatException e) {
                try {

                    creditHour = (int) (Float.parseFloat(tokens[1]) + Float.parseFloat(tokens[2]));
                    experHour = (int) Float.parseFloat(tokens[3]);
                } catch (Exception ef) {
                    System.out.println("Khng r thng tin khi lng ca lp "
                            + RCTTE.getRCTTE_Class_Code() + ": " + RCTTE.getRegularCourse().getRC_CreditHour());
                    creditHour = 0;
                    experHour = 0;
                }
            }

            //System.out.println(creditHourStr +": "+ creditHour);
            int arrangedHour = 0;
            List<RegularCourseTimetable> RCTT_List = new ArrayList<RegularCourseTimetable>();

            for (RegularCourseTimetableInterface RCTTI : RCTTI_List) {
                if (!RCTTI.getClasscode().equals(RCTTE.getRCTTE_Class_Code()))
                    continue;
                RegularCourseTimetable RCTT = new RegularCourseTimetable();
                RCTT.setRCTT_Day(RCTTI.getDay());
                RCTT.setRCTT_ID(RCTTI.getId());
                RCTT.setRCTT_Room_Code(RCTTI.getRoom());
                RCTT.setRCTT_Slots(RCTTI.getSlot());
                RCTT.setRCTT_Weeks(RCTTI.getWeek());
                RCTT.setRegularCourseTimetableEntry(RCTTE);
                RCTT_List.add(RCTT);
                String normSlot = norm.SlotNormalize(RCTTI.getSlot());
                if (normSlot != null)
                    arrangedHour += strConv.ExpandToListString(normSlot).size();
            }
            if (RCTT_List.size() == 0) {
                System.out.println("Lp " + RCTTE.getRCTTE_Class_Code() + "cha c xp lp no");
            }
            RCTTE.setListRegularCourseTimetable(RCTT_List);
            // Double the number of slots for half-semester classes
            try {
                String weeks = RCTTE.getListRegularCourseTimetable().get(0).getRCTT_Weeks();
                int weekNum = strConv.ExpandToListString(weeks).size();
                if (weekNum == 5)
                    creditHour *= 3;
                else if (weekNum == 8)
                    creditHour *= 2;
            } catch (Exception e) {
                arrangedHour = 0;
            }

            // If not enough number of arranged slots for the class RCTTE
            if (creditHour != arrangedHour) {
                RegularCourseTimetableEntryWrapper rCTTEW = new RegularCourseTimetableEntryWrapper();
                rCTTEW.setArrangedSlotNum(arrangedHour);
                rCTTEW.setListRegularCourseTimetable(RCTTE.getListRegularCourseTimetable());
                rCTTEW.setRCTTE_AcaYear_Code(RCTTE.getRCTTE_AcaYear_Code());
                rCTTEW.setRCTTE_Class_Code(RCTTE.getRCTTE_Class_Code());
                rCTTEW.setRCTTE_Class_Type(RCTTE.getRCTTE_Class_Type());
                rCTTEW.setRCTTE_Code(RCTTE.getRCTTE_Code());
                rCTTEW.setRCTTE_ID(RCTTE.getRCTTE_ID());
                rCTTEW.setRCTTE_Semester(RCTTE.getRCTTE_Semester());
                rCTTEW.setRCTTE_Semester_Type(RCTTE.getRCTTE_Semester_Type());
                rCTTEW.setRegularCourse(RCTTE.getRegularCourse());
                rCTTEW.setRequiredSlotNum(creditHour);
                if (creditHour > arrangedHour)
                    rCTTEW.setStatus("Thiu " + (creditHour - arrangedHour));
                else
                    rCTTEW.setStatus("Tha " + (arrangedHour - creditHour));
                failed_RCTTEW_List.add(rCTTEW);
            }
        }

        model.put("failedRegularCourseTimetableEntryList", failed_RCTTEW_List);
        model.put("regularCourseTimetableStatus", RCTTS);
        model.put("status",
                "Kt qu ny b? qua cc lp h?c i?u kin c s lng tn ch bng khng nh MIL1130 0(3-0-2-8) QS chung v KCT bn sng AK v PE1030 0(0-0-2-0) Gio dc th cht C");
        // System.exit(-1);
        return "cp.failedRegularCourseTimetableEntryList";
    }

    @RequestMapping(value = "/AddRegularTimetable", method = RequestMethod.GET)
    public String AddRegularTimetable(ModelMap model, HttpSession session) {

        /*
         * Get current user name and role
         */
        String currentUserName = session.getAttribute("currentUserName").toString();
        String userRole = session.getAttribute("currentUserRole").toString();

        // Get list reportingYear
        List<AcademicYear> academicYearList = academicYearService.list();
        AcademicYear curAcadYear = academicYearService.getCurAcadYear();
        List<AcademicYear> otherAcadYearList = new ArrayList<AcademicYear>();
        for (AcademicYear aY : academicYearList) {
            if (!aY.getACAYEAR_Code().equals(curAcadYear.getACAYEAR_Code()))
                otherAcadYearList.add(aY);
        }
        /*
         * Put data back to view
         */
        model.put("academicYearList", otherAcadYearList);
        model.put("curAcadYear", curAcadYear);
        model.put("regularTimetableFormAdd", new RegularTimetableValidation());

        return "cp.addRegularTimetable";
    }

    @RequestMapping(value = "/AddRegularTimetableFromSIS", method = RequestMethod.GET)
    public String AddRegularTimetableFromSIS(ModelMap model, HttpSession session) {

        /*
         * Get current user name and role
         */
        String currentUserName = session.getAttribute("currentUserName").toString();
        String userRole = session.getAttribute("currentUserRole").toString();

        // Get list reportingYear
        List<AcademicYear> academicYearList = academicYearService.list();
        AcademicYear curAcadYear = academicYearService.getCurAcadYear();
        List<AcademicYear> otherAcadYearList = new ArrayList<AcademicYear>();
        for (AcademicYear aY : academicYearList) {
            if (!aY.getACAYEAR_Code().equals(curAcadYear.getACAYEAR_Code()))
                otherAcadYearList.add(aY);
        }
        /*
         * Put data back to view
         */
        model.put("academicYearList", otherAcadYearList);
        model.put("curAcadYear", curAcadYear);
        model.put("regularTimetableFormAdd", new RegularTimetableFromSISValidation());

        return "cp.addRegularTimetableFromSIS";
    }

    @RequestMapping(value = "/CheckSlotNumFromExcelFile", method = RequestMethod.POST)
    public String checkSlotNumFromExcelFile(HttpServletRequest request,
            @Valid @ModelAttribute("checkSlotNumFromExcel") FileValidation fileValidation, BindingResult result,
            Map model, HttpSession session) {
        /*
         * Get list of paper category and journalList
         */
        List<AcademicYear> academicYearList = academicYearService.list();
        model.put("academicYearList", academicYearList);

        /*
         * Put data back to view
         */
        if (result.hasErrors()) {
            return "cp.checkSlotNumFromExcel";
        } else {
            /*
             * Prepare data for inserting DB
             */

            /**
             * Uploading file
             */
            MultipartFile sourceUploadFile = fileValidation.getFileUpload();
            String fileName = sourceUploadFile.getOriginalFilename();
            String sourceUploadFileSrc = "";
            try {
                //Creating Date in java with today's date.
                Date currentDate = new Date();
                //change date into string yyyyMMdd format example "20110914"
                SimpleDateFormat dateformatyyyyMMdd = new SimpleDateFormat("HHmmssddMMyyyy");
                String sCurrentDate = dateformatyyyyMMdd.format(currentDate);

                byte[] bytes = sourceUploadFile.getBytes();
                String path = request.getServletContext().getRealPath("uploads");
                File dir = new File(path + "/regularTimetables");
                if (!dir.exists()) {
                    dir.mkdirs();
                }

                // Create a file
                String currentUserName = session.getAttribute("currentUserName").toString();
                fileName = currentUserName + "_" + sCurrentDate + "_" + fileName;
                File serverFile = new File(dir.getAbsolutePath() + File.separator + fileName);
                if (serverFile.exists()) {
                    sourceUploadFileSrc = dir.getAbsolutePath() + File.separator + fileName;
                }
                // Save data into file
                BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
                stream.write(bytes);
                stream.close();
                boolean isToAdd = true;
                ReadTimeTableExcelFormat2 obj = new ReadTimeTableExcelFormat2();
                obj.readFileExcel(dir.getAbsolutePath() + File.separator + fileName);
                ArrayList<ClassRoomWrapper> invalidSlotNumList = obj.invalidSlotNumList;
                model.put("invalidSlotNumList", invalidSlotNumList);
                System.out.println(invalidSlotNumList.size());
            } catch (Exception e) {
                e.printStackTrace();
                model.put("status", "You failed to upload " + fileName + " => " + e.getMessage());
            }

            return "cp.invalidSlotNumList";
        }
    }

    @RequestMapping(value = "/CheckSlotNumFromExcel", method = RequestMethod.GET)
    public String checkSlotNumFromExcel(ModelMap model, HttpSession session) {

        /*
         * Get current user name and role
         */
        String currentUserName = session.getAttribute("currentUserName").toString();
        String userRole = session.getAttribute("currentUserRole").toString();

        model.put("checkSlotNumFromExcel", new FileValidation());

        return "cp.checkSlotNumFromExcel";
    }

    @RequestMapping(value = "/CheckOverlapRoomFromExcel", method = RequestMethod.GET)
    public String checkOverlapRoomFromExcel(ModelMap model, HttpSession session) {

        /*
         * Get current user name and role
         */
        String currentUserName = session.getAttribute("currentUserName").toString();
        String userRole = session.getAttribute("currentUserRole").toString();

        model.put("checkOverlapRoomFromExcel", new FileValidation());

        return "cp.checkOverlapRoomFromExcel";
    }

    @RequestMapping(value = "saveRegularTimetableFromSIS", method = RequestMethod.POST)
    public String saveRegularTimetableFromSIS(HttpServletRequest request,
            @Valid @ModelAttribute("regularTimetableFormAdd") RegularTimetableFromSISValidation regularTimetableFromSISValidation,
            BindingResult result, Map model, HttpSession session) {
        /*
         * Get list of paper category and journalList
         */
        List<AcademicYear> academicYearList = academicYearService.list();
        model.put("academicYearList", academicYearList);

        /*
         * Put data back to view
         */
        if (result.hasErrors()) {
            return "cp.addRegularTimetable";
        } else {
            try {

                List<RegularCourseTimetableStatus> RCTTS_List = regularCourseTimetableStatusService.loadRCTTSList();
                boolean isToAdd = true;
                for (RegularCourseTimetableStatus RCTTS : RCTTS_List) {
                    if ((RCTTS.getRCTTS_AcaYear_Code().equals(regularTimetableFromSISValidation.getAcademicYear()))
                            && (RCTTS.getRCTTS_Semester() == regularTimetableFromSISValidation.getSemester())) {
                        isToAdd = false;
                        break;
                    }
                }

                if (isToAdd)
                    regularCourseTimetableStatusService.save(regularTimetableFromSISValidation.getAcademicYear(),
                            regularTimetableFromSISValidation.getSemester(), 1);
                String[] tks = regularTimetableFromSISValidation.getAcademicYear().split("-");
                ReadTimeTableExcel readTimeTableExcel = new ReadTimeTableExcel();
                ArrayList<ClassRoom> classRooms = new ArrayList<ClassRoom>();

                String slotNum = "";
                String classCode = "";
                String courseCode = "";
                String dayStr = "";
                int startingSlot = 0;
                int endingSlot = 0;
                String secsion = "";
                String slots = "";
                String weeks = "";
                String roomName = "";
                String semesterType = "";
                String courseName = "";
                String facultyCode = "";
                String classType = "";
                String classInfo = "";
                String courseInfo = "";
                String classStatus = "";

                Connector cn = new Connector();
                String jsonPath = "http://127.0.0.1:9876/getTimeTable?term=" + tks[0]
                        + regularTimetableFromSISValidation.getSemester();
                String json = cn.getJson(jsonPath);
                System.out.println(json);
                if (json != "") {
                    json = "{ classes : " + json + "}";
                    //System.out.println(json);
                    try {
                        JSONObject obj = new JSONObject(json);
                        JSONArray classes = obj.getJSONArray("classes");

                        for (int i = 0; i < classes.length(); ++i) {
                            try {
                                JSONObject clss = classes.getJSONObject(i);
                                roomName = clss.getString("RoomName");
                                slotNum = clss.getString("LoadHoursCode");
                                classCode = Integer.toString(clss.getInt("ClassID"));
                                courseCode = clss.getString("CourseID");
                                courseName = clss.getString("Name");
                                facultyCode = clss.getString("AcademicUnitID");
                                dayStr = clss.getString("Weekday");
                                classType = clss.getString("SectionType");
                                weeks = clss.getString("WeekNote");
                                semesterType = "";
                                slots = clss.getString("TimeExp");
                                ///////CN CP NHT!!!!////
                                classInfo = "";
                                courseInfo = "";
                                classStatus = "";
                            } catch (NumberFormatException e) {
                                slots = "NULL";
                            } catch (Exception e) {
                                roomName = "null";
                            }
                            if (roomName == "null")
                                continue;
                            ClassRoom objClass = new ClassRoom(slotNum, classCode, courseCode, courseName, dayStr,
                                    slots, weeks, roomName, semesterType, facultyCode, classType, classInfo,
                                    courseInfo, classStatus);
                            classRooms.add(objClass);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                //= readTimeTableExcel.readFileExcel(dir.getAbsolutePath()+ File.separator + fileName);
                /*for(ClassRoom classroom: classRooms){
                      System.out.println(classroom.getWeeks()+ "  " + classroom.getSlots());
                      }*/

                System.out.println("S lp: " + classRooms.size());

                int err = 0;
                int rc = 0;
                int rctte = 0;
                ArrayList<String> error1 = new ArrayList<String>();
                ArrayList<String> error2 = new ArrayList<String>();
                ArrayList<String> error3 = new ArrayList<String>();
                ArrayList<String> error4 = new ArrayList<String>();
                int cnt = 0;
                String StatusMessages = "";
                for (ClassRoom classroom : classRooms) {
                    cnt++;
                    System.out.println(cnt + ":" + classroom.getClassCode());
                    try {
                        String roomCode = classroom.getRoom();
                        String note = "";
                        String roomBuilding = "";
                        int clusterID = 5;
                        int cap = -1;
                        int floor = 0;
                        Rooms room = roomsService.loadByCode(roomCode);
                        if (room == null) {
                            String[] tokens = roomCode.split("-");
                            for (int i = 1; i < tokens.length - 1; i++)
                                tokens[0] += "-" + tokens[i];
                            switch (tokens[0]) {
                            case "D3":
                            case "D5":
                            case "D3-5":
                            case "D7":
                            case "D9":
                                clusterID = 1;
                                break;
                            case "D4":
                            case "D6":
                                clusterID = 2;
                                break;
                            case "TC":
                                clusterID = 3;
                                break;
                            case "T":
                                clusterID = 4;
                                break;
                            default:
                                clusterID = 5;
                                break;
                            }
                            roomBuilding = tokens[0];
                            try {
                                floor = Integer.parseInt(tokens[tokens.length - 1].substring(0, 1));
                            } catch (NumberFormatException e) {
                                floor = -1;
                            }
                            if (roomsService.save(roomCode, roomBuilding, cap, note, floor,
                                    roomClusterService.loadByCode(clusterID)) != 0) {
                                room = roomsService.loadByCode(roomCode);
                                StatusMessages += "<b>Cp nht thm phng: </b>" + room.getR_Code() + "<br/>";
                            } else {
                                err++;
                                error4.add(
                                        classroom.getClassCode() + ": cannot find or add " + classroom.getRoom());
                            }
                        }
                        if (room != null) {
                            //System.out.println(classroom.getClassCode()+" "+classroom.getCourseCode()+" "+classroom.getDay()+" "+classroom.getRoom()+" "+classroom.getSemesterType()+" "+classroom.getSlotNum()+" "+classroom.getSlots()+" "+classroom.getWeeks()); 
                            String tempRCTTECode = regularTimetableFromSISValidation.getAcademicYear() + "-"
                                    + regularTimetableFromSISValidation.getSemester() + "-"
                                    + classroom.getClassCode();
                            RegularCourse RC = regularCourseService.loadByCode(classroom.getCourseCode());
                            if (RC == null) {
                                rc++;
                                if (regularCourseService.save(classroom.getCourseCode(), classroom.getCourseName(),
                                        classroom.getSlotNum(), classroom.getFacultyCode()) == 0) {

                                    err++;
                                    error1.add(classroom.getCourseCode());
                                }
                                RC = regularCourseService.loadByCode(classroom.getCourseCode());
                            }

                            RegularCourseTimetableEntry rCTTE = regularCourseTimetableEntryService
                                    .loadRCTTEByCode(tempRCTTECode);

                            if (rCTTE == null) {
                                rctte++;
                                if (regularCourseTimetableEntryService.save(
                                        regularTimetableFromSISValidation.getSemester(), classroom.getClassCode(),
                                        RC, tempRCTTECode, regularTimetableFromSISValidation.getAcademicYear(),
                                        classroom.getClassType(), classroom.getSemesterType(), "",
                                        classroom.getClassInfo(), classroom.getCourseInfo(),
                                        classroom.getClassStatus()) == 0) {
                                    err++;
                                    error2.add(classroom.getClassCode());
                                } else {
                                    rCTTE = regularCourseTimetableEntryService.loadRCTTEByCode(tempRCTTECode);
                                }
                            }
                            int day = 0;
                            try {
                                day = Integer.parseInt(classroom.getDay());
                            } catch (NumberFormatException e) {
                                day = 0;
                            }
                            //System.out.println(classroom.getCourseCode() + " "+ classroom.getSlotNum());
                            RegularCourseTimetable rCTT = regularCourseTimetableService
                                    .loadByCode(rCTTE.getRCTTE_Code() + "-" + day);
                            if (rCTT == null) {
                                if (regularCourseTimetableService.save(day, classroom.getSlots(),
                                        classroom.getWeeks(), room.getR_Code(), rCTTE) == 0) {
                                    err++;
                                    error3.add(classroom.getCourseCode() + " " + classroom.getClassCode() + " "
                                            + classroom.getDay());
                                } else {
                                    rCTT = regularCourseTimetableService
                                            .loadByCode(rCTTE.getRCTTE_Code() + "-" + day);
                                    StatusMessages += "<b>Thm mi lp " + rCTTE.getRCTTE_Class_Code()
                                            + ": </b><br/>" + "Tit " + rCTT.getRCTT_Slots() + " Th "
                                            + rCTT.getRCTT_Day() + " Tun " + rCTT.getRCTT_Weeks() + " Phng "
                                            + rCTT.getRCTT_Room_Code() + "<br/>";
                                    System.out.println("Thm mi lp" + rCTTE.getRCTTE_Class_Code());
                                }
                            } else {
                                if (!((rCTT.getRCTT_Day() == day)
                                        && (rCTT.getRCTT_Slots().equals(classroom.getSlots()))
                                        && (rCTT.getRCTT_Weeks().equals(classroom.getWeeks()))
                                        && (rCTT.getRCTT_Room_Code().equals(classroom.getRoom())))) {
                                    regularCourseTimetableService.edit(rCTT.getRCTT_ID(), day, classroom.getSlots(),
                                            classroom.getWeeks(), room.getR_Code(), rCTTE);
                                    StatusMessages += "<b>Cp nht li lp " + rCTTE.getRCTTE_Class_Code()
                                            + ": </b><br/>" + "Tit " + rCTT.getRCTT_Slots() + " Th "
                                            + rCTT.getRCTT_Day() + " Tun " + rCTT.getRCTT_Weeks() + " Phng "
                                            + rCTT.getRCTT_Room_Code() + "<br/>";
                                    rCTT = regularCourseTimetableService
                                            .loadByCode(rCTTE.getRCTTE_Code() + "-" + day);
                                    StatusMessages += "===> Tit " + rCTT.getRCTT_Slots() + " Th "
                                            + rCTT.getRCTT_Day() + " Tun " + rCTT.getRCTT_Weeks() + " Phng "
                                            + rCTT.getRCTT_Room_Code() + "<br/>";
                                    System.out.println("Cp nht li lp " + rCTTE.getRCTTE_Class_Code());
                                }
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        System.out.println("M lp: " + classroom.getClassCode()
                                + " li khng nhp c d liu!");
                    }

                }
                System.out.println(err + "");
                System.out.println("RC = " + rc);
                System.out.println("error1:");
                for (String s : error1) {
                    System.out.println(s);
                }
                System.out.println("RCTTE = " + rctte);
                System.out.println("error2:");
                for (String s : error2) {
                    System.out.println(s);
                }
                System.out.println("RCTT = " + classRooms.size());
                System.out.println("error3:");
                for (String s : error3) {
                    System.out.println(s);
                }
                System.out.println("error4:");
                for (String s : error4) {
                    System.out.println(s);
                }
                model.put("status", StatusMessages);

                //return "redirect:" + this.baseUrl + "/cp/RegularTimetables.html";

            } catch (Exception e) {
                e.printStackTrace();
                // model.put("status", "You failed to upload " + fileName + " => " + e.getMessage());
            }

            return "cp.addRegularTimetableFromSIS";
        }
    }

    /**
     * Save a paper
     * @param paperValid
     * @param result
     * @param model
     * @param session
     * @return String
     */
    @RequestMapping(value = "saveRegularTimetable", method = RequestMethod.POST)
    public String saveRegularTimetable(HttpServletRequest request,
            @Valid @ModelAttribute("regularTimetableFormAdd") RegularTimetableValidation regularTimetableValidation,
            BindingResult result, Map model, HttpSession session) {
        List<AcademicYear> academicYearList = academicYearService.list();
        model.put("academicYearList", academicYearList);

        if (result.hasErrors()) {
            return "cp.addRegularTimetable";
        } else {
            /**
             * Uploading file
             */
            MultipartFile sourceUploadFile = regularTimetableValidation.getRegularTimetableFileUpload();
            String fileName = sourceUploadFile.getOriginalFilename();
            String sourceUploadFileSrc = "";
            try {
                //Creating Date in java with today's date.
                Date currentDate = new Date();
                //change date into string yyyyMMdd format example "20110914"
                SimpleDateFormat dateformatyyyyMMdd = new SimpleDateFormat("HHmmssddMMyyyy");
                String sCurrentDate = dateformatyyyyMMdd.format(currentDate);

                byte[] bytes = sourceUploadFile.getBytes();
                String path = request.getServletContext().getRealPath("uploads");
                File dir = new File(path + "/regularTimetables");
                if (!dir.exists()) {
                    dir.mkdirs();
                }

                // Create a file
                String currentUserName = session.getAttribute("currentUserName").toString();
                fileName = currentUserName + "_" + sCurrentDate + "_" + fileName;
                File serverFile = new File(dir.getAbsolutePath() + File.separator + fileName);
                if (serverFile.exists()) {
                    sourceUploadFileSrc = dir.getAbsolutePath() + File.separator + fileName;
                }
                // Save data into file
                BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
                stream.write(bytes);
                stream.close();
                List<RegularCourseTimetableStatus> RCTTS_List = regularCourseTimetableStatusService.loadRCTTSList();
                boolean isToAdd = true;
                for (RegularCourseTimetableStatus RCTTS : RCTTS_List) {
                    if ((RCTTS.getRCTTS_AcaYear_Code().equals(regularTimetableValidation.getAcademicYear()))
                            && (RCTTS.getRCTTS_Semester() == regularTimetableValidation.getSemester())) {
                        isToAdd = false;
                        break;
                    }
                }
                if (isToAdd)
                    regularCourseTimetableStatusService.save(regularTimetableValidation.getAcademicYear(),
                            regularTimetableValidation.getSemester(), 1);
                ArrayList<ClassRoom> classRooms = ReadTimeTableExcel
                        .readFileExcel(dir.getAbsolutePath() + File.separator + fileName);

                int err = 0;
                int rc = 0;
                int rctte = 0;
                ArrayList<String> error1 = new ArrayList<String>();
                ArrayList<String> error2 = new ArrayList<String>();
                ArrayList<String> error3 = new ArrayList<String>();
                ArrayList<String> error4 = new ArrayList<String>();
                int cnt = 0;
                String StatusMessages = "";

                try (DataOutputStream out = new DataOutputStream(
                        new FileOutputStream("regularTimeTableUploadStatus.bin", false))) {
                    out.writeInt(classRooms.size());

                    for (ClassRoom classroom : classRooms) {
                        cnt++;
                        out.writeInt(cnt);
                        System.out.println(cnt + ":" + classroom.getClassCode());
                        try {
                            String roomCode = classroom.getRoom();
                            String note = "";
                            String roomBuilding = "";
                            int clusterID = 5;
                            int cap = -1;
                            int floor = 0;
                            Rooms room = roomsService.loadByCode(roomCode);
                            if (room == null) {
                                String[] tokens = roomCode.split("-");
                                for (int i = 1; i < tokens.length - 1; i++)
                                    tokens[0] += "-" + tokens[i];
                                switch (tokens[0]) {
                                case "D3":
                                case "D5":
                                case "D3-5":
                                case "D3,5":
                                case "D7":
                                case "D9":
                                    clusterID = 1;
                                    break;
                                case "D4":
                                case "D6":
                                    clusterID = 2;
                                    break;
                                case "TC":
                                    clusterID = 3;
                                    break;
                                case "T":
                                    clusterID = 4;
                                    break;
                                default:
                                    clusterID = 5;
                                    break;
                                }
                                roomBuilding = tokens[0];
                                try {
                                    floor = Integer.parseInt(tokens[tokens.length - 1].substring(0, 1));
                                } catch (NumberFormatException e) {
                                    floor = -1;
                                }
                                if (roomsService.save(roomCode, roomBuilding, cap, note, floor,
                                        roomClusterService.loadByCode(clusterID)) != 0) {
                                    room = roomsService.loadByCode(roomCode);
                                    StatusMessages += "<b>Cp nht thm phng: </b>" + room.getR_Code()
                                            + "<br/>";
                                } else {
                                    err++;
                                    error4.add(classroom.getClassCode() + ": cannot find or add "
                                            + classroom.getRoom());
                                }
                            }
                            /*      List<RegularCourseTimetableInterface> RCTTI_List = regularCourseTimetableInterfaceService.loadRCTTIList(regularTimetableValidation.getAcademicYear(),regularTimetableValidation.getSemester());
                            HashSet<String> classCodeSet=new HashSet<String>();
                            for(RegularCourseTimetableInterface rCTTI:RCTTI_List){
                             classCodeSet.add(rCTTI.getClasscode());
                            }
                             */
                            if (room != null) {
                                String tempRCTTECode = regularTimetableValidation.getAcademicYear() + "-"
                                        + regularTimetableValidation.getSemester() + "-" + classroom.getClassCode();
                                RegularCourse RC = regularCourseService.loadByCode(classroom.getCourseCode());
                                if (RC == null) {
                                    rc++;
                                    if (regularCourseService.save(classroom.getCourseCode(),
                                            classroom.getCourseName(), classroom.getSlotNum(),
                                            classroom.getFacultyCode()) == 0) {
                                        err++;
                                        error1.add(classroom.getCourseCode());
                                    }
                                    RC = regularCourseService.loadByCode(classroom.getCourseCode());
                                }

                                /*if(!classCodeSet.contains(classroom.getClassCode())){
                                if(regularCourseTimetableEntryService.save(regularTimetableValidation.getSemester(), classroom.getClassCode(), RC, tempRCTTECode, regularTimetableValidation.getAcademicYear(),classroom.getClassType(),classroom.getSemesterType(),"",classroom.getClassInfo(),classroom.getCourseInfo(),classroom.getClassStatus())==0){
                                   err++;
                                   error2.add(classroom.getClassCode());
                                }
                                } */
                                RegularCourseTimetableEntry rCTTE = regularCourseTimetableEntryService
                                        .loadRCTTEByCode(tempRCTTECode);

                                if (rCTTE == null) {
                                    rctte++;
                                    if (regularCourseTimetableEntryService.save(
                                            regularTimetableValidation.getSemester(), classroom.getClassCode(), RC,
                                            tempRCTTECode, regularTimetableValidation.getAcademicYear(),
                                            classroom.getClassType(), classroom.getSemesterType(), "",
                                            classroom.getClassInfo(), classroom.getCourseInfo(),
                                            classroom.getClassStatus()) == 0) {
                                        err++;
                                        error2.add(classroom.getClassCode());
                                    } else {
                                        rCTTE = regularCourseTimetableEntryService.loadRCTTEByCode(tempRCTTECode);
                                    }
                                }

                                int day = 0;
                                try {
                                    day = Integer.parseInt(classroom.getDay());
                                } catch (NumberFormatException e) {
                                    day = 0;
                                }
                                //System.out.println(classroom.getCourseCode() + " "+ classroom.getSlotNum());
                                RegularCourseTimetable rCTT = regularCourseTimetableService
                                        .loadByCode(rCTTE.getRCTTE_Code() + "-" + day);
                                if (rCTT == null) {
                                    if (regularCourseTimetableService.save(day, classroom.getSlots(),
                                            classroom.getWeeks(), room.getR_Code(), rCTTE) == 0) {
                                        err++;
                                        error3.add(classroom.getCourseCode() + " " + classroom.getClassCode() + " "
                                                + classroom.getDay());
                                    } else {
                                        //rCTT=regularCourseTimetableService.loadByCode(rCTTE.getRCTTE_Code()+"-"+day);
                                        //StatusMessages="Lp "+cnt+"/"+classRooms.size()+"<br/><b>Thm mi lp "+rCTTE.getRCTTE_Class_Code()+": </b><br/>"+"Tit "+classroom.getSlots()+" Th "+rCTT.getRCTT_Day()+" Tun "+classroom.getDay()+ " Phng "+classroom.getRoom()+"<br/>";
                                        //System.out.println("Thm mi lp "+rCTTE.getRCTTE_Class_Code());
                                        //model.put("status", StatusMessages);
                                    }
                                } else {
                                    if (!((rCTT.getRCTT_Day() == day)
                                            && (rCTT.getRCTT_Slots().equals(classroom.getSlots()))
                                            && (rCTT.getRCTT_Weeks().equals(classroom.getWeeks()))
                                            && (rCTT.getRCTT_Room_Code().equals(classroom.getRoom())))) {
                                        regularCourseTimetableService.edit(rCTT.getRCTT_ID(), day,
                                                classroom.getSlots(), classroom.getWeeks(), room.getR_Code(),
                                                rCTTE);
                                        //StatusMessages="Lp "+cnt+"/"+classRooms.size()+"<br/><b>Cp nht li lp "+rCTTE.getRCTTE_Class_Code()+": </b><br/>"+"Tit "+rCTT.getRCTT_Slots()+" Th "+rCTT.getRCTT_Day()+" Tun "+rCTT.getRCTT_Weeks()+ " Phng "+rCTT.getRCTT_Room_Code()+"<br/>";
                                        //rCTT=regularCourseTimetableService.loadByCode(rCTTE.getRCTTE_Code()+"-"+day);
                                        //StatusMessages+="===> Tit "+rCTT.getRCTT_Slots()+" Th "+rCTT.getRCTT_Day()+" Tun "+rCTT.getRCTT_Weeks()+ " Phng "+rCTT.getRCTT_Room_Code()+"<br/>";
                                        //System.out.println("Cp nht li lp "+rCTTE.getRCTTE_Class_Code());
                                        //model.put("status", StatusMessages);
                                    }
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            System.out.println("M lp: " + classroom.getClassCode()
                                    + " li khng nhp c d liu!");
                        }
                    }
                } catch (FileNotFoundException e) {
                    System.out.println(e.getMessage());
                } catch (IOException e) {
                    System.out.println(e.getMessage());
                } finally {
                    try (DataOutputStream out = new DataOutputStream(
                            new FileOutputStream("regularTimeTableUploadStatus.bin", false))) {
                    } catch (Exception e) {

                    }
                }
                model.put("status", StatusMessages);
                return "redirect:" + this.baseUrl + "/cp/RegularTimetables.html";
            } catch (Exception e) {
                e.printStackTrace();
                model.put("status", "You failed to upload " + fileName + " => " + e.getMessage());
            }

            return "cp.addRegularTimetable";
        }
    }

    @RequestMapping(value = "/AjaxRegularTimeTableUploadResponse.json", method = RequestMethod.GET)
    public @ResponseBody AjaxFileUpload ajaxResponse(ModelMap model, HttpSession session) {

        /*
         * Get current user name and role
         */
        String currentUserName = session.getAttribute("currentUserName").toString();
        String userRole = session.getAttribute("currentUserRole").toString();
        AjaxFileUpload res = new AjaxFileUpload();
        // Get list regulartimetables
        int curNum = 0;
        try (DataInputStream in = new DataInputStream(new FileInputStream("regularTimeTableUploadStatus.bin"))) {
            res.setTotalNum(in.readInt());
            while (true)
                curNum = in.readInt();
        } catch (FileNotFoundException e) {
            System.out.println(e.getMessage());
        } catch (EOFException e) {
            res.setCurNum(curNum);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }

        /*
         * Put data back to view
         */
        //model.put("regularCourseTimetableStatusList", regularCourseTimetableStatusList);           
        return res;
    }
}