1 30 31 package org.apache.commons.httpclient.util; 32 33 import org.apache.commons.httpclient.NameValuePair; 34 35 85 public class ParameterFormatter { 86 87 92 private static final char[] SEPARATORS = { 93 '(', ')', '<', '>', '@', 94 ',', ';', ':', '\\', '"', 95 '/', '[', ']', '?', '=', 96 '{', '}', ' ', '\t' 97 }; 98 99 103 private static final char[] UNSAFE_CHARS = { 104 '"', '\\' 105 }; 106 107 111 private boolean alwaysUseQuotes = true; 112 113 114 public ParameterFormatter() { 115 super(); 116 } 117 118 private static boolean isOneOf(char[] chars, char ch) { 119 for (int i = 0; i < chars.length; i++) { 120 if (ch == chars[i]) { 121 return true; 122 } 123 } 124 return false; 125 } 126 127 private static boolean isUnsafeChar(char ch) { 128 return isOneOf(UNSAFE_CHARS, ch); 129 } 130 131 private static boolean isSeparator(char ch) { 132 return isOneOf(SEPARATORS, ch); 133 } 134 135 142 public boolean isAlwaysUseQuotes() { 143 return alwaysUseQuotes; 144 } 145 146 152 public void setAlwaysUseQuotes(boolean alwaysUseQuotes) { 153 this.alwaysUseQuotes = alwaysUseQuotes; 154 } 155 156 167 public static void formatValue( 168 final StringBuffer buffer, final String value, boolean alwaysUseQuotes) { 169 if (buffer == null) { 170 throw new IllegalArgumentException ("String buffer may not be null"); 171 } 172 if (value == null) { 173 throw new IllegalArgumentException ("Value buffer may not be null"); 174 } 175 if (alwaysUseQuotes) { 176 buffer.append('"'); 177 for (int i = 0; i < value.length(); i++) { 178 char ch = value.charAt(i); 179 if (isUnsafeChar(ch)) { 180 buffer.append('\\'); 181 } 182 buffer.append(ch); 183 } 184 buffer.append('"'); 185 } else { 186 int offset = buffer.length(); 187 boolean unsafe = false; 188 for (int i = 0; i < value.length(); i++) { 189 char ch = value.charAt(i); 190 if (isSeparator(ch)) { 191 unsafe = true; 192 } 193 if (isUnsafeChar(ch)) { 194 buffer.append('\\'); 195 } 196 buffer.append(ch); 197 } 198 if (unsafe) { 199 buffer.insert(offset, '"'); 200 buffer.append('"'); 201 } 202 } 203 } 204 205 212 public void format(final StringBuffer buffer, final NameValuePair param) { 213 if (buffer == null) { 214 throw new IllegalArgumentException ("String buffer may not be null"); 215 } 216 if (param == null) { 217 throw new IllegalArgumentException ("Parameter may not be null"); 218 } 219 buffer.append(param.getName()); 220 String value = param.getValue(); 221 if (value != null) { 222 buffer.append("="); 223 formatValue(buffer, value, this.alwaysUseQuotes); 224 } 225 } 226 227 236 public String format(final NameValuePair param) { 237 StringBuffer buffer = new StringBuffer (); 238 format(buffer, param); 239 return buffer.toString(); 240 } 241 242 } 243 | Popular Tags |