Example usage for java.util GregorianCalendar get

List of usage examples for java.util GregorianCalendar get

Introduction

In this page you can find the example usage for java.util GregorianCalendar get.

Prototype

public int get(int field) 

Source Link

Document

Returns the value of the given calendar field.

Usage

From source file:com.mss.mirage.employee.general.EmployeeAction.java

public String getMyQuarterlyAppraisalSearch() {
    resultType = LOGIN;/*  w ww  .  j a  v a2s .co m*/

    if (httpServletRequest.getSession(false) != null && httpServletRequest.getSession(false)
            .getAttribute(ApplicationConstants.SESSION_USER_ID) != null) {
        userRoleId = Integer.parseInt(httpServletRequest.getSession(false)
                .getAttribute(ApplicationConstants.SESSION_ROLE_ID).toString());
        // String workingCountry = httpServletRequest.getSession(false).getAttribute(ApplicationConstants.WORKING_COUNTRY).toString();
        String empId = httpServletRequest.getSession(false).getAttribute(ApplicationConstants.SESSION_EMP_ID)
                .toString();

        if (AuthorizationManager.getInstance().isAuthorizedUser("QUARTERLY_APPRAISAL", userRoleId)) {
            try {
                GregorianCalendar cal = new GregorianCalendar();
                int year = cal.get(Calendar.YEAR);

                if (getYear() == 0) {
                    setYear(year);
                }

                queryString = "SELECT * FROM vwQuarterlyAppraisalsList  where EmpId=" + empId
                        + " and year(CreatedDate)=" + getYear();

                if (getQuarterly() != null && !"".equals(quarterly)) {
                    queryString = queryString + " AND Quarterly='" + getQuarterly() + "' ";
                }
                //  queryString=queryString+" ORDER BY yer,Quarterly";

                httpServletRequest.getSession(false).setAttribute(ApplicationConstants.QS_EMP_APPRAISAL_LIST,
                        queryString);

                resultType = SUCCESS;
            } catch (Exception ex) {
                //List errorMsgList = ExceptionToListUtility.errorMessages(ex);
                httpServletRequest.getSession(false).setAttribute("errorMessage", ex.toString());
                resultType = ERROR;
            }
        } //END-Authorization Checking
    } //Close Session Checking
    return resultType;
}

From source file:org.eevolution.form.VCRP.java

public CategoryDataset createDataset(Timestamp start, MResource r) {
    //System.out.println("Create new data set");
    GregorianCalendar gc1 = new GregorianCalendar();
    gc1.setTimeInMillis(start.getTime());
    gc1.clear(Calendar.MILLISECOND);
    gc1.clear(Calendar.SECOND);/*  ww w  .  ja va 2s.  co m*/
    gc1.clear(Calendar.MINUTE);
    gc1.clear(Calendar.HOUR_OF_DAY);

    Timestamp date = start;
    String namecapacity = Msg.translate(Env.getCtx(), "Capacity");
    System.out.println("\n Namecapacity :" + namecapacity);
    String nameload = Msg.translate(Env.getCtx(), "Load");
    System.out.println("\n Nameload :" + nameload);
    String namesummary = Msg.translate(Env.getCtx(), "Summary");
    System.out.println("\n Namesummary :" + namesummary);
    MResourceType t = new MResourceType(Env.getCtx(), r.getS_ResourceType_ID(), null);
    System.out.println("\n Resourcetype " + t);
    int days = 1;
    long hours = 0;

    if (t.isTimeSlot()) {

        hours = MMPCMRP.getHoursAvailable(t.getTimeSlotStart(), t.getTimeSlotEnd());

    } else {
        //fjviejo e-evolution MachineQty
        if (r.getDailyCapacity().multiply(r.getMachineQty()).compareTo(Env.ZERO) != 0)
            hours = r.getDailyCapacity().multiply(r.getMachineQty()).longValue();
        else
            //fjviejo e-evolution end
            hours = 24;
    }
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();

    //      Long Hours = new Long(hours);
    int C_UOM_ID = DB.getSQLValue(null, "SELECT C_UOM_ID FROM M_Product WHERE S_Resource_ID = ? ",
            r.getS_Resource_ID());
    MUOM uom = new MUOM(Env.getCtx(), C_UOM_ID, null);
    System.out.println("\n uom1 " + uom + "\n");
    //System.out.println("um.isHour()"+ uom.isHour() );
    if (!uom.isHour()) {
        System.out.println("\n uom2 " + uom + "\n");
        return dataset;
    }
    System.out.println("\n Dataset " + dataset + "\n");
    int summary = 0;
    //int cont = 1;
    DateFormat formatter = DateFormat.getDateInstance();

    /*
     *     Vit4B Modificado para que tome 28 dias y
     *
     *
     */

    while (days < 29) {
        /*
         *      VIT4B MODIFICACION PARA ACUMULADO DE DIAS
         *
         *
         *
                
                
        //System.out.println("Day Number" + days);
        String strday = formatter.format(date);
        //String day = new String(new Integer (date.getDate()).toString());
        String day = new String(formatter.format(date));
        //day = day.substring(0,5);
                
        int index = day.indexOf("/");
                
        String str = day.substring(0,index);
        System.out.println("str: " + str + " index de / " + index);
                
        String str2 = day.substring(index+1,day.length());
        System.out.println("str2 resto: " + str2);
                
        index = str2.indexOf("/");
        System.out.println(index);
                
        String str3 = str2.substring(0,index);
        System.out.println("str3: " + str3 + " index de / " + index);
                
        String str4 = str2.substring(index+1,str2.length());
        System.out.println(str4);
                
        System.out.println("dia: " + str);
        System.out.println("mes: " + str3);
        System.out.println("ao: " + str4);
                
        //day = str + str3;
                
        day = new String(str + str3);
                
                
        //day = day.substring(0,day.lastIndexOf("/"));
        //day =day.substring(0,3);
                
        //cont++;
                
        System.out.println("r.getS_Resource_ID()" + r.getS_Resource_ID());
        System.out.println("Date: "  +  date + " day: "  +  day);
        int seconds = getLoad(r.getS_Resource_ID(),date ,date);
        Long Hours = new Long(hours);
        System.out.println("Summary "+ summary);
        System.out.println("Capacity "+ hours);
        System.out.println("Load "+ seconds);
                
        /*
         *
         *      VIT4B MODIFICACION PARA ACUMULADO DE DIAS
         *
         *
         */

        /*
         *      ORIGINAL COMPIERE
         */

        String day = new String(new Integer(date.getDate()).toString());
        System.out.println("r.getS_Resource_ID()" + r.getS_Resource_ID());
        System.out.println("Date:" + date);

        /*
         *      VIT4B - Modificacin para calcular como se calcula el reporte CCRP
         *      en funcion de la carga parcial
         *
         *
         */

        int seconds = getLoad(r.getS_Resource_ID(), date, date);

        //BigDecimal value = calculateLoad(date, r, null);
        //int seconds = value.intValue();

        Long Hours = new Long(hours);
        System.out.println("Summary " + summary);
        System.out.println("Load " + seconds);

        /*
         *      FIN ORIGINAL COMPIERE
         *
         */

        switch (gc1.get(Calendar.DAY_OF_WEEK)) {
        case Calendar.SUNDAY:
            days++;
            if (t.isOnSunday()) { //System.out.println("si Sunday");
                                  //Msg.translate(Env.getCtx(), "OnSunday");
                dataset.addValue(hours, namecapacity, day);
                dataset.addValue(seconds / 3600, nameload, day);
                dataset.addValue(summary, namesummary, day);
                summary = summary + Hours.intValue() - (seconds / 3600); //+ (Hours.intValue() - ((seconds / 3600)));
                gc1.add(Calendar.DATE, 1);
                date = org.compiere.util.TimeUtil.addDays(date, 1);
                break;
            } else { //System.out.println("no Sunday");
                     //String day = Msg.translate(Env.getCtx(), "OnSunday") ;
                dataset.addValue(0, namecapacity, day);
                dataset.addValue(seconds / 3600, nameload, day);
                dataset.addValue(summary, namesummary, day);
                summary = summary - (seconds / 3600);
                gc1.add(Calendar.DATE, 1);
                date = org.compiere.util.TimeUtil.addDays(date, 1);
                break;
            }
        case Calendar.MONDAY:
            days++;
            if (t.isOnMonday()) { //System.out.println("si Monday");
                                  //String day = Msg.translate(Env.getCtx(), "OnMonday") ;
                dataset.addValue(hours, namecapacity, day);
                dataset.addValue(seconds / 3600, nameload, day);
                dataset.addValue(summary, namesummary, day);
                summary = summary + Hours.intValue() - (seconds / 3600);
                gc1.add(Calendar.DATE, 1);
                date = org.compiere.util.TimeUtil.addDays(date, 1);
                break;
            } else {
                //System.out.println("no Monday");
                //String day = Msg.translate(Env.getCtx(), "OnMonday")  ;
                dataset.addValue(0, namecapacity, day);
                dataset.addValue(seconds / 3600, nameload, day);
                dataset.addValue(summary, namesummary, day);
                summary = summary - (seconds / 3600);
                gc1.add(Calendar.DATE, 1);
                date = org.compiere.util.TimeUtil.addDays(date, 1);
                break;
            }
        case Calendar.TUESDAY:
            days++;
            if (t.isOnTuesday()) { //System.out.println("si TuesDay");
                                   //String day = Msg.translate(Env.getCtx(), "OnTuesday");
                dataset.addValue(hours, namecapacity, day);
                dataset.addValue(seconds / 3600, nameload, day);
                dataset.addValue(summary, namesummary, day);
                summary = summary + Hours.intValue() - (seconds / 3600);
                gc1.add(Calendar.DATE, 1);
                date = org.compiere.util.TimeUtil.addDays(date, 1);
                break;
            } else {
                //System.out.println("no TuesDay");
                //String day = Msg.translate(Env.getCtx(), "OnTuesday");
                dataset.addValue(0, namecapacity, day);
                dataset.addValue(seconds / 3600, nameload, day);
                dataset.addValue(summary, namesummary, day);
                summary = summary - (seconds / 3600);
                gc1.add(Calendar.DATE, 1);
                date = org.compiere.util.TimeUtil.addDays(date, 1);
                break;
            }
        case Calendar.WEDNESDAY:
            days++;
            if (t.isOnWednesday()) {
                //String day = Msg.translate(Env.getCtx(), "OnWednesday");
                dataset.addValue(hours, namecapacity, day);
                dataset.addValue(seconds / 3600, nameload, day);
                dataset.addValue(summary, namesummary, day);
                summary = summary + Hours.intValue() - (seconds / 3600);
                gc1.add(Calendar.DATE, 1);
                date = org.compiere.util.TimeUtil.addDays(date, 1);
                break;
            } else {

                //String day = Msg.translate(Env.getCtx(), "OnWednesday");
                dataset.addValue(0, namecapacity, day);
                dataset.addValue(seconds / 3600, nameload, day);
                dataset.addValue(summary, namesummary, day);
                summary = summary - (seconds / 3600);
                gc1.add(Calendar.DATE, 1);
                date = org.compiere.util.TimeUtil.addDays(date, 1);
                break;
            }
        case Calendar.THURSDAY:
            days++;
            if (t.isOnThursday()) {
                //String day = Msg.translate(Env.getCtx(), "OnThursday");
                dataset.addValue(hours, namecapacity, day);
                dataset.addValue(seconds / 3600, nameload, day);
                dataset.addValue(summary, namesummary, day);
                summary = summary + Hours.intValue() - (seconds / 3600);
                gc1.add(Calendar.DATE, 1);
                date = org.compiere.util.TimeUtil.addDays(date, 1);
                break;
            } else {

                //String day = Msg.translate(Env.getCtx(), "OnThursday");
                dataset.addValue(0, namecapacity, day);
                dataset.addValue(seconds / 3600, nameload, day);
                dataset.addValue(summary, namesummary, day);
                summary = summary - (seconds / 3600);
                gc1.add(Calendar.DATE, 1);
                date = org.compiere.util.TimeUtil.addDays(date, 1);
                break;
            }
        case Calendar.FRIDAY:
            days++;
            if (t.isOnFriday()) {
                //String day = Msg.translate(Env.getCtx(), "OnFriday");
                dataset.addValue(hours, namecapacity, day);
                dataset.addValue(seconds / 3600, nameload, day);
                dataset.addValue(summary, namesummary, day);
                summary = summary + Hours.intValue() - (seconds / 3600);
                gc1.add(Calendar.DATE, 1);
                date = org.compiere.util.TimeUtil.addDays(date, 1);
                break;
            } else {

                //String day = Msg.translate(Env.getCtx(), "OnFriday");
                dataset.addValue(0, namecapacity, day);
                dataset.addValue(seconds / 3600, nameload, day);
                dataset.addValue(summary, namesummary, day);
                summary = summary - (seconds / 3600);
                gc1.add(Calendar.DATE, 1);
                date = org.compiere.util.TimeUtil.addDays(date, 1);
                break;
            }
        case Calendar.SATURDAY:
            days++;
            if (t.isOnSaturday()) {
                //String day = Msg.translate(Env.getCtx(), "OnSaturday");
                dataset.addValue(hours, namecapacity, day);
                dataset.addValue(seconds / 3600, nameload, day);
                dataset.addValue(summary, namesummary, day);
                summary = summary + Hours.intValue() - (seconds / 3600);
                gc1.add(Calendar.DATE, 1);
                date = org.compiere.util.TimeUtil.addDays(date, 1);
                break;
            } else {
                //String day = Msg.translate(Env.getCtx(), "OnSaturday");
                dataset.addValue(0, namecapacity, day);
                dataset.addValue(seconds / 3600, nameload, day);
                dataset.addValue(summary, namesummary, day);
                summary = summary - (seconds / 3600);
                gc1.add(Calendar.DATE, 1);
                date = org.compiere.util.TimeUtil.addDays(date, 1);
                break;
            }
        }

    }
    return dataset;
}

From source file:com.mss.mirage.employee.general.EmployeeAction.java

public String teamQuaterAppraisalSearch() {
    resultType = LOGIN;//from w w  w.  j a  va  2 s  .  c om

    if (httpServletRequest.getSession(false) != null && httpServletRequest.getSession(false)
            .getAttribute(ApplicationConstants.SESSION_USER_ID) != null) {
        userRoleId = Integer.parseInt(httpServletRequest.getSession(false)
                .getAttribute(ApplicationConstants.SESSION_ROLE_ID).toString());
        // String workingCountry = httpServletRequest.getSession(false).getAttribute(ApplicationConstants.WORKING_COUNTRY).toString();
        String empId = httpServletRequest.getSession(false).getAttribute(ApplicationConstants.SESSION_EMP_ID)
                .toString();
        String loginId1 = httpServletRequest.getSession(false)
                .getAttribute(ApplicationConstants.SESSION_USER_ID).toString();
        if (AuthorizationManager.getInstance().isAuthorizedUser("QUARTERLY_APPRAISAL", userRoleId)) {
            try {

                GregorianCalendar cal = new GregorianCalendar();
                int year = cal.get(Calendar.YEAR);

                if (getYear() == 0) {
                    setYear(year);
                }
                Map rolesMap = (Map) httpServletRequest.getSession(false)
                        .getAttribute(ApplicationConstants.SESSION_MY_ROLES);
                //     queryString = "SELECT tblQuarterlyAppraisals.Id,EmpId,AppraisalId,CONCAT(fname,' ',mName,'.',lName) AS empName,DATE_FORMAT(tblQuarterlyAppraisals.CreatedDate,'%M') AS mnth, YEAR(tblQuarterlyAppraisals.CreatedDate) AS yer,tblQuarterlyAppraisals.CreatedDate,Quarterly,STATUS,SubmittedDate,ApprovedDate,OpperationTeamStatus,CONCAT(emp2.fname,'.',emp2.lName) AS approvedBy FROM tblQuarterlyAppraisals LEFT JOIN tblEmployee emp1 ON(tblQuarterlyAppraisals.EmpId=emp1.Id) LEFT JOIN tblEmployee emp2 ON(tblQuarterlyAppraisals.ApprovedBy=emp2.LoginId) where year(tblQuarterlyAppraisals.CreatedDate)=" + getYear();
                queryString = "SELECT * FROM vwQuarterlyAppraisalsList where year(CreatedDate)=" + getYear();
                Map myTeamMemebrs = new HashMap();
                // System.out.println("httpServletRequest.getSession(false).getAttribute(ApplicationConstants.SESSION_ROLE_NAME).toString()===" + httpServletRequest.getSession(false).getAttribute(ApplicationConstants.SESSION_ROLE_NAME).toString());
                if (httpServletRequest.getSession(false).getAttribute(ApplicationConstants.SESSION_ROLE_NAME)
                        .toString().equalsIgnoreCase("Employee")) {
                    if (loginId1.equals("rkalaga")) {
                        //  myTeamMemebrs = DataSourceDataProvider.getInstance().getAllEmployees();
                        myTeamMemebrs = DataSourceDataProvider.getInstance().getAllEmployeesByCountry("India");
                    } else {
                        myTeamMemebrs = (Map) httpServletRequest.getSession(false)
                                .getAttribute(ApplicationConstants.SESSION_MY_TEAM_MAP);
                    }
                } else if (httpServletRequest.getSession(false)
                        .getAttribute(ApplicationConstants.SESSION_ROLE_NAME).toString()
                        .equalsIgnoreCase("Operations")) {

                    String department = httpServletRequest.getSession(false)
                            .getAttribute(ApplicationConstants.SESSION_MY_DEPT_ID).toString();
                    int isManager = Integer.parseInt(httpServletRequest.getSession(false)
                            .getAttribute(ApplicationConstants.SESSION_IS_USER_MANAGER).toString());
                    String access[] = Properties.getProperty("QuarterlyAppraisal.Access")
                            .split(Pattern.quote(","));

                    List accessList = Arrays.asList(access);
                    if (accessList.contains(loginId1) || (department.equals("Operations") && isManager == 1)
                            || rolesMap.containsValue("Admin")) {
                        setAccessCount(1);
                    }
                    if (getAccessCount() == 1) {
                        //  myTeamMemebrs = DataSourceDataProvider.getInstance().getAllEmployees();
                        myTeamMemebrs = DataSourceDataProvider.getInstance().getAllEmployeesByCountry("India");

                    } else {
                        myTeamMemebrs = DataSourceDataProvider.getInstance().getInstance()
                                .getEmployeeNamesByOperationsContactId((httpServletRequest.getSession(false)
                                        .getAttribute(ApplicationConstants.SESSION_EMP_ID).toString()));

                    }
                    //  myTeamMemebrs = (Map) httpServletRequest.getSession(false).getAttribute(ApplicationConstants.SESSION_MY_TEAM_MAP);

                }
                String teamList = DataSourceDataProvider.getInstance().getTeamLoginIdList(myTeamMemebrs);
                setMyTeamMembers(myTeamMemebrs);
                if (loginId != null && !"".equals(loginId)) {
                    queryString = queryString + " AND loginId ='" + loginId + "'";
                } else {
                    if (!"".equals(teamList)) {
                        queryString = queryString + " AND loginId IN(" + teamList + ")";
                    } else {
                        queryString = queryString + " AND loginId IN('')";
                    }
                }
                if (getQuarterly() != null && !"".equals(quarterly)) {
                    queryString = queryString + " AND Quarterly='" + getQuarterly() + "' ";
                }

                if (status != null && !"".equals(status)) {
                    queryString = queryString + " AND status='" + status + "' ";
                }

                if (departmentId != null && !"".equals(departmentId)) {
                    queryString = queryString + " AND DepartmentId='" + departmentId + "' ";
                }
                if (practiceId != null && !"".equals(practiceId) && !"All".equals(practiceId)) {
                    queryString = queryString + " AND Practice='" + practiceId + "' ";
                }
                if (subPractice != null && !"".equals(subPractice) && !"All".equals(subPractice)) {
                    queryString = queryString + " AND SubPractice='" + subPractice + "' ";
                }
                if (opsContactId != null && !"".equals(opsContactId)) {
                    queryString = queryString + " AND OpsContactId=" + opsContactId + " ";
                }
                if (location != null && !"".equals(location)) {
                    queryString = queryString + " AND Location='" + location + "' ";
                }
                if (titleId != null && !"".equals(titleId)) {

                    String ManagerList = Properties.getProperty("Management.Quarter");
                    if (titleId.equals("Management")) {
                        queryString = queryString + " AND FIND_IN_SET(Title,'" + ManagerList + "') ";
                    } else {
                        queryString = queryString + " AND !FIND_IN_SET(Title,'" + ManagerList + "') ";
                    }
                }

                /* if (httpServletRequest.getSession(false).getAttribute(ApplicationConstants.SESSION_ROLE_NAME).toString().equalsIgnoreCase("Operations") || loginId1.equals("rkalaga")) {
                      queryString = queryString + " AND STATUS NOT IN ('Submitted','Entered') ";
                            
                            
                 }else{
                     queryString = queryString + " AND STATUS NOT IN ('Entered') ";
                 }*/

                //    queryString=queryString+" ORDER BY yer,Quarterly";
                String Country = (String) httpServletRequest.getSession(false)
                        .getAttribute(ApplicationConstants.Living_COUNTRY);
                if (rolesMap.containsValue("Admin")) {
                    setOpsContactIdMap(DataSourceDataProvider.getInstance().getOpsContactId(Country, "Yes"));
                } else {
                    setOpsContactIdMap(DataSourceDataProvider.getInstance().getOpsContactId(Country, "No"));
                }

                if (rolesMap.containsValue("Admin")) {
                    setLocationsMap(DataSourceDataProvider.getInstance().getEmployeeLocationsList("%"));
                } else {
                    setLocationsMap(DataSourceDataProvider.getInstance().getEmployeeLocationsList(Country));
                }
                httpServletRequest.getSession(false).setAttribute(ApplicationConstants.QS_EMP_APPRAISAL_LIST,
                        queryString);

                resultType = SUCCESS;
            } catch (Exception ex) {
                ex.printStackTrace();
                //List errorMsgList = ExceptionToListUtility.errorMessages(ex);
                httpServletRequest.getSession(false).setAttribute("errorMessage", ex.toString());
                resultType = ERROR;
            }
        } //END-Authorization Checking
    } //Close Session Checking
    return resultType;
}

From source file:org.sakaiproject.calendar.impl.BaseCalendarService.java

/**
 * Generates a list of time ranges for a week. Each range in the list is a day.
 * // w  w  w  . j  av  a  2  s . co  m
 * @param timeRange start & end date range
 * @param calendarReferenceList list of calendar(s) 
 * @param dailyTimeRange start and end hour/minute time range
 */
protected ArrayList getTimeRangeListForWeek(TimeRange timeRange, List calendarReferenceList,
        TimeRange dailyTimeRange) {
    TimeBreakdown startBreakdown = timeRange.firstTime().breakdownLocal();

    GregorianCalendar startCalendarDate = (GregorianCalendar) GregorianCalendar
            .getInstance(m_timeService.getLocalTimeZone(), rb.getLocale());
    startCalendarDate.set(startBreakdown.getYear(), startBreakdown.getMonth() - 1, startBreakdown.getDay(), 0,
            0, 0);

    ArrayList weekDayTimeRanges = new ArrayList();

    TimeBreakdown startBreakDown = dailyTimeRange.firstTime().breakdownLocal();

    TimeBreakdown endBreakDown = dailyTimeRange.lastTime().breakdownLocal();

    // Search all seven weekdays
    // Note: no assumption can be made regarding the first day being Sunday, 
    // since in some locales, the first weekday is Monday.
    for (int i = 0; i <= 6; i++) {
        //
        // Use the same start/end times for all days.
        //
        Time curStartTime = m_timeService.newTimeLocal(startCalendarDate.get(GregorianCalendar.YEAR),
                startCalendarDate.get(GregorianCalendar.MONTH) + 1,
                startCalendarDate.get(GregorianCalendar.DAY_OF_MONTH), startBreakDown.getHour(),
                startBreakDown.getMin(), startBreakDown.getSec(), startBreakDown.getMs());

        Time curEndTime = m_timeService.newTimeLocal(startCalendarDate.get(GregorianCalendar.YEAR),
                startCalendarDate.get(GregorianCalendar.MONTH) + 1,
                startCalendarDate.get(GregorianCalendar.DAY_OF_MONTH), endBreakDown.getHour(),
                endBreakDown.getMin(), endBreakDown.getSec(), endBreakDown.getMs());

        TimeRange newTimeRange = m_timeService.newTimeRange(curStartTime, curEndTime, true, false);
        weekDayTimeRanges.add(newTimeRange);

        // Move to the next day.
        startCalendarDate.add(GregorianCalendar.DATE, 1);
    }

    return weekDayTimeRanges;
}

From source file:gov.llnl.lustre.lwatch.PlotFrame2.java

/**
 * Update the control widgets to reflect the current time settings.
 *//*from   ww  w .  j  a v a 2  s.  co m*/

public void updateControlValues() {
    int tindx = ovIDX / nCurvesSelected;

    int[] daysInMonth = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
    //long xstart = rawTimes[tindx][startIndex];
    //long xstop = rawTimes[tindx][stopIndex];

    /***
        if (localDebug) {
       Debug.out("\nxstart before = " + (new Date(xstart)).toString() +
            "  stopIndex = " + startIndex);
       Debug.out("xstop before = " + (new Date(xstop)).toString() +
            "  stopIndex = " + stopIndex);
           }
            
        if (xstop < (3600000*48)) {  // Invalid time value
       while ((stopIndex > 0) && ((rawTimes[ovIDX][stopIndex]) < (3600000*48))) {
           if (localDebug)
          Debug.out(stopIndex + "  " + xstop);
           xstop = rawTimes[tindx][--stopIndex];
       }
        }
    ***/

    if (limitedDebug) {
        Debug.out("dataPointCount[0] = " + dataPointCount[0]);
        Debug.out("tsStartPlot after = " + tsStartPlot);
        Debug.out("tsEndPlot after = " + tsEndPlot + "\n");
    }

    Date dstart = new Date(tsStartPlot.getTime()); //xstart);
    Date dstop = new Date(tsEndPlot.getTime()); //xstop);
    GregorianCalendar cal = new GregorianCalendar();

    if (localDebug)
        Debug.out("dstart = " + dstart.toString() + "\ndstop = " + dstop.toString());

    // Set the Start widgets.
    cal.setTime(dstart);
    int yrstart = cal.get(Calendar.YEAR);
    yrChooser.setSelectedYear(yrstart);
    int mnthstart = cal.get(Calendar.MONTH);
    monthChooser.setSelectedMonth(mnthstart);
    int daystart = cal.get(Calendar.DAY_OF_MONTH);
    dayChooser.setSelectedDay(daystart);
    int hrstart = cal.get(Calendar.HOUR_OF_DAY);
    hourChooser.setSelectedHour(hrstart);
    int minstart = cal.get(Calendar.MINUTE);
    minuteChooser.setSelectedMinute(minstart);

    // Set the End widgets.
    cal.setTime(dstop);
    int yrstop = cal.get(Calendar.YEAR);
    yrEndChooser.setSelectedYear(yrstop);
    int mnthstop = cal.get(Calendar.MONTH);
    monthEndChooser.setSelectedMonth(mnthstop);
    int daystop = cal.get(Calendar.DAY_OF_MONTH);
    dayEndChooser.setSelectedDay(daystop);
    int hrstop = cal.get(Calendar.HOUR_OF_DAY);
    hourEndChooser.setSelectedHour(hrstop);
    int minstop = cal.get(Calendar.MINUTE);
    minuteEndChooser.setSelectedMinute(minstop);

    // Set the Duration widgets.
    long durationhours = (tsEndPlot.getTime() - tsStartPlot.getTime()) / HOUR;
    //Debug.out("Length of chart plot interval = " + durationhours + " hours");
    int yrDur = yrstop - yrstart;
    //Debug.out("yrDur = " + yrDur);
    int mnthDur = mnthstop - mnthstart;
    //Debug.out("mnthDur = " + mnthDur);
    if (mnthDur < 0) {
        yrDur = Math.max(0, yrDur - 1);
        mnthDur = 12 - mnthstart + mnthstop;
        //Debug.out("Adjusted mnthDur = " + mnthDur);
    }
    int dayDur = daystop - daystart;
    //Debug.out("dayDur = " + dayDur);
    if (dayDur < 0) {
        mnthDur = Math.max(0, mnthDur - 1);
        dayDur = daysInMonth[mnthstart] - daystart + daystop;
        //Debug.out("Adjusted dayDur = " + dayDur);
    }
    int hrDur = hrstop - hrstart;
    //Debug.out("hrDur = " + hrDur);
    if (hrDur < 0) {
        dayDur = Math.max(0, dayDur - 1);
        hrDur = 24 - hrstart + hrstop;
        //Debug.out("Adjusted hrDur = " + hrDur);
    }
    int minDur = minstop - minstart;
    //Debug.out("minDur = " + minDur + "\n");
    if (minDur < 0) {
        hrDur = Math.max(0, hrDur - 1);
        minDur = 60 - minstart + minstop;
        //Debug.out("Adjusted minDur = " + minDur + "\n");
    }

    yrDurChooser.setSelected(yrDur);
    monthDurChooser.setSelected(mnthDur);
    dayDurChooser.setSelected(dayDur);
    hourDurChooser.setSelected(hrDur);
    minuteDurChooser.setSelected(minDur);

}

From source file:gov.nih.nci.cadsr.sentinel.database.DBAlertOracle.java

/**
 * Get the Alerts which are active for the target date provided.
 *
 * @param target_//  w w w .  j  a v a2 s .  c om
 *        The target date, typically the date an Auto Run process is
 *        started.
 * @return null if an error, otherwise the list of valid alert definitions.
 */
public AlertRec[] selectAlerts(Timestamp target_) {
    String select = "select al_idseq, name, created_by " + "from sbrext.sn_alert_view_ext "
            + "where al_status <> 'I' AND " + "(auto_freq_unit = 'D' OR "
            + "(auto_freq_unit = 'W' AND auto_freq_value = ?) OR "
            + "(auto_freq_unit = 'M' AND auto_freq_value = ?)) "
            + "order by upper(created_by) asc, upper(name) asc";

    // Get day and date from target to qualify the select.
    GregorianCalendar tdate = new GregorianCalendar();
    tdate.setTimeInMillis(target_.getTime());
    int dayWeek = tdate.get(Calendar.DAY_OF_WEEK);
    int dayMonth = tdate.get(Calendar.DAY_OF_MONTH);

    PreparedStatement pstmt = null;
    ResultSet rs = null;
    AlertRec[] recs = null;
    try {
        // Set SQL arguments
        pstmt = _conn.prepareStatement(select);
        pstmt.setInt(1, dayWeek);
        pstmt.setInt(2, dayMonth);

        // Retrieve all applicable definition ids.
        rs = pstmt.executeQuery();
        Vector<String> list = new Vector<String>();
        while (rs.next()) {
            list.add(rs.getString(1));
        }
        rs.close();
        rs = null;
        pstmt.close();
        pstmt = null;

        // There may be nothing to do.
        if (list.size() == 0)
            recs = new AlertRec[0];
        else {
            // retrieve the full alert definition, we will need it.
            recs = new AlertRec[list.size()];
            int keep = 0;
            int ndx;
            for (ndx = 0; ndx < recs.length; ++ndx) {
                // Be sure we can read the Alert Definition.
                recs[keep] = selectAlert((String) list.get(ndx));
                if (recs[keep] == null)
                    return null;

                // Check the date. We do this here and not in the SQL because
                // 99.99% of the time this will return true and complicating the
                // SQL isn't necessary.
                if (recs[keep].isActive(target_))
                    ++keep;

                // In the RARE situation that the alert is inactive at this
                // point,
                // we reset the object pointer to release the memory.
                else
                    recs[keep] = null;
            }

            // Return the results. It is possible that sometimes the last entry
            // in the
            // list will be null. Consequently the use of the list should be in
            // a loop
            // with the following condition: "cnt < recs.length && recs[cnt] !=
            // null"
            if (keep != ndx) {
                // Only process the ones that are Active.
                AlertRec trecs[] = new AlertRec[keep];
                for (ndx = 0; ndx < keep; ++ndx)
                    trecs[ndx] = recs[ndx];
                recs = trecs;
            }
        }
    } catch (SQLException ex) {
        _errorCode = DBAlertUtil.getSQLErrorCode(ex);
        _errorMsg = _errorCode + ": " + select + "\n\n" + ex.toString();
        _logger.error(_errorMsg);
    } finally {
        closeCursors(pstmt, rs);
    }
    return recs;
}

From source file:org.sakaiproject.calendar.impl.BaseCalendarService.java

/**
 * Returns a list of daily time ranges for every day in a range.
 * /*w w w  . j  a  v a 2 s .  c o  m*/
 * @param timeRange
 *        overall time range
 * @param dailyTimeRange
 *        representative daily time range (start hour/minute, end hour/minute). If null, this parameter is ignored.
 */
protected ArrayList splitTimeRangeIntoListOfSingleDayTimeRanges(TimeRange timeRange, TimeRange dailyTimeRange) {

    TimeBreakdown startBreakdown = timeRange.firstTime().breakdownLocal();
    TimeBreakdown endBreakdown = timeRange.lastTime().breakdownLocal();

    GregorianCalendar startCalendarDate = new GregorianCalendar();
    startCalendarDate.set(startBreakdown.getYear(), startBreakdown.getMonth() - 1, startBreakdown.getDay(), 0,
            0, 0);

    long numDaysInTimeRange = getNumberDaysGivenTwoDates(startBreakdown.getYear(),
            startBreakdown.getMonth() - 1, startBreakdown.getDay(), endBreakdown.getYear(),
            endBreakdown.getMonth() - 1, endBreakdown.getDay());

    ArrayList splitTimeRanges = new ArrayList();

    TimeBreakdown dailyStartBreakDown = null;
    TimeBreakdown dailyEndBreakDown = null;

    if (dailyTimeRange != null) {
        dailyStartBreakDown = dailyTimeRange.firstTime().breakdownLocal();
        dailyEndBreakDown = dailyTimeRange.lastTime().breakdownLocal();
    }

    for (long i = 0; i < numDaysInTimeRange; i++) {
        Time curStartTime = null;
        Time curEndTime = null;

        if (dailyTimeRange != null) {
            //
            // Use the same start/end times for all days.
            //
            curStartTime = m_timeService.newTimeLocal(startCalendarDate.get(GregorianCalendar.YEAR),
                    startCalendarDate.get(GregorianCalendar.MONTH) + 1,
                    startCalendarDate.get(GregorianCalendar.DAY_OF_MONTH), dailyStartBreakDown.getHour(),
                    dailyStartBreakDown.getMin(), dailyStartBreakDown.getSec(), dailyStartBreakDown.getMs());

            curEndTime = m_timeService.newTimeLocal(startCalendarDate.get(GregorianCalendar.YEAR),
                    startCalendarDate.get(GregorianCalendar.MONTH) + 1,
                    startCalendarDate.get(GregorianCalendar.DAY_OF_MONTH), dailyEndBreakDown.getHour(),
                    dailyEndBreakDown.getMin(), dailyEndBreakDown.getSec(), dailyEndBreakDown.getMs());

            splitTimeRanges.add(m_timeService.newTimeRange(curStartTime, curEndTime, true, false));
        } else {
            //
            // Add a full day range since no start/stop time was specified.
            //
            splitTimeRanges.add(getFullDayTimeRangeFromYMD(startCalendarDate.get(GregorianCalendar.YEAR),
                    startCalendarDate.get(GregorianCalendar.MONTH) + 1,
                    startCalendarDate.get(GregorianCalendar.DAY_OF_MONTH)));
        }

        // Move to the next day.
        startCalendarDate.add(GregorianCalendar.DATE, 1);
    }

    return splitTimeRanges;
}

From source file:gov.noaa.pfel.coastwatch.Projects.java

/**
 * Processes one CalCOFI2012 tsv file into a .nc file.
 * //  ww  w . jav  a 2  s.co  m
 * <p>The var sequence of latitude, latitudeMinutes, latitudeLocation
 * will be converted to 1 latitude column (decimal degrees).
 * Similar with longitude.
 *
 * <p>If units are yyMM, var will be converted to yyyyMM and units="".
 *
 * <p>If units are yyMMdd, var will be converted to yyyyMMdd, then
 * to "seconds since 1970-01-01T00:00:00Z" (assuming Pacific time zone) 
 * and sets attribute: time_precision=1970-01-01.
 *
 * <p>If units of variable after yyMMdd are HHmm, the date and time will
 * be combined into one "seconds since 1970-01-01T00:00:00Z" variable.
 *
 * <p>If variableName="timeZone", this checks to see if arriveDate value 
 * timeZone offset is as expected.
 *
 * @param dir
 * @param tableName  e.g., CC_TOWS
 * @param info  with 4 strings (name, type, units, long_name) for each variable 
 * @param towTypesDescription will be added as description=[towTypesDescrption]
 *   when variableName=towTypeCode.
 * @return the table, as saved in the .nc file.
 */
public static Table processOneCalcofi2012(String dir, String tableName, String info[],
        String towTypesDescription) throws Exception {

    String rowName = "row";
    int cutoffYear = 20; // fourDigitYear += twoDigitYear < cutoffYear? 2000 : 1900;

    /*  make tsv into ERDDAP-style .json table
    //{
    //  "table": {
    //    "columnNames": ["longitude", "latitude", "time", "sea_surface_temperature"],
    //    "columnTypes": ["float", "float", "String", "float"],
    //    "columnUnits": ["degrees_east", "degrees_north", "UTC", "degree_C"],
    //    "rows": [
    //      [180.099, 0.032, "2007-10-04T12:00:00Z", 27.66],
    //      [180.099, 0.032, null, null],
    //      [189.971, -7.98, "2007-10-04T12:00:00Z", 29.08]
    //    ]
    //}
    */
    String inFile = dir + tableName + ".txt";
    String2.log("\n* processOneCalcofi2012 " + inFile);
    StringArray names = new StringArray();
    StringArray types = new StringArray();
    StringArray units = new StringArray();
    StringArray lNames = new StringArray();
    Test.ensureEqual(info.length % 4, 0, "info.length=" + info.length);
    int nVars = info.length / 4;
    int n = 0;
    for (int v = 0; v < nVars; v++) {
        names.add(info[n++]);
        types.add(info[n++]);
        units.add(info[n++]);
        lNames.add(info[n++]);
    }

    String fromFile[] = String2.readFromFile(inFile);
    if (fromFile[0].length() > 0)
        throw new RuntimeException(fromFile[0]);
    String lines = String2.replaceAll(fromFile[1], "\t", ",");
    lines = String2.replaceAll(lines, "\n", "],\n[");
    lines = "{\n" + "  \"table\": {\n" + "    \"columnNames\": [" + names.toJsonCsvString() + "],\n"
            + "    \"columnTypes\": [" + types.toJsonCsvString() + "],\n" + "    \"columnUnits\": ["
            + units.toJsonCsvString() + "],\n" + "    \"rows\": [\n" + "["
            + lines.substring(0, lines.length() - 3) + "\n" + "]\n" + "}\n";
    String2.log(lines.substring(0, Math.min(lines.length(), 1500)));
    Table table = new Table();
    table.readJson(inFile, lines);
    String2.log("Before adjustments:\n" + String2.annotatedString(table.dataToString(5)));
    int nRows = table.nRows();
    int nErrors = 0;

    //things where nColumns won't change
    for (int v = 0; v < table.nColumns(); v++) {
        PrimitiveArray pa = table.getColumn(v);
        String vName = table.getColumnName(v);
        Attributes atts = table.columnAttributes(v);

        //longNames
        atts.add("long_name", lNames.get(v)); //relies on original var lists

        //timeZone
        nErrors = 0;
        if ("timeZone".equals(vName)) {
            PrimitiveArray arrivePA = table.getColumn("arriveDate"); //still yyMMdd
            GregorianCalendar gc = new GregorianCalendar(TimeZone.getTimeZone("America/Los_Angeles"));
            Calendar2.clearSmallerFields(gc, Calendar2.DATE);
            for (int row = 0; row < nRows; row++) {
                String val = arrivePA.getString(row);
                if (val.matches("[0-9]{6}")) {
                    int year = String2.parseInt(val.substring(0, 2));
                    gc.set(Calendar2.YEAR, year < cutoffYear ? 2000 : 1900);
                    gc.set(Calendar2.MONTH, String2.parseInt(val.substring(2, 4)) - 1); //0..
                    gc.set(Calendar2.DATE, String2.parseInt(val.substring(4, 6)));
                    int fileHas = pa.getInt(row);
                    int calculated = -gc.get(Calendar.ZONE_OFFSET) / (60 * 60 * 1000) + //in hours
                            -gc.get(Calendar.DST_OFFSET) / (60 * 60 * 1000); //in hours
                    if (fileHas != calculated) {
                        nErrors++;
                        if (nErrors <= 5)
                            String2.log("ERROR: col=" + vName + " row=" + row + " timeZone=" + fileHas
                                    + " != calculated(" + val + ")=" + calculated);
                    }
                }
            }
            if (nErrors > 0)
                String2.pressEnterToContinue("Bob: check US daylight savings time rules. On/near these dates?\n"
                        + "https://en.wikipedia.org/wiki/History_of_time_in_the_United_States\n" + "nErrors="
                        + nErrors);
        }

    }

    //things where nColumns may change
    for (int v = 0; v < table.nColumns(); v++) {
        PrimitiveArray pa = table.getColumn(v);
        String vName = table.getColumnName(v);
        Attributes atts = table.columnAttributes(v);
        String vUnits = atts.getString("units");
        Attributes nextAtts = v < table.nColumns() - 1 ? table.columnAttributes(v + 1) : new Attributes();

        //towTypeCode
        if ("towTypeCode".equals(vName))
            atts.add("description", towTypesDescription);

        //latitude
        nErrors = 0;
        if ("latitude".equals(vName) && "latitudeMinutes".equals(table.getColumnName(v + 1))
                && "latitudeLocation".equals(table.getColumnName(v + 2))) {
            FloatArray fa = new FloatArray(nRows, false); //float avoids, e.g., xx.33333333333333
            PrimitiveArray pa1 = table.getColumn(v + 1);
            PrimitiveArray pa2 = table.getColumn(v + 2);
            for (int row = 0; row < nRows; row++) {
                String loc = pa2.getString(row);
                String combo = pa.getString(row) + " " + pa1.getString(row) + " " + loc;
                float f = //will be NaN if trouble
                        (pa.getFloat(row) + (pa1.getFloat(row) / 60))
                                * (loc.equals("N") ? 1 : loc.equals("S") ? -1 : Float.NaN);
                fa.atInsert(row, f);
                if (combo.length() > 2 && //2 spaces
                        (f < -90 || f > 90 || Float.isNaN(f))) {
                    nErrors++;
                    if (nErrors <= 5)
                        String2.log("ERROR: col=" + vName + " row=" + row + " lat=" + combo + " -> " + f);
                }
            }
            table.setColumn(v, fa);
            table.removeColumn(v + 2);
            table.removeColumn(v + 1);
        }
        if (nErrors > 0)
            String2.pressEnterToContinue("nErrors=" + nErrors);

        //longitude
        nErrors = 0;
        if ("longitude".equals(vName) && "longitudeMinutes".equals(table.getColumnName(v + 1))
                && "longitudeLocation".equals(table.getColumnName(v + 2))) {
            FloatArray fa = new FloatArray(nRows, false); //float avoids, e.g., xx.33333333333333
            PrimitiveArray pa1 = table.getColumn(v + 1);
            PrimitiveArray pa2 = table.getColumn(v + 2);
            for (int row = 0; row < nRows; row++) {
                String loc = pa2.getString(row);
                String combo = pa.getString(row) + " " + pa1.getString(row) + " " + loc;
                float f = //will be NaN if trouble
                        (pa.getFloat(row) + (pa1.getFloat(row) / 60))
                                * (loc.equals("E") ? 1 : loc.equals("W") ? -1 : Float.NaN);
                fa.atInsert(row, f);
                if (combo.length() > 2 && //2 spaces
                        (f < -180 || f > 180 || Float.isNaN(f))) {
                    nErrors++;
                    if (nErrors <= 5)
                        String2.log("ERROR: col=" + vName + " row=" + row + " lat=" + combo + " -> " + f);
                }
            }
            table.setColumn(v, fa);
            table.removeColumn(v + 2);
            table.removeColumn(v + 1);
        }
        if (nErrors > 0)
            String2.pressEnterToContinue("nErrors=" + nErrors);

        //yyMM  add century to cruiseYYMM
        nErrors = 0;
        if ("yyMM".equals(vUnits)) {
            for (int row = 0; row < nRows; row++) {
                String val = pa.getString(row);
                if (val.matches("[0-9]{4}")) {
                    int year = String2.parseInt(val.substring(0, 2));
                    pa.setString(row, (year < cutoffYear ? "20" : "19") + val);
                } else {
                    if (val.length() != 0) {
                        nErrors++;
                        if (nErrors <= 5)
                            String2.log("ERROR: col=" + vName + " row=" + row + " yyMM=" + val);
                    }
                    pa.setString(row, ""); //set to MV
                }
            }
            atts.set("units", ""); //leave it as a String identifier
        }
        if (nErrors > 0)
            String2.pressEnterToContinue("nErrors=" + nErrors);

        //yyMMdd
        nErrors = 0;
        if ("yyMMdd".equals(vUnits)) {
            String nextUnits = nextAtts.getString("units");
            boolean nextHasMinutes = "HHmm".equals(nextUnits);
            if (nextHasMinutes)
                String2.log("combining yyMMdd and next column (HHmm)");
            String nextVName = nextHasMinutes ? table.getColumnName(v + 1) : "";
            DoubleArray datePA = new DoubleArray(nRows, false);
            PrimitiveArray minutesPA = nextHasMinutes ? table.getColumn(v + 1) : (PrimitiveArray) null;
            //??!! Use Zulu or local, or time_zone data (in one table only)?
            GregorianCalendar gc = new GregorianCalendar(TimeZone.getTimeZone("America/Los_Angeles"));
            Calendar2.clearSmallerFields(gc, Calendar2.DATE);
            for (int row = 0; row < nRows; row++) {
                String val = pa.getString(row);
                if (val.matches("[0-9]{6}")) {
                    int year = String2.parseInt(val.substring(0, 2));
                    gc.set(Calendar2.YEAR, year < cutoffYear ? 2000 : 1900);
                    gc.set(Calendar2.MONTH, String2.parseInt(val.substring(2, 4)) - 1); //0..
                    gc.set(Calendar2.DATE, String2.parseInt(val.substring(4, 6)));
                    if (nextHasMinutes) {
                        Calendar2.clearSmallerFields(gc, Calendar2.DATE);
                        int HHmm = minutesPA.getInt(row);
                        if (HHmm < 0 || HHmm > 2359) {
                            nErrors++;
                            if (nErrors <= 5)
                                String2.log("ERROR: col=" + nextVName + " row=" + row + " HHmm="
                                        + minutesPA.getString(row));
                        } else {
                            gc.set(Calendar2.HOUR_OF_DAY, HHmm / 100);
                            gc.set(Calendar2.MINUTE, HHmm % 100);
                        }
                    }
                    datePA.add(Calendar2.gcToEpochSeconds(gc));
                } else {
                    if (val.length() != 0) {
                        nErrors++;
                        if (nErrors <= 5)
                            String2.log("ERROR: col=" + vName + " row=" + row + " yyMMdd=" + val);
                    }
                    datePA.add(Double.NaN);
                }
            }
            table.setColumn(v, datePA);
            atts.set("units", Calendar2.SECONDS_SINCE_1970);
            atts.set("time_precision", //AKA EDV.TIME_PRECISION 
                    nextHasMinutes ? "1970-01-01T00:00" : "1970-01-01");
            if (nextHasMinutes)
                table.removeColumn(v + 1);
        }
        if (nErrors > 0)
            String2.pressEnterToContinue("nErrors=" + nErrors);

    }

    //save as .nc
    String2.log("After adjustments:\n" + String2.annotatedString(table.dataToString(5)));
    table.saveAsFlatNc(dir + tableName + ".nc", rowName, false);
    return table;
}

From source file:com.lp.server.fertigung.ejbfac.FertigungFacBean.java

@TransactionAttribute(TransactionAttributeType.NEVER)
public KapazitaetsvorschauDto getKapazitaetsvorschau(TheClientDto theClientDto) throws EJBExceptionLP {
    KapazitaetsvorschauDto kapDto = null;
    Session session = null;/*  w w  w . j  a v  a2  s .  co  m*/
    try {

        // ------------------------------------------------------------------
        // -----
        // Benoetigte Parameter holen
        // ------------------------------------------------------------------
        // -----
        // Default Sicht nach Wochen
        // final int iSicht = FertigungFac.KAPAZITAETSVORSCHAU_NACH_WOCHEN;
        // Anzahl der angezeigten Vatergruppen. Alles andere wird nach
        // "Sonstige" verdichtet
        final ParametermandantDto parameterAnzahlGruppen = getParameterFac().getMandantparameter(
                theClientDto.getMandant(), ParameterFac.KATEGORIE_FERTIGUNG,
                ParameterFac.PARAMETER_FERTIGUNG_KAPAZITAETSVORSCHAU_ANZAHL_GRUPPEN);
        final int iParamAnzahlGruppen = (Integer) parameterAnzahlGruppen.getCWertAsObject();
        // Angezeigter Zeitraum = Anzahl der Spalten
        final ParametermandantDto parameterZeitraum = getParameterFac().getMandantparameter(
                theClientDto.getMandant(), ParameterFac.KATEGORIE_FERTIGUNG,
                ParameterFac.PARAMETER_FERTIGUNG_KAPAZITAETSVORSCHAU_ZEITRAUM);
        final int iParamZeitraum = (Integer) parameterZeitraum.getCWertAsObject();

        // ------------------------------------------------------------------
        // -----
        // Hibernate-Session erstellen
        // ------------------------------------------------------------------
        // -----
        SessionFactory factory = FLRSessionFactory.getFactory();
        session = factory.openSession();
        // ------------------------------------------------------------------
        // -----
        // Artikel- / Maschinen-Vatergruppen holen
        // ------------------------------------------------------------------
        // -----
        // Alle Artikel-Vatergruppen
        Criteria cArtikelVatergruppen = session.createCriteria(FLRArtikelgruppe.class);
        cArtikelVatergruppen.add(Restrictions.isNull(ArtikelFac.FLR_ARTIKELGRUPPE_FLRARTIKELGRUPPE));
        List<?> listArtikelgruppen = cArtikelVatergruppen.list();
        // Alle Maschinen-Vatergruppen
        Criteria cMaschinengruppen = session.createCriteria(FLRMaschinengruppe.class);
        List<?> listMaschinengruppen = cMaschinengruppen.list();
        // ------------------------------------------------------------------
        // -----
        // Anzahl der sub-Diagramme bestimmen
        // das ist grundsaetzlich (iParamAnzahlGruppen + 1) x 2 ...
        // (Anzahl d. anzuzeigenden Vatergruppen + Sonstige) f. AZ und
        // Maschinen
        // wenn es weniger Vatergruppen als anzuzeigende gibt, reduziert
        // sich das aber
        // Gibt es keine Vatergruppe, wird daher alles nach "Sonstige"
        // verdichtet
        // ------------------------------------------------------------------
        // -----
        final int iAnzuzeigendeArtikelgruppen = Math.min(iParamAnzahlGruppen, listArtikelgruppen.size());

        final int iAnzuzeigendeMaschinengruppen = Math.min(iParamAnzahlGruppen, listMaschinengruppen.size());

        final int iAnzahlZeilen = iAnzuzeigendeArtikelgruppen + 1 + iAnzuzeigendeMaschinengruppen + 1;

        // ------------------------------------------------------------------
        // -----
        // Dto initialisieren
        // ------------------------------------------------------------------
        // -----
        kapDto = new KapazitaetsvorschauDto(iAnzahlZeilen, iParamZeitraum);
        // ------------------------------------------------------------------
        // -----
        // Beschriftung der x-Achse ermitteln. das sind die Kalenderwochen
        // ------------------------------------------------------------------
        // -----
        HashMap<Integer, Integer> hmKWIndizes = new HashMap<Integer, Integer>();

        String[] kw = new String[iParamZeitraum];
        GregorianCalendar gc = new GregorianCalendar();
        for (int i = 0; i < kw.length; i++) {
            int iKw = gc.get(GregorianCalendar.WEEK_OF_YEAR);
            kw[i] = "" + iKw;
            kapDto.setISpaltenueberschrift(i, kw[i]);
            hmKWIndizes.put(gc.get(GregorianCalendar.WEEK_OF_YEAR), i);
            gc.setTimeInMillis(gc.getTimeInMillis() + 7 * 24 * 60 * 60 * 1000); // 1 Woche dazu
        }
        // ------------------------------------------------------------------
        // -----
        // Beschriftung der y-Achse ermitteln. das sind die Namen der
        // Vatergruppen bzw. 2 x "Sonstige".
        // Weiters werden die Indizes im Daten-Array fuer die jeweiligen
        // Gruppen festgelegt.
        // ------------------------------------------------------------------
        // -----
        String sSonstige = getTextRespectUISpr("lp.sonstige", theClientDto.getMandant(),
                theClientDto.getLocUi());

        HashMap<Integer, Integer> hmArtikelGruppenIndizes = new HashMap<Integer, Integer>();
        HashMap<Integer, Integer> hmMaschinenGruppenIndizes = new HashMap<Integer, Integer>();

        // zuerst die Artikelvatergruppen
        for (int i = 0; i < iAnzuzeigendeArtikelgruppen; i++) {
            FLRArtikelgruppe item = (FLRArtikelgruppe) listArtikelgruppen.get(i);
            kapDto.setIZeilenueberschrift(i, item.getC_nr());
            hmArtikelGruppenIndizes.put(item.getI_id(), i);
        }
        // Dann Sonstige Artikelgruppen
        final int indexSonstigeArtikelGruppen = iAnzuzeigendeArtikelgruppen;
        kapDto.setIZeilenueberschrift(indexSonstigeArtikelGruppen, sSonstige);
        // Maschinengruppen
        for (int i = 0; i < iAnzuzeigendeMaschinengruppen; i++) {
            FLRMaschinengruppe item = (FLRMaschinengruppe) listMaschinengruppen.get(i);
            int index = iAnzuzeigendeArtikelgruppen + 1 + i;
            kapDto.setIZeilenueberschrift(index, item.getC_bez());
            hmMaschinenGruppenIndizes.put(item.getI_id(), index);
        }
        // zuletzt Sonstige Maschinengruppen
        final int indexSonstigeMaschinenGruppen = iAnzuzeigendeArtikelgruppen + 1
                + iAnzuzeigendeMaschinengruppen;
        kapDto.setIZeilenueberschrift(indexSonstigeMaschinenGruppen, sSonstige);

        // ------------------------------------------------------------------
        // -----
        // Lose holen
        // ------------------------------------------------------------------
        // -----
        Criteria cLose = session.createCriteria(FLRLos.class);
        // Filter nach Mandant
        cLose.add(Restrictions.eq(FertigungFac.FLR_LOS_MANDANT_C_NR, theClientDto.getMandant()));
        // Alle Stati ausser Erledigt, Gestoppt, Storniert
        Collection<String> cLoseStati = new LinkedList<String>();
        cLoseStati.add(FertigungFac.STATUS_ERLEDIGT);
        cLoseStati.add(FertigungFac.STATUS_GESTOPPT);
        cLoseStati.add(FertigungFac.STATUS_STORNIERT);
        cLose.add(Restrictions.not(Restrictions.in(FertigungFac.FLR_LOS_STATUS_C_NR, cLoseStati)));
        List<?> listLose = cLose.list();
        // ------------------------------------------------------------------
        // -----
        // Auswertungszeitraum und verfuegbare Kapazitaeten ermitteln
        // ------------------------------------------------------------------
        // -----

        // 3 Monate in die zukunft
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(System.currentTimeMillis());
        c.set(Calendar.MONTH, c.get(Calendar.MONTH) + 3);
        java.util.Date dMax = Helper.cutDate(new java.sql.Date(c.getTimeInMillis()));

        java.sql.Timestamp tVon = Helper.cutTimestamp(new java.sql.Timestamp(System.currentTimeMillis()));
        java.sql.Timestamp tBis = Helper.cutTimestamp(new java.sql.Timestamp(dMax.getTime()));
        // Verfuegbare Zeiten holen
        SollverfuegbarkeitDto[] oVerfuegbar = getZeiterfassungFac().getVerfuegbareSollzeit(tVon, tBis,
                theClientDto);
        // diese nun aufteilen
        for (int i = 0; i < oVerfuegbar.length; i++) {
            SollverfuegbarkeitDto svDto = oVerfuegbar[i];
            // "normale" AZ
            if (svDto.isBMannarbeitszeit()) {
                // die sind einer Artikelgruppe zugeordnet
                if (svDto.getIGruppeid() != null) {
                    Integer iZeile = hmArtikelGruppenIndizes.get(svDto.getIGruppeid());
                    // ist das eine sichtbare Gruppe
                    if (iZeile != null) {
                        for (int iSpalte = 0; iSpalte < kapDto.getDetails()[iZeile].length; iSpalte++) {
                            // mal 5 Tage
                            kapDto.addBdVerfuegbareStunden(iZeile, iSpalte,
                                    svDto.getNSollstunden().multiply(new BigDecimal(5)));
                        }
                    }
                    // wenn nicht, dann zu den sonstigen
                    else {
                        for (int iSpalte = 0; iSpalte < kapDto
                                .getDetails()[indexSonstigeArtikelGruppen].length; iSpalte++) {
                            // mal 5 Tage
                            kapDto.addBdVerfuegbareStunden(indexSonstigeArtikelGruppen, iSpalte,
                                    svDto.getNSollstunden().multiply(new BigDecimal(5)));
                        }
                    }
                }
                // Rest = Sonstige Artikelgruppen
                else {
                    if (svDto.getTDatum() != null) {
                        // Die KW dieses Datums ermitteln, damit das
                        // zugeordnet werden kann
                        GregorianCalendar gcSV = new GregorianCalendar();
                        gcSV.setTime(svDto.getTDatum());
                        int kwSV = gcSV.get(Calendar.WEEK_OF_YEAR);
                        Integer iIndexDerKW = hmKWIndizes.get(kwSV);
                        if (iIndexDerKW != null) {
                            // Hier nicht mit 5 multiplizieren, da es fuer
                            // jeden Tag einen eigenen Eintrag gibt
                            kapDto.addBdVerfuegbareStunden(indexSonstigeArtikelGruppen, iIndexDerKW,
                                    svDto.getNSollstunden());
                        } else {
                            // diese KW wird nicht mehr angezeigt - brauch
                            // ich nicht einrechnen
                        }
                    }
                }
            }
            // Maschinenzeit - die Verfuegbarkeit ist jeden Tag gleich
            else {
                Integer iZeile = hmMaschinenGruppenIndizes.get(svDto.getIGruppeid());
                // ist das eine sichtbare Gruppe
                if (iZeile != null) {
                    for (int iSpalte = 0; iSpalte < kapDto.getDetails()[iZeile].length; iSpalte++) {
                        // mal 5 Tage
                        kapDto.addBdVerfuegbareStunden(iZeile, iSpalte,
                                svDto.getNSollstunden().multiply(new BigDecimal(5)));
                    }
                }
                // wenn nicht, dann zu den sonstigen
                else {
                    for (int iSpalte = 0; iSpalte < kapDto
                            .getDetails()[indexSonstigeMaschinenGruppen].length; iSpalte++) {
                        // mal 5 Tage
                        kapDto.addBdVerfuegbareStunden(indexSonstigeMaschinenGruppen, iSpalte,
                                svDto.getNSollstunden().multiply(new BigDecimal(5)));
                    }
                }
            }
        }
        // ------------------------------------------------------------------
        // -----
        // Offene Zeiten ermitteln
        // ------------------------------------------------------------------
        // -----
        for (Iterator<?> iter = listLose.iterator(); iter.hasNext();) {
            FLRLos los = (FLRLos) iter.next();
            // Offene Menge ermitteln
            BigDecimal bdOffen = los.getN_losgroesse();
            for (Iterator<?> iterAblieferung = los.getAblieferungset().iterator(); iterAblieferung.hasNext();) {
                FLRLosablieferung item = (FLRLosablieferung) iterAblieferung.next();
                bdOffen = bdOffen.subtract(item.getN_menge());
            }
            // nur Lose mit tatsaechlich offener Menge>0
            if (bdOffen.compareTo(new BigDecimal(0)) > 0) {
                // Faktor zur Berechnung der offenen Zeiten = offene Menge /
                // Losgroesse. 2 Nachkommastellen sollten reichen.
                BigDecimal bdFaktor = bdOffen.divide(los.getN_losgroesse(), 2, BigDecimal.ROUND_HALF_EVEN);
                // Arbeitsplan holen
                Criteria cLosAZ = session.createCriteria(FLRLossollarbeitsplan.class);
                cLosAZ.add(Restrictions.eq(FertigungFac.FLR_LOSSOLLARBEITSPLAN_LOS_I_ID, los.getI_id()));
                List<?> listLosAZ = cLosAZ.list();
                // fuer alle Taetigkeiten
                for (Iterator<?> iterAZ = listLosAZ.iterator(); iterAZ.hasNext();) {
                    FLRLossollarbeitsplan losAZ = (FLRLossollarbeitsplan) iterAZ.next();
                    BigDecimal bdOffeneStunden = losAZ.getN_gesamtzeit().multiply(bdFaktor);
                    // ------------------------------------------------------
                    // -----------------
                    // Index der Gruppe bestimmen, der ich das zuordnen muss
                    // ------------------------------------------------------
                    // -----------------
                    int iZeilenIndex;
                    // 1. nach Maschinengruppe
                    // 2. nach Artikelgruppe der Taetigkeit
                    FLRMaschine flrMaschine = losAZ.getFlrmaschine();
                    Integer iMaschinengruppeIId = null;
                    Integer iArtikelgruppeIId = null;
                    if (flrMaschine != null) {
                        FLRMaschinengruppe flrMaschinengruppe = flrMaschine.getFlrmaschinengruppe();
                        if (flrMaschinengruppe != null) {
                            // Wenn diese Maschinengruppe dargestellt wird,
                            // dann kommt hier der index raus.
                            Integer i = hmMaschinenGruppenIndizes.get(flrMaschinengruppe.getI_id());
                            iMaschinengruppeIId = flrMaschinengruppe.getI_id();
                            if (i != null) {
                                iZeilenIndex = i;
                            }
                            // wenn nicht -> sonstige.
                            else {
                                iZeilenIndex = indexSonstigeMaschinenGruppen;
                            }
                        }
                        // Maschinen ohne Maschinengruppe werden nach
                        // "Sonstige" verdichtet.
                        else {
                            iZeilenIndex = indexSonstigeMaschinenGruppen;
                        }
                    } else {
                        FLRArtikel flrArtikel = losAZ.getFlrartikel();
                        FLRArtikelgruppe flrArtikelgruppe = flrArtikel.getFlrartikelgruppe();
                        if (flrArtikelgruppe != null) {
                            // Wenn diese Artikelgruppe dargestellt wird,
                            // dann kommt hier der index raus.
                            Integer i = hmArtikelGruppenIndizes.get(flrArtikelgruppe.getI_id());
                            iArtikelgruppeIId = flrArtikelgruppe.getI_id();
                            if (i != null) {
                                iZeilenIndex = i;
                            }
                            // wenn nicht -> sonstige.
                            else {
                                iZeilenIndex = indexSonstigeArtikelGruppen;
                            }
                        }
                        // Taetigkeiten ohne Artikelgruppe werden nach
                        // "Sonstige" verdichtet.
                        else {
                            iZeilenIndex = indexSonstigeArtikelGruppen;
                        }
                    }
                    // ------------------------------------------------------
                    // -----------------
                    // Jetzt hab ich die Gruppe, der ich das zuordnen muss
                    // nun muss die Zeit aufgeteilt werden
                    // ------------------------------------------------------
                    // -----------------
                    java.util.Date tLosStarttermin = los.getT_produktionsbeginn();
                    java.util.Date tLosEndetermin = los.getT_produktionsende();
                    // beide Termine duerfen nicht vor heute liegen
                    if (tLosStarttermin.before(getDate())) {
                        tLosStarttermin = getDate();
                    }
                    if (tLosEndetermin.before(getDate())) {
                        tLosEndetermin = getDate();
                    }
                    // Anzahl der betroffenen Kalenderwochen bestimmen
                    GregorianCalendar gcStart = new GregorianCalendar();
                    gcStart.setTime(tLosStarttermin);
                    GregorianCalendar gcEnde = new GregorianCalendar();
                    gcEnde.setTime(tLosEndetermin);
                    int iStartKW = gcStart.get(Calendar.WEEK_OF_YEAR);
                    int iEndeKW = gcEnde.get(Calendar.WEEK_OF_YEAR);
                    int iAnzahlKW = 1 + iEndeKW - iStartKW;
                    // nun auf die Wochen aufteilen
                    BigDecimal bdOffeneStundenJeWoche = bdOffeneStunden;

                    if (iAnzahlKW > 0) {
                        bdOffeneStundenJeWoche = bdOffeneStunden.divide(new BigDecimal(iAnzahlKW), 2,
                                RoundingMode.HALF_UP);
                    }

                    for (int iAktuelleKW = iStartKW; iAktuelleKW <= iEndeKW; iAktuelleKW++) {
                        Integer indexDerKW = hmKWIndizes.get(iAktuelleKW);
                        // wird diese Woche auch angezeigt?
                        if (indexDerKW != null) {
                            KapazitaetsvorschauDetailDto detailDto = new KapazitaetsvorschauDetailDto();
                            detailDto.setArtikelgruppeIId(iArtikelgruppeIId);
                            detailDto.setArtikelIIdTaetigkeit(losAZ.getFlrartikel().getI_id());
                            detailDto.setBdDauer(bdOffeneStundenJeWoche);
                            detailDto.setLosIId(los.getI_id());
                            detailDto.setLossollarbeitsplanIId(losAZ.getI_id());
                            detailDto.setMaschinengruppeIId(iMaschinengruppeIId);
                            kapDto.addDetail(iZeilenIndex, indexDerKW, detailDto);
                        }
                    }
                }
            }
        }

        // ------------------------------------------------------------------
        // -----
        // Diagramm aus den Daten erstellen
        // ------------------------------------------------------------------
        // -----
        SymbolAxis xAchse = new SymbolAxis("KW", kw);
        CombinedDomainXYPlot plot = new CombinedDomainXYPlot(xAchse);
        for (int iZeile = 0; iZeile < kapDto.getDetails().length; iZeile++) {
            XYSeries datenZeile = new XYSeries(kapDto.getIZeilenueberschrift(iZeile));
            // Balkenfarben festlegen ( >100% = rot, sonst hellgrau)
            // fuer jede zeile und jede spalte
            Paint[][] paints = new Paint[1][kapDto.getDetails()[iZeile].length];
            for (int iSpalte = 0; iSpalte < kapDto.getDetails()[iZeile].length; iSpalte++) {
                BigDecimal bdVerfuegbar = kapDto.getBdVerfuegbareStunden()[iZeile][iSpalte];
                BigDecimal bdBenoetigt = new BigDecimal(0);
                // Benoetigte Zeit jet Gruppe je Woche ermitteln
                for (Iterator<?> iter = kapDto.getDetails()[iZeile][iSpalte].iterator(); iter.hasNext();) {
                    KapazitaetsvorschauDetailDto item = (KapazitaetsvorschauDetailDto) iter.next();
                    bdBenoetigt = bdBenoetigt.add(item.getBdDauer());
                }
                BigDecimal value = new BigDecimal(0);
                if (bdVerfuegbar.compareTo(new BigDecimal(0)) > 0) {
                    value = (bdBenoetigt.multiply(new BigDecimal(100))).divide(bdVerfuegbar, 4,
                            BigDecimal.ROUND_HALF_EVEN);
                    if (value.doubleValue() > 100.0) {
                        paints[0][iSpalte] = Color.red;
                    } else {
                        paints[0][iSpalte] = Color.lightGray;
                    }
                }
                // tage ohne Verfuegbarkeit mach ich 100% und weisz
                else {
                    value = new BigDecimal(100.0);
                    // Wochen ohne Kapazitaet aber mit geplanter Zeit
                    if (bdBenoetigt.compareTo(new BigDecimal(0)) > 0) {
                        paints[0][iSpalte] = Color.MAGENTA;
                    }
                    // Wenn nichts verfuegbar aber auch nichts benoetigt ->
                    // weiss
                    else {
                        paints[0][iSpalte] = Color.white;
                    }
                }
                XYDataItem data = new XYDataItem(iSpalte, value.doubleValue());
                datenZeile.add(data);
            }
            // Zur Collection
            XYSeriesCollection xyDataset = new XYSeriesCollection();
            xyDataset.addSeries(datenZeile);

            // subplot erstellen
            XYItemRenderer renderer1 = new CustomXYBarRenderer(paints);

            // renderer1.setItemLabelsVisible(true);
            // Legende nicht anzeigen
            renderer1.setBaseSeriesVisibleInLegend(false);
            NumberAxis zeilenAchse = new NumberAxis(kapDto.getIZeilenueberschrift(iZeile));
            // Beschriftung der Y-Achse um 90 grad drehen
            zeilenAchse.setLabelAngle(Math.PI / 2.0);
            zeilenAchse.setAutoRange(true);
            XYPlot subplot1 = new XYPlot(xyDataset, null, zeilenAchse, renderer1);
            subplot1.setRangeAxisLocation(AxisLocation.BOTTOM_OR_LEFT);
            // Markierung bei 100%
            final Marker target = new ValueMarker(100.0);
            target.setPaint(Color.darkGray);
            // target.setLabel("100 %"); // Label
            // target.setLabelAnchor(RectangleAnchor.TOP_RIGHT);
            // target.setLabelTextAnchor(TextAnchor.BOTTOM_RIGHT);
            subplot1.addRangeMarker(target);

            plot.add(subplot1); // plot.add(subplot1, 1);
        }
        JFreeChart lStackedBarChart = new JFreeChart(plot);

        kapDto.setJfcKapazitaetsvorschau(lStackedBarChart);
    } catch (RemoteException ex) {
        throwEJBExceptionLPRespectOld(ex);
    } finally {
        if (session != null) {
            session.close();
        }
    }
    return kapDto;
}

From source file:com.aimluck.eip.schedule.util.ScheduleUtils.java

public static boolean isDuplicateFacilitySchedule(EipTSchedule schedule, List<Integer> facilityIdList,
        Integer _old_scheduleid, Date _old_viewDate) {
    /*  *///from  ww  w .  j  a v a 2s . c  o  m
    GregorianCalendar cald = new GregorianCalendar();

    boolean result = false;
    {

        Date start_date;
        Date end_date;
        String repeat_pattern;
        String repeat_type;
        String repeat_week = null;
        boolean week_0;
        boolean week_1;
        boolean week_2;
        boolean week_3;
        boolean week_4;
        boolean week_5;
        boolean week_6;
        boolean day_of_week_in_month_1;
        boolean day_of_week_in_month_2;
        boolean day_of_week_in_month_3;
        boolean day_of_week_in_month_4;
        boolean day_of_week_in_month_5;
        boolean[] day_of_week_in_month_array = new boolean[5];
        String limit_flag;
        int month_day = -1;
        int year_month = -1;
        int year_day = -1;
        Integer db_scheduleid = null;
        boolean[] week_array = new boolean[7];
        boolean unlimited_repeat = false;
        try {
            start_date = schedule.getStartDate();

            end_date = schedule.getEndDate();

            repeat_pattern = schedule.getRepeatPattern();

            repeat_type = repeat_pattern.substring(0, 1);

            day_of_week_in_month_1 = repeat_pattern.matches("W.......1.?");

            day_of_week_in_month_2 = repeat_pattern.matches("W.......2.?");

            day_of_week_in_month_3 = repeat_pattern.matches("W.......3.?");

            day_of_week_in_month_4 = repeat_pattern.matches("W.......4.?");

            day_of_week_in_month_5 = repeat_pattern.matches("W.......5.?");

            if (repeat_type.equals("W")) {
                if (repeat_pattern.length() == 9) {
                    repeat_week = "0";
                    day_of_week_in_month_1 = true;
                    day_of_week_in_month_2 = true;
                    day_of_week_in_month_3 = true;
                    day_of_week_in_month_4 = true;
                    day_of_week_in_month_5 = true;
                } else {
                    repeat_week = repeat_pattern.substring(8, 9);
                }
            }

            limit_flag = repeat_pattern.substring(repeat_pattern.length() - 1);

            week_0 = repeat_pattern.matches("W1........?");

            week_1 = repeat_pattern.matches("W.1.......?");

            week_2 = repeat_pattern.matches("W..1......?");

            week_3 = repeat_pattern.matches("W...1.....?");

            week_4 = repeat_pattern.matches("W....1....?");

            week_5 = repeat_pattern.matches("W.....1...?");

            week_6 = repeat_pattern.matches("W......1..?");

            if (repeat_pattern.startsWith("M")) {
                month_day = Integer.parseInt(repeat_pattern.substring(1, 3));
            }

            if (repeat_pattern.startsWith("Y")) {
                year_month = Integer.parseInt(repeat_pattern.substring(1, 3));
                year_day = Integer.parseInt(repeat_pattern.substring(3, 5));
            }
            // ???1??????
            if (repeat_pattern.startsWith("N")) {
                Calendar cal = Calendar.getInstance();
                cal.setTime(start_date);
                int dow = cal.get(Calendar.DAY_OF_WEEK);
                week_0 = (dow == Calendar.SUNDAY);
                week_1 = (dow == Calendar.MONDAY);
                week_2 = (dow == Calendar.TUESDAY);
                week_3 = (dow == Calendar.WEDNESDAY);
                week_4 = (dow == Calendar.THURSDAY);
                week_5 = (dow == Calendar.FRIDAY);
                week_6 = (dow == Calendar.SATURDAY);
                month_day = cal.get(Calendar.DAY_OF_MONTH);
                int dowim = cal.get(Calendar.DAY_OF_WEEK_IN_MONTH);
                day_of_week_in_month_1 = (dowim == 1);
                day_of_week_in_month_2 = (dowim == 2);
                day_of_week_in_month_3 = (dowim == 3);
                day_of_week_in_month_4 = (dowim == 4);
                day_of_week_in_month_5 = (dowim == 5);
                year_month = cal.get(Calendar.MONTH) + 1;
                year_day = cal.get(Calendar.DAY_OF_MONTH);
            } else if (repeat_pattern.endsWith("N")) {
                unlimited_repeat = true;
            }

            week_array[0] = week_0;
            week_array[1] = week_1;
            week_array[2] = week_2;
            week_array[3] = week_3;
            week_array[4] = week_4;
            week_array[5] = week_5;
            week_array[6] = week_6;

            day_of_week_in_month_array[0] = day_of_week_in_month_1;
            day_of_week_in_month_array[1] = day_of_week_in_month_2;
            day_of_week_in_month_array[2] = day_of_week_in_month_3;
            day_of_week_in_month_array[3] = day_of_week_in_month_4;
            day_of_week_in_month_array[4] = day_of_week_in_month_5;

        } catch (RuntimeException e) {
            logger.error("schedule", e);
            return false;
        } catch (Exception e) {
            logger.error("schedule", e);
            return false;
        }

        if (repeat_type.equals("S")) {
            // ??0:00:00?????23:59:59??
            Calendar cal = Calendar.getInstance();
            cal.setTime(end_date);
            cal.add(Calendar.DATE, 1);
            cal.add(Calendar.MINUTE, -1);
            end_date = cal.getTime();
        }

        // ???
        if (facilityIdList.size() > 0) {//
            List<Integer> fids = facilityIdList;
            SelectQuery<EipTScheduleMap> fquery = Database.query(EipTScheduleMap.class);
            Expression fexp1 = ExpressionFactory.inExp(EipTScheduleMap.USER_ID_PROPERTY, fids);
            fquery.setQualifier(fexp1);

            Expression fexp2 = ExpressionFactory.matchExp(EipTScheduleMap.TYPE_PROPERTY,
                    ScheduleUtils.SCHEDULEMAP_TYPE_FACILITY);
            fquery.andQualifier(fexp2);

            Expression oneexp = null;// 1
            Expression spanexp = null;// 
            Expression rdexp = null;// 
            Expression rwexp = null;// 
            Expression rwexp2 = null;
            // Expression rwlexp = null;
            Expression rmexp = null;// 
            Expression ryexp = null;

            { // ?
                Expression exp100 = ExpressionFactory.matchExp(
                        EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "." + EipTSchedule.REPEAT_PATTERN_PROPERTY,
                        "N");

                try {
                    if (!unlimited_repeat) {
                        Expression exp101 = ExpressionFactory.lessOrEqualExp(
                                EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "." + EipTSchedule.START_DATE_PROPERTY,
                                end_date);// EipTSchedule.START_DATE_PROPERTY <= end_date
                        Expression exp102 = ExpressionFactory.greaterExp(
                                EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "." + EipTSchedule.END_DATE_PROPERTY,
                                start_date);// EipTSchedule.END_DATE_PROPERTY > start_date

                        oneexp = exp100.andExp(exp101.andExp(exp102));

                    } else {
                        oneexp = exp100;
                    }
                } catch (Exception e) {

                }
            }

            { // ?
                Expression exp200 = ExpressionFactory.matchExp(
                        EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "." + EipTSchedule.REPEAT_PATTERN_PROPERTY,
                        "S");

                try {
                    if (!unlimited_repeat) {
                        // ??00:00??????
                        Calendar cal_end = Calendar.getInstance();
                        cal_end.setTime(end_date);
                        cal_end = DateUtils.truncate(cal_end, Calendar.DAY_OF_MONTH);
                        Expression exp201 = ExpressionFactory.lessOrEqualExp(
                                EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "." + EipTSchedule.START_DATE_PROPERTY,
                                cal_end.getTime());
                        // EipTSchedule.START_DATE_PROPERTY <= end_date
                        Calendar cal_start = Calendar.getInstance();
                        cal_start.setTime(start_date);
                        cal_start = DateUtils.truncate(cal_start, Calendar.DAY_OF_MONTH);
                        Expression exp202 = ExpressionFactory.greaterOrEqualExp(
                                EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "." + EipTSchedule.END_DATE_PROPERTY,
                                cal_start.getTime());
                        // EipTSchedule.END_DATE_PROPERTY >= start_date

                        spanexp = exp200.andExp(exp201.andExp(exp202));

                    } else {
                        spanexp = exp200;
                    }
                } catch (Exception e) {

                }
            }

            { // ??
              // char lim = 'N';
                if ("ON".equals(limit_flag)) {
                    // lim = 'L';
                }

                { // "D".equals(repeat_type.getValue())
                    Expression dexp01 = ExpressionFactory.likeExp(
                            EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "." + EipTSchedule.REPEAT_PATTERN_PROPERTY,
                            "D_");
                    rdexp = dexp01;
                }

                { // "W".equals(repeat_type.getValue())
                    Expression wexp = null;
                    List<Expression> wexps = new ArrayList<Expression>();
                    if (week_0 == true) {
                        wexp = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "W1_______");
                        wexps.add(wexp);
                    }
                    if (week_1 == true) {
                        wexp = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "W_1______");
                        wexps.add(wexp);
                    }
                    if (week_2 == true) {
                        wexp = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "W__1_____");
                        wexps.add(wexp);
                    }
                    if (week_3 == true) {
                        wexp = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "W___1____");
                        wexps.add(wexp);
                    }
                    if (week_4 == true) {
                        wexp = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "W____1___");
                        wexps.add(wexp);
                    }
                    if (week_5 == true) {
                        wexp = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "W_____1__");
                        wexps.add(wexp);
                    }
                    if (week_6 == true) {
                        wexp = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "W______1_");
                        wexps.add(wexp);
                    }
                    if (wexps.size() > 0) {
                        rwexp = wexps.get(0);
                        int wexpssize = wexps.size();
                        for (int k = 1; k < wexpssize; k++) {
                            rwexp = rwexp.orExp(wexps.get(k));
                        }
                    } else {
                        rwexp = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "W________");
                    }
                }
                {
                    Expression wexp2 = null;
                    List<Expression> wexps2 = new ArrayList<Expression>();
                    Expression wnexp = null;
                    List<Expression> wnexp2 = new ArrayList<Expression>();

                    if (week_0 == true) {
                        wexp2 = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "W1________");
                        wexps2.add(wexp2);
                    }
                    if (week_1 == true) {
                        wexp2 = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "W_1_______");
                        wexps2.add(wexp2);
                    }
                    if (week_2 == true) {
                        wexp2 = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "W__1______");
                        wexps2.add(wexp2);
                    }
                    if (week_3 == true) {
                        wexp2 = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "W___1_____");
                        wexps2.add(wexp2);
                    }
                    if (week_4 == true) {
                        wexp2 = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "W____1____");
                        wexps2.add(wexp2);
                    }
                    if (week_5 == true) {
                        wexp2 = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "W_____1___");
                        wexps2.add(wexp2);
                    }
                    if (week_6 == true) {
                        wexp2 = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "W______1__");
                        wexps2.add(wexp2);
                    }
                    if (repeat_week != null && repeat_week.equals("1") || day_of_week_in_month_1) {
                        wnexp = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "W_______1_");
                        wnexp2.add(wnexp);
                    }
                    if (repeat_week != null && repeat_week.equals("2") || day_of_week_in_month_2) {
                        wnexp = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "W_______2_");
                        wnexp2.add(wnexp);
                    }
                    if (repeat_week != null && repeat_week.equals("3") || day_of_week_in_month_3) {
                        wnexp = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "W_______3_");
                        wnexp2.add(wnexp);
                    }
                    if (repeat_week != null && repeat_week.equals("4") || day_of_week_in_month_4) {
                        wnexp = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "W_______4_");
                        wnexp2.add(wnexp);
                    }
                    if (repeat_week != null && repeat_week.equals("5") || day_of_week_in_month_5) {
                        wnexp = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "W_______5_");
                        wnexp2.add(wnexp);
                    }
                    if (wexps2.size() > 0 && wnexp2.size() > 0) {
                        for (int k = 0; k < wexps2.size(); k++) {
                            for (int l = 0; l < wnexp2.size(); l++) {
                                if (k == 0 && l == 0) {
                                    rwexp2 = wexps2.get(k).andExp(wnexp2.get(l));
                                } else {
                                    rwexp2 = rwexp2.orExp(wexps2.get(k).andExp(wnexp2.get(l)));
                                }
                            }
                        }
                    } else {
                        rwexp2 = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "W_________");
                    }

                }

                { // "M".equals(repeat_type.getValue())
                    if (month_day > 0) { // ????????
                        DecimalFormat exF = new DecimalFormat("00");
                        String md_str = exF.format(month_day);
                        rmexp = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "M" + md_str + "_");

                    } else if (year_day > 0 && year_month > 0) { // ??
                        DecimalFormat exG = new DecimalFormat("00");
                        String yd_str = exG.format(year_day);
                        rmexp = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "M" + yd_str + "_");
                    } else {
                        rmexp = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "M___");
                    }
                }

                { // "Y".equals(repeat_type.getValue())
                    if (year_day > 0 && year_month > 0) { // ????????
                        DecimalFormat exG = new DecimalFormat("00");
                        String ym_str = exG.format(year_month);
                        String yd_str = exG.format(year_day);

                        ryexp = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "Y" + ym_str + yd_str + "_");
                    } else if (month_day > 0) { // ??
                        DecimalFormat exF = new DecimalFormat("00");
                        String md_str = exF.format(month_day);
                        ryexp = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "Y__" + md_str + "_");
                    } else {
                        ryexp = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "Y_____");
                    }
                }

                Expression repeatexp = oneexp;
                if (rdexp != null) {
                    repeatexp = repeatexp.orExp(rdexp);
                }
                if (rwexp != null) {
                    repeatexp = repeatexp.orExp(rwexp);
                }
                if (rwexp2 != null) {
                    repeatexp = repeatexp.orExp(rwexp2);
                }
                if (rmexp != null) {
                    repeatexp = repeatexp.orExp(rmexp);
                }
                if (spanexp != null) {
                    repeatexp = repeatexp.orExp(spanexp);
                }
                if (ryexp != null) {
                    repeatexp = repeatexp.orExp(ryexp);
                }
                fquery.andQualifier(repeatexp);
            }

            db_scheduleid = schedule.getScheduleId();
            if (db_scheduleid != null && db_scheduleid >= 0) {
                Expression exp00 = ExpressionFactory.noMatchDbExp(
                        EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "." + EipTSchedule.SCHEDULE_ID_PK_COLUMN,
                        db_scheduleid);
                fquery.andQualifier(exp00);
            }

            fquery.distinct(true);
            List<EipTScheduleMap> f_list = fquery.fetchList();
            if (f_list != null && f_list.size() > 0) {
                // ?????
                boolean existFacility = false;
                int f_list_size = f_list.size();
                for (int i = 0; i < f_list_size; i++) {
                    EipTScheduleMap map = f_list.get(i);

                    Date dbStartDate = map.getEipTSchedule().getStartDate();
                    Date dbEndDate = map.getEipTSchedule().getEndDate();

                    boolean containtsRs = false;
                    // ??????
                    String ptn = map.getEipTSchedule().getRepeatPattern();
                    if (ptn.charAt(0) == 'S') { // 
                        try {
                            // ??0:00:00?????23:59:59??
                            Calendar cal = Calendar.getInstance();
                            cal.setTime(dbEndDate);
                            cal.add(Calendar.DATE, 1);
                            cal.add(Calendar.MINUTE, -1);
                            dbEndDate = cal.getTime();

                            if ((end_date.after(dbStartDate) && start_date.before(dbEndDate))
                                    || unlimited_repeat) {
                                containtsRs = true;
                            }
                        } catch (Exception e) {
                            containtsRs = false;
                        }
                    } else if (ptn.charAt(0) == 'N') { // ?
                        if ("D".equals(repeat_type) || "N".equals(repeat_type)) { //  or
                            // ?
                            try {
                                if ((dbStartDate.before(end_date) && dbEndDate.after(start_date))
                                        || unlimited_repeat) {
                                    containtsRs = true;
                                }
                            } catch (Exception e) {
                                containtsRs = false;
                            }
                        } else {
                            if ((dbStartDate.before(end_date) && dbEndDate.after(start_date))
                                    || unlimited_repeat) {
                                containtsRs = true;
                            }
                        }
                    } else if (ptn.charAt(0) == 'D') {// 
                        if (ptn.charAt(1) == 'L') {
                            try {
                                if ((dbStartDate.before(end_date) && dbEndDate.after(start_date))
                                        || unlimited_repeat) {
                                    containtsRs = true;
                                }
                            } catch (Exception e) {
                                containtsRs = false;
                            }
                        } else {
                            containtsRs = true;
                        }
                    } else if (ptn.charAt(0) == 'W') {
                        if (ptn.length() == 9) {
                            if (ptn.charAt(8) == 'L') {
                                try {
                                    if ((dbStartDate.before(end_date) && dbEndDate.after(start_date))
                                            || unlimited_repeat) {
                                        containtsRs = true;
                                    }
                                } catch (Exception e) {
                                    containtsRs = false;
                                }
                            } else {
                                containtsRs = true;
                            }
                        } else if (ptn.length() == 10) {
                            if (ptn.charAt(9) == 'L') {
                                try {
                                    if ((dbStartDate.before(end_date) && dbEndDate.after(start_date))
                                            || unlimited_repeat) {
                                        containtsRs = true;
                                    }
                                } catch (Exception e) {
                                    containtsRs = false;
                                }
                            } else {
                                containtsRs = true;
                            }
                        }
                    } else if (ptn.charAt(0) == 'M') {
                        if (ptn.charAt(3) == 'L') {
                            try {
                                if ((dbStartDate.before(end_date) && dbEndDate.after(start_date))
                                        || unlimited_repeat) {
                                    containtsRs = true;
                                }
                            } catch (Exception e) {
                                containtsRs = false;
                            }
                        } else {
                            containtsRs = true;
                        }
                    } else if (ptn.charAt(0) == 'Y') {
                        if (ptn.charAt(5) == 'L') {
                            try {
                                if ((dbStartDate.before(end_date) && dbEndDate.after(start_date))
                                        || unlimited_repeat) {
                                    containtsRs = true;
                                }
                            } catch (Exception e) {
                                containtsRs = false;
                            }
                        } else {
                            containtsRs = true;
                        }
                    } else {
                        containtsRs = true;
                    }

                    if (containtsRs) {
                        /* ?????? */
                        int ss_flg = ScheduleUtils.compareTime(start_date, dbEndDate);
                        int se_flg = ScheduleUtils.compareTime(end_date, dbStartDate);
                        if (ss_flg > 0 && se_flg < 0) {
                            /* ???????????? */
                            if (!"N".equals(ptn) && ptn.endsWith("N") && unlimited_repeat) {// ?(?????&&???)&&????
                                existFacility = true;
                            } else {
                                Date _start_date = null;
                                Date _end_date = null;

                                if (!"N".equals(ptn) && ptn.endsWith("N") && !unlimited_repeat) {// ?(??&&???)&&???
                                    _start_date = (Date) start_date.clone();
                                    _end_date = (Date) end_date.clone();
                                } else if (("N".equals(ptn) || !ptn.endsWith("N")) && unlimited_repeat) {// ?(?||??)&&????
                                    _start_date = (Date) dbStartDate.clone();
                                    _end_date = (Date) dbEndDate.clone();
                                } else if (("N".equals(ptn) || !ptn.endsWith("N")) && !unlimited_repeat) {// ?(?||??)&&???

                                    if (dbStartDate.after(start_date)) {
                                        _start_date = (Date) dbStartDate.clone();
                                    } else {
                                        _start_date = (Date) start_date.clone();
                                    }

                                    if (dbEndDate.before(end_date)) {
                                        _end_date = (Date) dbEndDate.clone();
                                    } else {
                                        _end_date = (Date) end_date.clone();
                                    }

                                }

                                if ((_start_date == null) || (_end_date == null)) {
                                    continue;
                                }

                                /* ??? */
                                Expression dexp1 = ExpressionFactory.matchExp(EipTSchedule.NAME_PROPERTY,
                                        "dummy");// 

                                Expression dexp2 = ExpressionFactory.matchExp(EipTSchedule.PARENT_ID_PROPERTY,
                                        map.getScheduleId());

                                if (db_scheduleid != null) {
                                    Expression dexp21 = ExpressionFactory
                                            .matchExp(EipTSchedule.PARENT_ID_PROPERTY, db_scheduleid);
                                    dexp2 = dexp2.orExp(dexp21);
                                }
                                Expression dexp3 = null;

                                cald.setTime(_start_date);
                                cald.set(Calendar.MILLISECOND, 0);
                                cald.set(Calendar.SECOND, 0);
                                cald.set(Calendar.MINUTE, 0);
                                cald.set(Calendar.HOUR_OF_DAY, 0);
                                Date ddate = cald.getTime();// _start_date?
                                List<EipTSchedule> temp = null;

                                if ("N".equals(repeat_pattern)) {
                                    /* ?????????????? */
                                    if ((_old_scheduleid != null) && (_old_viewDate != null)) {
                                        if ((_old_scheduleid.intValue() == map.getScheduleId().intValue())
                                                && compareToDate(_start_date, _old_viewDate) == 0) {
                                            continue;
                                        }
                                    }

                                    try {
                                        dexp3 = ExpressionFactory.matchExp(EipTSchedule.START_DATE_PROPERTY,
                                                ddate);
                                        temp = Database
                                                .query(EipTSchedule.class, dexp1.andExp(dexp2).andExp(dexp3))
                                                .fetchList();
                                        if (temp == null || temp.size() <= 0) {
                                            existFacility = true;
                                            break;
                                        }
                                    } catch (Exception e) {
                                        logger.error("[DuplicateFacilityCheck]: ", e);
                                        existFacility = true;
                                        break;
                                    }
                                } else if (repeat_pattern.startsWith("D")) {
                                    while (!ddate.after(_end_date)) {
                                        if (matchDay(cald, ptn)) {
                                            try {
                                                dexp3 = ExpressionFactory
                                                        .matchExp(EipTSchedule.START_DATE_PROPERTY, ddate);
                                                temp = Database.query(EipTSchedule.class,
                                                        dexp1.andExp(dexp2).andExp(dexp3)).fetchList();
                                                if (temp == null || temp.size() <= 0) {
                                                    existFacility = true;
                                                    break;
                                                }
                                            } catch (Exception e) {
                                                logger.error("[DuplicateFacilityCheck]: ", e);
                                                existFacility = true;
                                                break;
                                            }
                                        }
                                        cald.add(Calendar.DATE, 1);
                                        ddate = cald.getTime();
                                    }
                                } else if (repeat_pattern.startsWith("S")) {
                                    while (!ddate.after(_end_date)) {
                                        try {
                                            dexp3 = ExpressionFactory.matchExp(EipTSchedule.START_DATE_PROPERTY,
                                                    ddate);
                                            temp = Database.query(EipTSchedule.class,
                                                    dexp1.andExp(dexp2).andExp(dexp3)).fetchList();
                                            if (temp == null || temp.size() <= 0) {
                                                existFacility = true;
                                                break;
                                            }
                                        } catch (Exception e) {
                                            logger.error("[DuplicateFacilityCheck]: ", e);
                                            existFacility = true;
                                            break;
                                        }
                                        cald.add(Calendar.DATE, 1);
                                        ddate = cald.getTime();
                                    }
                                } else if (repeat_pattern.startsWith("W")) {
                                    /* ? */
                                    int wlen = week_array.length;
                                    int wlen2 = day_of_week_in_month_array.length;
                                    if (wlen < 1 || wlen2 < 1) {
                                        continue;
                                    }
                                    int k;
                                    int l;
                                    while (!ddate.after(_end_date)) {
                                        k = (cald.get(Calendar.DAY_OF_WEEK) - 1) % wlen;
                                        l = (cald.get(Calendar.DAY_OF_WEEK_IN_MONTH) - 1) % wlen2;
                                        if ((week_array[k] == true) && (day_of_week_in_month_array[l] == true)
                                                && matchDay(cald, ptn)) {
                                            try {
                                                dexp3 = ExpressionFactory
                                                        .matchExp(EipTSchedule.START_DATE_PROPERTY, ddate);
                                                temp = Database.query(EipTSchedule.class,
                                                        dexp1.andExp(dexp2).andExp(dexp3)).fetchList();// SQL
                                                if (temp == null || temp.size() <= 0) {
                                                    existFacility = true;// true????
                                                    break;
                                                }
                                            } catch (Exception e) {
                                                logger.error("[DuplicateFacilityCheck]: ", e);
                                                existFacility = true;
                                                break;
                                            }
                                        }
                                        cald.add(Calendar.DATE, 1);
                                        ddate = cald.getTime();
                                    }
                                } else if (repeat_pattern.startsWith("M")) {
                                    /* ?? */
                                    cald.setTime(dbStartDate);
                                    cald.set(Calendar.MILLISECOND, 0);
                                    cald.set(Calendar.SECOND, 0);
                                    cald.set(Calendar.MINUTE, 0);
                                    cald.set(Calendar.HOUR_OF_DAY, 0);

                                    if (month_day > 0) {
                                        cald.set(Calendar.DAY_OF_MONTH, month_day);
                                    } else {
                                        continue;
                                    }
                                    Date tmp_date = cald.getTime();
                                    while (tmp_date.before(ddate)) {
                                        cald.add(Calendar.MONTH, 1);
                                        /* ???????????????? */
                                        while (month_day > cald.getActualMaximum(Calendar.DAY_OF_MONTH)) {
                                            cald.add(Calendar.MONTH, 1);
                                            cald.set(Calendar.DAY_OF_MONTH, month_day);
                                            if (tmp_date.before(tmp_date)) {
                                                break;
                                            }
                                        }
                                        tmp_date = cald.getTime();
                                    }
                                    ddate = tmp_date;
                                    /*  */
                                    while (!ddate.after(_end_date)) {
                                        if (matchDay(cald, ptn)) {
                                            try {
                                                dexp3 = ExpressionFactory
                                                        .matchExp(EipTSchedule.START_DATE_PROPERTY, ddate);
                                                temp = Database.query(EipTSchedule.class,
                                                        dexp1.andExp(dexp2).andExp(dexp3)).fetchList();
                                                if (temp == null || temp.size() <= 0) {
                                                    existFacility = true;
                                                    break;
                                                }

                                            } catch (Exception e) {
                                                logger.error("[DuplicateFacilityCheck]: ", e);
                                                existFacility = true;
                                                break;
                                            }
                                        }
                                        cald.add(Calendar.MONTH, 1);
                                        /* ???????????????? */
                                        while (month_day > cald.getActualMaximum(Calendar.DAY_OF_MONTH)) {
                                            cald.add(Calendar.MONTH, 1);
                                            cald.set(Calendar.DAY_OF_MONTH, month_day);
                                            if (!ddate.after(_end_date)) {
                                                break;
                                            }
                                        }
                                        ddate = cald.getTime();
                                    }
                                } else if (repeat_pattern.startsWith("Y")) {
                                    /* ?? */
                                    cald.setTime(dbStartDate);
                                    cald.set(Calendar.MILLISECOND, 0);
                                    cald.set(Calendar.SECOND, 0);
                                    cald.set(Calendar.MINUTE, 0);
                                    cald.set(Calendar.HOUR_OF_DAY, 0);

                                    if (year_month > 0 && year_day > 0) {
                                        cald.set(Calendar.MONTH, year_month - 1);
                                        cald.set(Calendar.DAY_OF_MONTH, year_day);
                                    } else {
                                        continue;
                                    }
                                    Date tmp_date = cald.getTime();
                                    while (tmp_date.before(ddate)) {
                                        cald.add(Calendar.MONTH, 1);
                                        /* ???????????????? */
                                        while (year_day > cald.getActualMaximum(Calendar.DAY_OF_MONTH)) {
                                            cald.add(Calendar.MONTH, 1);
                                            cald.set(Calendar.DAY_OF_MONTH, year_day);
                                            if (tmp_date.before(tmp_date)) {
                                                break;
                                            }
                                        }
                                        tmp_date = cald.getTime();
                                    }
                                    ddate = tmp_date;
                                    /*  */
                                    while (!ddate.after(_end_date)) {
                                        if (matchDay(cald, ptn)) {
                                            try {
                                                dexp3 = ExpressionFactory
                                                        .matchExp(EipTSchedule.START_DATE_PROPERTY, ddate);
                                                temp = Database.query(EipTSchedule.class,
                                                        dexp1.andExp(dexp2).andExp(dexp3)).fetchList();
                                                if (temp == null || temp.size() <= 0) {
                                                    existFacility = true;
                                                    break;
                                                }
                                            } catch (Exception e) {
                                                logger.error("[DuplicateFacilityCheck]: ", e);
                                                existFacility = true;
                                                break;
                                            }
                                        }
                                        cald.add(Calendar.MONTH, 1);
                                        /* ???????????????? */
                                        while (year_day > cald.getActualMaximum(Calendar.DAY_OF_MONTH)) {
                                            cald.add(Calendar.MONTH, 1);
                                            cald.set(Calendar.DAY_OF_MONTH, year_day);
                                            if (!ddate.after(_end_date)) {
                                                break;
                                            }
                                        }
                                        ddate = cald.getTime();
                                    }
                                } else {
                                    continue;
                                }
                            }
                        }
                    }
                    if (existFacility) {
                        break;
                    }
                }
                if (existFacility) {
                    return existFacility;
                }
            }
        }
    }
    return result;
}