aboutsummaryrefslogtreecommitdiffstats
path: root/linguistics/src/main/java/com/yahoo/language/LocaleFactory.java
diff options
context:
space:
mode:
Diffstat (limited to 'linguistics/src/main/java/com/yahoo/language/LocaleFactory.java')
-rw-r--r--linguistics/src/main/java/com/yahoo/language/LocaleFactory.java57
1 files changed, 57 insertions, 0 deletions
diff --git a/linguistics/src/main/java/com/yahoo/language/LocaleFactory.java b/linguistics/src/main/java/com/yahoo/language/LocaleFactory.java
new file mode 100644
index 00000000000..2610550dfd2
--- /dev/null
+++ b/linguistics/src/main/java/com/yahoo/language/LocaleFactory.java
@@ -0,0 +1,57 @@
+// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+package com.yahoo.language;
+
+import java.util.Locale;
+
+/**
+ * @author <a href="mailto:simon@yahoo-inc.com">Simon Thoresen</a>
+ */
+public final class LocaleFactory {
+
+ private static final Locale UNKNOWN = new Locale("", "", "");
+
+ private LocaleFactory() {
+ // hide
+ }
+
+ /**
+ * <p>Implements a simple parser for RFC5646 language tags. The language tag is parsed into a Locale.</p>
+ *
+ * @param tag The language tag to parse.
+ * @return The corrseponding Locale.
+ */
+ @SuppressWarnings("ConstantConditions")
+ public static Locale fromLanguageTag(String tag) {
+ // TODO: Should be replaced by return Locale.forLanguageTag(tag); ?
+
+ tag.getClass(); // throws NullPointerException
+ tag = tag.trim();
+ if (tag.isEmpty()) {
+ return UNKNOWN;
+ }
+ String language = "";
+ String region = "";
+ String script = "";
+ String[] parts = tag.split("-");
+ for (int partIdx = 0; partIdx < parts.length; ++partIdx) {
+ String part = parts[partIdx];
+ int partLen = part.length();
+ if (partIdx == 0) {
+ if (partLen == 2 || partLen == 3) {
+ language = part;
+ }
+ } else if (partIdx == 1 || partIdx == 2) {
+ if (partLen == 2 || partLen == 3) {
+ region = part;
+ } else if (partLen == 4) {
+ script = part;
+ }
+ }
+ }
+ if (language.isEmpty()) {
+ return UNKNOWN;
+ }
+ return new Locale(language, region, script);
+ }
+
+}