1 21 package net.mlw.vlh.adapter.hibernate.util.setter; 22 23 import java.text.ParseException ; 24 import java.text.SimpleDateFormat ; 25 import java.util.Date ; 26 27 import net.sf.hibernate.HibernateException; 28 import net.sf.hibernate.Query; 29 30 import org.apache.commons.logging.Log; 31 import org.apache.commons.logging.LogFactory; 32 33 37 public class TimestampSetter extends AbstractSetter 38 { 39 42 private static final Log LOGGER = LogFactory.getLog(TimestampSetter.class); 43 44 public static final String DEFAULT_FORMAT = "MM/dd/yyyy HH:mm:ss"; 45 46 private SimpleDateFormat formatter = new SimpleDateFormat (DEFAULT_FORMAT); 47 48 51 public void set(Query query, String key, Object value) throws HibernateException, ParseException 52 { 53 Date date = null; 54 if (value instanceof String ) 55 { 56 if (LOGGER.isInfoEnabled()) 57 { 58 LOGGER.info("The key='" + key + "'s value is instance of a String, now is parsing to date."); 59 } 60 date = formatter.parse((String ) value); 61 } 62 else if (value instanceof Date ) 63 { 64 date = (Date ) value; 65 } 66 else if (value == null) 67 { 68 if (LOGGER.isInfoEnabled()) 69 { 70 LOGGER.info("The key='" + key + "'s value is null."); 71 } 72 } 73 else 74 { 75 if (LOGGER.isWarnEnabled()) 76 { 77 LOGGER.warn("The key's='" + key + "' value='" + value + "' was expected as Date or String parseable to Date."); 78 } 79 throw new IllegalArgumentException ("Cannot convert value of class " + value.getClass().getName() + " to timestamp (key=" + key 80 + ")"); 81 } 82 83 if (LOGGER.isInfoEnabled()) 84 { 85 LOGGER.info("The key='" + key + "' was set to the query as Timestamp with the value date='" + date + "'."); 86 } 87 88 query.setTimestamp(key, date); 89 } 90 91 94 public void setFormat(String format) 95 { 96 formatter = new SimpleDateFormat (format); 97 } 98 } | Popular Tags |