You are viewing a plain text version of this content. The canonical link for it is here.
Posted to ddlutils-dev@db.apache.org by to...@apache.org on 2006/12/03 08:35:00 UTC

svn commit: r481733 - in /db/ddlutils/trunk/src: java/org/apache/ddlutils/io/converters/ test/org/apache/ddlutils/io/converters/

Author: tomdz
Date: Sat Dec  2 23:34:57 2006
New Revision: 481733

URL: http://svn.apache.org/viewvc?view=rev&rev=481733
Log:
Made date and time converters more robust

Modified:
    db/ddlutils/trunk/src/java/org/apache/ddlutils/io/converters/DateConverter.java
    db/ddlutils/trunk/src/java/org/apache/ddlutils/io/converters/TimeConverter.java
    db/ddlutils/trunk/src/test/org/apache/ddlutils/io/converters/TestDateConverter.java
    db/ddlutils/trunk/src/test/org/apache/ddlutils/io/converters/TestTimeConverter.java

Modified: db/ddlutils/trunk/src/java/org/apache/ddlutils/io/converters/DateConverter.java
URL: http://svn.apache.org/viewvc/db/ddlutils/trunk/src/java/org/apache/ddlutils/io/converters/DateConverter.java?view=diff&rev=481733&r1=481732&r2=481733
==============================================================================
--- db/ddlutils/trunk/src/java/org/apache/ddlutils/io/converters/DateConverter.java (original)
+++ db/ddlutils/trunk/src/java/org/apache/ddlutils/io/converters/DateConverter.java Sat Dec  2 23:34:57 2006
@@ -23,6 +23,14 @@
 import java.sql.Types;
 import java.util.Calendar;
 
+import org.apache.ddlutils.DdlUtilsException;
+import org.apache.oro.text.regex.MalformedPatternException;
+import org.apache.oro.text.regex.MatchResult;
+import org.apache.oro.text.regex.Pattern;
+import org.apache.oro.text.regex.PatternCompiler;
+import org.apache.oro.text.regex.Perl5Compiler;
+import org.apache.oro.text.regex.Perl5Matcher;
+
 /**
  * Converts between {@link java.sql.Date} and {@link java.lang.String} using the standard
  * representation "yyyy", or "yyyy-mm", or "yyyy-mm-dd".
@@ -31,6 +39,8 @@
  */
 public class DateConverter implements SqlTypeConverter 
 {
+    /** The regular expression pattern for the parsing of ISO dates. */
+    private Pattern _datePattern;
 	/** The calendar object to convert to/from dates. */
 	private Calendar _calendar;
 
@@ -39,8 +49,18 @@
 	 */
 	public DateConverter()
 	{
-		_calendar = Calendar.getInstance();
+        PatternCompiler compiler = new Perl5Compiler();
+
+        try
+        {
+            _datePattern = compiler.compile("(\\d{2,4})(?:\\-(\\d{2}))?(?:\\-(\\d{2}))?.*");
+        }
+        catch (MalformedPatternException ex)
+        {
+            throw new DdlUtilsException(ex);
+        }
 
+        _calendar = Calendar.getInstance();
 		_calendar.setLenient(false);
 	}
 
@@ -57,46 +77,46 @@
         {
             // we're not using {@link java.sql.Date#valueOf(String)} as this method is too strict
             // it only parses the full spec "yyyy-mm-dd"
+            Perl5Matcher matcher = new Perl5Matcher();
+            int          year    = 1970;
+            int          month   = 1;
+            int          day     = 1;
 
-            String dateAsText = textRep;
-            int    year       = 1970;
-            int    month      = 1;
-            int    day        = 1;
-            int    slashPos   = dateAsText.indexOf('-');
-
-            try
+            if (matcher.matches(textRep, _datePattern))
             {
-                if (slashPos < 0)
-                {
-                    year = Integer.parseInt(dateAsText);
-                }
-                else
+                MatchResult match     = matcher.getMatch();
+                int         numGroups = match.groups();
+
+                try
                 {
-                    year       = Integer.parseInt(dateAsText.substring(0, slashPos));
-                    dateAsText = dateAsText.substring(slashPos + 1);
-                    slashPos   = dateAsText.indexOf('-');
-                    if (slashPos < 0)
+                    year = Integer.parseInt(match.group(1));
+                    if ((numGroups > 2) && (match.group(2) != null))
                     {
-                        month = Integer.parseInt(dateAsText);
+                        month = Integer.parseInt(match.group(2));
                     }
-                    else
+                    if ((numGroups > 3) && (match.group(3) != null))
                     {
-                        month = Integer.parseInt(dateAsText.substring(0, slashPos));
-                        day   = Integer.parseInt(dateAsText.substring(slashPos + 1));
+                        day = Integer.parseInt(match.group(3));
                     }
                 }
-
+                catch (NumberFormatException ex)
+                {
+                    throw new ConversionException("Not a valid date : " + textRep, ex);
+                }
                 _calendar.clear();
-                _calendar.set(year, month - 1, day);
-                return new Date(_calendar.getTimeInMillis());
-            }
-            catch (NumberFormatException ex)
-            {
-                throw new ConversionException(ex);
+                try
+                {
+                    _calendar.set(year, month - 1, day);
+                    return new Date(_calendar.getTimeInMillis());
+                }
+                catch (IllegalArgumentException ex)
+                {
+                    throw new ConversionException("Not a valid date : " + textRep, ex);
+                }
             }
-            catch (IllegalArgumentException ex)
+            else
             {
-                throw new ConversionException(ex);
+                throw new ConversionException("Not a valid date : " + textRep);
             }
         }
         else

Modified: db/ddlutils/trunk/src/java/org/apache/ddlutils/io/converters/TimeConverter.java
URL: http://svn.apache.org/viewvc/db/ddlutils/trunk/src/java/org/apache/ddlutils/io/converters/TimeConverter.java?view=diff&rev=481733&r1=481732&r2=481733
==============================================================================
--- db/ddlutils/trunk/src/java/org/apache/ddlutils/io/converters/TimeConverter.java (original)
+++ db/ddlutils/trunk/src/java/org/apache/ddlutils/io/converters/TimeConverter.java Sat Dec  2 23:34:57 2006
@@ -23,6 +23,14 @@
 import java.sql.Types;
 import java.util.Calendar;
 
+import org.apache.ddlutils.DdlUtilsException;
+import org.apache.oro.text.regex.MalformedPatternException;
+import org.apache.oro.text.regex.MatchResult;
+import org.apache.oro.text.regex.Pattern;
+import org.apache.oro.text.regex.PatternCompiler;
+import org.apache.oro.text.regex.Perl5Compiler;
+import org.apache.oro.text.regex.Perl5Matcher;
+
 /**
  * Converts between {@link java.sql.Time} and {@link java.lang.String} using the standard
  * representation "hh:mm:ss".
@@ -31,6 +39,8 @@
  */
 public class TimeConverter implements SqlTypeConverter 
 {
+    /** The regular expression pattern for the parsing of ISO times. */
+    private Pattern _timePattern;
 	/** The calendar object to convert to/from times. */
 	private Calendar _calendar;
 
@@ -39,8 +49,18 @@
 	 */
 	public TimeConverter()
 	{
-		_calendar = Calendar.getInstance();
+        PatternCompiler compiler = new Perl5Compiler();
+
+        try
+        {
+            _timePattern = compiler.compile("(?:\\d{4}\\-\\d{2}\\-\\d{2}\\s)?(\\d{2})(?::(\\d{2}))?(?::(\\d{2}))?(?:\\..*)?");
+        }
+        catch (MalformedPatternException ex)
+        {
+            throw new DdlUtilsException(ex);
+        }
 
+        _calendar = Calendar.getInstance();
 		_calendar.setLenient(false);
 	}
 
@@ -57,48 +77,48 @@
         {
             // we're not using {@link java.sql.Time#valueOf(String)} as this method is too strict
             // it only parses the full spec "hh:mm:ss"
+            Perl5Matcher matcher = new Perl5Matcher();
+            int          hours   = 0;
+            int          minutes = 0;
+            int          seconds = 0;
 
-            String timeAsText = textRep;
-            int    hours      = 0;
-            int    minutes    = 0;
-            int    seconds    = 0;
-            int    slashPos   = timeAsText.indexOf(':');
-
-            try
+            if (matcher.matches(textRep, _timePattern))
             {
-                if (slashPos < 0)
-                {
-                    hours = Integer.parseInt(timeAsText);
-                }
-                else
+                MatchResult match     = matcher.getMatch();
+                int         numGroups = match.groups();
+
+                try
                 {
-                    hours      = Integer.parseInt(timeAsText.substring(0, slashPos));
-                    timeAsText = timeAsText.substring(slashPos + 1);
-                    slashPos   = timeAsText.indexOf(':');
-                    if (slashPos < 0)
+                    hours = Integer.parseInt(match.group(1));
+                    if ((numGroups > 2) && (match.group(2) != null))
                     {
-                        minutes = Integer.parseInt(timeAsText);
+                        minutes = Integer.parseInt(match.group(2));
                     }
-                    else
+                    if ((numGroups > 3) && (match.group(3) != null))
                     {
-                        minutes = Integer.parseInt(timeAsText.substring(0, slashPos));
-                        seconds = Integer.parseInt(timeAsText.substring(slashPos + 1));
+                        seconds = Integer.parseInt(match.group(3));
                     }
                 }
-
+                catch (NumberFormatException ex)
+                {
+                    throw new ConversionException("Not a valid time : " + textRep, ex);
+                }
                 _calendar.clear();
-                _calendar.set(Calendar.HOUR_OF_DAY, hours);
-                _calendar.set(Calendar.MINUTE, minutes);
-                _calendar.set(Calendar.SECOND, seconds);
-                return new Time(_calendar.getTimeInMillis());
-            }
-            catch (NumberFormatException ex)
-            {
-                throw new ConversionException(ex);
+                try
+                {
+                    _calendar.set(Calendar.HOUR_OF_DAY, hours);
+                    _calendar.set(Calendar.MINUTE, minutes);
+                    _calendar.set(Calendar.SECOND, seconds);
+                    return new Time(_calendar.getTimeInMillis());
+                }
+                catch (IllegalArgumentException ex)
+                {
+                    throw new ConversionException("Not a valid time : " + textRep, ex);
+                }
             }
-            catch (IllegalArgumentException ex)
+            else
             {
-                throw new ConversionException(ex);
+                throw new ConversionException("Not a valid time : " + textRep);
             }
         }
         else

Modified: db/ddlutils/trunk/src/test/org/apache/ddlutils/io/converters/TestDateConverter.java
URL: http://svn.apache.org/viewvc/db/ddlutils/trunk/src/test/org/apache/ddlutils/io/converters/TestDateConverter.java?view=diff&rev=481733&r1=481732&r2=481733
==============================================================================
--- db/ddlutils/trunk/src/test/org/apache/ddlutils/io/converters/TestDateConverter.java (original)
+++ db/ddlutils/trunk/src/test/org/apache/ddlutils/io/converters/TestDateConverter.java Sat Dec  2 23:34:57 2006
@@ -107,6 +107,23 @@
     }
 
     /**
+     * Tests a full datetime string.
+     */
+    public void testNormalConvertFromFullDateTimeString()
+    {
+        String   textRep = "2005-06-07 10:11:12";
+        Calendar cal     = Calendar.getInstance();
+
+        cal.clear();
+        cal.set(2005, 5, 7);
+
+        Object result = _dateConverter.convertFromString(textRep, Types.DATE);
+
+        assertTrue(result instanceof Date);
+        assertEquals(cal.getTimeInMillis(), ((Date)result).getTime());
+    }
+
+    /**
      * Tests converting with an invalid SQL type.
      */
     public void testConvertFromStringWithInvalidSqlType()

Modified: db/ddlutils/trunk/src/test/org/apache/ddlutils/io/converters/TestTimeConverter.java
URL: http://svn.apache.org/viewvc/db/ddlutils/trunk/src/test/org/apache/ddlutils/io/converters/TestTimeConverter.java?view=diff&rev=481733&r1=481732&r2=481733
==============================================================================
--- db/ddlutils/trunk/src/test/org/apache/ddlutils/io/converters/TestTimeConverter.java (original)
+++ db/ddlutils/trunk/src/test/org/apache/ddlutils/io/converters/TestTimeConverter.java Sat Dec  2 23:34:57 2006
@@ -111,6 +111,26 @@
     }
 
     /**
+     * Tests a full ISO datetime string.
+     */
+    public void testNormalConvertFromIsoDateTimeString()
+    {
+        String   textRep = "2004-01-13 04:45:09.245";
+        Calendar cal     = Calendar.getInstance();
+
+        cal.setLenient(false);
+        cal.clear();
+        cal.set(Calendar.HOUR, 4);
+        cal.set(Calendar.MINUTE, 45);
+        cal.set(Calendar.SECOND, 9);
+
+        Object result = _timeConverter.convertFromString(textRep, Types.TIME);
+
+        assertTrue(result instanceof Time);
+        assertEquals(cal.getTimeInMillis(), ((Time)result).getTime());
+    }
+
+    /**
      * Tests converting with an invalid SQL type.
      */
     public void testConvertFromStringWithInvalidSqlType()