-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathStrictLocaleDeserializer.java
More file actions
82 lines (69 loc) · 2.5 KB
/
StrictLocaleDeserializer.java
File metadata and controls
82 lines (69 loc) · 2.5 KB
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
82
/*
* Copyright 2016-2025 Berry Cloud Ltd. All rights reserved.
*/
package dev.learning.xapi.jackson;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.KeyDeserializer;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import java.io.IOException;
import java.util.Locale;
import java.util.MissingResourceException;
/**
* Strict Locale deserializer.
*
* @author István Rátkai (Selindek)
*/
public class StrictLocaleDeserializer extends StdDeserializer<Locale> {
private static final long serialVersionUID = 7182941951585541965L;
/** Default constructor. */
public StrictLocaleDeserializer() {
super(String.class);
}
/** {@inheritDoc} */
@Override
public Locale deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
throws IOException {
if (jsonParser.getCurrentToken() != JsonToken.VALUE_STRING) {
throw deserializationContext.wrongTokenException(
jsonParser,
(JavaType) null,
JsonToken.VALUE_STRING,
"Attempted to parse non-String value to Locale");
}
return validateLocale(jsonParser.getValueAsString(), deserializationContext);
}
static Locale validateLocale(String localeString, DeserializationContext deserializationContext)
throws JsonMappingException {
var locale = Locale.forLanguageTag(localeString);
try {
// test validity of language and country codes (throws exception)
locale.getISO3Language();
locale.getISO3Country();
} catch (final MissingResourceException e) { // Named parameter required by Google Java Style
locale = null;
}
// test the validity of the whole key
if (locale == null || !locale.toLanguageTag().equalsIgnoreCase(localeString)) {
throw deserializationContext.weirdStringException(
localeString, Locale.class, "Invalid locale");
}
return locale;
}
/**
* Strict Locale Key deserializer.
*
* @author István Rátkai (Selindek)
*/
public static class StrictLocaleKeyDeserializer extends KeyDeserializer {
/** {@inheritDoc} */
@Override
public Object deserializeKey(String key, DeserializationContext deserializationContext)
throws IOException {
return validateLocale(key, deserializationContext);
}
}
}