aboutsummaryrefslogtreecommitdiffstats
path: root/main/src/cgeo/geocaching/Parameters.java
blob: fdbbe3b775ba9fb735b12ffd74cf71207a4f3b1b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package cgeo.geocaching;

import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

/**
 * List of key/values pairs to be used in a GET or POST request.
 * 
 */
public class Parameters extends ArrayList<NameValuePair> {

    private static final long serialVersionUID = 1L;

    /**
     * @param keyValues
     *            list of initial key/value pairs
     * @throws InvalidParameterException
     *             if the number of key/values is unbalanced
     */
    public Parameters(final String... keyValues) {
        super();
        put(keyValues);
    }

    private static final Comparator<NameValuePair> comparator = new Comparator<NameValuePair>() {
        @Override
        public int compare(final NameValuePair nv1, final NameValuePair nv2) {
            final int comparedKeys = nv1.getName().compareTo(nv2.getName());
            return comparedKeys != 0 ? comparedKeys : nv1.getValue().compareTo(nv2.getValue());
        }
    };

    /**
     * Add new key/value pairs to the current parameters.
     *
     * @param keyValues
     *            list of key/value pairs
     * @throws InvalidParameterException
     *             if the number of key/values is unbalanced
     */
    public void put(final String... keyValues) {
        if (keyValues.length % 2 == 1) {
            throw new InvalidParameterException("odd number of parameters");
        }
        for (int i = 0; i < keyValues.length; i += 2) {
            add(new BasicNameValuePair(keyValues[i], keyValues[i + 1]));
        }
    }

    /**
     * Lexically sort key/value pairs first by key, then by value.
     *
     * Some signing algorithms need the values to be ordered before issuing the signature.
     */
    public void sort() {
        Collections.sort(this, comparator);
    }

    /**
     * @return the URL encoded string corresponding to those parameters
     */
    @Override
    public String toString() {
        return URLEncodedUtils.format(this, HTTP.UTF_8);
    }

}