Example usage for java.util Calendar clone

List of usage examples for java.util Calendar clone

Introduction

In this page you can find the example usage for java.util Calendar clone.

Prototype

@Override
public Object clone() 

Source Link

Document

Creates and returns a copy of this object.

Usage

From source file:com.alkacon.opencms.calendar.CmsCalendarDisplay.java

/**
 * Returns the previous time range to show calendar entries for.<p>
 * Used for the navigation./*from  w  w w  .j a v a 2  s.  c o m*/
 * 
 * @param actual the actual date from which the previous time range should be calculated
 * @param type the type of period
 * @return a date for which a list of calendar entries should be shown
 */
public Calendar getPreviousPeriod(Calendar actual, int type) {

    Calendar cal = (Calendar) actual.clone();
    switch (type) {
    case PERIOD_DAY:
        cal.add(Calendar.DAY_OF_YEAR, -1);
        break;
    case PERIOD_MONTH:
        cal.add(Calendar.MONTH, -1);
        break;
    case PERIOD_WEEK:
        cal.add(Calendar.WEEK_OF_YEAR, -1);
        break;
    case PERIOD_YEAR:
        cal.add(Calendar.YEAR, -1);
        break;
    default:
        break;
    }

    return cal;
}

From source file:com.alkacon.opencms.v8.calendar.CmsSerialDateWidget.java

/**
 * Returns the macro resolver with initialized macros to generate the serial date input form.<p>
 * //from   w w  w.  jav a2 s.c o m
 * @param cms an initialized instance of a CmsObject
 * @param widgetDialog the dialog where the widget is used on
 * @param param the widget parameter to generate the widget for
 * @return the macro resolver with initialized macros
 */
protected CmsMacroResolver getMacroResolverForForm(CmsObject cms, I_CmsWidgetDialog widgetDialog,
        I_CmsWidgetParameter param) {

    CmsMacroResolver resolver = CmsMacroResolver.newInstance();
    // set cms object and localized messages in resolver
    resolver.setCmsObject(cms);
    CmsMessages messages = new CmsMessages(CmsSerialDateWidget.class.getPackage().getName() + ".messages",
            widgetDialog.getLocale());
    resolver.setMessages(messages);
    // delete empty macros which were not replaced
    resolver.setKeepEmptyMacros(false);

    // create the serial entry date object
    String paramValue = param.getStringValue(cms);
    Map<String, String> params = CmsStringUtil.splitAsMap(paramValue,
            String.valueOf(CmsProperty.VALUE_LIST_DELIMITER), String.valueOf(CmsProperty.VALUE_MAP_DELIMITER));
    // create the entry date from the field values
    CmsCalendarEntryDateSerial entryDate = CmsCalendarSerialDateFactory.getSerialDate(params,
            widgetDialog.getLocale());
    if (entryDate == null) {
        // no entry date created yet, build an empty default date
        Calendar start = new GregorianCalendar(widgetDialog.getLocale());
        Calendar end = (Calendar) start.clone();
        entryDate = new CmsCalendarEntryDateSerial(start, end);
        entryDate.setSerialEndType(I_CmsCalendarSerialDateOptions.END_TYPE_NEVER);
    }

    // vars for daily options
    String dayDailyInterval = "1";
    boolean dayEveryWorkingDay = false;
    // vars for weekly options
    String weekWeeklyInterval = "1";
    // vars for monthly options
    int monthSelectedIndexWeekDayOfMonth = 0;
    int monthSelectedWeekDay = -1;
    String monthDayOfMonth = "1";
    String monthMonthlyInterval = "1";
    String monthMonthlyIntervalWeekDay = "1";
    boolean monthUseWeekday = false;
    // vars for yearly options
    String yearDayOfMonth = "1";
    boolean yearUseWeekday = false;
    int yearSelectedIndexMonth = 0;
    int yearSelectedIndexWeekDayOfMonth = 0;
    int yearSelectedWeekDayDay = -1;
    int yearSelectedIndexWeekDayMonth = 0;

    if (entryDate.getSerialOptions() != null) {
        // fill the variables depending on the selected serial date type
        String serialTypeMacroPrefix = MACRO_PREFIX_PARAMVALUE + PARAM_SERIALTYPE + ".";
        // set serial type radio selection
        resolver.addMacro(serialTypeMacroPrefix + entryDate.getSerialOptions().getSerialType(), ATTR_CHECKED);
        switch (entryDate.getSerialOptions().getSerialType()) {
        // set values for the selected serial type
        case I_CmsCalendarSerialDateOptions.TYPE_DAILY:
            CmsCalendarSerialDateDailyOptions dailyOptions = (CmsCalendarSerialDateDailyOptions) entryDate
                    .getSerialOptions();
            dayEveryWorkingDay = dailyOptions.isEveryWorkingDay();
            dayDailyInterval = String.valueOf(dailyOptions.getDailyInterval());
            break;
        case I_CmsCalendarSerialDateOptions.TYPE_WEEKLY:
            CmsCalendarSerialDateWeeklyOptions weeklyOptions = (CmsCalendarSerialDateWeeklyOptions) entryDate
                    .getSerialOptions();
            weekWeeklyInterval = String.valueOf(weeklyOptions.getWeeklyInterval());
            // check the chosen week day checkboxes
            serialTypeMacroPrefix = MACRO_PREFIX_PARAMVALUE + PARAM_WEEK_WEEKDAY + ".";
            if (weeklyOptions.getWeekDays().contains(new Integer(Calendar.MONDAY))) {
                resolver.addMacro(serialTypeMacroPrefix + Calendar.MONDAY, ATTR_CHECKED);
            }
            if (weeklyOptions.getWeekDays().contains(new Integer(Calendar.TUESDAY))) {
                resolver.addMacro(serialTypeMacroPrefix + Calendar.TUESDAY, ATTR_CHECKED);
            }
            if (weeklyOptions.getWeekDays().contains(new Integer(Calendar.WEDNESDAY))) {
                resolver.addMacro(serialTypeMacroPrefix + Calendar.WEDNESDAY, ATTR_CHECKED);
            }
            if (weeklyOptions.getWeekDays().contains(new Integer(Calendar.THURSDAY))) {
                resolver.addMacro(serialTypeMacroPrefix + Calendar.THURSDAY, ATTR_CHECKED);
            }
            if (weeklyOptions.getWeekDays().contains(new Integer(Calendar.FRIDAY))) {
                resolver.addMacro(serialTypeMacroPrefix + Calendar.FRIDAY, ATTR_CHECKED);
            }
            if (weeklyOptions.getWeekDays().contains(new Integer(Calendar.SATURDAY))) {
                resolver.addMacro(serialTypeMacroPrefix + Calendar.SATURDAY, ATTR_CHECKED);
            }
            if (weeklyOptions.getWeekDays().contains(new Integer(Calendar.SUNDAY))) {
                resolver.addMacro(serialTypeMacroPrefix + Calendar.SUNDAY, ATTR_CHECKED);
            }
            break;
        case I_CmsCalendarSerialDateOptions.TYPE_MONTHLY:
            CmsCalendarSerialDateMonthlyOptions monthlyOptions = (CmsCalendarSerialDateMonthlyOptions) entryDate
                    .getSerialOptions();
            monthUseWeekday = monthlyOptions.isUseWeekDay();
            if (!monthlyOptions.isUseWeekDay()) {
                monthDayOfMonth = String.valueOf(monthlyOptions.getDayOfMonth());
                monthMonthlyInterval = String.valueOf(monthlyOptions.getMonthlyInterval());
            } else {
                // set selected index of select boxes
                monthSelectedIndexWeekDayOfMonth = monthlyOptions.getDayOfMonth() - 1;
                monthSelectedWeekDay = monthlyOptions.getWeekDay();
                monthMonthlyIntervalWeekDay = String.valueOf(monthlyOptions.getMonthlyInterval());
            }
            break;
        case I_CmsCalendarSerialDateOptions.TYPE_YEARLY:
            CmsCalendarSerialDateYearlyOptions yearlyOptions = (CmsCalendarSerialDateYearlyOptions) entryDate
                    .getSerialOptions();
            yearUseWeekday = yearlyOptions.isUseWeekDay();
            if (!yearlyOptions.isUseWeekDay()) {
                yearDayOfMonth = String.valueOf(yearlyOptions.getDayOfMonth());
                yearSelectedIndexMonth = yearlyOptions.getMonth();
            } else {
                yearSelectedIndexWeekDayOfMonth = yearlyOptions.getDayOfMonth() - 1;
                yearSelectedWeekDayDay = yearlyOptions.getWeekDay();
                yearSelectedIndexWeekDayMonth = yearlyOptions.getMonth();
            }
            break;
        default:
            // nothing do do here, should never happen
        }
    } else {
        // no serial entry created yet, add some defaults
        resolver.addMacro(
                MACRO_PREFIX_PARAMVALUE + PARAM_SERIALTYPE + "." + I_CmsCalendarSerialDateOptions.TYPE_DAILY,
                ATTR_CHECKED);
        resolver.addMacro(MACRO_PREFIX_PARAMVALUE + PARAM_WEEK_WEEKDAY + "." + Calendar.MONDAY, ATTR_CHECKED);

    }
    // set time settings
    String startTime = getCalendarLocalizedTime(widgetDialog.getLocale(), widgetDialog.getMessages(),
            entryDate.getStartDate().getTimeInMillis(), false, true);
    resolver.addMacro(MACRO_PREFIX_PARAMVALUE + PARAM_STARTTIME, startTime);

    String endTime = "";
    if (!entryDate.getStartDate().equals(entryDate.getEndDate())) {
        // end time is different from start time, get localized value
        endTime = getCalendarLocalizedTime(widgetDialog.getLocale(), widgetDialog.getMessages(),
                entryDate.getEndDate().getTimeInMillis(), false, true);
    }
    resolver.addMacro(MACRO_PREFIX_PARAMVALUE + PARAM_ENDTIME, endTime);

    resolver.addMacro("select.durationdays",
            buildSelectDurationDays(PARAM_DURATIONDAYS, messages, entryDate.getDuration()));

    // set found values to serial option tabs
    // daily options
    resolver.addMacro(MACRO_PREFIX_PARAMVALUE + PARAM_DAY_DAILYINTERVAL, dayDailyInterval);
    resolver.addMacro(MACRO_PREFIX_PARAMVALUE + PARAM_DAY_EVERYWORKINGDAY + "." + dayEveryWorkingDay,
            ATTR_CHECKED);

    // weekly options
    resolver.addMacro(MACRO_PREFIX_PARAMVALUE + PARAM_WEEK_WEEKLYINTERVAL, weekWeeklyInterval);

    // monthly options
    // mark the correct radio
    resolver.addMacro(MACRO_PREFIX_PARAMVALUE + PARAM_MONTH_SERIALMONTHDAY + "." + monthUseWeekday,
            ATTR_CHECKED);
    // set the macros for the day of month options
    resolver.addMacro(MACRO_PREFIX_PARAMVALUE + PARAM_MONTH_DAYOFMONTH, monthDayOfMonth);
    resolver.addMacro(MACRO_PREFIX_PARAMVALUE + PARAM_MONTH_MONTHLYINTERVAL, monthMonthlyInterval);
    // set the macros for the week day of month options
    resolver.addMacro(MACRO_PREFIX_PARAMVALUE + PARAM_MONTH_MONTHLYINTERVALWEEKDAY,
            monthMonthlyIntervalWeekDay);
    // build the select boxes
    resolver.addMacro("select.monthnumberofweekday",
            buildSelectNumberOfWeekDayOfMonth(
                    PARAM_MONTH_NUMBEROFWEEKDAYOFMONTH, "onfocus=\"document.getElementById('"
                            + PARAM_MONTH_SERIALMONTHDAY + ".true').checked = true;\"",
                    messages, monthSelectedIndexWeekDayOfMonth));
    resolver.addMacro("select.monthweekday",
            buildSelectWeekDay(PARAM_MONTH_WEEKDAY, "onfocus=\"document.getElementById('"
                    + PARAM_MONTH_SERIALMONTHDAY + ".true').checked = true;\"", messages,
                    monthSelectedWeekDay));

    // yearly options
    // mark the correct radio
    resolver.addMacro(MACRO_PREFIX_PARAMVALUE + PARAM_YEAR_SERIALYEARDAY + "." + yearUseWeekday, ATTR_CHECKED);
    // set the macros for the day of month options
    resolver.addMacro(MACRO_PREFIX_PARAMVALUE + PARAM_YEAR_DAYOFMONTH, yearDayOfMonth);
    resolver.addMacro("select.yearmonth", buildSelectMonth(PARAM_YEAR_MONTH,
            "onfocus=\"document.getElementById('" + PARAM_YEAR_SERIALYEARDAY + ".false').checked = true;\"",
            messages, yearSelectedIndexMonth));
    // set the macros for the week day of month options
    resolver.addMacro("select.yearnumberofweekday",
            buildSelectNumberOfWeekDayOfMonth(PARAM_YEAR_WEEKDAYOFMONTH, "onfocus=\"document.getElementById('"
                    + PARAM_YEAR_SERIALYEARDAY + ".true').checked = true;\"", messages,
                    yearSelectedIndexWeekDayOfMonth));
    resolver.addMacro("select.yearweekday",
            buildSelectWeekDay(PARAM_YEAR_WEEKDAY, "onfocus=\"document.getElementById('"
                    + PARAM_YEAR_SERIALYEARDAY + ".true').checked = true;\"", messages,
                    yearSelectedWeekDayDay));
    resolver.addMacro("select.yearmonthweekday",
            buildSelectMonth(PARAM_YEAR_WEEKDAYMONTH, "onfocus=\"document.getElementById('"
                    + PARAM_YEAR_SERIALYEARDAY + ".true').checked = true;\"", messages,
                    yearSelectedIndexWeekDayMonth));

    // set serial duration values

    // set start date
    resolver.addMacro("calendar.startdate",
            buildDateInput("startdate", widgetDialog, entryDate.getStartDate()));
    Calendar serialEndDate = entryDate.getSerialEndDate();
    if (serialEndDate == null) {
        serialEndDate = entryDate.getStartDate();
    }
    resolver.addMacro("calendar.serialenddate", buildDateInput("serialenddate", widgetDialog, serialEndDate));

    // set occurences
    int occurences = 10;
    if (entryDate.getSerialEndType() == I_CmsCalendarSerialDateOptions.END_TYPE_TIMES) {
        occurences = entryDate.getOccurences();
    }
    resolver.addMacro(MACRO_PREFIX_PARAMVALUE + PARAM_OCCURENCES, String.valueOf(occurences));

    // set the end type radio buttons
    resolver.addMacro(MACRO_PREFIX_PARAMVALUE + PARAM_ENDTYPE + "." + entryDate.getSerialEndType(),
            ATTR_CHECKED);

    return resolver;
}

From source file:com.xunlei.util.DateUtils.java

/**
 * <p>//from   ww w .jav a2  s  .c o  m
 * This constructs an <code>Iterator</code> over each day in a date range defined by a focus date and range style.
 * </p>
 * <p>
 * For instance, passing Thursday, July 4, 2002 and a <code>RANGE_MONTH_SUNDAY</code> will return an <code>Iterator</code> that starts with Sunday, June 30, 2002 and ends with Saturday, August 3,
 * 2002, returning a Calendar instance for each intermediate day.
 * </p>
 * <p>
 * This method provides an iterator that returns Calendar objects. The days are progressed using {@link Calendar#add(int, int)}.
 * </p>
 * 
 * @param focus the date to work with
 * @param rangeStyle the style constant to use. Must be one of {@link DateUtils#RANGE_MONTH_SUNDAY}, {@link DateUtils#RANGE_MONTH_MONDAY}, {@link DateUtils#RANGE_WEEK_SUNDAY},
 *        {@link DateUtils#RANGE_WEEK_MONDAY}, {@link DateUtils#RANGE_WEEK_RELATIVE}, {@link DateUtils#RANGE_WEEK_CENTER}
 * @return the date iterator
 * @throws IllegalArgumentException if the date is <code>null</code>
 * @throws IllegalArgumentException if the rangeStyle is invalid
 */
public static Iterator iterator(Calendar focus, int rangeStyle) {
    if (focus == null) {
        throw new IllegalArgumentException("The date must not be null");
    }
    Calendar start = null;
    Calendar end = null;
    int startCutoff = Calendar.SUNDAY;
    int endCutoff = Calendar.SATURDAY;
    switch (rangeStyle) {
    case RANGE_MONTH_SUNDAY:
    case RANGE_MONTH_MONDAY:
        // Set start to the first of the month
        start = truncate(focus, Calendar.MONTH);
        // Set end to the last of the month
        end = (Calendar) start.clone();
        end.add(Calendar.MONTH, 1);
        end.add(Calendar.DATE, -1);
        // Loop start back to the previous sunday or monday
        if (rangeStyle == RANGE_MONTH_MONDAY) {
            startCutoff = Calendar.MONDAY;
            endCutoff = Calendar.SUNDAY;
        }
        break;
    case RANGE_WEEK_SUNDAY:
    case RANGE_WEEK_MONDAY:
    case RANGE_WEEK_RELATIVE:
    case RANGE_WEEK_CENTER:
        // Set start and end to the current date
        start = truncate(focus, Calendar.DATE);
        end = truncate(focus, Calendar.DATE);
        switch (rangeStyle) {
        case RANGE_WEEK_SUNDAY:
            // already set by default
            break;
        case RANGE_WEEK_MONDAY:
            startCutoff = Calendar.MONDAY;
            endCutoff = Calendar.SUNDAY;
            break;
        case RANGE_WEEK_RELATIVE:
            startCutoff = focus.get(Calendar.DAY_OF_WEEK);
            endCutoff = startCutoff - 1;
            break;
        case RANGE_WEEK_CENTER:
            startCutoff = focus.get(Calendar.DAY_OF_WEEK) - 3;
            endCutoff = focus.get(Calendar.DAY_OF_WEEK) + 3;
            break;
        }
        break;
    default:
        throw new IllegalArgumentException("The range style " + rangeStyle + " is not valid.");
    }
    if (startCutoff < Calendar.SUNDAY) {
        startCutoff += 7;
    }
    if (startCutoff > Calendar.SATURDAY) {
        startCutoff -= 7;
    }
    if (endCutoff < Calendar.SUNDAY) {
        endCutoff += 7;
    }
    if (endCutoff > Calendar.SATURDAY) {
        endCutoff -= 7;
    }
    while (start.get(Calendar.DAY_OF_WEEK) != startCutoff) {
        start.add(Calendar.DATE, -1);
    }
    while (end.get(Calendar.DAY_OF_WEEK) != endCutoff) {
        end.add(Calendar.DATE, 1);
    }
    return new DateIterator(start, end);
}

From source file:org.apache.camel.component.mongodb.MongoDbTailableCursorConsumerTest.java

@Test
public void testPersistentTailTrackIncreasingDateField() throws Exception {
    assertEquals(0, cappedTestCollection.count());
    final MockEndpoint mock = getMockEndpoint("mock:test");
    final Calendar startTimestamp = Calendar.getInstance();

    // get default tracking collection
    DBCollection trackingCol = db.getCollection(MongoDbTailTrackingConfig.DEFAULT_COLLECTION);
    trackingCol.drop();/*from w w  w.ja v a2 s .  c om*/
    trackingCol = db.getCollection(MongoDbTailTrackingConfig.DEFAULT_COLLECTION);

    // create a capped collection with max = 1000
    cappedTestCollection = db.createCollection(cappedTestCollectionName,
            BasicDBObjectBuilder.start().add("capped", true).add("size", 1000000000).add("max", 1000).get());

    addTestRoutes();
    context.startRoute("tailableCursorConsumer2");

    mock.expectedMessageCount(300);
    // pump 300 records
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            for (int i = 1; i <= 300; i++) {
                Calendar c = (Calendar) (startTimestamp.clone());
                c.add(Calendar.MINUTE, i);
                cappedTestCollection.insert(
                        BasicDBObjectBuilder.start("increasing", c.getTime()).add("string", "value" + i).get(),
                        WriteConcern.SAFE);
            }
        }
    });

    // start the data pumping
    t.start();
    // before we continue wait for the data pump to end
    t.join();
    mock.assertIsSatisfied();
    mock.reset();
    // ensure that the persisted lastVal is startTimestamp + 300min
    Calendar cal300 = (Calendar) startTimestamp.clone();
    cal300.add(Calendar.MINUTE, 300);
    context.stopRoute("tailableCursorConsumer2");
    assertEquals(cal300.getTime(), trackingCol.findOne(new BasicDBObject("persistentId", "darwin"))
            .get(MongoDbTailTrackingConfig.DEFAULT_FIELD));
    context.startRoute("tailableCursorConsumer2");

    // expect 300 messages and not 600
    mock.expectedMessageCount(300);
    // pump 300 records
    t = new Thread(new Runnable() {
        @Override
        public void run() {
            for (int i = 301; i <= 600; i++) {
                Calendar c = (Calendar) (startTimestamp.clone());
                c.add(Calendar.MINUTE, i);
                cappedTestCollection.insert(
                        BasicDBObjectBuilder.start("increasing", c.getTime()).add("string", "value" + i).get(),
                        WriteConcern.SAFE);
            }
        }
    });
    // start the data pumping
    t.start();
    // before we continue wait for the data pump to end
    t.join();
    mock.assertIsSatisfied();
    Object firstBody = mock.getExchanges().get(0).getIn().getBody();
    assertTrue(firstBody instanceof DBObject);
    Calendar cal301 = (Calendar) startTimestamp.clone();
    cal301.add(Calendar.MINUTE, 301);
    assertEquals(cal301.getTime(), ((DBObject) firstBody).get("increasing"));
    // check that the persisted lastVal after stopping the route is startTimestamp + 600min
    context.stopRoute("tailableCursorConsumer2");
    Calendar cal600 = (Calendar) startTimestamp.clone();
    cal600.add(Calendar.MINUTE, 600);
    assertEquals(cal600.getTime(), trackingCol.findOne(new BasicDBObject("persistentId", "darwin"))
            .get(MongoDbTailTrackingConfig.DEFAULT_FIELD));
}

From source file:org.kuali.mobility.events.controllers.CalendarController.java

@RequestMapping(value = "/listEvents", method = RequestMethod.GET)
public String listEvents(HttpServletRequest request, Model uiModel, @RequestParam(required = true) String date,
        @RequestParam(required = true) String beginDate, @RequestParam(required = true) String endDate) {
    User user = (User) request.getSession().getAttribute(Constants.KME_USER_KEY);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    Calendar selectedDate = Calendar.getInstance();
    Calendar beginCalendar = Calendar.getInstance();
    Calendar endCalendar = Calendar.getInstance();
    try {//  ww  w  . ja v  a  2 s.  com
        if (date != null) {
            selectedDate.setTime(sdf.parse(date));
        }
        if (beginDate != null) {
            beginCalendar.setTime(sdf.parse(beginDate));
        }
        if (endDate != null) {
            endCalendar.setTime(sdf.parse(endDate));
        }
    } catch (ParseException e) {
        return list(request, uiModel, date);
    }
    try {
        Filter filter = (Filter) request.getSession().getAttribute("calendar.event.filterId");
        ListViewEvents listViewEvents = calendarEventOAuthService.retrieveViewEventsList(user.getUserId(),
                selectedDate.getTime(), beginCalendar.getTime(), endCalendar.getTime(),
                filter != null ? filter.getFilterId() : null);

        Calendar currentEndDate = (Calendar) endCalendar.clone();
        Calendar previousDate = (Calendar) beginCalendar.clone();
        previousDate.add(Calendar.DATE, -listViewEvents.getAppData().getListViewFutureDaysLimit());
        endCalendar.add(Calendar.DATE, listViewEvents.getAppData().getListViewFutureDaysLimit());

        SimpleDateFormat my = new SimpleDateFormat("yyyyMM");
        uiModel.addAttribute("selectedDate", sdf.format(selectedDate.getTime()));
        uiModel.addAttribute("monthSelectedDate", my.format(selectedDate.getTime()));
        uiModel.addAttribute("beginDate", sdf.format(beginCalendar.getTime()));
        uiModel.addAttribute("endDate", sdf.format(endCalendar.getTime()));
        uiModel.addAttribute("currentEndDate", sdf.format(currentEndDate.getTime()));
        uiModel.addAttribute("previousDate", sdf.format(previousDate.getTime()));
        uiModel.addAttribute("days", listViewEvents.getAppData().getListViewFutureDaysLimit());
        uiModel.addAttribute("viewData", listViewEvents.getViewData());
        uiModel.addAttribute("appData", listViewEvents.getAppData());
        uiModel.addAttribute("events", listViewEvents.getEvents());
        uiModel.addAttribute("filter", filter);
    } catch (PageLevelException pageLevelException) {
        uiModel.addAttribute("message", pageLevelException.getMessage());
        return "calendar/message";
    }
    return "calendar/list";
}

From source file:com.alkacon.opencms.calendar.CmsCalendarDisplay.java

/**
 * Returns the list of calendar entries as {@link CmsCalendarEntry} objects for the specified day.<p>
 * /*from  www  .  j a v  a2s. co m*/
 * @param year the year of the day to display
 * @param day the day of the year to get the entries for
 * @return the list of calendar entries for the specified day
 */
public Map getEntriesForDay(int year, int day) {

    Calendar startDay = new GregorianCalendar(getJsp().getRequestContext().getLocale());
    startDay.set(Calendar.YEAR, year);
    startDay.set(Calendar.DAY_OF_YEAR, day);

    Calendar endDay = (Calendar) startDay.clone();
    return getEntriesForDays(startDay, endDay);
}

From source file:com.frameworkset.platform.sanylog.action.CounterController.java

/**
 * @param siteId/*ww w  . j a v  a  2  s.c  o m*/
 * @param type
 * @param model
 * @return
 */
public String showBrowserCounterDistribute(int siteId, String type, String startTime, String endTime,
        ModelMap model) throws Exception {

    if (!"custom".equals(type)) {

        Calendar startDate = Calendar.getInstance();
        Calendar endDate = Calendar.getInstance();

        if ("yesterday".equals(type)) {
            startDate.add(Calendar.DAY_OF_MONTH, -1);
            endDate = (Calendar) startDate.clone();
        } else if ("week".equals(type)) {
            int offset = startDate.get(Calendar.DAY_OF_WEEK);
            startDate.add(Calendar.DAY_OF_MONTH, offset - (offset * 2 - 1));
            endDate = (Calendar) startDate.clone();
            endDate.add(Calendar.DAY_OF_MONTH, 6);
        } else if ("7days".equals(type)) {
            startDate.add(Calendar.DAY_OF_MONTH, -6);
        } else if ("month".equals(type)) {
            int offset = startDate.get(Calendar.DAY_OF_MONTH);
            startDate.add(Calendar.DAY_OF_MONTH, offset - (offset * 2 - 1));
            endDate = (Calendar) startDate.clone();
            endDate.add(Calendar.MONTH, 1);
            endDate.add(Calendar.DAY_OF_MONTH, -1);
        } else if ("30days".equals(type)) {
            startDate.add(Calendar.DAY_OF_MONTH, -30);
        }

        startTime = DateUtils.format(startDate.getTime(), DateUtils.ISO8601_DATE_PATTERN);
        endTime = DateUtils.format(endDate.getTime(), DateUtils.ISO8601_DATE_PATTERN);
    }

    // ??
    List<BrowserVisitInfo> browserVisitInfoList = counterManager.getBrowserVisitInfo(siteId, startTime,
            endTime);

    if (!CollectionUtils.isEmpty(browserVisitInfoList)) {
        if ("week".equals(type) || "7days".equals(type) || "month".equals(type) || "30days".equals(type)) {
            browserVisitInfoList.remove(1);
            browserVisitInfoList.remove(1);
        }
    }

    model.addAttribute("browserVisitInfoList", browserVisitInfoList);

    model.addAttribute("startTime", startTime);
    model.addAttribute("endTime", endTime);

    model.addAttribute("siteId", siteId);
    model.addAttribute("type", type);

    String browserCounterForwordPage = "showBrowserCounterDayDistribute.page";
    String browserTypeForwordPage = "showBrowserTypeDayDistribute.page";
    String browserIPForwordPage = "showBrowserIPDayDistribute.page";

    if ("today".equals(type) || "yesterday".equals(type) || "custom".equals(type)) {
        browserCounterForwordPage = "showBrowserCounterHourDistribute.page";
        browserTypeForwordPage = "showBrowserTypeDistributeToday.page";
        browserIPForwordPage = "showBrowserIPDistributeToday.page";
    }

    model.addAttribute("browserCounterForwordPage", browserCounterForwordPage);
    model.addAttribute("browserTypeForwordPage", browserTypeForwordPage);
    model.addAttribute("browserIPForwordPage", browserIPForwordPage);

    return "path:showBrowserCounterDistribute";
}

From source file:tw.edu.chit.struts.action.language.ReportPrintAction.java

/**
 * ???//  w  w w.j  a  v a  2s .co  m
 * 
 * @param mapping org.apache.struts.action.ActionMapping object
 * @param form org.apache.struts.action.ActionForm object
 * @param request request javax.servlet.http.HttpServletRequest object
 * @param response response javax.servlet.http.HttpServletResponse object
 * @param sterm 
 */
@SuppressWarnings("unchecked")
private void printDeptStdSkillList2(ActionMapping mapping, DynaActionForm form, HttpServletRequest request,
        HttpServletResponse response, String sterm) throws Exception {

    HttpSession session = request.getSession(false);
    AdminManager am = (AdminManager) getBean(IConstants.ADMIN_MANAGER_BEAN_NAME);
    MemberManager mm = (MemberManager) getBean(MEMBER_MANAGER_BEAN_NAME);

    Member member = (Member) getUserCredential(session).getMember();
    Empl empl = mm.findEmplByOid(member.getOid());
    ServletContext context = request.getSession().getServletContext();

    DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
    Calendar cal = Calendar.getInstance();
    Calendar cal1 = (Calendar) cal.clone();
    Calendar cal2 = (Calendar) cal.clone();
    if (StringUtils.isNotBlank(form.getString("licenseValidDateStart"))
            || StringUtils.isNotBlank(form.getString("licenseValidDateEnd"))) {
        Date from = StringUtils.isBlank(form.getString("licenseValidDateStart")) ? null
                : Toolket.parseNativeDate(form.getString("licenseValidDateStart"));
        // ???
        Date to = StringUtils.isBlank(form.getString("licenseValidDateEnd")) ? Calendar.getInstance().getTime()
                : Toolket.parseNativeDate(form.getString("licenseValidDateEnd"));

        cal1.setTime(from);
        cal1.set(Calendar.HOUR_OF_DAY, 0);
        cal1.set(Calendar.MINUTE, 0);
        cal1.set(Calendar.SECOND, 0);
        cal1.set(Calendar.MILLISECOND, 0);

        cal2.setTime(to);
        cal2.set(Calendar.HOUR_OF_DAY, 23);
        cal2.set(Calendar.MINUTE, 59);
        cal2.set(Calendar.SECOND, 59);
        cal2.set(Calendar.MILLISECOND, 999);
    }

    String hql = "FROM StdSkill s WHERE s.amountDate IS NOT NULL AND s.deptNo = ? "
            + "AND s.licenseValidDate BETWEEN ? AND ? ORDER BY s.studentNo";

    List<StdSkill> skills = (List<StdSkill>) am.find(hql, new Object[] { "0", cal1.getTime(), cal2.getTime() }); // 

    File templateXLS = new File(context.getRealPath("/WEB-INF/reports/DeptStdSkillList2.xls"));
    HSSFWorkbook workbook = Toolket.getHSSFWorkbook(templateXLS);
    HSSFSheet sheet = workbook.getSheetAt(0);

    // Header
    Toolket.setCellValue(sheet, 0, 0,
            "?" + Toolket.getEmpUnit(empl.getUnit())
                    + "??? (" + df.format(cal1.getTime()) + "~"
                    + df.format(cal2.getTime()) + ")");

    int index = 2;
    Student student = null;
    Graduate graduate = null;
    List<LicenseCode> codes = null;
    List<LicenseCode961> code961s = null;
    LicenseCode code = null;
    LicenseCode961 code961 = null;
    String checkStr1 = "???\n?\n???";
    String checkStr2 = "?\n?";

    for (StdSkill skill : skills) {

        student = mm.findStudentByNo(skill.getStudentNo());
        if (student == null) {
            graduate = mm.findGraduateByStudentNo(skill.getStudentNo());
            if (graduate != null) {
                student = new Student();
                BeanUtils.copyProperties(graduate, student);
            }
        }

        if (student != null || graduate != null) {
            Toolket.setCellValue(sheet, index, 0, String.valueOf(index - 1));
            Toolket.setCellValue(sheet, index, 1, StringUtils.isBlank(student.getDepartClass()) ? ""
                    : Toolket.getSchoolName(student.getDepartClass()));
            Toolket.setCellValue(sheet, index, 2, Toolket.getClassFullName(student.getDepartClass()));
            Toolket.setCellValue(sheet, index, 3, student.getStudentNo());
            Toolket.setCellValue(sheet, index, 4, student.getStudentName());
            Toolket.setCellValue(sheet, index, 5, student.getIdno());
            Toolket.setCellValue(sheet, index, 9, String.valueOf(skill.getAmount()));
            Toolket.setCellValue(sheet, index, 10, "");
            Toolket.setCellValue(sheet, index, 11, checkStr1);
            Toolket.setCellValue(sheet, index, 12, checkStr2);

            codes = (List<LicenseCode>) am
                    .findLicenseCodesBy(new LicenseCode(Integer.valueOf(skill.getLicenseCode())));

            if (!codes.isEmpty()) {
                code = codes.get(0);
                Toolket.setCellValue(sheet, index, 6, code.getName());
                Toolket.setCellValue(sheet, index, 7, code.getDeptName());
                Toolket.setCellValue(sheet, index, 8, code.getLevel());
            } else {
                code961s = (List<LicenseCode961>) am
                        .findLicenseCode961sBy(new LicenseCode961(Integer.valueOf(skill.getLicenseCode())));
                if (!code961s.isEmpty()) {
                    code961 = code961s.get(0);
                    Toolket.setCellValue(sheet, index, 6, code961.getName());
                    Toolket.setCellValue(sheet, index, 7, code961.getDeptName());
                    Toolket.setCellValue(sheet, index, 8, code961.getLevel());
                }
            }

            index++;
        }
    }

    File tempDir = new File(
            context.getRealPath("/WEB-INF/reports/temp/" + getUserCredential(session).getMember().getIdno()
                    + (new SimpleDateFormat("yyyyMMdd").format(new Date()))));
    if (!tempDir.exists())
        tempDir.mkdirs();

    File output = new File(tempDir, "DeptStdSkillList2.xls");
    FileOutputStream fos = new FileOutputStream(output);
    workbook.write(fos);
    fos.close();

    JasperReportUtils.printXlsToFrontEnd(response, output);
    output.delete();
    tempDir.delete();
}

From source file:com.alkacon.opencms.calendar.CmsCalendarDisplay.java

/**
 * Returns all displayed days of the specified year with their corresponding entries as lists.<p>
 * /* w ww  . j  a v  a  2  s .  c  o  m*/
 * The key of the Map has to be a Date object.<p>
 * 
 * The Map values are always lists of {@link CmsCalendarEntry} objects, if no entries are available for a specific day,
 * an empty List is returned.<p>
 * 
 * @param year the year of the month to display
 * @return all displayed days of the specified day range with their corresponding entries as lists
 */
public Map getEntriesForYear(int year) {

    Calendar startDay = new GregorianCalendar(getJsp().getRequestContext().getLocale());
    startDay.set(Calendar.YEAR, year);
    startDay.set(Calendar.MONTH, Calendar.JANUARY);
    startDay.set(Calendar.DAY_OF_MONTH, 1);

    Calendar endDay = (Calendar) startDay.clone();
    endDay.set(Calendar.MONTH, Calendar.DECEMBER);
    endDay.set(Calendar.DAY_OF_MONTH, 31);

    return getEntriesForDays(startDay, endDay);
}

From source file:com.ecofactor.qa.automation.newapp.service.MockDataServiceImpl.java

/**
 * Load st events./* ww w .ja v  a 2  s.c om*/
 * 
 * @param thermostatId
 *            the thermostat id
 */
private void loadSTEvents(Integer thermostatId) {

    Set<Calendar> times = timeEventMap.keySet();
    Calendar lastTime = null;
    for (Calendar time : times) {
        lastTime = time;
    }

    boolean generated = false;
    if (!timeEventMap.isEmpty()) {
        if (mode.equals("Cool")) {
            generated = timeEventMap.get(lastTime).getAlgorithmId() == ST3_COOL;
        } else if (mode.equals("Heat")) {
            generated = timeEventMap.get(lastTime).getAlgorithmId() == ST3_HEAT;
        }
    }

    if (timeEventMap.isEmpty() || !generated) {
        int position = getCurrentPosition(thermostatId);
        int gap = (position >= 10) ? position / 10 : 0;

        Calendar endTime = DateUtil.getUTCCalendar();
        Calendar startTime = null;

        if (position == 0) {
            startTime = (Calendar) endTime.clone();
            startTime.add(Calendar.MINUTE, -10);
        } else if (position > jobDataList.size()) {
            startTime = jobDataList.get(jobDataList.size() - 1).getEnd();
            startTime = DateUtil.getUTCCalendar(startTime);
        } else if (gap > 0) {
            startTime = jobDataList.get(gap - 1).getEnd();
            startTime = DateUtil.getUTCCalendar(startTime);
        }

        if (startTime != null) {
            MockEvent me = new MockEvent(this, MockEventType.ST);
            me.setProperty("start", startTime);
            me.setProperty("end", endTime);
            mockConsumer.fireEvent(me);
        }
    }
}