1 16 package org.apache.myfaces.convert; 17 18 import javax.faces.component.UIComponent; 19 import javax.faces.context.FacesContext; 20 import javax.faces.convert.Converter; 21 import javax.faces.convert.ConverterException; 22 import java.io.UnsupportedEncodingException ; 23 import java.net.URLDecoder ; 24 import java.net.URLEncoder ; 25 import java.util.StringTokenizer ; 26 27 31 public class StringArrayConverter 32 implements Converter 33 { 34 public Object getAsObject(FacesContext context, UIComponent component, String value) 35 throws ConverterException 36 { 37 try 38 { 39 StringTokenizer tokenizer = new StringTokenizer (value, ","); 40 String [] newValue = new String [tokenizer.countTokens()]; 41 for (int i = 0; tokenizer.hasMoreTokens(); i++) 42 { 43 newValue[i] = URLDecoder.decode(tokenizer.nextToken(), "UTF-8"); 44 } 45 return newValue; 46 } 47 catch (UnsupportedEncodingException e) 48 { 49 throw new RuntimeException (e); 50 } 51 } 52 53 public String getAsString(FacesContext context, UIComponent component, Object value) 54 throws ConverterException 55 { 56 return getAsString((String [])value, 57 true); } 59 60 61 public static String getAsString(String [] strings, 62 boolean escapeCommas) 63 { 64 try 65 { 66 if (strings == null || strings.length == 0) 67 { 68 return null; 69 } 70 else if (strings.length == 1) 71 { 72 73 return escapeCommas 74 ? URLEncoder.encode(strings[0], "UTF-8") : strings[0]; 76 } 77 else 78 { 79 StringBuffer buf = new StringBuffer (); 80 for (int i = 0; i < strings.length; i++) 81 { 82 if (i > 0) 83 { 84 buf.append(','); 85 } 86 String s = strings[i]; 87 if (escapeCommas) 88 { 89 s = URLEncoder.encode(s, "UTF-8"); 91 } 92 buf.append(s); 93 } 94 return buf.toString(); 95 } 96 } 97 catch (UnsupportedEncodingException e) 98 { 99 throw new RuntimeException (e); 100 } 101 } 102 103 } 104 | Popular Tags |