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 String q = url.getQuery();
90 public static MultiMap<String, String> urlparams(Request req) {
91 return(urlparams(req.url()));
94 public static String encquery(Map<String, String> pars) {
95 StringBuilder buf = new StringBuilder();
97 for(Map.Entry<String, String> par : pars.entrySet()) {
100 buf.append(Misc.urlq(par.getKey()));
102 buf.append(Misc.urlq(par.getValue()));
105 return(buf.toString());
108 public static MultiMap<String, String> postparams(Request req) {
109 if(req.method() != "POST")
111 String clens = req.inheaders().get("Content-Length");
116 clen = Integer.parseInt(clens);
117 } catch(NumberFormatException e) {
120 String ctype = req.inheaders().get("Content-Type");
123 ctype = ctype.toLowerCase();
124 if(ctype.equals("application/x-www-form-urlencoded")) {
125 if(clen > (1 << 20)) /* Just to be safe */
129 data = Misc.readall(req.input());
130 } catch(IOException e) {
133 String dec = new String(data, Misc.utf8);
134 return(urlparams(dec));