List of usage examples for java.text DateFormat setLenient
public void setLenient(boolean lenient)
From source file:org.kuali.kra.rules.SaveCustomAttributeRule.java
/** * Validates the format/length of custom attribute. * @param customAttribute The custom attribute to validate * @param errorKey The error key on the interface * @return/* ww w . j a va 2 s . c o m*/ */ private boolean validateAttributeFormat(CustomAttribute customAttribute, CustomAttributeDataType customAttributeDataType, String errorKey) { boolean isValid = true; Integer maxLength = customAttribute.getDataLength(); String attributeValue = customAttribute.getValue(); if ((maxLength != null) && (maxLength.intValue() < attributeValue.length())) { reportError(errorKey, RiceKeyConstants.ERROR_MAX_LENGTH, customAttribute.getLabel(), maxLength.toString()); isValid = false; } final ValidationPattern validationPattern = VALIDATION_CLASSES .get(customAttributeDataType.getDescription()); // if there is no data type matched, then set error ? Pattern validationExpression = validationPattern.getRegexPattern(); String validFormat = getValidFormat(customAttributeDataType.getDescription()); if (validationExpression != null && !ALL_REGEX.equals(validationExpression.pattern())) { if (customAttributeDataType.getDescription().equalsIgnoreCase(DATE)) { if (!attributeValue.matches(DATE_REGEX)) { reportError(errorKey, RiceKeyConstants.ERROR_INVALID_FORMAT, customAttribute.getLabel(), attributeValue, validFormat); isValid = false; } } else if (!validationExpression.matcher(attributeValue).matches()) { reportError(errorKey, KeyConstants.ERROR_INVALID_FORMAT_WITH_FORMAT, customAttribute.getLabel(), attributeValue, validFormat); isValid = false; } } if (isValid && customAttributeDataType.getDescription().equals("Date")) { if (!StringUtils.isEmpty(attributeValue)) { try { DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT); dateFormat.setLenient(false); dateFormat.parse(attributeValue); } catch (ParseException e) { reportError(errorKey, KeyConstants.ERROR_DATE, attributeValue, customAttribute.getLabel()); isValid = false; } } } // validate BO data against the database contents String lookupClass = customAttribute.getLookupClass(); if (lookupClass != null && lookupClass.equals("org.kuali.kra.bo.KcPerson")) { if (customAttribute.getDataTypeCode().equals("1") && customAttribute.getLookupReturn().equals("userName")) { validFormat = getValidFormat(customAttributeDataType.getDescription()); KcPersonService kps = getKcPersonService(); KcPerson customPerson = kps.getKcPersonByUserName(customAttribute.getValue()); if (customPerson == null) { GlobalVariables.getErrorMap().putError(errorKey, RiceKeyConstants.ERROR_EXISTENCE, customAttribute.getLabel(), attributeValue, validFormat); return false; } else { return true; } } else { // can only validate for userName, if fullName, etc is used then a lookup // is assumed that a lookup is being used, in which case validation // is not necessary return true; } } else if (lookupClass != null && lookupClass.equals("org.kuali.kra.bo.ArgValueLookup")) { ArgValueLookupValuesFinder finder = new ArgValueLookupValuesFinder(); finder.setArgName(customAttribute.getLookupReturn()); List<KeyLabelPair> kv = finder.getKeyValues(); Iterator<KeyLabelPair> i = kv.iterator(); while (i.hasNext()) { KeyLabelPair element = (KeyLabelPair) i.next(); String label = element.getLabel().toLowerCase(); if (label.equals(attributeValue.toLowerCase())) { return true; } } validFormat = getValidFormat(customAttributeDataType.getDescription()); GlobalVariables.getErrorMap().putError(errorKey, RiceKeyConstants.ERROR_EXISTENCE, customAttribute.getLabel(), attributeValue, validFormat); return false; } else if (lookupClass != null) { Class boClass = null; try { boClass = Class.forName(lookupClass); } catch (ClassNotFoundException cnfE) { /* Do nothing, checked on input */ } if (isInvalid(boClass, keyValue(customAttribute.getLookupReturn(), customAttribute.getValue()))) { validFormat = getValidFormat(customAttributeDataType.getDescription()); GlobalVariables.getErrorMap().putError(errorKey, RiceKeyConstants.ERROR_EXISTENCE, customAttribute.getLabel(), attributeValue, validFormat); return false; } } return isValid; }
From source file:org.andromda.timetracker.web.timecarddetails.TimecardDetailsFormImpl.java
/** * Default constructor/*from ww w .j av a 2 s.com*/ */ public TimecardDetailsFormImpl() { // - setup the default java.util.Date.toString() formatter final DateFormat dateFormatter = new SimpleDateFormat("EEE MMM dd hh:mm:ss zzz yyyy"); dateFormatter.setLenient(true); this.dateTimeFormatters.put(null, dateFormatter); }
From source file:org.apache.empire.struts2.jsp.controls.TextInputControl.java
protected Object parseDate(String s, DateFormat df) { // Try to convert try {//from w ww .ja v a2s. com // Parse Date df.setLenient(true); return df.parseObject(s); } catch (Exception e) { return error(FieldErrors.InputNoDateFormat, null, s); } }
From source file:org.kuali.rice.core.impl.datetime.DateTimeServiceImpl.java
/** * @see org.kuali.rice.core.api.datetime.DateTimeService#toString(java.util.Date, * java.lang.String)/*from w w w .ja v a2 s . co m*/ */ public String toString(Date date, String pattern) { DateFormat dateFormat = new SimpleDateFormat(pattern); dateFormat.setLenient(false); return dateFormat.format(date); }
From source file:org.apache.ws.security.message.token.Timestamp.java
/** * Constructs a <code>Timestamp</code> object and parses the * <code>wsu:Timestamp</code> element to initialize it. * * @param timestampElement the <code>wsu:Timestamp</code> element that * contains the timestamp data//w w w . j a va2s . c o m * @param bspCompliant whether the Timestamp processing complies with the BSP spec */ public Timestamp(Element timestampElement, boolean bspCompliant) throws WSSecurityException { element = timestampElement; customElements = new ArrayList<Element>(); String strCreated = null; String strExpires = null; for (Node currentChild = element.getFirstChild(); currentChild != null; currentChild = currentChild .getNextSibling()) { if (Node.ELEMENT_NODE == currentChild.getNodeType()) { Element currentChildElement = (Element) currentChild; if (WSConstants.CREATED_LN.equals(currentChild.getLocalName()) && WSConstants.WSU_NS.equals(currentChild.getNamespaceURI())) { if (strCreated == null) { String valueType = currentChildElement.getAttribute("ValueType"); if (bspCompliant && valueType != null && !"".equals(valueType)) { // We can't have a ValueType attribute as per the BSP spec throw new WSSecurityException(WSSecurityException.INVALID_SECURITY, "invalidTimestamp"); } strCreated = ((Text) currentChildElement.getFirstChild()).getData(); } else { // Test for multiple Created elements throw new WSSecurityException(WSSecurityException.INVALID_SECURITY, "invalidTimestamp"); } } else if (WSConstants.EXPIRES_LN.equals(currentChild.getLocalName()) && WSConstants.WSU_NS.equals(currentChild.getNamespaceURI())) { if (strExpires != null || (bspCompliant && strCreated == null)) { // // Created must appear before Expires and we can't have multiple Expires // elements // throw new WSSecurityException(WSSecurityException.INVALID_SECURITY, "invalidTimestamp"); } else { String valueType = currentChildElement.getAttribute("ValueType"); if (bspCompliant && valueType != null && !"".equals(valueType)) { // We can't have a ValueType attribute as per the BSP spec throw new WSSecurityException(WSSecurityException.INVALID_SECURITY, "invalidTimestamp"); } strExpires = ((Text) currentChildElement.getFirstChild()).getData(); } } else { if (bspCompliant) { throw new WSSecurityException(WSSecurityException.INVALID_SECURITY, "invalidTimestamp"); } customElements.add(currentChildElement); } } } // We must have a Created element if (bspCompliant && strCreated == null) { throw new WSSecurityException(WSSecurityException.INVALID_SECURITY, "invalidTimestamp"); } // Parse the dates DateFormat zulu = new XmlSchemaDateFormat(); if (bspCompliant) { zulu.setLenient(false); } try { if (LOG.isDebugEnabled()) { LOG.debug("Current time: " + zulu.format(new Date())); } if (strCreated != null) { createdDate = zulu.parse(strCreated); if (LOG.isDebugEnabled()) { LOG.debug("Timestamp created: " + zulu.format(createdDate)); } } if (strExpires != null) { expiresDate = zulu.parse(strExpires); if (LOG.isDebugEnabled()) { LOG.debug("Timestamp expires: " + zulu.format(expiresDate)); } } } catch (ParseException e) { throw new WSSecurityException(WSSecurityException.INVALID_SECURITY, "invalidTimestamp", null, e); } }
From source file:org.kuali.rice.core.impl.datetime.DateTimeServiceImpl.java
protected Date parse(String dateString, String pattern) throws ParseException { if (!StringUtils.isBlank(dateString)) { DateFormat dateFormat = new SimpleDateFormat(pattern); dateFormat.setLenient(false); ParsePosition parsePosition = new ParsePosition(0); Date testDate = dateFormat.parse(dateString, parsePosition); // Ensure that the entire date String can be parsed by the current format. if (testDate == null) { throw new ParseException("The date that you provided is invalid.", parsePosition.getErrorIndex()); } else if (parsePosition.getIndex() != dateString.length()) { throw new ParseException("The date that you provided is invalid.", parsePosition.getIndex()); }// w w w . jav a 2 s . c om // Ensure that the date's year lies between 1000 and 9999, to help prevent database-related date errors. Calendar testCalendar = Calendar.getInstance(); testCalendar.setLenient(false); testCalendar.setTime(testDate); if (testCalendar.get(Calendar.YEAR) < 1000 || testCalendar.get(Calendar.YEAR) > 9999) { throw new ParseException("The date that you provided is not between the years 1000 and 9999.", -1); } if (testCalendar.get(Calendar.YEAR) == 1970 && !pattern.contains("y".toLowerCase())) { Calendar curCalendar = Calendar.getInstance(); curCalendar.setTime(new java.util.Date()); testCalendar.set(Calendar.YEAR, curCalendar.get(Calendar.YEAR)); testDate = testCalendar.getTime(); } return testDate; } return null; }
From source file:org.apache.camel.dataformat.bindy.format.DatePatternFormat.java
public Date parse(String string) throws Exception { Date date;//from w w w .j ava 2 s . co m DateFormat df = this.getDateFormat(); ObjectHelper.notNull(this.pattern, "pattern"); // Check length of the string with date pattern // To avoid to parse a string date : 20090901-10:32:30 when // the pattern is yyyyMMdd if (string.length() <= this.pattern.length()) { // Force the parser to be strict in the syntax of the date to be // converted df.setLenient(false); date = df.parse(string); return date; } else { throw new FormatException("Date provided does not fit the pattern defined"); } }
From source file:org.mule.modules.clarizen.api.ClarizenDateConverter.java
/** * Parse a String into a <code>Calendar</code> object * using the specified <code>DateFormat</code>. * * @param sourceType The type of the value being converted * @param targetType The type to convert the value to * @param value The String date value./*from ww w . ja v a 2 s. c om*/ * @param format The DateFormat to parse the String value. * * @return The converted Calendar object. * @throws ConversionException if the String cannot be converted. */ @SuppressWarnings("rawtypes") private Calendar parse(Class sourceType, Class targetType, String value, DateFormat format) { format.setLenient(false); ParsePosition pos = new ParsePosition(0); Date parsedDate = format.parse(value, pos); // ignore the result (use the Calendar) if (pos.getErrorIndex() >= 0 || pos.getIndex() != value.length() || parsedDate == null) { String msg = "Error converting '" + classToString(sourceType) + "' to '" + classToString(targetType) + "'"; if (format instanceof SimpleDateFormat) { msg += " using pattern '" + ((SimpleDateFormat) format).toPattern() + "'"; } throw new ConversionException(msg); } Calendar calendar = format.getCalendar(); return calendar; }
From source file:javadz.beanutils.locale.converters.DateLocaleConverter.java
/** * Convert the specified locale-sensitive input object into an output object of the * specified type.// w w w.ja v a 2 s . c o m * * @param value The input object to be converted * @param pattern The pattern is used for the convertion * @return the converted Date value * * @exception org.apache.commons.beanutils.ConversionException * if conversion cannot be performed successfully * @throws ParseException if an error occurs parsing */ protected Object parse(Object value, String pattern) throws ParseException { // Handle Date if (value instanceof java.util.Date) { return value; } // Handle Calendar if (value instanceof java.util.Calendar) { return ((java.util.Calendar) value).getTime(); } if (locPattern) { pattern = convertLocalizedPattern(pattern, locale); } // Create Formatter - use default if pattern is null DateFormat formatter = pattern == null ? DateFormat.getDateInstance(DateFormat.SHORT, locale) : new SimpleDateFormat(pattern, locale); formatter.setLenient(isLenient); // Parse the Date ParsePosition pos = new ParsePosition(0); String strValue = value.toString(); Object parsedValue = formatter.parseObject(strValue, pos); if (pos.getErrorIndex() > -1) { throw new ConversionException("Error parsing date '" + value + "' at position=" + pos.getErrorIndex()); } if (pos.getIndex() < strValue.length()) { throw new ConversionException( "Date '" + value + "' contains unparsed characters from position=" + pos.getIndex()); } return parsedValue; }
From source file:fr.paris.lutece.plugins.suggest.utils.SuggestUtils.java
/** * return a timestamp Object which correspond with the string specified in * parameter.//from w ww . j a va2 s . c o m * @param strDate the date who must convert * @param locale the locale * @return a timestamp Object which correspond with the string specified in * parameter. */ public static Timestamp getLastMinute(String strDate, Locale locale) { try { Date date; DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, locale); dateFormat.setLenient(false); date = dateFormat.parse(strDate.trim()); Calendar caldate = new GregorianCalendar(); caldate.setTime(date); caldate.set(Calendar.MILLISECOND, 0); caldate.set(Calendar.SECOND, 0); caldate.set(Calendar.HOUR_OF_DAY, caldate.getActualMaximum(Calendar.HOUR_OF_DAY)); caldate.set(Calendar.MINUTE, caldate.getActualMaximum(Calendar.MINUTE)); Timestamp timeStamp = new Timestamp(caldate.getTimeInMillis()); return timeStamp; } catch (ParseException e) { return null; } }