1 13 package com.tonbeller.wcf.format; 14 15 import java.util.ArrayList ; 16 import java.util.HashMap ; 17 import java.util.Iterator ; 18 import java.util.List ; 19 import java.util.Locale ; 20 import java.util.Map ; 21 22 25 public class Formatter implements BasicTypes { 26 List handlerList = new ArrayList (); Map handlerMap = new HashMap (); 28 Locale locale; 29 30 33 public Formatter() { 34 } 35 36 37 public void setLocale(Locale locale) { 38 this.locale = locale; 39 for (Iterator it = handlerList.iterator(); it.hasNext(); ) { 40 FormatHandler fh = (FormatHandler)it.next(); 41 fh.setLocale(locale); 42 } 43 } 44 45 public Locale getLocale() { 46 return locale; 47 } 48 49 52 public void addHandler(FormatHandler newHandler) { 53 String type = newHandler.getName(); 54 FormatHandler oldHandler = (FormatHandler) handlerMap.get(type); 55 if (oldHandler != null) { 56 handlerMap.remove(type); 57 handlerList.remove(oldHandler); 58 } 59 60 handlerMap.put(type, newHandler); 61 handlerList.add(newHandler); 62 } 63 64 69 public FormatHandler getHandler(String type) { 70 if (type == null || type.length() == 0) 71 type = BasicTypes.STRING_TYPE; 72 return (FormatHandler) handlerMap.get(type); 73 } 74 75 78 public String format(String type, Object value, String userPattern) { 79 FormatHandler fh = getHandler(type); 80 if (fh == null) 81 return String.valueOf(value); 82 return fh.format(value, userPattern); 83 } 84 85 88 public Object parse(String type, String value, String userPattern) { 89 FormatHandler fh = getHandler(type); 90 if (fh == null) 91 return value; 92 return fh.parse(value, userPattern); 93 } 94 95 98 public FormatHandler guessHandler(Object value) { 99 Iterator it = handlerList.iterator(); 100 while (it.hasNext()) { 101 FormatHandler fh = (FormatHandler) it.next(); 102 if (fh.canHandle(value)) 103 return fh; 104 } 105 return null; 106 } 107 108 109 110 } | Popular Tags |