1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.springframework.extensions.webscripts.form;
20
21 import java.net.URLDecoder;
22 import java.util.HashMap;
23 import java.util.LinkedHashMap;
24 import java.util.Map;
25
26 import org.springframework.extensions.surf.util.Content;
27 import org.springframework.extensions.webscripts.Format;
28 import org.springframework.extensions.webscripts.FormatReader;
29 import org.springframework.extensions.webscripts.WebScriptException;
30 import org.springframework.extensions.webscripts.WebScriptRequest;
31 import org.springframework.extensions.webscripts.WebScriptResponse;
32
33
34
35
36
37
38
39
40 public class UrlEncodedFormReader implements FormatReader<Object>
41 {
42
43 private static final String DEFAULT_ENCODING = "UTF-8";
44 private static final String DECODED_PARAMS = "decodedparams";
45
46
47
48
49 public Class<? extends Object> getDestinationClass()
50 {
51 return Object.class;
52 }
53
54
55
56
57 public String getSourceMimetype()
58 {
59 return Format.XWWWFORMURLENCODED.mimetype();
60 }
61
62
63
64
65 public Object read(WebScriptRequest req)
66 {
67 Content content = req.getContent();
68 if (content == null)
69 {
70 throw new WebScriptException("Failed to convert request to URL-unencoded");
71 }
72
73 Object result = null;
74 try
75 {
76 String contentString = content.getContent();
77 String[] params = contentString.split("&");
78 Map<String, String> decodedParams = new LinkedHashMap<String, String>(params.length);
79
80 String encoding = content.getEncoding();
81 String encodingToUse = encoding == null ? DEFAULT_ENCODING : encoding;
82
83 for (String param : params)
84 {
85 String[] nameAndValue = param.split("=");
86
87 String decodedName = URLDecoder.decode(nameAndValue[0], encodingToUse);
88 String decodedValue = URLDecoder.decode(nameAndValue[1], encodingToUse);
89
90 if (decodedName.length() > 0)
91 {
92 decodedParams.put(decodedName, decodedValue);
93 }
94 }
95
96 result = decodedParams;
97 }
98 catch (Exception exception)
99 {
100 throw new WebScriptException("Failed to convert request to URL-unencoded", exception);
101 }
102 return result;
103 }
104
105
106
107
108 public Map<String, Object> createScriptParameters(WebScriptRequest req, WebScriptResponse res)
109 {
110 Map<String, Object> params = new HashMap<String, Object>();
111 params.put(DECODED_PARAMS, read(req));
112 return params;
113 }
114 }