{
if (StringUtil.nullOrEmptyOrBlankString(string) ) {
return string;
}
int maxBytesPerChar = 10;
FastStringBuffer out = new FastStringBuffer(string.length());
ByteArrayOutputStream buf = new ByteArrayOutputStream(maxBytesPerChar);
OutputStreamWriter writer = null;
try {
writer = new OutputStreamWriter(buf, encoding);
}
catch (UnsupportedEncodingException uee0) {
try {
writer = new OutputStreamWriter(buf, DefaultCharacterEncoding);
}
catch (UnsupportedEncodingException uee1) {
// This never happens.
uee1.printStackTrace();
}
}
for (int i = 0; i < string.length(); i++) {
int c = (int)string.charAt(i);
if (dontNeedEncoding.get(c)) {
if (c == ' ') {
if (isPlusAllowed) {
c = '+';
}
else {
out.append("%20");
continue;
}
}
out.append((char)c);
}
else {
// convert to external encoding before hex conversion
try {
writer.write(c);
writer.flush();
}
catch(IOException e) {
buf.reset();
continue;
}
byte[] ba = buf.toByteArray();
for (int j = 0; j < ba.length; j++) {
out.append('%');
char ch = Character.forDigit((ba[j] >> 4) & 0xF, 16);
// converting to use uppercase letter as part of
// the hex value if ch is a letter.
if (Character.isLetter(ch)) {
ch -= caseDiff;
}
out.append(ch);
ch = Character.forDigit(ba[j] & 0xF, 16);
if (Character.isLetter(ch)) {
ch -= caseDiff;
}
out.append(ch);
}
buf.reset();
}
}
return out.toString();
}