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:org.languagetool.rules.AbstractDateCheckFilter.java

private Calendar getDate(Map<String, String> args) {
    String yearArg = args.get("year");
    int year;//from  w  ww.ja v  a  2 s .  co m
    if (yearArg == null && TestHackHelper.isJUnitTest()) {
        // Volkswagen-style testing
        // Hack for tests of date - weekday match with missing year
        // in production, we assume the current year
        // For xml tests, we use weekdays of the year 2014
        year = 2014;
    } else if (yearArg == null) {
        // assume current year for rule DATUM_WOCHENTAG_OHNE_JAHR etc.
        year = getCalendar().get(Calendar.YEAR);
    } else {
        year = Integer.parseInt(yearArg);
    }
    int month = getMonthFromArguments(args);
    int dayOfMonth = getDayOfMonthFromArguments(args);

    Calendar calendar = getCalendar();
    calendar.setLenient(false); // be strict about validity of dates
    //noinspection MagicConstant
    calendar.set(year, month, dayOfMonth, 0, 0, 0);
    return calendar;
}

From source file:org.languagetool.rules.AbstractFutureDateFilter.java

private Calendar getDate(Map<String, String> args) {
    int year = Integer.parseInt(getRequired("year", args));
    int month = getMonthFromArguments(args);
    int dayOfMonth = getDayOfMonthFromArguments(args);

    Calendar calendar = getCalendar();
    calendar.setLenient(false); // be strict about validity of dates
    //noinspection MagicConstant
    calendar.set(year, month, dayOfMonth, 0, 0, 0);
    return calendar;
}

From source file:org.mule.modules.clarizen.api.ClarizenDateConverter.java

/**
 * Convert a long value to the specified Date type for this
 * <i>Converter</i>./*from w  w  w  .  j  av  a  2  s . c  o m*/
 * <p>
 *
 * This method handles conversion to the following types:
 * <ul>
 *     <li><code>java.util.Date</code></li>
 *     <li><code>java.util.Calendar</code></li>
 *     <li><code>java.sql.Date</code></li>
 *     <li><code>java.sql.Time</code></li>
 *     <li><code>java.sql.Timestamp</code></li>
 * </ul>
 *
 * @param type The Date type to convert to
 * @param value The long value to convert.
 * @return The converted date value.
 */
@SuppressWarnings("rawtypes")
private Object toDate(Class type, long value) {

    // java.util.Date
    if (type.equals(Date.class)) {
        return new Date(value);
    }

    // java.sql.Date
    if (type.equals(java.sql.Date.class)) {
        return new java.sql.Date(value);
    }

    // java.sql.Time
    if (type.equals(java.sql.Time.class)) {
        return new java.sql.Time(value);
    }

    // java.sql.Timestamp
    if (type.equals(java.sql.Timestamp.class)) {
        return new java.sql.Timestamp(value);
    }

    // java.util.Calendar
    if (type.equals(Calendar.class)) {
        Calendar calendar = null;
        if (locale == null && timeZone == null) {
            calendar = Calendar.getInstance();
        } else if (locale == null) {
            calendar = Calendar.getInstance(timeZone);
        } else if (timeZone == null) {
            calendar = Calendar.getInstance(locale);
        } else {
            calendar = Calendar.getInstance(timeZone, locale);
        }
        calendar.setTime(new Date(value));
        calendar.setLenient(false);
        return calendar;
    }

    String msg = classToString(getClass()) + " cannot handle conversion to '" + classToString(type) + "'";
    throw new ConversionException(msg);
}

From source file:org.openanzo.test.client.TestDateTime.java

/**
 * The java.util.Calendar API makes it tricky to get a calendar initialized in a predictable state since most ways to create it use the system default time
 * zone, locale, and sometimes the current time.
 * //from  ww w.  java  2 s. c  om
 * This method helps ensure getting a calendar object that is more predictable across different systems.
 * 
 * @return a new fairly clean Calendar, ready for you to put your dirty paws all over it.
 */
private Calendar getCleanCalendar() {
    Calendar cal = Calendar.getInstance();
    cal.setTimeZone(DateUtils.UTC_TIME_ZONE);
    cal.clear();
    cal.setLenient(false);
    return cal;
}

From source file:org.openbravo.advpaymentmngt.actionHandler.UnMatchSelectedTransactionsActionHandler.java

@Override
protected JSONObject execute(Map<String, Object> parameters, String data) {
    JSONObject result = new JSONObject();
    JSONObject errorMessage = new JSONObject();
    try {//from   w  ww.j a va2s.com
        OBContext.setAdminMode(true);
        final JSONObject jsonData = new JSONObject(data);
        SimpleDateFormat xmlDateTimeFormat = JsonUtils.createJSTimeFormat();

        List<String> errorLines = new ArrayList<String>();

        final JSONArray bankStatementLineIds = jsonData.getJSONArray("bankStatementLineIds");
        int bankStatementLineIdsLength = bankStatementLineIds != null ? bankStatementLineIds.length() : 0;
        int alreadyCleared = 0;
        for (int i = 0; i < bankStatementLineIdsLength; i++) {
            JSONObject bankStatementLine = bankStatementLineIds.getJSONObject(i);
            if (!bankStatementLine.getBoolean("cleared")) {
                log.info(
                        "Skipping " + bankStatementLine.getString("referenceNo") + " line as it's not matched");
                alreadyCleared++;
            } else {
                try {
                    Date date = xmlDateTimeFormat.parse(bankStatementLine.getString("bslUpdated"));
                    final FIN_BankStatementLine bsline = OBDal.getInstance().get(FIN_BankStatementLine.class,
                            bankStatementLine.getString("id"));
                    Date bbddBSLUpdated = bsline.getUpdated();
                    // Remove milis
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(OBDateUtils.convertDateToUTC(bbddBSLUpdated));
                    calendar.setLenient(true);
                    calendar.set(Calendar.MILLISECOND, 0);
                    if (date.getTime() != calendar.getTimeInMillis()) {
                        log.error("The record " + bankStatementLine.getString("referenceNo")
                                + " is newer in the database. Avoid unmatching it");
                        throw new OBStaleObjectException("@APRM_StaleDate@");
                    }
                    final FIN_FinaccTransaction transaction = bsline.getFinancialAccountTransaction();
                    if (transaction != null) {
                        APRM_MatchingUtility.unmatch(bsline);
                    }
                } catch (Exception e) {
                    errorLines.add(bankStatementLine.getString("referenceNo"));
                }
            }
        }

        /* Build Message */
        int totalSuccess = bankStatementLineIdsLength - errorLines.size() - alreadyCleared;
        String severity = "error";
        String title = "";
        String msg = "";
        if (totalSuccess > 0) {
            severity = "success";
            title = OBMessageUtils.messageBD("Success");
            msg = OBMessageUtils.getI18NMessage("APRM_UnmatchedRecords",
                    new String[] { String.valueOf(totalSuccess) });
        }
        if (!errorLines.isEmpty()) {
            if (totalSuccess > 0) {
                severity = "warning";
                title = OBMessageUtils.messageBD("Warning");
            } else {
                severity = "error";
                title = OBMessageUtils.messageBD("Error");
            }

            if (StringUtils.isNotBlank(msg)) {
                msg += "<br/>";
            }
            msg += OBMessageUtils.getI18NMessage("APRM_ErrorOnUnmatchingRecords",
                    new String[] { String.valueOf(errorLines.size()) });
            for (String string : errorLines) {
                msg += string + ", ";
            }
            msg = msg.substring(0, msg.length() - 2);
        }
        errorMessage.put("severity", severity);
        errorMessage.put("title", title);
        errorMessage.put("text", msg);
        result.put("message", errorMessage);

    } catch (Exception e) {
        OBDal.getInstance().rollbackAndClose();
        log.error("Error Unmatching Transaction", e);
        try {
            Throwable ex = DbUtility.getUnderlyingSQLException(e);
            String message = OBMessageUtils.translateError(ex.getMessage()).getMessage();
            errorMessage = new JSONObject();
            errorMessage.put("severity", "error");
            errorMessage.put("title", OBMessageUtils.messageBD("Error"));
            errorMessage.put("text", message);
            result.put("message", errorMessage);
        } catch (Exception e2) {
            log.error("Message could not be built", e2);
        }
    } finally {
        OBContext.restorePreviousMode();
    }
    return result;
}

From source file:org.pentaho.di.core.Const.java

/**
 * Remove time from a date.//from  w  w w.  j  a v  a2s  .c om
 *
 * @return a date without hour.
 */
public static Date removeTimeFromDate(Date input) {
    if (input == null) {
        return null;
    }
    // Get an instance of the Calendar.
    Calendar calendar = Calendar.getInstance();

    // Make sure the calendar will not perform automatic correction.
    calendar.setLenient(false);

    // Set the time of the calendar to the given date.
    calendar.setTime(input);

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

    // Return the date again.
    return calendar.getTime();
}

From source file:org.sweble.wikitext.engine.MassExpansionTest.java

private WikiConfigImpl fixConfig(WikiConfigImpl config) {
    config.setSiteName("English Wikipedia");

    config.setRuntimeInfo(new WikiRuntimeInfo() {
        @Override//from   www.j a  v a2s  . c  o m
        public Calendar getDateAndTime(Locale locale) {
            Calendar timestamp = new GregorianCalendar(locale);
            timestamp.setLenient(true);
            timestamp.set(2012, 9, 18, 14, 25, 13);
            return timestamp;
        }

        @Override
        public Calendar getDateAndTime() {
            return getDateAndTime(Locale.getDefault());
        }
    });

    return config;
}

From source file:org.unitime.timetable.solver.studentsct.StudentSectioningDatabaseLoader.java

private String datePatternName(DatePattern dp, TimeLocation time) {
    if ("never".equals(iDatePatternFormat))
        return dp.getName();
    if ("extended".equals(iDatePatternFormat) && dp.getType() != DatePattern.sTypeExtended)
        return dp.getName();
    if ("alternate".equals(iDatePatternFormat) && dp.getType() == DatePattern.sTypeAlternate)
        return dp.getName();
    if (time.getWeekCode().isEmpty())
        return time.getDatePatternName();
    Calendar cal = Calendar.getInstance(Locale.US);
    cal.setLenient(true);
    cal.setTime(iDatePatternFirstDate);//from w ww.j a  va2 s  .  co  m
    int idx = time.getWeekCode().nextSetBit(0);
    cal.add(Calendar.DAY_OF_YEAR, idx);
    Date first = null;
    while (idx < time.getWeekCode().size() && first == null) {
        if (time.getWeekCode().get(idx)) {
            int dow = cal.get(Calendar.DAY_OF_WEEK);
            switch (dow) {
            case Calendar.MONDAY:
                if ((time.getDayCode() & DayCode.MON.getCode()) != 0)
                    first = cal.getTime();
                break;
            case Calendar.TUESDAY:
                if ((time.getDayCode() & DayCode.TUE.getCode()) != 0)
                    first = cal.getTime();
                break;
            case Calendar.WEDNESDAY:
                if ((time.getDayCode() & DayCode.WED.getCode()) != 0)
                    first = cal.getTime();
                break;
            case Calendar.THURSDAY:
                if ((time.getDayCode() & DayCode.THU.getCode()) != 0)
                    first = cal.getTime();
                break;
            case Calendar.FRIDAY:
                if ((time.getDayCode() & DayCode.FRI.getCode()) != 0)
                    first = cal.getTime();
                break;
            case Calendar.SATURDAY:
                if ((time.getDayCode() & DayCode.SAT.getCode()) != 0)
                    first = cal.getTime();
                break;
            case Calendar.SUNDAY:
                if ((time.getDayCode() & DayCode.SUN.getCode()) != 0)
                    first = cal.getTime();
                break;
            }
        }
        cal.add(Calendar.DAY_OF_YEAR, 1);
        idx++;
    }
    if (first == null)
        return time.getDatePatternName();
    cal.setTime(iDatePatternFirstDate);
    idx = time.getWeekCode().length() - 1;
    cal.add(Calendar.DAY_OF_YEAR, idx);
    Date last = null;
    while (idx >= 0 && last == null) {
        if (time.getWeekCode().get(idx)) {
            int dow = cal.get(Calendar.DAY_OF_WEEK);
            switch (dow) {
            case Calendar.MONDAY:
                if ((time.getDayCode() & DayCode.MON.getCode()) != 0)
                    last = cal.getTime();
                break;
            case Calendar.TUESDAY:
                if ((time.getDayCode() & DayCode.TUE.getCode()) != 0)
                    last = cal.getTime();
                break;
            case Calendar.WEDNESDAY:
                if ((time.getDayCode() & DayCode.WED.getCode()) != 0)
                    last = cal.getTime();
                break;
            case Calendar.THURSDAY:
                if ((time.getDayCode() & DayCode.THU.getCode()) != 0)
                    last = cal.getTime();
                break;
            case Calendar.FRIDAY:
                if ((time.getDayCode() & DayCode.FRI.getCode()) != 0)
                    last = cal.getTime();
                break;
            case Calendar.SATURDAY:
                if ((time.getDayCode() & DayCode.SAT.getCode()) != 0)
                    last = cal.getTime();
                break;
            case Calendar.SUNDAY:
                if ((time.getDayCode() & DayCode.SUN.getCode()) != 0)
                    last = cal.getTime();
                break;
            }
        }
        cal.add(Calendar.DAY_OF_YEAR, -1);
        idx--;
    }
    if (last == null)
        return time.getDatePatternName();
    Formats.Format<Date> dpf = Formats.getDateFormat(Formats.Pattern.DATE_PATTERN);
    return dpf.format(first) + (first.equals(last) ? "" : " - " + dpf.format(last));
}

From source file:picocash.Picocash.java

private List<Transaction> getTransactionsForSelectedMonth(Account account, int year, int month) {
    log.debug("selected [" + account + "] on [" + year + "/" + month + "]");
    Calendar date = Calendar.getInstance();
    date.setLenient(false);
    date.set(Calendar.YEAR, year);
    date.set(Calendar.MONTH, month);
    date.set(Calendar.DAY_OF_MONTH, date.getActualMinimum(Calendar.DAY_OF_MONTH));
    date.set(Calendar.HOUR_OF_DAY, date.getActualMinimum(Calendar.HOUR_OF_DAY));
    date.set(Calendar.MINUTE, date.getActualMinimum(Calendar.MINUTE));
    date.set(Calendar.SECOND, date.getActualMinimum(Calendar.SECOND));
    date.set(Calendar.MILLISECOND, date.getActualMinimum(Calendar.MILLISECOND));
    long startDate = date.getTimeInMillis();
    if (log.isTraceEnabled()) {
        log.trace("startDate [" + date.getTime() + "]");
    }//from   w  w  w  .j a  va  2 s  . co  m
    date.set(Calendar.DAY_OF_MONTH, date.getActualMaximum(Calendar.DAY_OF_MONTH));
    date.set(Calendar.HOUR_OF_DAY, date.getActualMaximum(Calendar.HOUR_OF_DAY));
    date.set(Calendar.MINUTE, date.getActualMaximum(Calendar.MINUTE));
    date.set(Calendar.SECOND, date.getActualMaximum(Calendar.SECOND));
    date.set(Calendar.MILLISECOND, date.getActualMaximum(Calendar.MILLISECOND));
    long endDate = date.getTimeInMillis();
    if (log.isTraceEnabled()) {
        log.trace("endDate [" + date.getTime() + "]");
    }
    final List<Transaction> transactions = Services.getSelectedPersistenceMan()
            .getAllTransactionsForAccount(account, startDate, endDate);
    if (log.isTraceEnabled()) {
        final List<Transaction> allTransactionsForAccount = Services.getSelectedPersistenceMan()
                .getAllTransactionsForAccount(account);
        for (Transaction transaction : allTransactionsForAccount) {
            final long transactionDate = transaction.getTransactionDate();
            Calendar test = Calendar.getInstance();
            test.setTimeInMillis(transactionDate);
            log.trace(test.getTime());
        }
        log.trace("current available transactions [" + transactions.size() + "]");
    }
    return transactions;
}