1 22 package org.jboss.util.propertyeditor; 23 24 import java.beans.PropertyEditorSupport ; 25 import java.security.AccessController ; 26 import java.security.PrivilegedAction ; 27 import java.text.DateFormat ; 28 import java.text.ParseException ; 29 import java.text.SimpleDateFormat ; 30 import java.util.Date ; 31 32 import org.jboss.util.NestedRuntimeException; 33 34 44 public class DateEditor extends PropertyEditorSupport 45 { 46 47 private static DateFormat [] formats; 48 static 49 { 50 initialize(); 51 } 52 53 58 public static void initialize() 59 { 60 PrivilegedAction action = new PrivilegedAction () 61 { 62 public Object run() 63 { 64 String defaultFormat = System.getProperty("org.jboss.util.propertyeditor.DateEditor.format", 65 "MMM d, yyyy"); 66 formats = new DateFormat [] 67 { 68 new SimpleDateFormat (defaultFormat), 69 new SimpleDateFormat ("EEE MMM d HH:mm:ss z yyyy"), 71 new SimpleDateFormat ("EEE, d MMM yyyy HH:mm:ss Z") 73 }; 74 return null; 75 } 76 }; 77 AccessController.doPrivileged(action); 78 } 79 80 81 private String text; 82 83 88 public void setValue(Object value) 89 { 90 if (value instanceof Date ) 91 { 92 text = null; 93 super.setValue(value); 94 } 95 else 96 { 97 throw new IllegalArgumentException ("setValue() expected java.util.Date value, got " 98 + value.getClass().getName()); 99 } 100 } 101 102 108 public void setAsText(String text) 109 { 110 ParseException pe = null; 111 112 for (int i = 0; i < formats.length; i++) 113 { 114 try 115 { 116 DateFormat df = formats[i]; 118 Date date = df.parse(text); 119 120 this.text = text; 122 super.setValue(date); 123 124 return; 126 } 127 catch (ParseException e) 128 { 129 pe = e; 131 } 132 } 133 throw new NestedRuntimeException(pe); 135 } 136 137 144 public String getAsText() 145 { 146 if (text == null) 147 { 148 DateFormat df = formats[formats.length - 1]; 149 Date date = (Date )getValue(); 150 text = df.format(date); 151 } 152 return text; 153 } 154 155 } | Popular Tags |