Example usage for java.util Calendar setLenient

List of usage examples for java.util Calendar setLenient

Introduction

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

Prototype

public void setLenient(boolean lenient) 

Source Link

Document

Specifies whether or not date/time interpretation is to be lenient.

Usage

From source file:events.TeamVsTeam.TeamVsTeam.java

public void scheduleEventStart() {
    try {/*from  w w  w. ja va2 s .  c  o m*/
        Calendar currentTime = Calendar.getInstance();
        Calendar nextStartTime = null;
        Calendar testStartTime = null;

        for (String timeOfDay : Config.EVENT_TvTStartTime) {
            testStartTime = Calendar.getInstance();
            testStartTime.setLenient(true);

            String[] splitTimeOfDay = timeOfDay.split(":");

            testStartTime.set(Calendar.HOUR_OF_DAY, Integer.parseInt(splitTimeOfDay[0]));
            testStartTime.set(Calendar.MINUTE, Integer.parseInt(splitTimeOfDay[1]));

            if (testStartTime.getTimeInMillis() < currentTime.getTimeInMillis()) {
                testStartTime.add(Calendar.DAY_OF_MONTH, 1);
            }

            if ((nextStartTime == null)
                    || (testStartTime.getTimeInMillis() < nextStartTime.getTimeInMillis())) {
                nextStartTime = testStartTime;
            }

            if (_startTask != null) {
                _startTask.cancel(false);
                _startTask = null;
            }
            _startTask = ThreadPoolManager.getInstance().schedule(new StartTask(),
                    nextStartTime.getTimeInMillis() - System.currentTimeMillis());

        }

        currentTime = null;
        nextStartTime = null;
        testStartTime = null;

    } catch (Exception e) {
        _log.warn("TvT: Error figuring out a start time. Check TvT_StartTime in config file.");
    }
}

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

public static boolean setFormDataDelegate(RunData rundata, Context context, ALData formdata, Field[] fields,
        List<String> msgList) throws ALPageNotFoundException, ALDBErrorException {
    if (fields == null || fields.length == 0) {
        return false;
    }//from  w ww.  j ava  2  s  . co m

    boolean res = false;

    try {
        String FORMAT_DATE = "yyyyMMdd";
        String FORMAT_TIME = "HHmm";
        int FORMAT_DATE_LEN = FORMAT_DATE.length();
        int FORMAT_TIME_LEN = FORMAT_TIME.length();

        int length = fields.length;
        for (int i = 0; i < length; i++) {
            fields[i].setAccessible(true);
            String name = fields[i].getName();
            Object obj = fields[i].get(formdata);
            // ? ALCellDateTimeField ??
            if (obj instanceof ALCellDateTimeField) {
                String dateString = new StringBuffer().append(name).append("_date").toString();
                String timeString = new StringBuffer().append(name).append("_time").toString();

                ALCellDateTimeField field = (ALCellDateTimeField) obj;
                String dateStr = null;
                String timeStr = null;
                Calendar cal = Calendar.getInstance();
                if (rundata.getParameters().containsKey(dateString)) {
                    dateStr = rundata.getParameters().getString(dateString);
                } else {
                    continue;
                }
                if (rundata.getParameters().containsKey(timeString)) {
                    timeStr = rundata.getParameters().getString(timeString);
                } else {
                    continue;
                }

                if (dateStr.length() != FORMAT_DATE_LEN) {
                    // ?????????
                    msgList.add(ALLocalizationUtils.getl10n("SCHEDULE_MESSAGE_NON_DAY"));
                    continue;
                }

                if (timeStr.length() != FORMAT_TIME_LEN) {
                    // ?????????
                    msgList.add(ALLocalizationUtils.getl10n("SCHEDULE_MESSAGE_NON_TIME"));
                    continue;
                }

                List<String> tmpList = new ArrayList<String>();
                ALCellStringField sf = new ALCellStringField(dateStr);
                sf.setTrim(true);
                sf.setCharacterType(ALStringField.TYPE_NUMBER);
                sf.setValue(dateStr);
                sf.validate(tmpList);
                if (tmpList.size() != 0) {
                    msgList.add(ALLocalizationUtils.getl10n("SCHEDULE_MESSAGE_NON_DAY"));
                    continue;
                }

                sf = new ALCellStringField(timeStr);
                sf.setTrim(true);
                sf.setCharacterType(ALStringField.TYPE_NUMBER);
                sf.setValue(timeStr);
                sf.validate(tmpList);
                if (tmpList.size() != 0) {
                    msgList.add(ALLocalizationUtils.getl10n("SCHEDULE_MESSAGE_NON_TIME"));
                    continue;
                }

                Date date = null;
                // ???
                SimpleDateFormat sdf = new SimpleDateFormat(FORMAT_DATE);
                sdf.setLenient(false);
                sdf.setTimeZone(TimeZone.getDefault());
                if (!dateStr.equals("")) {
                    try {
                        date = sdf.parse(dateStr);
                    } catch (Exception e) {
                        msgList.add(ALLocalizationUtils.getl10n("SCHEDULE_MESSAGE_NON_DAY"));
                        continue;
                    }
                } else {
                    continue;
                }
                Date time = null;
                SimpleDateFormat sdf2 = new SimpleDateFormat(FORMAT_TIME);
                sdf2.setLenient(false);
                sdf2.setTimeZone(TimeZone.getDefault());
                if (!timeStr.equals("")) {
                    try {
                        time = sdf2.parse(timeStr);
                    } catch (Exception e) {
                        msgList.add(ALLocalizationUtils.getl10n("SCHEDULE_MESSAGE_NON_TIME"));
                        continue;
                    }
                } else {
                    continue;
                }

                Calendar cal2 = Calendar.getInstance();
                cal2.setTime(time);

                cal.setLenient(false);
                cal.setTime(date);
                cal.set(Calendar.HOUR_OF_DAY, cal2.get(Calendar.HOUR_OF_DAY));
                cal.set(Calendar.MINUTE, cal2.get(Calendar.MINUTE));
                cal.set(Calendar.SECOND, 0);
                cal.set(Calendar.MILLISECOND, 0);

                field.setValue(cal.getTime());

                // ? ALCellDateField ??
            } else if (obj instanceof ALCellDateField) {
                ALCellDateField field = (ALCellDateField) obj;
                Date date = null;
                ALDateContainer con = new ALDateContainer();
                String dateString = new StringBuffer().append(name).toString();
                String dateStr = null;
                if (rundata.getParameters().containsKey(name)) {
                    dateStr = rundata.getParameters().getString(dateString);
                } else {
                    continue;
                }

                if (dateStr.length() != FORMAT_DATE_LEN) {
                    // ?????????
                    msgList.add(ALLocalizationUtils.getl10n("SCHEDULE_MESSAGE_NON_DAY"));
                    continue;
                }

                List<String> tmpList = new ArrayList<String>();
                ALCellStringField sf = new ALCellStringField(dateStr);
                sf.setTrim(true);
                sf.setCharacterType(ALStringField.TYPE_NUMBER);
                sf.setValue(dateStr);
                sf.validate(tmpList);
                if (tmpList.size() != 0) {
                    msgList.add(ALLocalizationUtils.getl10n("SCHEDULE_MESSAGE_NON_DAY"));
                    continue;
                }

                // ???
                SimpleDateFormat sdf = new SimpleDateFormat(FORMAT_DATE);
                sdf.setLenient(false);
                sdf.setTimeZone(TimeZone.getDefault());
                try {
                    date = sdf.parse(dateStr);
                } catch (Exception e) {
                    msgList.add(ALLocalizationUtils.getl10n("SCHEDULE_MESSAGE_NON_DAY"));
                    continue;
                }

                Calendar cal = Calendar.getInstance();
                cal.setLenient(false);
                cal.setTime(date);
                cal.set(Calendar.HOUR_OF_DAY, 0);
                cal.set(Calendar.MINUTE, 0);
                cal.set(Calendar.SECOND, 0);
                cal.set(Calendar.MILLISECOND, 0);

                con.setYear(cal.get(Calendar.YEAR));
                con.setMonth(cal.get(Calendar.MONTH) + 1);
                con.setDay(cal.get(Calendar.DATE));
                field.setValue(con);

                // ? ALAbstractField ??
            } else if (obj instanceof ALAbstractField) {
                ALAbstractField field = (ALAbstractField) obj;
                if (rundata.getParameters().containsKey(name)) {
                    field.setValue(rundata.getParameters().getString(name));
                }
            }
        }

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

From source file:com.clark.func.Functions.java

/**
 * Sets the specified field to a date returning a new object. This does not
 * use a lenient calendar. The original date object is unchanged.
 * /*  ww  w .j av a 2  s . c om*/
 * @param date
 *            the date, not null
 * @param calendarField
 *            the calendar field to set the amount to
 * @param amount
 *            the amount to set
 * @return a new Date object set with the specified value
 * @throws IllegalArgumentException
 *             if the date is null
 * @since 2.4
 */
private static Date setDate(Date date, int calendarField, int amount) {
    if (date == null) {
        throw new IllegalArgumentException("The date must not be null");
    }
    // getInstance() returns a new object, so this method is thread safe.
    Calendar c = Calendar.getInstance();
    c.setLenient(false);
    c.setTime(date);
    c.set(calendarField, amount);
    return c.getTime();
}

From source file:org.alfresco.web.ui.common.Utils.java

/**
 * Parse XML format date YYYY-MM-DDTHH:MM:SS
 * @param isoDate String/*from  w  w  w.  ja va2 s.c o  m*/
 * @return Date or null if failed to parse
 */
public static Date parseXMLDateFormat(String isoDate) {
    Date parsed = null;

    try {
        int offset = 0;

        // extract year
        int year = Integer.parseInt(isoDate.substring(offset, offset += 4));
        if (isoDate.charAt(offset) != '-') {
            throw new IndexOutOfBoundsException("Expected - character but found " + isoDate.charAt(offset));
        }

        // extract month
        int month = Integer.parseInt(isoDate.substring(offset += 1, offset += 2));
        if (isoDate.charAt(offset) != '-') {
            throw new IndexOutOfBoundsException("Expected - character but found " + isoDate.charAt(offset));
        }

        // extract day
        int day = Integer.parseInt(isoDate.substring(offset += 1, offset += 2));
        if (isoDate.charAt(offset) != 'T') {
            throw new IndexOutOfBoundsException("Expected T character but found " + isoDate.charAt(offset));
        }

        // extract hours, minutes, seconds and milliseconds
        int hour = Integer.parseInt(isoDate.substring(offset += 1, offset += 2));
        if (isoDate.charAt(offset) != ':') {
            throw new IndexOutOfBoundsException("Expected : character but found " + isoDate.charAt(offset));
        }
        int minutes = Integer.parseInt(isoDate.substring(offset += 1, offset += 2));
        if (isoDate.charAt(offset) != ':') {
            throw new IndexOutOfBoundsException("Expected : character but found " + isoDate.charAt(offset));
        }
        int seconds = Integer.parseInt(isoDate.substring(offset += 1, offset += 2));

        // initialize Calendar object
        Calendar calendar = Calendar.getInstance();
        calendar.setLenient(false);
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, month - 1);
        calendar.set(Calendar.DAY_OF_MONTH, day);
        calendar.set(Calendar.HOUR_OF_DAY, hour);
        calendar.set(Calendar.MINUTE, minutes);
        calendar.set(Calendar.SECOND, seconds);

        // extract the date
        parsed = calendar.getTime();
    } catch (IndexOutOfBoundsException e) {
    } catch (NumberFormatException e) {
    } catch (IllegalArgumentException e) {
    }

    return parsed;
}

From source file:org.apache.axis2.databinding.utils.ConverterUtil.java

/**
 * Converts a given string into a date. Code from Axis1 DateDeserializer.
 *
 * @param source/*www  .  j  av a2 s. c om*/
 * @return Returns Date.
 */
public static Date convertToDate(String source) {

    // the lexical form of the date is '-'? yyyy '-' mm '-' dd zzzzzz?
    if ((source == null) || source.trim().equals("")) {
        return null;
    }
    source = source.trim();
    boolean bc = false;
    if (source.startsWith("-")) {
        source = source.substring(1);
        bc = true;
    }

    int year = 0;
    int month = 0;
    int day = 0;
    int timeZoneOffSet = TimeZone.getDefault().getRawOffset();

    if (source.length() >= 10) {
        //first 10 numbers must give the year
        if ((source.charAt(4) != '-') || (source.charAt(7) != '-')) {
            throw new RuntimeException("invalid date format (" + source + ") with out - s at correct place ");
        }
        year = Integer.parseInt(source.substring(0, 4));
        month = Integer.parseInt(source.substring(5, 7));
        day = Integer.parseInt(source.substring(8, 10));

        if (source.length() > 10) {
            String restpart = source.substring(10);
            if (restpart.startsWith("Z")) {
                // this is a gmt time zone value
                timeZoneOffSet = 0;
            } else if (restpart.startsWith("+") || restpart.startsWith("-")) {
                // this is a specific time format string
                if (restpart.charAt(3) != ':') {
                    throw new RuntimeException(
                            "invalid time zone format (" + source + ") without : at correct place");
                }
                int hours = Integer.parseInt(restpart.substring(1, 3));
                int minits = Integer.parseInt(restpart.substring(4, 6));
                timeZoneOffSet = ((hours * 60) + minits) * 60000;
                if (restpart.startsWith("-")) {
                    timeZoneOffSet = timeZoneOffSet * -1;
                }
            } else {
                throw new RuntimeException("In valid string sufix");
            }
        }
    } else {
        throw new RuntimeException("In valid string to parse");
    }

    Calendar calendar = Calendar.getInstance();
    calendar.clear();
    calendar.setLenient(false);
    calendar.set(Calendar.YEAR, year);
    //xml month stars from the 1 and calendar month is starts with 0
    calendar.set(Calendar.MONTH, month - 1);
    calendar.set(Calendar.DAY_OF_MONTH, day);
    calendar.set(Calendar.ZONE_OFFSET, timeZoneOffSet);

    // set the day light off set only if time zone
    if (source.length() >= 10) {
        calendar.set(Calendar.DST_OFFSET, 0);
    }
    calendar.getTimeInMillis();
    if (bc) {
        calendar.set(Calendar.ERA, GregorianCalendar.BC);
    }

    return calendar.getTime();

}

From source file:org.apache.axis2.databinding.utils.ConverterUtil.java

/**
 * Code from Axis1 code base Note - We only follow the convention in the latest schema spec
 *
 * @param source/*from  www  . j ava 2 s  . c  om*/
 * @return Returns Calendar.
 */
public static Calendar convertToDateTime(String source) {

    if ((source == null) || source.trim().equals("")) {
        return null;
    }
    source = source.trim();
    // the lexical representation of the date time as follows
    // '-'? yyyy '-' mm '-' dd 'T' hh ':' mm ':' ss ('.' s+)? (zzzzzz)?
    Date date = null;
    Calendar calendar = Calendar.getInstance();
    calendar.clear();
    calendar.setLenient(false);

    if (source.startsWith("-")) {
        source = source.substring(1);
        calendar.set(Calendar.ERA, GregorianCalendar.BC);
    }

    int year = 0;
    int month = 0;
    int day = 0;
    int hour = 0;
    int minite = 0;
    int second = 0;
    long miliSecond = 0;
    int timeZoneOffSet = TimeZone.getDefault().getRawOffset();

    if ((source != null) && (source.length() >= 19)) {
        if ((source.charAt(4) != '-') || (source.charAt(7) != '-') || (source.charAt(10) != 'T')
                || (source.charAt(13) != ':') || (source.charAt(16) != ':')) {
            throw new RuntimeException("invalid date format (" + source + ") with out - s at correct place ");
        }
        year = Integer.parseInt(source.substring(0, 4));
        month = Integer.parseInt(source.substring(5, 7));
        day = Integer.parseInt(source.substring(8, 10));
        hour = Integer.parseInt(source.substring(11, 13));
        minite = Integer.parseInt(source.substring(14, 16));
        second = Integer.parseInt(source.substring(17, 19));

        int milliSecondPartLength = 0;

        if (source.length() > 19) {
            String rest = source.substring(19);
            if (rest.startsWith(".")) {
                // i.e this have the ('.'s+) part
                if (rest.endsWith("Z")) {
                    // this is in gmt time zone
                    timeZoneOffSet = 0;
                    calendar.setTimeZone(TimeZone.getTimeZone("GMT"));
                    miliSecond = Integer.parseInt(rest.substring(1, rest.lastIndexOf("Z")));
                    milliSecondPartLength = rest.substring(1, rest.lastIndexOf("Z")).trim().length();
                } else if ((rest.lastIndexOf("+") > 0) || (rest.lastIndexOf("-") > 0)) {
                    // this is given in a general time zione
                    String timeOffSet = null;
                    if (rest.lastIndexOf("+") > 0) {
                        timeOffSet = rest.substring(rest.lastIndexOf("+") + 1);
                        miliSecond = Integer.parseInt(rest.substring(1, rest.lastIndexOf("+")));
                        milliSecondPartLength = rest.substring(1, rest.lastIndexOf("+")).trim().length();
                        // we keep +1 or -1 to finally calculate the value
                        timeZoneOffSet = 1;

                    } else if (rest.lastIndexOf("-") > 0) {
                        timeOffSet = rest.substring(rest.lastIndexOf("-") + 1);
                        miliSecond = Integer.parseInt(rest.substring(1, rest.lastIndexOf("-")));
                        milliSecondPartLength = rest.substring(1, rest.lastIndexOf("-")).trim().length();
                        // we keep +1 or -1 to finally calculate the value
                        timeZoneOffSet = -1;
                    }
                    if (timeOffSet.charAt(2) != ':') {
                        throw new RuntimeException(
                                "invalid time zone format (" + source + ") without : at correct place");
                    }
                    int hours = Integer.parseInt(timeOffSet.substring(0, 2));
                    int minits = Integer.parseInt(timeOffSet.substring(3, 5));
                    timeZoneOffSet = ((hours * 60) + minits) * 60000 * timeZoneOffSet;

                } else {
                    // i.e it does not have time zone
                    miliSecond = Integer.parseInt(rest.substring(1));
                    milliSecondPartLength = rest.substring(1).trim().length();
                }

            } else {
                if (rest.startsWith("Z")) {
                    calendar.setTimeZone(TimeZone.getTimeZone("GMT"));
                    // this is in gmt time zone
                    timeZoneOffSet = 0;
                } else if (rest.startsWith("+") || rest.startsWith("-")) {
                    // this is given in a general time zione
                    if (rest.charAt(3) != ':') {
                        throw new RuntimeException(
                                "invalid time zone format (" + source + ") without : at correct place");
                    }
                    int hours = Integer.parseInt(rest.substring(1, 3));
                    int minits = Integer.parseInt(rest.substring(4, 6));
                    timeZoneOffSet = ((hours * 60) + minits) * 60000;
                    if (rest.startsWith("-")) {
                        timeZoneOffSet = timeZoneOffSet * -1;
                    }
                } else {
                    throw new NumberFormatException("in valid time zone attribute");
                }
            }
        }
        calendar.set(Calendar.YEAR, year);
        // xml month is started from 1 and calendar month is started from 0
        calendar.set(Calendar.MONTH, month - 1);
        calendar.set(Calendar.DAY_OF_MONTH, day);
        calendar.set(Calendar.HOUR_OF_DAY, hour);
        calendar.set(Calendar.MINUTE, minite);
        calendar.set(Calendar.SECOND, second);
        if (milliSecondPartLength != 3) {
            // milisecond part represenst the fraction of the second so we have to
            // find the fraction and multiply it by 1000. So if milisecond part
            // has three digits nothing required
            miliSecond = miliSecond * 1000;
            for (int i = 0; i < milliSecondPartLength; i++) {
                miliSecond = miliSecond / 10;
            }
        }
        calendar.set(Calendar.MILLISECOND, (int) miliSecond);
        calendar.set(Calendar.ZONE_OFFSET, timeZoneOffSet);
        // set the day light offset only if the time zone is present
        if (source.length() > 19) {
            calendar.set(Calendar.DST_OFFSET, 0);
        }

    } else {
        throw new NumberFormatException("date string can not be less than 19 characters");
    }

    return calendar;
}

From source file:org.carewebframework.common.DateUtil.java

/**
 * <p>//from ww w .  j a  v a 2  s.c  om
 * Convert a string value to a date/time. Attempts to convert using the four locale-specific
 * date formats (FULL, LONG, MEDIUM, SHORT). If these fail, looks to see if T+/-offset or
 * N+/-offset is used.
 * </p>
 * <p>
 * TODO: probably we can make the "Java parse" portion a bit smarter by using a better variety
 * of formats, maybe to catch Euro-style input as well.
 * </p>
 * <p>
 * TODO: probably we can add something like "t+d" or "t-y" as valid cases; in these scenarios,
 * the coefficient was omitted and could be defaulted to 1.
 * </p>
 * 
 * @param s <code>String</code> containing value to be converted.
 * @return <code>Date</code> object corresponding to the input value, or <code>null</code> if
 *         the parsing failed to resolve a valid Date.
 */
public static Date parseDate(String s) {
    Date result = null;

    if (s != null && !s.isEmpty()) {
        s = s.toLowerCase(); // make lc

        if ((PATTERN_EXT_DATE.matcher(s)).matches()) { // is an extended date?
            try {
                s = s.replaceAll("\\s+", ""); // strip space since they not
                // delim
                String _k = s.substring(1); // _k will ultimately be the multiplier value
                char k = 'd'; // k = s, n, h, d (default), m, or y

                if (1 == s.length()) {
                    _k = "0";
                } else {
                    if ((PATTERN_SPECIFIES_UNITS.matcher(s)).matches()) {
                        _k = s.substring(1, s.length() - 1);
                        k = s.charAt(s.length() - 1);
                    }
                }

                if ('+' == _k.charAt(0)) { // clip positive coefficient...
                    _k = _k.substring(1);
                }

                int field = Calendar.DAY_OF_YEAR;
                int offset = Integer.parseInt(_k);
                Calendar c = Calendar.getInstance();
                c.setLenient(false);

                if (s.charAt(0) == 't') {
                    c.setTime(DateUtil.today());
                }

                switch (k) {
                case 'y': // years
                    field = Calendar.YEAR;
                    break;
                case 'm': // months
                    field = Calendar.MONTH;
                    break;
                case 'h': // hours
                    field = Calendar.HOUR_OF_DAY;
                    break;
                case 'n': // minutes
                    field = Calendar.MINUTE;
                    break;
                case 's': // seconds
                    field = Calendar.SECOND;
                    break;
                }

                c.add(field, offset);
                result = c.getTime();
                // format
            } catch (Exception e) {
                return null; // found unparseable date (e.g. t-y)
            }
        } else {
            result = tryParse(s);

            if (result != null) {
                return result;
            }

            s = s.replaceAll("[\\.|-]", "/"); // dots, dashes to slashes
            result = tryParse(s);

            if (result != null) {
                return result;
            }

            s = s.replaceAll("\\s", "/"); // last chance to parse: spaces to
            result = tryParse(s); // slashes!
        }
    }

    return result;
}

From source file:org.carewebframework.common.DateUtil.java

/**
 * Adds specified number of days to date and, optionally strips the time component.
 * //from   ww w.  j av a  2  s  . co m
 * @param date Date value to process.
 * @param daysOffset # of days to add.
 * @param stripTime If true, strip the time component.
 * @return Input value the specified operations applied.
 */
public static Date addDays(Date date, int daysOffset, boolean stripTime) {
    if (date == null) {
        return null;
    }

    Calendar calendar = Calendar.getInstance();
    calendar.setLenient(false); // Make sure the calendar will not perform
    // automatic correction.
    calendar.setTime(date); // Set the time of the calendar to the given
    // date.

    if (stripTime) { // Remove the hours, minutes, seconds and milliseconds.
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
    }

    calendar.add(Calendar.DAY_OF_MONTH, daysOffset);
    return calendar.getTime();

}

From source file:org.dashbuilder.dataset.backend.BackendIntervalBuilderDynamicDate.java

public IntervalList build(DataSetHandler handler, ColumnGroup columnGroup) {
    IntervalDateRangeList results = new IntervalDateRangeList(columnGroup);
    DataSet dataSet = handler.getDataSet();
    List values = dataSet.getColumnById(columnGroup.getSourceId()).getValues();
    if (values.isEmpty()) {
        return results;
    }/*from ww  w.  j  a v a  2  s  .c  om*/

    // Sort the column dates.
    DataSetSort sortOp = new DataSetSort();
    sortOp.addSortColumn(new ColumnSort(columnGroup.getSourceId(), SortOrder.ASCENDING));
    DataSetHandler sortResults = handler.sort(sortOp);
    List<Integer> sortedRows = sortResults.getRows();
    if (sortedRows == null || sortedRows.isEmpty()) {
        return results;
    }

    // Get the lower & upper limits.
    SortedList sortedValues = new SortedList(values, sortedRows);
    Date minDate = (Date) sortedValues.get(0);
    Date maxDate = (Date) sortedValues.get(sortedValues.size() - 1);

    // If min/max are equals then create a single interval.
    if (minDate.compareTo(maxDate) == 0) {
        IntervalDateRange interval = new IntervalDateRange(DAY, minDate, maxDate);
        for (int row = 0; row < sortedValues.size(); row++)
            interval.rows.add(row);
        results.add(interval);
        return results;
    }

    // Calculate the interval type used according to the constraints set.
    int maxIntervals = columnGroup.getMaxIntervals();
    if (maxIntervals < 1)
        maxIntervals = 15;
    DateIntervalType intervalType = YEAR;
    long millis = (maxDate.getTime() - minDate.getTime());
    for (DateIntervalType type : values()) {
        long nintervals = millis / getDurationInMillis(type);
        if (nintervals < maxIntervals) {
            intervalType = type;
            break;
        }
    }

    // Ensure the interval mode obtained is always greater or equals than the preferred interval size.
    DateIntervalType intervalSize = null;
    if (!StringUtils.isBlank(columnGroup.getIntervalSize())) {
        intervalSize = getByName(columnGroup.getIntervalSize());
    }
    if (intervalSize != null && compare(intervalType, intervalSize) == -1) {
        intervalType = intervalSize;
    }

    // Adjust the minDate according to the interval type.
    Calendar gc = GregorianCalendar.getInstance();
    gc.setLenient(false);
    gc.setTime(minDate);
    if (YEAR.equals(intervalType)) {
        gc.set(Calendar.MONTH, 0);
        gc.set(Calendar.DAY_OF_MONTH, 1);
        gc.set(Calendar.HOUR, 0);
        gc.set(Calendar.MINUTE, 0);
        gc.set(Calendar.SECOND, 0);
        gc.set(Calendar.MILLISECOND, 0);
    }
    if (QUARTER.equals(intervalType)) {
        int currentMonth = gc.get(Calendar.MONTH);
        int firstMonthYear = columnGroup.getFirstMonthOfYear().getIndex();
        int rest = Quarter.getPositionInQuarter(firstMonthYear, currentMonth);
        gc.add(Calendar.MONTH, rest * -1);
        gc.set(Calendar.DAY_OF_MONTH, 1);
        gc.set(Calendar.HOUR, 0);
        gc.set(Calendar.MINUTE, 0);
        gc.set(Calendar.SECOND, 0);
        gc.set(Calendar.MILLISECOND, 0);
    }
    if (MONTH.equals(intervalType)) {
        gc.set(Calendar.DAY_OF_MONTH, 1);
        gc.set(Calendar.HOUR, 0);
        gc.set(Calendar.MINUTE, 0);
        gc.set(Calendar.SECOND, 0);
        gc.set(Calendar.MILLISECOND, 0);
    }
    if (DAY.equals(intervalType) || DAY_OF_WEEK.equals(intervalType)) {
        gc.set(Calendar.HOUR, 0);
        gc.set(Calendar.MINUTE, 0);
        gc.set(Calendar.SECOND, 0);
        gc.set(Calendar.MILLISECOND, 0);
    }
    if (HOUR.equals(intervalType)) {
        gc.set(Calendar.MINUTE, 0);
        gc.set(Calendar.SECOND, 0);
        gc.set(Calendar.MILLISECOND, 0);
    }
    if (MINUTE.equals(intervalType)) {
        gc.set(Calendar.SECOND, 0);
        gc.set(Calendar.MILLISECOND, 0);
    }
    if (SECOND.equals(intervalType)) {
        gc.set(Calendar.MILLISECOND, 0);
    }

    // Create the intervals according to the min/max dates.
    int index = 0;
    while (gc.getTime().compareTo(maxDate) <= 0) {
        Date intervalMinDate = gc.getTime();

        // Go to the next interval
        if (MILLENIUM.equals(intervalType)) {
            gc.add(Calendar.YEAR, 1000);
        }
        if (CENTURY.equals(intervalType)) {
            gc.add(Calendar.YEAR, 100);
        }
        if (DECADE.equals(intervalType)) {
            gc.add(Calendar.YEAR, 10);
        }
        if (YEAR.equals(intervalType)) {
            gc.add(Calendar.YEAR, 1);
        }
        if (QUARTER.equals(intervalType)) {
            gc.add(Calendar.MONTH, 3);
        }
        if (MONTH.equals(intervalType)) {
            gc.add(Calendar.MONTH, 1);
        }
        if (WEEK.equals(intervalType)) {
            gc.add(Calendar.DAY_OF_MONTH, 7);
        }
        if (DAY.equals(intervalType) || DAY_OF_WEEK.equals(intervalType)) {
            gc.add(Calendar.DAY_OF_MONTH, 1);
        }
        if (HOUR.equals(intervalType)) {
            gc.add(Calendar.HOUR_OF_DAY, 1);
        }
        if (MINUTE.equals(intervalType)) {
            gc.add(Calendar.MINUTE, 1);
        }
        if (SECOND.equals(intervalType)) {
            gc.add(Calendar.SECOND, 1);
        }

        // Create the interval.
        Date intervalMaxDate = gc.getTime();
        IntervalDateRange interval = new IntervalDateRange(intervalType, intervalMinDate, intervalMaxDate);
        results.add(interval);

        // Add the target rows to the interval.
        boolean stop = false;
        while (!stop) {
            if (index >= sortedValues.size()) {
                stop = true;
            } else {
                Date dateValue = (Date) sortedValues.get(index);
                Integer row = sortedRows.get(index);
                if (dateValue.before(intervalMaxDate)) {
                    interval.rows.add(row);
                    index++;
                } else {
                    stop = true;
                }
            }
        }
    }

    // Reverse intervals if requested
    boolean asc = columnGroup.isAscendingOrder();
    if (!asc)
        Collections.reverse(results);

    return results;
}

From source file:org.dashbuilder.dataset.IntervalBuilderDynamicDate.java

protected Calendar firstIntervalDate(DateIntervalType intervalType, Date minDate, ColumnGroup columnGroup) {
    Calendar c = GregorianCalendar.getInstance();
    c.setLenient(false);
    c.setTime(minDate);/* www  .j  a  va 2s .c  om*/
    if (YEAR.equals(intervalType)) {
        c.set(Calendar.MONTH, 0);
        c.set(Calendar.DAY_OF_MONTH, 1);
        c.set(Calendar.HOUR, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
    }
    if (QUARTER.equals(intervalType)) {
        int currentMonth = c.get(Calendar.MONTH);
        int firstMonthYear = columnGroup.getFirstMonthOfYear().getIndex();
        int rest = Quarter.getPositionInQuarter(firstMonthYear, currentMonth + 1);
        c.add(Calendar.MONTH, rest * -1);
        c.set(Calendar.DAY_OF_MONTH, 1);
        c.set(Calendar.HOUR, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
    }
    if (MONTH.equals(intervalType)) {
        c.set(Calendar.DAY_OF_MONTH, 1);
        c.set(Calendar.HOUR, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
    }
    if (DAY.equals(intervalType) || DAY_OF_WEEK.equals(intervalType) || WEEK.equals(intervalType)) {
        c.set(Calendar.HOUR, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
    }
    if (HOUR.equals(intervalType)) {
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
    }
    if (MINUTE.equals(intervalType)) {
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
    }
    if (SECOND.equals(intervalType)) {
        c.set(Calendar.MILLISECOND, 0);
    }
    return c;
}