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

Java tutorial

Introduction

Here is the source code for vn.webapp.controller.cp.RoomsController.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.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
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.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.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;

import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

/**
 * Customize
 */
import vn.webapp.controller.BaseWeb;
import vn.webapp.service.AcademicYearService;
import vn.webapp.service.RegularCourse.ExamService;
import vn.webapp.service.RegularCourse.RegularCourseTimetableEntryService;
import vn.webapp.service.RegularCourse.RegularCourseTimetableService;
import vn.webapp.service.RoomClusterService;
import vn.webapp.service.RoomLoanService;
import vn.webapp.service.RoomsService;
import vn.webapp.service.RegularCourse.RegularCourseTimetableInterfaceService;
import vn.webapp.service.RegularCourse.RegularCourseTimetableStatusService;
import vn.webapp.validation.QueryRoomValidation;
import vn.webapp.validation.RegularTimetableEditValidation;
import vn.webapp.validation.RoomEditValidation;
import vn.webapp.validation.RoomLoanValidation;
import vn.webapp.validation.RoomValidation;
import vn.webapp.model.AcademicYear;
import vn.webapp.model.RoomCluster;
import vn.webapp.model.RoomLoan;
import vn.webapp.model.Rooms;
import vn.webapp.model.RegularCourse.Exam;
import vn.webapp.model.RegularCourse.ExamStatus;
import vn.webapp.model.RegularCourse.RegularCourse;
import vn.webapp.model.RegularCourse.RegularCourseTimetable;
import vn.webapp.model.RegularCourse.RegularCourseTimetableEntry;
import vn.webapp.model.RegularCourse.RegularCourseTimetableInterface;
import vn.webapp.model.RegularCourse.RegularCourseTimetableStatus;
import vn.webapp.utilities.StringConvert;

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

    @Autowired
    private RoomsService roomsService;

    @Autowired
    private RoomLoanService roomLoanService;

    @Autowired
    private RoomClusterService roomClusterService;

    @Autowired
    private AcademicYearService academicYearService;

    @Autowired
    private RegularCourseTimetableInterfaceService regularCourseTimetableInterfaceService;

    @Autowired
    private RegularCourseTimetableEntryService regularCourseTimetableEntryService;

    @Autowired
    private RegularCourseTimetableService regularCourseTimetableService;

    @Autowired
    private RegularCourseTimetableStatusService regularCourseTimetableStatusService;

    @Autowired
    private ExamService examService;

    /**
    *
    * @param model
    * @return
    */
    @RequestMapping(value = "/Rooms", method = RequestMethod.GET)
    public String Rooms(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<Rooms> roomsList = roomsService.listRooms();

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

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

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

        model.put("roomAdd", new RoomValidation());

        return "cp.addRoom";
    }

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

        /*
         * Get current user name and role
         */
        Rooms room = roomsService.loadByID(roomId);

        model.put("room", room);
        model.put("roomFormEdit", new RoomEditValidation());

        return "cp.editRoom";
    }

    @RequestMapping(value = "edit-a-room", method = RequestMethod.POST)
    public String saveRegularTimetable(HttpServletRequest request,
            @Valid @ModelAttribute("roomFormEdit") RoomEditValidation roomEditValidation, BindingResult result,
            Map model, HttpSession session) {

        if (result.hasErrors()) {
            return "cp.editRoom";
        } else {
            try {
                Rooms room = roomsService.loadByCode(roomEditValidation.getRoomName());
                roomsService.edit(room.getR_ID(), room.getR_Code(), room.getR_Building(),
                        roomEditValidation.getRoomCapacity(), roomEditValidation.getRoomNote(),
                        roomEditValidation.getRoomFloor(), room.getRoomCluster());
                return "redirect:" + this.baseUrl + "/cp/Rooms.html";
            } catch (Exception e) {
                model.put("status", "You failed to edit room" + roomEditValidation.getRoomName());
            }
        }
        return "cp.editRoom";
    }

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

        /*
         * Get current user name and role
         */

        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);
        }

        model.put("queryRoom", new QueryRoomValidation());
        model.put("academicYearList", otherAcadYearList);
        model.put("curAcadYear", curAcadYear);

        return "cp.queryRoom";
    }

    @RequestMapping(value = "executeQueryRoom", method = RequestMethod.POST)
    public String queryRoom(HttpServletRequest request,
            @Valid @ModelAttribute("queryRoom") QueryRoomValidation queryRoomValidation, BindingResult result,
            Map model, HttpSession session) {
        if (result.hasErrors()) {
            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);
            }
            model.put("academicYearList", otherAcadYearList);
            model.put("curAcadYear", curAcadYear);
            return "cp.queryRoom";
        } else {
            String academicYear = queryRoomValidation.getAcademicYear();
            int maxCap = queryRoomValidation.getCapacityMax();
            if (maxCap == 0) {
                maxCap = 300;
                queryRoomValidation.setCapacityMax(300);
            }
            int minCap = queryRoomValidation.getCapacityMin();
            String dateString = queryRoomValidation.getDayMonthYearInput_day();
            String dayString = queryRoomValidation.getDayWeekInput_day();
            String weekString = queryRoomValidation.getDayWeekInput_week();
            String building = queryRoomValidation.getRoomBuilding();
            String slotStart = queryRoomValidation.getSlotStart();
            String slotEnd = queryRoomValidation.getSlotEnd();

            /* Convert date to day and week */
            if (!dateString.equals("")) {
                //System.out.println(dateString);
                List<AcademicYear> academicYearList = academicYearService.list();
                String firstdateStr = "";
                String enddateStr = "";
                for (AcademicYear aY : academicYearList) {
                    if (aY.getACAYEAR_Code().equals(academicYear)) {
                        firstdateStr = aY.getACAYEAR_FromDate();
                        enddateStr = aY.getACAYEAR_ToDate();
                        break;
                    }
                }

                DateTimeFormatter fmt = DateTimeFormat.forPattern("dd-MM-yyyy");
                LocalDate firstdate = fmt.parseLocalDate(firstdateStr);
                LocalDate enddate = fmt.parseLocalDate(enddateStr);
                LocalDate querydate = fmt.parseLocalDate(dateString);
                int dayNum = Days.daysBetween(firstdate, querydate).getDays();
                if ((dayNum <= 0) || (Days.daysBetween(querydate, enddate).getDays() < 0)) {
                    model.put("status",
                            "Ngy bn nhp khng c trong nm h?c. Hy ch?n ngy hp l!");
                    return "cp.searchroom";
                }
                dayString = Integer.toString(querydate.getDayOfWeek() + 1);
                if (dayString.equals("1"))
                    dayString = "Ch nht";
                weekString = Integer.toString(dayNum / 7 + 1);
                queryRoomValidation.setDayWeekInput_day(dayString);
                queryRoomValidation.setDayWeekInput_week(weekString);
            } else if (dayString.equals("") && weekString.equals("")) {
                model.put("status", "Khng th truy vn phng v thiu thng tin ngy thng");
                return "cp.searchroom";
            }
            try {
                /* Convert input week string into list of weeks */
                StringConvert strConv = new StringConvert();
                List<String> weeks = strConv.ExpandToListString(weekString);

                /* Convert input day string into list of days */
                List<String> days = strConv.ExpandToListString(dayString);

                /* Convert input slot string into list of slots */
                List<String> slots = strConv.ExpandToListString(slotStart + "-" + slotEnd);

                List<Rooms> roomsList = roomsService.listRooms();

                List<RegularCourseTimetableInterface> RCTTI_List = regularCourseTimetableInterfaceService
                        .loadRCTTIList(academicYear);

                List<Exam> examList = examService.loadExamList(academicYear);

                List<RoomLoan> roomLoanList = roomLoanService.listRoomLoans();

                List<Rooms> freeRoomList = new ArrayList<Rooms>();
                boolean isRoomAvail = true;
                for (Rooms room : roomsList) {
                    isRoomAvail = true;
                    for (RegularCourseTimetableInterface classinfo : RCTTI_List) {
                        String stt = classinfo.getClassStatus();
                        if (stt != null
                                && (stt.toLowerCase().contains("hy") || stt.toLowerCase().contains("hu")))
                            continue;
                        if (!(room.getR_Code().equals(classinfo.getRoom())))
                            continue;
                        else {

                            List<String> classWeeks = strConv.ExpandToListString(classinfo.getWeek());
                            boolean isContainWeek = false;
                            for (String weekstr : weeks) {
                                if (classWeeks.contains(weekstr)) {
                                    isContainWeek = true;
                                    break;
                                }
                            }
                            if (!isContainWeek)
                                continue;
                            if (!days.contains(Integer.toString(classinfo.getDay())))
                                continue;
                            String[] tokenSlots = strConv.Expand(classinfo.getSlot()).split("[,]");
                            int firstSlot = Integer.parseInt(tokenSlots[0]);
                            int lastSlot = Integer.parseInt(tokenSlots[tokenSlots.length - 1]);
                            boolean isSlotBusy = false;
                            for (String slot : slots) {
                                if ((firstSlot - Integer.parseInt(slot))
                                        * (lastSlot - Integer.parseInt(slot)) <= 0) {
                                    isSlotBusy = true;
                                    break;
                                }
                            }
                            if (isSlotBusy) {
                                isRoomAvail = false;
                                break;
                            }
                        }
                    }
                    if (isRoomAvail) {
                        for (Exam ex : examList) {
                            if (!(room.getR_Code().equals(ex.getRCE_Room_Code())))
                                continue;
                            else {
                                boolean isContainWeek = false;
                                if (weeks.contains(Integer.toString(ex.getRCE_Week()))) {
                                    isContainWeek = true;
                                }
                                if (!isContainWeek)
                                    continue;
                                if (!days.contains(Integer.toString(ex.getRCE_Day())))
                                    continue;
                                String[] tokenSlots = ex.getRCE_Slots().split("[,]");
                                int firstSlot = Integer.parseInt(tokenSlots[0]);
                                int lastSlot = Integer.parseInt(tokenSlots[tokenSlots.length - 1]);
                                boolean isSlotBusy = false;
                                for (String slot : slots) {
                                    if ((firstSlot - Integer.parseInt(slot))
                                            * (lastSlot - Integer.parseInt(slot)) <= 0) {
                                        isSlotBusy = true;
                                        break;
                                    }
                                }
                                if (isSlotBusy) {
                                    isRoomAvail = false;
                                    break;
                                }
                            }
                        }
                    }

                    if (isRoomAvail) {
                        for (RoomLoan rl : roomLoanList) {
                            if (!(room.getR_Code().equals(rl.getRL_R_Code())))
                                continue;
                            else {
                                List<String> rlWeeks = strConv.ExpandToListString(rl.getRL_Week());
                                boolean isContainWeek = false;
                                for (String weekstr : weeks) {
                                    if (rlWeeks.contains(weekstr)) {
                                        isContainWeek = true;
                                        break;
                                    }
                                }
                                if (!isContainWeek)
                                    continue;
                                boolean isContainDay = false;
                                List<String> rlDays = strConv.ExpandToListString(rl.getRL_Day());
                                for (String daystr : days) {
                                    if (rlDays.contains(daystr)) {
                                        isContainDay = true;
                                        break;
                                    }
                                }
                                if (!isContainDay)
                                    continue;

                                String[] tokenSlots = strConv.Expand(rl.getRL_Slots()).split("[,]");
                                int firstSlot = Integer.parseInt(tokenSlots[0]);
                                int lastSlot = Integer.parseInt(tokenSlots[tokenSlots.length - 1]);
                                boolean isSlotBusy = false;
                                for (String slot : slots) {
                                    if ((firstSlot - Integer.parseInt(slot))
                                            * (lastSlot - Integer.parseInt(slot)) <= 0) {
                                        isSlotBusy = true;
                                        break;
                                    }
                                }
                                if (isSlotBusy) {
                                    isRoomAvail = false;
                                    break;
                                }
                            }
                        }
                    }

                    if (isRoomAvail) {
                        boolean isShowed = true;
                        if ((room.getR_Capacity() < minCap) || (room.getR_Capacity() > maxCap))
                            isShowed = false;
                        if ((!building.equals("Tt c")) && (!building.equals(room.getR_Building())))
                            isShowed = false;
                        if (isShowed)
                            freeRoomList.add(room);
                    }
                }
                System.out.println("C " + freeRoomList.size() + " phng trng!");
                model.put("roomsList", freeRoomList);
                model.put("query", queryRoomValidation);
                return "cp.searchroom";
            } catch (Exception e) {
                model.put("status", "C li xy ra trong lc truy vn:\n" + e.getMessage());
                return "cp.searchroom";
            }

        }
    }

    /**
     * Save a room
         
     */
    @RequestMapping(value = "saveRoom", method = RequestMethod.POST)
    public String saveRoom(HttpServletRequest request,
            @Valid @ModelAttribute("roomAdd") RoomValidation roomValidation, BindingResult result, Map model,
            HttpSession session) {
        /*
         * Get list of paper category and journalList
         */

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

            /**
             * Uploading file
             */
            MultipartFile sourceUploadFile = roomValidation.getRoomsUpload();
            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 + "/rooms");
                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();

                HustRoomData roomData = new HustRoomData();
                List<RoomInfo> roominfos = roomData
                        .readFileExcel(dir.getAbsolutePath() + File.separator + fileName);
                for (RoomInfo ri : roominfos) {
                    RoomCluster roomCluster = roomClusterService.loadByCode(ri.getClusterID());
                    Rooms r = roomsService.loadByCode(ri.getRoomCode());
                    if (r == null)
                        roomsService.save(ri.getRoomCode(), ri.getBuilding(), ri.getCapacity(), ri.getNote(),
                                ri.getFloor(), roomCluster);
                    else
                        roomsService.edit(r.getR_ID(), ri.getRoomCode(), ri.getBuilding(), ri.getCapacity(),
                                ri.getNote(), ri.getFloor(), roomCluster);
                }

                /**
                 * Preparing data for adding into DB
                 */

                //if(i_InsertAPaper > 0){
                //model.put("status", "Successfully saved a paper: ");
                return "redirect:" + this.baseUrl + "/cp/Rooms.html";
                //}
            } catch (Exception e) {
                model.put("status", "You failed to upload " + fileName + " => " + e.getMessage());
            }
            return "cp.rooms";
        }
    }

    @RequestMapping(value = "/RoomTimetableDetails/{id}", method = RequestMethod.GET)
    public String RoomTimeTableDetails(ModelMap model, @PathVariable("id") int roomID, HttpSession session) {
        List<Rooms> roomsList = roomsService.listRooms();
        Rooms room = new Rooms();
        for (Rooms r : roomsList) {
            if (r.getR_ID() == roomID) {
                room = r;
                break;
            }
        }
        AcademicYear curAcadYear = academicYearService.getCurAcadYear();

        List<RegularCourseTimetableInterface> RCTTI_List = regularCourseTimetableInterfaceService
                .loadRCTTIList(curAcadYear.getACAYEAR_Code());

        List<RegularCourseTimetableInterface> RCTTI_List_Res = new ArrayList<RegularCourseTimetableInterface>();

        // StringConvert strConv=new StringConvert();
        for (RegularCourseTimetableInterface RCTTI : RCTTI_List) {
            String stt = RCTTI.getClassStatus();
            if (stt != null && (stt.toLowerCase().contains("hy") || stt.toLowerCase().contains("hu")))
                continue;
            if (room.getR_Code().equals(RCTTI.getRoom())) {
                RCTTI.setSlot(RCTTI.getSlot());
                RCTTI.setWeek(RCTTI.getWeek());
                RCTTI_List_Res.add(RCTTI);
            }
        }
        model.put("timeTableDetails", RCTTI_List_Res);
        return "cp.roomTimeTableDetails";
    }

    @RequestMapping(value = "/RoomLoans", method = RequestMethod.GET)
    public String RoomLoans(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<RoomLoan> roomLoanList = roomLoanService.listRoomLoans();
        /*
         * Put data back to view
         */
        model.put("roomLoanList", roomLoanList);
        return "cp.roomloans";
    }

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

        /*
         * Get current user name and role
         */

        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);
        }

        model.put("roomLoanFormAdd", new RoomLoanValidation());
        model.put("academicYearList", otherAcadYearList);
        model.put("curAcadYear", curAcadYear);
        if (session.getAttribute("errorAddRoomLoanFwd") != null) {
            model.put("err", (String) session.getAttribute("errorAddRoomLoanFwd"));
            session.removeAttribute("errorAddRoomLoanFwd");
        }
        return "cp.addRoomLoan";
    }

    @RequestMapping(value = "add-a-room-loan", method = RequestMethod.POST)
    public String addARoomLoan(HttpServletRequest request,
            @Valid @ModelAttribute("roomLoanFormAdd") RoomLoanValidation roomLoanValidation, BindingResult result,
            Map model, HttpSession session) {

        if (result.hasErrors()) {
            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);
            }
            model.put("academicYearList", otherAcadYearList);
            model.put("curAcadYear", curAcadYear);
            return "cp.addRoomLoan";
        } else {
            String academicYear = roomLoanValidation.getAcademicYear();
            String dateString = roomLoanValidation.getDayMonthYearInput_day();
            String dayString = roomLoanValidation.getDayWeekInput_day();
            String weekString = roomLoanValidation.getDayWeekInput_week();
            String room = roomLoanValidation.getRoomCode();
            String slotStart = roomLoanValidation.getSlotStart();
            String slotEnd = roomLoanValidation.getSlotEnd();

            /* Convert date to day and week */
            List<AcademicYear> academicYearList = academicYearService.list();
            String firstdateStr = "";
            String enddateStr = "";
            for (AcademicYear aY : academicYearList) {
                if (aY.getACAYEAR_Code().equals(academicYear)) {
                    firstdateStr = aY.getACAYEAR_FromDate();
                    enddateStr = aY.getACAYEAR_ToDate();
                    break;
                }
            }

            DateTimeFormatter fmt = DateTimeFormat.forPattern("dd-MM-yyyy");
            LocalDate firstdate = fmt.parseLocalDate(firstdateStr);
            LocalDate enddate = fmt.parseLocalDate(enddateStr);

            if (!dateString.equals("")) {
                LocalDate querydate = fmt.parseLocalDate(dateString);
                int dayNum = Days.daysBetween(firstdate, querydate).getDays();
                if ((dayNum <= 0) || (Days.daysBetween(querydate, enddate).getDays() < 0)) {
                    session.setAttribute("errorAddRoomLoanFwd",
                            "Ngy bn nhp khng c trong nm h?c. Hy ch?n ngy hp l!");
                    return "cp.addRoomLoan";
                }
                dayString = Integer.toString(querydate.getDayOfWeek() + 1);
                if (dayString.equals("8"))
                    dayString = "Ch nht";
                weekString = Integer.toString(dayNum / 7 + 1);
                roomLoanValidation.setDayWeekInput_day(dayString);
                roomLoanValidation.setDayWeekInput_week(weekString);
            } else if (!(dayString.equals("") || weekString.equals(""))) {
                try {
                    if (dayString.equals("Ch nht"))
                        dayString = "8";
                    LocalDate querydate = firstdate
                            .plusDays(7 * (Integer.parseInt(weekString) - 1) + Integer.parseInt(dayString) - 2);
                    roomLoanValidation.setDayMonthYearInput_day(querydate.toString());
                } catch (Exception e) {
                    roomLoanValidation.setDayMonthYearInput_day("Nhi?u ngy");
                }
            } else {
                session.setAttribute("errorAddRoomLoanFwd", "Khng th thm thng tin mn phng "
                        + roomLoanValidation.getRoomCode() + " v thiu thng tin ngy thng mn phng");
                return "redirect:" + this.baseUrl + "/cp/AddRoomLoan.html";
            }

            if (roomsService.loadByCode(room) == null) {
                session.setAttribute("errorAddRoomLoanFwd", "M phng " + room
                        + " khng c trong c s d liu phng. Hy kim tra li!");
                return "redirect:" + this.baseUrl + "/cp/AddRoomLoan.html";
            }

            try {
                String RL_Code = roomLoanValidation.getRoomCode() + "-" + roomLoanValidation.getAcademicYear() + "-"
                        + roomLoanValidation.getDayWeekInput_week() + "-"
                        + roomLoanValidation.getDayWeekInput_day();
                RoomLoan roomLoan = roomLoanService.loadByCode(RL_Code);
                if (roomLoan == null)
                    roomLoanService.save(roomLoanValidation.getRoomCode(), roomLoanValidation.getDayWeekInput_day(),
                            roomLoanValidation.getDayWeekInput_week(), roomLoanValidation.getAcademicYear(),
                            roomLoanValidation.getDayMonthYearInput_day(),
                            roomLoanValidation.getSlotStart() + "-" + roomLoanValidation.getSlotEnd(),
                            roomLoanValidation.getNote());
                return "redirect:" + this.baseUrl + "/cp/RoomLoans.html";
            } catch (Exception e) {
                model.put("status", "You failed to edit room loan for" + roomLoanValidation.getRoomCode());
            }
        }
        return "cp.addRoomLoan";
    }

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

        /*
         * Get current user name and role
         */

        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);
        }

        RoomLoan roomLoan = roomLoanService.loadByID(rL_Id);

        model.put("roomLoan", roomLoan);
        model.put("roomLoanFormEdit", new RoomLoanValidation());
        model.put("academicYearList", otherAcadYearList);
        model.put("curAcadYear", curAcadYear);
        if (session.getAttribute("errorEditARoomLoanFwd") != null) {
            model.put("err", (String) session.getAttribute("errorEditARoomLoanFwd"));
            session.removeAttribute("errorEditARoomLoanFwd");
        }
        return "cp.editRoomLoan";
    }

    @RequestMapping(value = "edit-a-room-loan", method = RequestMethod.POST)
    public String editARoomLoan(HttpServletRequest request,
            @Valid @ModelAttribute("roomLoanFormEdit") RoomLoanValidation roomLoanValidation, BindingResult result,
            Map model, HttpSession session) {

        if (result.hasErrors()) {
            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);
            }

            RoomLoan roomLoan = roomLoanService.loadByID(roomLoanValidation.getRoomLoanID());

            model.put("roomLoan", roomLoan);
            model.put("academicYearList", otherAcadYearList);
            model.put("curAcadYear", curAcadYear);
            return "cp.editRoomLoan";
        } else {
            String academicYear = roomLoanValidation.getAcademicYear();
            String dateString = roomLoanValidation.getDayMonthYearInput_day();
            String dayString = roomLoanValidation.getDayWeekInput_day();
            String weekString = roomLoanValidation.getDayWeekInput_week();
            String room = roomLoanValidation.getRoomCode();
            String slotStart = roomLoanValidation.getSlotStart();
            String slotEnd = roomLoanValidation.getSlotEnd();

            /* Convert date to day and week */
            List<AcademicYear> academicYearList = academicYearService.list();
            String firstdateStr = "";
            String enddateStr = "";
            for (AcademicYear aY : academicYearList) {
                if (aY.getACAYEAR_Code().equals(academicYear)) {
                    firstdateStr = aY.getACAYEAR_FromDate();
                    enddateStr = aY.getACAYEAR_ToDate();
                    break;
                }
            }

            DateTimeFormatter fmt = DateTimeFormat.forPattern("dd-MM-yyyy");
            LocalDate firstdate = fmt.parseLocalDate(firstdateStr);
            LocalDate enddate = fmt.parseLocalDate(enddateStr);

            if (!dateString.equals("")) {
                LocalDate querydate = fmt.parseLocalDate(dateString);
                int dayNum = Days.daysBetween(firstdate, querydate).getDays();
                int dayNum1 = Days.daysBetween(querydate, enddate).getDays();
                if ((dayNum <= 0) || (Days.daysBetween(querydate, enddate).getDays() < 0)) {
                    session.setAttribute("errorEditARoomLoanFwd",
                            "Ngy bn nhp khng c trong nm h?c. Hy ch?n ngy hp l!");
                    return "redirect:" + this.baseUrl + "/cp/EditRoomLoan/" + roomLoanValidation.getRoomLoanID()
                            + ".html";
                }
                dayString = Integer.toString(querydate.getDayOfWeek() + 1);
                if (dayString.equals("8"))
                    dayString = "Ch nht";
                weekString = Integer.toString(dayNum / 7 + 1);
                roomLoanValidation.setDayWeekInput_day(dayString);
                roomLoanValidation.setDayWeekInput_week(weekString);
            } else if (!(dayString.equals("") || weekString.equals(""))) {
                try {
                    if (dayString.equals("Ch nht"))
                        dayString = "8";
                    LocalDate querydate = firstdate
                            .plusDays(7 * (Integer.parseInt(weekString) - 1) + Integer.parseInt(dayString) - 2);
                    roomLoanValidation.setDayMonthYearInput_day(querydate.toString());
                } catch (Exception e) {
                    roomLoanValidation.setDayMonthYearInput_day("Nhi?u ngy");
                }
            } else {
                //model.put("status", "Khng th sa thng tin mn phng " + roomLoanValidation.getRoomCode()+" v thiu thng tin ngy thng mn phng");
                session.setAttribute("errorEditARoomLoanFwd", "Khng th sa thng tin mn phng "
                        + roomLoanValidation.getRoomCode()
                        + " v thiu thng tin ngy thng mn phng. Hy sa li thng tin!");
                return "redirect:" + this.baseUrl + "/cp/EditRoomLoan/" + roomLoanValidation.getRoomLoanID()
                        + ".html";
            }

            if (roomsService.loadByCode(room) == null) {
                session.setAttribute("errorEditARoomLoanFwd", "M phng " + room
                        + " khng c trong c s d liu phng. Hy kim tra li!");
                return "redirect:" + this.baseUrl + "/cp/EditRoomLoan/" + roomLoanValidation.getRoomLoanID()
                        + ".html";
            }

            try {
                String RL_Code = roomLoanValidation.getRoomCode() + "-" + roomLoanValidation.getAcademicYear() + "-"
                        + roomLoanValidation.getDayWeekInput_week() + "-"
                        + roomLoanValidation.getDayWeekInput_day();
                RoomLoan roomLoan = roomLoanService.loadByID(roomLoanValidation.getRoomLoanID());
                if (roomLoan != null)
                    if (roomLoanValidation.getNote().isEmpty())
                        roomLoanValidation.setNote(roomLoan.getRL_Note());
                roomLoanService.edit(roomLoanValidation.getRoomLoanID(), roomLoanValidation.getRoomCode(),
                        roomLoanValidation.getDayWeekInput_day(), roomLoanValidation.getDayWeekInput_week(),
                        roomLoanValidation.getAcademicYear(), roomLoanValidation.getDayMonthYearInput_day(),
                        roomLoanValidation.getSlotStart() + "-" + roomLoanValidation.getSlotEnd(),
                        roomLoanValidation.getNote());
                return "redirect:" + this.baseUrl + "/cp/RoomLoans.html";
            } catch (Exception e) {
                model.put("status", "You failed to edit room loan for" + roomLoanValidation.getRoomCode());
            }
        }
        return "cp.editRoomLoan";
    }

    @RequestMapping(value = "/remove-a-room-loan/{id}", method = RequestMethod.GET)
    public String DeleteARoomLoan(ModelMap model, @PathVariable("id") int Id, HttpSession session) {
        RoomLoan roomLoan = roomLoanService.loadByID(Id);
        roomLoanService.remove(Id);
        List<RoomLoan> roomLoanList = roomLoanService.listRoomLoans();
        model.put("roomLoanList", roomLoanList);
        model.put("status", "? xa thnh cng ng k mn phng" + roomLoan.getRL_R_Code());
        return "cp.roomloans";
    }

    @RequestMapping(value = "/remove-a-room/{id}", method = RequestMethod.GET)
    public String DeleteARoom(ModelMap model, @PathVariable("id") int Id, HttpSession session) {
        Rooms room = roomsService.loadByID(Id);
        AcademicYear curAcadYear = academicYearService.getCurAcadYear();
        List<RegularCourseTimetableInterface> RCTTI_List = regularCourseTimetableInterfaceService
                .loadRCTTIList(curAcadYear.getACAYEAR_Code());
        List<RegularCourseTimetableInterface> RCTTI_List_Res = new ArrayList<RegularCourseTimetableInterface>();
        // StringConvert strConv=new StringConvert();
        for (RegularCourseTimetableInterface RCTTI : RCTTI_List) {
            if (room.getR_Code().equals(RCTTI.getRoom())) {
                RCTTI.setSlot(RCTTI.getSlot());
                RCTTI.setWeek(RCTTI.getWeek());
                RCTTI_List_Res.add(RCTTI);
            }
        }
        if (RCTTI_List_Res.isEmpty()) {
            roomsService.remove(Id);
            model.put("status", "? xa thnh cng phng " + room.getR_Code());
        } else {
            roomsService.edit(room.getR_ID(), room.getR_Code(), room.getR_Building(), -1, room.getR_Note(),
                    room.getR_Floor(), room.getRoomCluster());
            model.put("status", "Khng th xa phng " + room.getR_Code()
                    + " v ang c lch h?c. <br> H thng s a phng ra kh?i danh sch qun l bng cch thit lp sc cha l -1. \n Nu mun khi phc li bn hy thay i sc cha ca phng ny  danh sch cc phng pha di.");
        }
        List<Rooms> roomsList = roomsService.listRooms();
        model.put("roomsList", roomsList);
        return "cp.rooms";
    }

}