1 package dolda.jsvc.util;
7 import java.nio.charset.CharacterCodingException;
10 public static class EncodingException extends RequestRestart {
11 public EncodingException(String msg) {
15 public void respond(Request req) {
16 throw(Restarts.stdresponse(400, "Invalid parameter encoding", getMessage()));
20 public static MultiMap<String, String> urlparams(String q) {
22 MultiMap<String, String> ret = new WrappedMultiMap<String, String>(new TreeMap<String, Collection<String>>());
24 String key = null; /* Java is stupid. */
25 MixedBuffer buf = new MixedBuffer();
28 int c = (i >= q.length())?-1:(q.charAt(i++));
31 if(q.length() - i < 2)
32 throw(new EncodingException("Invalid character escape"));
34 buf.append((byte)((Misc.hex2int(q.charAt(i)) << 4) | Misc.hex2int(q.charAt(i + 1))));
35 } catch(NumberFormatException e) {
36 throw(new EncodingException("Invalid character escape"));
41 buf = new MixedBuffer();
44 ret.add(buf.convert(), "");
45 buf = new MixedBuffer();
50 ret.add(buf.convert(), "");
51 buf = new MixedBuffer();
56 } else if(st == "val") {
58 if(q.length() - i < 2)
59 throw(new EncodingException("Invalid character escape"));
61 buf.append((byte)((Misc.hex2int(q.charAt(i)) << 4) | Misc.hex2int(q.charAt(i + 1))));
62 } catch(NumberFormatException e) {
63 throw(new EncodingException("Invalid character escape"));
66 } else if((c == '&') || (c == -1)) {
67 ret.add(key, buf.convert());
68 buf = new MixedBuffer();
78 } catch(CharacterCodingException e) {
79 throw(new EncodingException("Escaped parameter text is not proper UTF-8"));
83 public static MultiMap<String, String> urlparams(URL url) {
84 return(urlparams(url.getQuery()));
87 public static MultiMap<String, String> urlparams(Request req) {
88 return(urlparams(req.url()));
91 public static String encquery(Map<String, String> pars) {
92 StringBuilder buf = new StringBuilder();
94 for(Map.Entry<String, String> par : pars.entrySet()) {
97 buf.append(Misc.urlq(par.getKey()));
99 buf.append(Misc.urlq(par.getValue()));
102 return(buf.toString());