File: GeocacheCode.java

package info (click to toggle)
gpsprune 26.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 5,824 kB
  • sloc: java: 52,154; sh: 25; makefile: 21; python: 15
file content (81 lines) | stat: -rw-r--r-- 2,183 bytes parent folder | download | duplicates (4)
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
75
76
77
78
79
80
81
package tim.prune.data;

public abstract class GeocacheCode
{
	/** Supported providers of cache codes */
	private enum Provider
	{
		GEOCACHING_COM("GC", "https://coord.info/"),
		OPENCACHING_DE("OC", "https://www.opencaching.de/");

		private final String _prefix;
		private final String _url;

		Provider(String inPrefix, String inUrl) {
			_prefix = inPrefix;
			_url = inUrl;
		}

		static Provider getProvider(String inCode)
		{
			if (inCode == null || inCode.length() < 2) {
				return null;
			}
			for (Provider provider : values())
			{
				// Assume that all prefixes are the first two characters
				if (provider._prefix.charAt(0) == inCode.charAt(0)
						&& provider._prefix.charAt(1) == inCode.charAt(1)) {
					return provider;
				}
			}
			return null;
		}
	}

	/** @return true if the given code is recognised and valid */
	public static boolean isValidCode(String inCode)
	{
		if (inCode == null || !isLengthValid(inCode.length())) {
			return false;
		}
		Provider provider = Provider.getProvider(inCode);
		return provider != null && verifyCharactersAreValid(inCode);
	}

	/** @return true if the length of the code is acceptable */
	private static boolean isLengthValid(int inLength) {
		return inLength > 4 && inLength <= 8;
	}

	/**
	 * @return true if the code only contains valid letters and numbers,
	 * but this doesn't mean that it starts with a recognised prefix
	 */
	private static boolean verifyCharactersAreValid(String inCode)
	{
		// Note, only upper case ASCII letters and numbers are allowed
		final String allowedChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		for (int i=0; i<inCode.length(); i++)
		{
			if (allowedChars.indexOf(inCode.charAt(i)) < 0) {
				return false;
			}
		}
		return true;
	}

	/** @return a suitable URL for the given code, or null if not available */
	public static String getUrl(String inCode)
	{
		Provider provider = Provider.getProvider(inCode);
		if (provider != null
			&& inCode != null
			&& isLengthValid(inCode.length())
			&& verifyCharactersAreValid(inCode))
		{
			return provider._url + inCode;
		}
		return null;
	}
}