1 16 package org.apache.cocoon.woody.datatype.convertor; 17 18 import org.outerj.i18n.DateFormat; 19 import org.outerj.i18n.I18nSupport; 20 21 import java.util.Locale ; 22 import java.util.Date ; 23 import java.text.ParseException ; 24 25 45 public class FormattingDateConvertor implements Convertor { 46 47 private int style; 48 49 private int variant; 50 51 private LocaleMap localizedPatterns; 52 53 private String nonLocalizedPattern; 54 55 public static final int DATE = 1; 56 public static final int TIME = 2; 57 public static final int DATE_TIME = 3; 58 59 public FormattingDateConvertor() { 60 this.style = java.text.DateFormat.SHORT; 61 this.variant = DATE; 62 this.localizedPatterns = new LocaleMap(); 63 } 64 65 public Object convertFromString(String value, Locale locale, Convertor.FormatCache formatCache) { 66 DateFormat dateFormat = getDateFormat(locale, formatCache); 67 try { 68 return dateFormat.parse(value); 69 } catch (ParseException e) { 70 return null; 71 } 72 } 73 74 public String convertToString(Object value, Locale locale, Convertor.FormatCache formatCache) { 75 DateFormat dateFormat = getDateFormat(locale, formatCache); 76 return dateFormat.format((Date )value); 77 } 78 79 private final DateFormat getDateFormat(Locale locale, Convertor.FormatCache formatCache) { 80 DateFormat dateFormat = null; 81 if (formatCache != null) 82 dateFormat = (DateFormat)formatCache.get(); 83 if (dateFormat == null) { 84 dateFormat = getDateFormat(locale); 85 if (formatCache != null) 86 formatCache.store(dateFormat); 87 } 88 return dateFormat; 89 } 90 91 protected DateFormat getDateFormat(Locale locale) { 92 DateFormat dateFormat = null; 93 94 switch (variant) { 95 case DATE: 96 dateFormat = I18nSupport.getInstance().getDateFormat(style, locale); 97 break; 98 case TIME: 99 dateFormat = I18nSupport.getInstance().getTimeFormat(style, locale); 100 break; 101 case DATE_TIME: 102 dateFormat = I18nSupport.getInstance().getDateTimeFormat(style, style, locale); 103 break; 104 } 105 106 String pattern = (String )localizedPatterns.get(locale); 107 108 if (pattern != null) 109 dateFormat.applyLocalizedPattern(pattern); 110 else if (nonLocalizedPattern != null) 111 dateFormat.applyPattern(nonLocalizedPattern); 112 113 return dateFormat; 114 } 115 116 public Class getTypeClass() { 117 return Date .class; 118 } 119 120 124 public void setStyle(int style) { 125 this.style = style; 126 } 127 128 public void setVariant(int variant) { 129 if (variant != DATE && variant != TIME && variant != DATE_TIME) 130 throw new IllegalArgumentException ("Invalid value for variant parameter."); 131 this.variant = variant; 132 } 133 134 public void addFormattingPattern(Locale locale, String pattern) { 135 localizedPatterns.put(locale, pattern); 136 } 137 138 public void setNonLocalizedPattern(String pattern) { 139 this.nonLocalizedPattern = pattern; 140 } 141 } 142 | Popular Tags |