2 * Sone - RequestChangeFilter.java - Copyright © 2010–2013 David Roden
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package net.pterodactylus.sone.template;
20 import java.io.UnsupportedEncodingException;
22 import java.net.URISyntaxException;
23 import java.net.URLEncoder;
24 import java.util.Collection;
25 import java.util.HashMap;
27 import java.util.Map.Entry;
29 import net.pterodactylus.sone.web.page.FreenetRequest;
30 import net.pterodactylus.util.template.Filter;
31 import net.pterodactylus.util.template.TemplateContext;
34 * This filter expects a {@link FreenetRequest} as input and outputs a
35 * {@link URI} that is modified by the parameters. The name of the parameter is
36 * handed in as “name”, the new value is stored in “value”.
38 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
40 public class RequestChangeFilter implements Filter {
43 public Object format(TemplateContext templateContext, Object data, Map<String, Object> parameters) {
44 FreenetRequest request = (FreenetRequest) data;
45 String name = String.valueOf(parameters.get("name"));
46 String value = String.valueOf(parameters.get("value"));
48 Map<String, String> values = new HashMap<String, String>();
49 Collection<String> parameterNames = request.getHttpRequest().getParameterNames();
50 for (String parameterName : parameterNames) {
51 values.put(parameterName, request.getHttpRequest().getParam(parameterName));
53 values.put(name, value);
55 StringBuilder query = new StringBuilder();
57 for (Entry<String, String> parameterEntry : values.entrySet()) {
58 query.append((query.length() == 0) ? '?' : '&');
59 query.append(URLEncoder.encode(parameterEntry.getKey(), "UTF-8"));
61 query.append(URLEncoder.encode(parameterEntry.getValue(), "UTF-8"));
63 String oldUri = request.getUri().toString();
64 int questionMark = oldUri.indexOf('?');
65 if (questionMark == -1) {
66 questionMark = oldUri.length();
68 URI u = new URI(oldUri.substring(0, questionMark) + query.toString());
70 } catch (UnsupportedEncodingException uee1) {
71 /* UTF-8 not supported? I don’t think so. */
72 } catch (URISyntaxException use1) {
73 use1.printStackTrace();