Test for URLEncoder

- test added
- source formatted

Signed-off-by: Laszlo Hornyak <laszlo.hornyak@gmail.com>
This commit is contained in:
Laszlo Hornyak 2013-09-29 15:25:53 +02:00 committed by Daan Hoogland
parent c61997f022
commit 13e7a7308b
2 changed files with 34 additions and 24 deletions

View File

@ -34,19 +34,16 @@ import java.util.BitSet;
* @author Remy Maucherat
*/
public class URLEncoder {
protected static final char[] hexadecimal = { '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
static CharsetEncoder asciiEncoder =
Charset.forName("US-ASCII").newEncoder(); // or "ISO-8859-1" for ISO Latin 1
//Array containing the safe characters set.
protected BitSet safeCharacters = new BitSet(256);
public URLEncoder() {
for (char i = 'a'; i <= 'z'; i++) {
addSafeCharacter(i);
@ -59,15 +56,14 @@ public class URLEncoder {
}
}
public void addSafeCharacter(char c) {
private void addSafeCharacter(char c) {
safeCharacters.set(c);
}
public String encode(String path) {
int maxBytesPerChar = 10;
StringBuffer rewrittenPath = new StringBuffer(path.length());
ByteArrayOutputStream buf = new ByteArrayOutputStream(
maxBytesPerChar);
ByteArrayOutputStream buf = new ByteArrayOutputStream(maxBytesPerChar);
OutputStreamWriter writer = null;
try {
writer = new OutputStreamWriter(buf, "UTF8");
@ -75,10 +71,11 @@ public class URLEncoder {
e.printStackTrace();
writer = new OutputStreamWriter(buf);
}
for (int i = 0; i < path.length(); i++) {
int c = (int) path.charAt(i);
//NOTICE - !isPureAscii(path.charAt(i)) check was added by CloudStack
// NOTICE - !isPureAscii(path.charAt(i)) check was added by
// CloudStack
if (safeCharacters.get(c) || !isPureAscii(path.charAt(i))) {
rewrittenPath.append((char) c);
} else {
@ -95,20 +92,19 @@ public class URLEncoder {
// Converting each byte in the buffer
byte toEncode = ba[j];
rewrittenPath.append('%');
int low = (int) (toEncode & 0x0f);
int high = (int) ((toEncode & 0xf0) >> 4);
rewrittenPath.append(hexadecimal[high]);
rewrittenPath.append(hexadecimal[low]);
}
buf.reset();
int low = (int) (toEncode & 0x0f);
int high = (int) ((toEncode & 0xf0) >> 4);
rewrittenPath.append(hexadecimal[high]);
rewrittenPath.append(hexadecimal[low]);
}
buf.reset();
}
return rewrittenPath.toString();
}
//NOTICE - this part was added by CloudStack
public static boolean isPureAscii(Character v) {
return asciiEncoder.canEncode(v);
}
return rewrittenPath.toString();
}
// NOTICE - this part was added by CloudStack
public static boolean isPureAscii(Character v) {
return asciiEncoder.canEncode(v);
}
}

View File

@ -0,0 +1,14 @@
package com.cloud.utils.encoding;
import org.junit.Assert;
import org.junit.Test;
public class UrlEncoderTest {
@Test
public void encode() {
Assert.assertEquals("%2Ftmp%2F", new URLEncoder().encode("/tmp/"));
Assert.assertEquals("%20", new URLEncoder().encode(" "));
Assert.assertEquals("%5F", new URLEncoder().encode("_"));
Assert.assertEquals("%25", new URLEncoder().encode("%"));
}
}