aboutsummaryrefslogtreecommitdiff
path: root/app/src/main/java/moe/yuuta/gplicense/util/URIQueryDecoder.java
blob: 273e85fc422c7ff05c1d88a446f4501ff444a12d (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
package moe.yuuta.gplicense.util;

import com.elvishew.xlog.XLog;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
import java.util.Map;
import java.util.Scanner;

public class URIQueryDecoder {
    /**
     * Decodes the query portion of the passed-in URI.
     *
     * @param encodedURI the URI containing the query to decode
     * @param results a map containing all query parameters. Query parameters that do not have a
     *            value will map to a null string
     */
    static public void DecodeQuery(URI encodedURI, Map<String, String> results) {
        Scanner scanner = new Scanner(encodedURI.getRawQuery());
        scanner.useDelimiter("&");
        try {
            while (scanner.hasNext()) {
                String param = scanner.next();
                String[] valuePair = param.split("=");
                String name, value;
                if (valuePair.length == 1) {
                    value = null;
                } else if (valuePair.length == 2) {
                    value = URLDecoder.decode(valuePair[1], "UTF-8");
                } else {
                    throw new IllegalArgumentException("query parameter invalid");
                }
                name = URLDecoder.decode(valuePair[0], "UTF-8");
                results.put(name, value);
            }
        } catch (UnsupportedEncodingException e) {
            // This should never happen.
            XLog.e("UQD", "UTF-8 Not Recognized as a charset.  Device configuration Error.");
        }
    }
}