Example usage for org.joda.time Days daysBetween

List of usage examples for org.joda.time Days daysBetween

Introduction

In this page you can find the example usage for org.joda.time Days daysBetween.

Prototype

public static Days daysBetween(ReadablePartial start, ReadablePartial end) 

Source Link

Document

Creates a Days representing the number of whole days between the two specified partial datetimes.

Usage

From source file:view.EmprestimoInternalFrame.java

private void DevolveEmprestimoBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DevolveEmprestimoBtnActionPerformed
    int idx[] = emprestimoTable.getSelectedRows();
    if (idx.length > 0) {
        int id_emprestimo = Integer
                .valueOf(emprestimoTable.getValueAt(emprestimoTable.getSelectedRow(), 0).toString());
        if (id_emprestimo != 0) {
            Emprestimo e = EmprestimoController.Pegar(id_emprestimo);
            LocalDateTime hoje = new LocalDateTime(System.currentTimeMillis());
            LocalDateTime fim = new LocalDateTime(e.getData_fim());
            int dias = Days.daysBetween(hoje, fim).getDays();
            dias = dias * -1;/* ww  w.ja  va2  s.  c  o  m*/
            double total = 0.0;
            int response;
            if (dias > 0) {
                for (int i = 0; i < dias; i++) {
                    total = e.getId_exemplar().stream().map((_item) -> juros_dia).reduce(total,
                            (accumulator, _item) -> accumulator + _item);
                }
            }

            JLabel nome = new JLabel();
            nome.setFont(new Font("Dialog", Font.BOLD, 14));
            JLabel juros = new JLabel();
            juros.setFont(new Font("Dialog", Font.BOLD, 14));
            JLabel total_ex = new JLabel();
            total_ex.setFont(new Font("Dialog", Font.BOLD, 14));
            Object[] message = { "Locatrio:", nome, "Total de Exemplares: ", total_ex, "Total de Juros:",
                    juros, "Prosseguir com devoluo?" };
            nome.setText(emprestimoTable.getValueAt(emprestimoTable.getSelectedRow(), 1).toString());
            juros.setText("" + NumberFormat.getCurrencyInstance().format(total));
            total_ex.setText("" + e.getId_exemplar().size());

            response = JOptionPane.showConfirmDialog(null, message, "Devoluo", JOptionPane.YES_NO_OPTION,
                    JOptionPane.QUESTION_MESSAGE);
            if (response == JOptionPane.YES_OPTION) {
                if (EmprestimoController.Apagar(id_emprestimo)) {
                    updateEmprestimoTable("");
                    if (lif != null)
                        lif.updateExemplarTableModel("");
                }
            }
        }
    } else {
        DevolveEmprestimoBtn.setEnabled(false);
    }
}

From source file:view.EmprestimoInternalFrame.java

private void RenovaEmprestimoBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RenovaEmprestimoBtnActionPerformed
    int idx[] = emprestimoTable.getSelectedRows();
    if (idx.length > 0) {
        int id_emprestimo = Integer
                .valueOf(emprestimoTable.getValueAt(emprestimoTable.getSelectedRow(), 0).toString());
        if (id_emprestimo != 0) {
            Emprestimo e = EmprestimoController.Pegar(id_emprestimo);
            LocalDateTime hoje = new LocalDateTime(System.currentTimeMillis());
            LocalDateTime fim = new LocalDateTime(e.getData_fim());
            int dias = Days.daysBetween(hoje, fim).getDays();
            dias = dias * -1;/*from  w  ww . j  av a2 s.  c o  m*/
            double total = 0.0;
            int response;
            if (dias > 0) {
                for (int i = 0; i < dias; i++) {
                    total = e.getId_exemplar().stream().map((_item) -> juros_dia).reduce(total,
                            (accumulator, _item) -> accumulator + _item);
                }
            }
            JLabel nome = new JLabel();
            nome.setFont(new Font("Dialog", Font.BOLD, 14));
            JLabel juros = new JLabel();
            juros.setFont(new Font("Dialog", Font.BOLD, 14));
            JLabel total_ex = new JLabel();
            total_ex.setFont(new Font("Dialog", Font.BOLD, 14));
            JSpinner diaSpinner = new JSpinner(new SpinnerNumberModel());
            diaSpinner.setFont(new Font("Dialog", Font.BOLD, 18));
            diaSpinner.setValue(prazo_default);
            Object[] message = { "Locatrio:", nome, "Total de Exemplares: ", total_ex, "Total de Juros:",
                    juros, "Dias p/ Devoluo:", diaSpinner, "O juros ser zerado. Renovar?" };
            nome.setText(emprestimoTable.getValueAt(emprestimoTable.getSelectedRow(), 1).toString());
            juros.setText("" + NumberFormat.getCurrencyInstance().format(total));
            total_ex.setText("" + e.getId_exemplar().size());

            response = JOptionPane.showConfirmDialog(null, message, "Devoluo", JOptionPane.YES_NO_OPTION,
                    JOptionPane.QUESTION_MESSAGE);
            if (response == JOptionPane.YES_OPTION) {
                int plus_days = Integer.valueOf(diaSpinner.getValue().toString());
                if (plus_days < 0)
                    plus_days = plus_days * -1;
                System.out.println("" + plus_days);
                if (EmprestimoController.Renovar(id_emprestimo, plus_days)) {
                    updateEmprestimoTable("");
                }
            }
        }
    } else
        RenovaEmprestimoBtn.setEnabled(false);
}

From source file:View.FormExtratoMultas.java

private void inicializarPainel() {

    jEPMultas.setContentType("text/html");

    String HTML = "";

    HTMLEditorKit editorKit = (HTMLEditorKit) jEPMultas.getEditorKit();
    StyleSheet ss = new StyleSheet();
    Enumeration e = editorKit.getStyleSheet().getStyleNames();
    while (e.hasMoreElements()) {
        ss.addRule(e.nextElement().toString());
    }//w  w  w . j a v  a2s. c  o  m
    ss.addRule("table {font-family: Latin Modern Math, LM Math; font-size: 10px; align: right; width: 100%}");
    ss.addRule(
            "th {font-family: Latin Modern Math, LM Math; font-size: 10px; font-weight:bold; text-align: center; outline-width: 0px; margin: 0px;  border-width: 1px; border-style: solid; border-color: #000000;}");
    ss.addRule(
            "td {font-family: Latin Modern Math, LM Math; font-size: 10px; padding: 3px; margin: 0px; border-width: 1px; border-style: solid; border-color: #000000;}");
    jEPMultas.setDocument(new HTMLDocument(ss));

    if (multaList == null || multaList.isEmpty()) {
        Aviso.showError("Nenhuma multa selecionada.");
        return;
    }

    multaList.sort(new Multa());

    int idAtual;
    int idPassado = -1;
    int rowCount = 1;
    double total = 0;

    HTML = HTML.concat("<table>");
    for (Multa multaVO : multaList) {
        Pessoa pessoaResponsavel;
        if (multaVO.getPessoa() == null)
            pessoaResponsavel = multaVO.getCarteira().getTitular();
        else
            pessoaResponsavel = multaVO.getPessoa();

        idAtual = pessoaResponsavel.getIdPessoa();

        if (idAtual != idPassado) {
            if (idPassado != -1) {
                HTML = totalMultaPessoa(HTML, total);
            }
            rowCount = 1;
            total = 0;
            HTML = HTML.concat("<tr style=\"background-color:#FFFFFF\"></tr>");

            HTML = HTML.concat("<tr style=\"background-color:#0080FF\">" + "<th width=\"100%\" colspan=\"7\">"
                    + pessoaResponsavel.getNome() + "</th>" + "</tr>");

            HTML = HTML.concat(
                    "<tr style= \"background-color:#3399FF\" >" + "<th > Placa </th>" + "<th > Infrao </th>"
                            + "<th > Pontuao </th>" + "<th > Data da Ocorrncia </th>" + "<th > Atraso </th>"
                            + "<th > Valor Original </th>" + "<th > Valor Final </th>" + "</tr>");
        }

        Automovel auto = multaVO.getAutomovel();
        Autuacao autuacao = multaVO.getAutuacao();

        Date emissao = multaVO.getDataEmissao();
        boolean temAtraso;

        DateTime dataInicio = new DateTime(emissao);
        DateTime dataFinal = new DateTime();

        Days dias = Days.daysBetween(dataInicio, dataFinal);

        temAtraso = dias.getDays() > autuacao.getPrazo();

        SimpleDateFormat formataData = new SimpleDateFormat("dd/MM/yyyy");
        String date = formataData.format(emissao);

        double custoReal = MultaController.calcularMulta(multaVO, temAtraso);
        total += custoReal;

        HTML = HTML.concat("<tr style= "
                + ((rowCount % 2 == 0) ? "\"background-color:#99CCFF\" " : "\"background-color:#CCE5FF\" ")
                + ">" + "<th >" + auto.getPlaca() + "</th>" + "<th >" + autuacao.getTitulo() + "</th>" + "<th >"
                + autuacao.getPontuacao() + "</th>" + "<th >" + date + "</th>" + "<th >"
                + ((temAtraso) ? "Atrasado!" : "OK!") + "</th>" + "<th >" + "R$ " + autuacao.getCusto()
                + "</th>" + "<th >" + "R$ " + custoReal + "</th>" + "</tr>");

        idPassado = idAtual;
        rowCount++;
    }

    HTML = totalMultaPessoa(HTML, total);
    HTML = HTML.concat("</table>");

    jEPMultas.setText(HTML);

}

From source file:View.LimitePrincipal.java

private void opcoesComboActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_opcoesComboActionPerformed
    // TODO add your handling code here:
    CardLayout layout = (CardLayout) painelCards.getLayout();
    if (evt.getSource() == opcoesCombo) {
        int option = opcoesCombo.getSelectedIndex();
        if (option == 0) {
            layout.show(painelCards, "card2");
        } else if (option == 1) {
            layout.show(painelCards, "card3");
        } else if (option == 2) {
            layout.show(painelCards, "card4");
        } else if (option == 3) {
            comboIsbnExemplar.removeAllItems();
            for (int i = 0; i < vecPublicacao.size(); i++) {
                Publicacao tempPub = (Publicacao) vecPublicacao.get(i);
                comboIsbnExemplar.addItem(Integer.toString(tempPub.getIsbn()));
            }/*w  w w. ja  va  2  s .  c om*/
            layout.show(painelCards, "card5");
        } else if (option == 4) {
            comboIsbnCOP.removeAllItems();
            for (int i = 0; i < vecPublicacao.size(); i++) {
                Publicacao tempPub = (Publicacao) vecPublicacao.get(i);
                comboIsbnCOP.addItem(Integer.toString(tempPub.getIsbn()));
            }
            layout.show(painelCards, "card6");
        } else if (option == 5) {
            comboIsbnRE.removeAllItems();
            for (int i = 0; i < vecPublicacao.size(); i++) {
                Publicacao tempPub = (Publicacao) vecPublicacao.get(i);
                comboIsbnRE.addItem(Integer.toString(tempPub.getIsbn()));
            }
            comboCodRE.removeAllItems();
            for (int j = 0; j < vecAssociado.size(); j++) {
                Associado tempAss = (Associado) vecAssociado.get(j);
                comboCodRE.addItem(Integer.toString(tempAss.getCodigo()));
            }
            layout.show(painelCards, "card7");
        } else if (option == 6) {
            comboIsbnRD.removeAllItems();
            for (int i = 0; i < vecPublicacao.size(); i++) {
                Publicacao tempPublicacao = (Publicacao) vecPublicacao.get(i);
                comboIsbnRD.addItem(Integer.toString(tempPublicacao.getIsbn()));
            }
            layout.show(painelCards, "card8");
        } else if (option == 7) {
            DefaultListModel list = new DefaultListModel();
            listaGRA.removeAll();
            Date hoje = new Date();
            for (int i = 0; i < vecEmprestimo.size(); i++) {
                Emprestimo tempEmprestimo = (Emprestimo) vecEmprestimo.get(i);
                int dias = Days.daysBetween(new DateTime(tempEmprestimo.getData()), new DateTime(hoje))
                        .getDays();
                if (dias > 6) {
                    for (int j = 0; j < vecAssociado.size(); j++) {
                        Associado tempAssociado = (Associado) vecAssociado.get(j);
                        if (tempEmprestimo.getCodAssociado()
                                .equals(Integer.toString(tempAssociado.getCodigo()))) {
                            if (("Prof".equals(tempAssociado.getStatus())) && (dias > 14)) {
                                list.addElement(("Exemplar: " + tempEmprestimo.getNumExemplar() + "    ISBN: "
                                        + tempEmprestimo.getIsbn() + "    Nome: " + tempAssociado.getNome()
                                        + "    Cdigo: " + tempAssociado.getCodigo() + "    Status: "
                                        + tempAssociado.getStatus() + "    Multa: R$" + (dias - 13)));
                            } else if (("PosGrad".equals(tempAssociado.getStatus())) && (dias > 10)) {
                                list.addElement(("Exemplar: " + tempEmprestimo.getNumExemplar() + "    ISBN: "
                                        + tempEmprestimo.getIsbn() + "    Nome: " + tempAssociado.getNome()
                                        + "    Cdigo: " + tempAssociado.getCodigo() + "    Status: "
                                        + tempAssociado.getStatus() + "    Multa: R$" + (dias - 9)));
                            } else if ("Grad".equals(tempAssociado.getStatus())) {
                                list.addElement(("Exemplar: " + tempEmprestimo.getNumExemplar() + "    ISBN: "
                                        + tempEmprestimo.getIsbn() + "    Nome: " + tempAssociado.getNome()
                                        + "    Cdigo: " + tempAssociado.getCodigo() + "    Status: "
                                        + tempAssociado.getStatus() + "    Multa: R$" + (dias - 6)));
                            }
                        }
                    }
                }
            }
            listaGRA.setModel(list);
            listaGRA.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            layout.show(painelCards, "card9");
        }
    }
}

From source file:View.LimitePrincipal.java

private void devolverRDActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_devolverRDActionPerformed
    // TODO add your handling code here:
    String ok = "ok";
    Date hoje = new Date();

    try {/*from   w ww.  j a  va2s. c  o m*/
        if (textIsbnRD.isEmpty() || textNumRD.isEmpty()) {
            JOptionPane.showMessageDialog(painelCards, "Por favor, preencha todos os campos",
                    "Erro no Cadastro", JOptionPane.ERROR_MESSAGE);
            ok = "ops";
        }
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(painelCards, "Por favor, preencha todos os campos", "Erro no Cadastro",
                JOptionPane.ERROR_MESSAGE);
        ok = "ops";
    }

    if ("ok".equals(ok)) {
        for (int i = 0; i < vecEmprestimo.size(); i++) {
            Emprestimo tempEmprestimo = (Emprestimo) vecEmprestimo.get(i);
            if (tempEmprestimo.getIsbn().equals(textIsbnRD)
                    && tempEmprestimo.getNumExemplar().equals(textNumRD)) {
                int dias = Days.daysBetween(new DateTime(tempEmprestimo.getData()), new DateTime(hoje))
                        .getDays();

                if (dias > 6) {
                    for (int j = 0; j < vecAssociado.size(); j++) {
                        Associado tempAssociado = (Associado) vecAssociado.get(j);
                        if (tempEmprestimo.getCodAssociado()
                                .equals(Integer.toString(tempAssociado.getCodigo()))) {
                            if (("Prof".equals(tempAssociado.getStatus())) && (dias > 14)) {
                                JOptionPane.showMessageDialog(painelCards,
                                        "Devoluo Realizada\nMulta total de: R& " + (dias - 13),
                                        "Devoluo", JOptionPane.INFORMATION_MESSAGE);
                            } else if (("PosGrad".equals(tempAssociado.getStatus())) && (dias > 10)) {
                                JOptionPane.showMessageDialog(painelCards,
                                        "Devoluo Realizada\nMulta total de: R$ " + (dias - 9),
                                        "Devoluo", JOptionPane.INFORMATION_MESSAGE);
                            } else if ("Grad".equals(tempAssociado.getStatus())) {
                                JOptionPane.showMessageDialog(painelCards,
                                        "Devoluo Realizada\nMulta total de: R$" + (dias - 6), "Devoluo",
                                        JOptionPane.INFORMATION_MESSAGE);
                            }
                        }
                    }
                } else {
                    for (int j = 0; j < vecAssociado.size(); j++) {
                        Associado tempAssociado = (Associado) vecAssociado.get(j);
                        if (tempEmprestimo.getCodAssociado()
                                .equals(Integer.toString(tempAssociado.getCodigo()))) {
                            JOptionPane.showMessageDialog(painelCards,
                                    "Devoluo Realizada\nNo Possui Multas", "Devoluo",
                                    JOptionPane.INFORMATION_MESSAGE);
                        }
                    }
                }

                vecEmprestimo.remove(i);
                for (int j = 0; j < vecExemplar.size(); j++) {
                    Exemplar tempExemplar = (Exemplar) vecExemplar.get(j);
                    if (tempExemplar.getIsbn().equals(textIsbnRD)
                            && (tempExemplar.getNumero() == Integer.parseInt(textNumRD))) {
                        tempExemplar.setEmprestado(false);
                        vecExemplar.remove(j);
                        vecExemplar.add(j, tempExemplar);
                        break;
                    }
                }
                break;
            }
        }
    }
}

From source file:view.popups.timePeriod.AddTimePeriodPopup.java

/**
 * Henter timeperiods, og tager hjde for hvad der er valgt i forbindelse
 * med om den oprettede regel skal gentages eller ej.
 * @return en liste af tidsperioder.//from  w  w  w.  j a v a2s . c o m
 */
private ArrayList<TimePeriod> getRepeatedTimeInvestments() {
    LocalDateTime startTime = cStart.getValue();
    LocalDateTime endTime = cEnd.getValue();
    Room room = cRoom.getValue();
    ObservableList<Employee> employees = lEmp.getItems();
    ArrayList<TimePeriod> timePeriods = new ArrayList<>();

    for (int i = 0; i < employees.size(); i++) {
        Employee employee = employees.get(i);
        if (!cEmp.isDisabled()) {
            if (rbRepeat.isSelected()) {
                if (repeat > 0) {
                    for (int j = 0; j < repeat; j++) {
                        TimePeriod tpToAdd = new TimePeriod(startTime, endTime, min, max, room, employee);
                        int daysBetween = Days.daysBetween(startTime, endTime).getDays();
                        startTime = endTime.plusDays(1);
                        endTime = startTime.plusDays(daysBetween);

                        timePeriods.add(tpToAdd);
                    }
                }

            } else {
                TimePeriod tpToAdd = new TimePeriod(startTime, endTime, min, max, room, employee);

                timePeriods.add(tpToAdd);
            }
        } else {
            break;
        }
    }
    return timePeriods;
}

From source file:vn.webapp.controller.cp.RoomsController.java

@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);
        }// w  w  w  .j  a v  a2  s.com
        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";
        }

    }
}

From source file:vn.webapp.controller.cp.RoomsController.java

@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);
        }//from ww  w .  java  2s  . c  o  m
        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";
}

From source file:vn.webapp.controller.cp.RoomsController.java

@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);
        }//ww  w  . j  av a 2 s  .  c o  m

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