Example usage for java.text SimpleDateFormat setLenient

List of usage examples for java.text SimpleDateFormat setLenient

Introduction

In this page you can find the example usage for java.text SimpleDateFormat setLenient.

Prototype

public void setLenient(boolean lenient) 

Source Link

Document

Specify whether or not date/time parsing is to be lenient.

Usage

From source file:squash.booking.lambdas.core.BackupManager.java

private void validateDates(List<String> datesToCheck) throws Exception {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    sdf.setLenient(false);
    if (datesToCheck.stream().filter((dateToCheck) -> {
        try {/*  w  ww. j  a v a  2  s.  co  m*/
            sdf.parse(dateToCheck);
        } catch (ParseException e) {
            logger.log("The date has an invalid format: " + dateToCheck);
            return true;
        }
        return false;
    }).count() > 0) {
        throw new Exception("One of the dates has an invalid format");
    }
}

From source file:org.jasig.portlet.announcements.controller.AdminAnnouncementController.java

@InitBinder("announcement")
public void initBinder(WebDataBinder binder) {
    SimpleDateFormat dateFormat = new SimpleDateFormat(customDateFormat);
    dateFormat.setLenient(false);
    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    binder.registerCustomEditor(Topic.class, topicEditor);
    binder.setAllowedFields(new String[] { "id", "created", "author", "title", "abstractText", "message",
            "link", "startDisplay", "endDisplay", "parent", "action", "attachments" });
}

From source file:org.dspace.search.DSIndexer.java

/**
 * Helper function to retrieve a date using a best guess of the potential date encodings on a field
 *  //from  w  ww.  ja v a  2 s.  com
 * @param t
 * @return
 */
private static Date toDate(String t) {
    SimpleDateFormat[] dfArr;

    // Choose the likely date formats based on string length
    switch (t.length()) {
    case 4:
        dfArr = new SimpleDateFormat[] { new SimpleDateFormat("yyyy") };
        break;
    case 6:
        dfArr = new SimpleDateFormat[] { new SimpleDateFormat("yyyyMM") };
        break;
    case 7:
        dfArr = new SimpleDateFormat[] { new SimpleDateFormat("yyyy-MM") };
        break;
    case 8:
        dfArr = new SimpleDateFormat[] { new SimpleDateFormat("yyyyMMdd"), new SimpleDateFormat("yyyy MMM") };
        break;
    case 10:
        dfArr = new SimpleDateFormat[] { new SimpleDateFormat("yyyy-MM-dd") };
        break;
    case 11:
        dfArr = new SimpleDateFormat[] { new SimpleDateFormat("yyyy MMM dd") };
        break;
    case 20:
        dfArr = new SimpleDateFormat[] { new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") };
        break;
    default:
        dfArr = new SimpleDateFormat[] { new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") };
        break;
    }

    for (SimpleDateFormat df : dfArr) {
        try {
            // Parse the date
            df.setCalendar(Calendar.getInstance(TimeZone.getTimeZone("UTC")));
            df.setLenient(false);
            return df.parse(t);
        } catch (ParseException pe) {
            log.error("Unable to parse date format", pe);
        }
    }

    return null;
}

From source file:org.squale.welcom.struts.action.WRequestProcessor.java

/**
 * effectue un populate en conction des dates
 * /* www  .j  a v a  2 s. com*/
 * @param form : fomulaire
 * @param request : request
 * @parem element : Nom du champs
 */
private void processPopulateDate(final HttpServletRequest request, final ActionForm form,
        final String element) {
    if (element.endsWith("WDate") && !element.equals("WDate")) {

        final String field = element.substring(0, element.lastIndexOf("WDate"));

        String formattedDate = TagUtils.getDateHeureFromDateTag(request, field);

        final HashMap formatMaps = (HashMap) request.getSession().getAttribute(DATE_FORMAT_KEY);

        try {
            final Class propertyType = PropertyUtils.getPropertyType(form, field);
            if (propertyType != null) {
                boolean isTypeDate = propertyType.equals(Date.class);
                Object emptyValue = null;
                if (!isTypeDate) {
                    emptyValue = "";
                }

                if ((formatMaps != null) && (formatMaps.get(field + "WDate") != null)) {
                    String pattern = (String) formatMaps.get(field + "WDate");

                    if (formatMaps.get(field + "WHour") != null) {
                        pattern = pattern + " " + formatMaps.get(field + "WHour");
                    }

                    if (GenericValidator.isBlankOrNull(formattedDate)) {
                        BeanUtils.setProperty(form, field, emptyValue);
                    } else {
                        Locale locale = (Locale) request.getSession().getAttribute(Globals.LOCALE_KEY);
                        SimpleDateFormat dateFormat = new SimpleDateFormat(pattern, locale);
                        dateFormat.setLenient(false);

                        try {
                            Date newDate = dateFormat.parse(formattedDate);

                            if (dateFormat.format(newDate).equals(formattedDate)) {
                                try {
                                    if (isTypeDate) {
                                        LayoutUtils.setProperty(form, field, newDate);
                                    } else {
                                        LayoutUtils.setProperty(form, field, String.valueOf(newDate.getTime()));
                                    }
                                } catch (SecurityException e1) {
                                    e1.printStackTrace();
                                }
                            } else {
                                BeanUtils.setProperty(form, field, emptyValue);
                            }
                        } catch (ParseException e) {
                            e.printStackTrace();
                            LayoutUtils.setProperty(form, field, emptyValue);
                        }
                    }
                } else {
                    if (formattedDate == null) {
                        formattedDate = "";
                    }
                    BeanUtils.setProperty(form, field, formattedDate);
                }

            }

        } catch (final JspException e1) {
            e1.printStackTrace();
        } catch (final IllegalAccessException e3) {
            e3.printStackTrace();
        } catch (final InvocationTargetException e3) {
            e3.printStackTrace();
        } catch (final NoSuchMethodException e3) {
            e3.printStackTrace();
        }

    }
}

From source file:com.gdut.dongjun.service.net_server.handler.msg_decoder.ControlMeasureDataReceiver.java

/**
 * @description   ?/*from  w w  w. j av a2s  . co m*/
 * @param substring
 * @return
 */
private boolean timeCheckStrict(String substring) {
    String[] checked = ControlMearsureDeviceCommandUtil.cutString(2, substring);
    SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
    format.setLenient(false);
    try {
        format.parse("20" + timeCheck(checked[0]) + timeCheck(checked[1]) + timeCheck(checked[2]));
        return true;
    } catch (ParseException e) {
        return false;
    }
}

From source file:org.betaconceptframework.astroboa.portal.utility.CalendarUtils.java

public String convertDateToString(Date date, String dateFormatPattern) {
    SimpleDateFormat dateFormat = (SimpleDateFormat) DateFormat.getDateInstance();
    dateFormat.setLenient(false); // be strict in the formatting
    // apply accepted pattern
    dateFormat.applyPattern(dateFormatPattern);

    return dateFormat.format(date);
}

From source file:com.haulmont.cuba.web.gui.components.WebTimeField.java

private boolean checkStringValue(String value) {
    if (value.equals(placeholder) || StringUtils.isEmpty(value))
        return true;
    SimpleDateFormat sdf = new SimpleDateFormat(timeFormat);
    sdf.setLenient(false);
    try {/*from  w  ww  . j a  v  a  2s . c  o m*/
        sdf.parse(value);
        return true;
    } catch (ParseException e) {
        return false;
    }
}

From source file:net.kw.shrdlu.grtgtfs.Activities.RiderAlertsActivity.java

/**
 * Get the latest twitter info. Some of this copied from http://www.vogella.com/articles/AndroidJSON/article.html
 */// w  ww  .  j  a va  2 s .  c  o m
ArrayList<String[]> readTwitterFeed() {
    final StringBuilder builder = new StringBuilder();
    final HttpClient client = new DefaultHttpClient();
    final HttpGet httpGet = new HttpGet(TwitterURL + TwitterQry);
    httpGet.setHeader("Authorization", "Bearer " + AccessToken);

    try {
        final HttpResponse response = client.execute(httpGet);

        final StatusLine statusLine = response.getStatusLine();
        final int statusCode = statusLine.getStatusCode();
        if (statusCode == 200) {
            final HttpEntity entity = response.getEntity();
            final InputStream content = entity.getContent();
            final BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            reader.close();
            content.close();

            // Result is an array of tweets
            final JSONArray arr = (JSONArray) new JSONTokener(builder.toString()).nextValue();

            final ArrayList<String[]> tweets = new ArrayList<>();

            // Need to grok dates of form "created_at": "Thu, 15 Nov 2012 18:27:17 +0000"
            final SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss ZZZZZ yyyy");
            dateFormat.setLenient(true);

            for (int i = 0; i < arr.length(); i++) {
                final String text = arr.getJSONObject(i).get("text").toString();
                String tweettime = arr.getJSONObject(i).get("created_at").toString();

                // Extract & reformat the date
                Date created;
                final GregorianCalendar cal = new GregorianCalendar();
                try {
                    created = dateFormat.parse(tweettime);
                    cal.setTime(created);
                    String day, mon;

                    day = cal.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.getDefault());
                    mon = cal.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.getDefault());

                    tweettime = String.format("%s %02d:%02d - %s %d", day, cal.get(Calendar.HOUR_OF_DAY),
                            cal.get(Calendar.MINUTE), mon, cal.get(Calendar.DAY_OF_MONTH));

                } catch (final Exception e) {
                    Log.d(TAG, "Exception: " + e.getMessage() + ", parsing tweet date `" + tweettime + "'");
                    tweettime = "--:--";
                }

                tweets.add(new String[] { tweettime, text });
            }

            return tweets;

        } else {
            Log.d(TAG, "Failed to download twitter info");
        }
    } catch (final ClientProtocolException e) {
        Log.d(TAG, "ClientProtocolException: " + e.getMessage() + ", Failed to download twitter info");
    } catch (final IOException e) {
        Log.d(TAG, "IOException: " + e.getMessage() + ", Failed to download twitter info");
    } catch (final Exception e) {
        Log.d(TAG, "Exception: " + e.getMessage() + ", Failed to download twitter info");
    }

    return null;
}

From source file:com.jd.survey.web.security.LoginController.java

@InitBinder
public void initBinder(WebDataBinder binder) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
    dateFormat.setLenient(false);
    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true, 10));
}

From source file:com.haulmont.cuba.web.gui.components.WebTimeField.java

@Override
public void setValue(Object value) {
    Preconditions.checkArgument(value == null || value instanceof Date, "Value must be an instance of Date");
    if (value != null) {
        SimpleDateFormat sdf = new SimpleDateFormat(this.timeFormat);
        sdf.setLenient(false);

        super.setValue(sdf.format(value));
    } else {/*from w  ww  . j a v a 2 s. co m*/
        super.setValue(null);
    }
}