diff --git a/src/main/java/com/force/i18n/LabelUtils.java b/src/main/java/com/force/i18n/LabelUtils.java index 11f6883..ab0c6be 100644 --- a/src/main/java/com/force/i18n/LabelUtils.java +++ b/src/main/java/com/force/i18n/LabelUtils.java @@ -130,7 +130,7 @@ public static String getSampleGrammarFile(@Nullable String grammar) { } else { // If they pasted in a whole file, it's fine. if (!grammar.contains("") && !grammar.contains("") - && !grammar.contains("") && !grammar.contains("")) { + && !grammar.contains("") && !grammar.contains("")) { StringBuilder sb = new StringBuilder(grammar.length() + 100); sb.append(""); sb.append(""); @@ -139,7 +139,7 @@ public static String getSampleGrammarFile(@Nullable String grammar) { return sb.toString(); } else { // Remove the dtd which confuses the parser - String fixedGrammar = grammar.replace("", ""); + String fixedGrammar = grammar.replace("", ""); fixedGrammar = fixedGrammar.replace("", ""); fixedGrammar = fixedGrammar.replace("", ""); fixedGrammar = fixedGrammar.replace("", ""); @@ -180,46 +180,63 @@ public String nounify(String input, LanguageDictionary dictionary) { return new Nounifier(dictionary).nounifyString(input); } - /** - * Set of locale langauges strings where the results are JDK dependent + /* + * Map of locale langauges strings where the results are JDK dependent. + * Java 17 fixed legacy language code and autmatically replace it in {@code java.util.Locale} (JDK-8267069). This is + * for backward compatibility. */ - static final Set JDK_DEPENDENT_LANGUAGE = ImmutableSet.of(LanguageConstants.YIDDISH_ISO, - LanguageConstants.HEBREW_ISO, LanguageConstants.INDONESIAN_ISO); - + static final Map JDK_DEPENDENT_LANGUAGE = Map.of( // + LanguageConstants.YIDDISH_ISO, LanguageConstants.YIDDISH, // + LanguageConstants.HEBREW_ISO, LanguageConstants.HEBREW, // + LanguageConstants.INDONESIAN_ISO, LanguageConstants.INDONESIAN); - public static List getFileNames(HumanLanguage language,URL rootDirectory, String basename ) { + public static List getFileNames(HumanLanguage language, URL rootDirectory, String basename ) { List list = new ArrayList<>(); try { - Locale locale = language.getLocale(); - list.add(new URL(rootDirectory, locale.getLanguage() + '/' + basename)); + final Locale locale = language.getLocale(); + final String override = language.getOverrideLanguage(); + final boolean hasOverride = override != null && !locale.getLanguage().equals(override); + + list.add(getUrl(rootDirectory, locale.getLanguage(), basename)); + // If the override language is set, add it + if (hasOverride) list.add(getUrl(rootDirectory, override, basename)); // If the iso code for the language changed between JDK versions, use the old isocode for the directory - if (JDK_DEPENDENT_LANGUAGE.contains(locale.getLanguage())) { - list.add(new URL(rootDirectory, language.getOverrideLanguage() + '/' + basename)); + if (JDK_DEPENDENT_LANGUAGE.containsKey(locale.getLanguage())) { + list.add(getUrl(rootDirectory, JDK_DEPENDENT_LANGUAGE.get(locale.getLanguage()), basename)); + } + + if (!locale.getCountry().isEmpty()) { + /* + * Code required because there is no Chinese traditional locale in jdk Locale.java and taiwan and Hong + * kong are 2 different countries + * We will assume that Hong Kong (HK country code) derive the Traditional Chinese from Taiwan (TW) + * In the future, to define Hong Kong label, a new directory will need to be created zh/HK. + */ + if (language.getLocaleString().equals(LanguageConstants.CHINESE_HK)) { + // adding Taiwan as fallback. assuming no override, or variant are set for this + list.add(getUrl(rootDirectory, locale.getLanguage(), Locale.TRADITIONAL_CHINESE.getCountry(), basename)); + list.add(getUrl(rootDirectory, locale.getLanguage(), locale.getCountry(), basename)); + } else { + list.add(getUrl(rootDirectory, locale.getLanguage(), locale.getCountry(), basename)); + if (hasOverride) list.add(getUrl(rootDirectory, override, locale.getCountry(), basename)); + + if (!locale.getVariant().isEmpty()) { + list.add(getUrl(rootDirectory, locale.getLanguage(), locale.getCountry(), locale.getVariant(), basename)); + if (hasOverride) list.add(getUrl(rootDirectory, override, locale.getCountry(), locale.getVariant(), basename)); + } + } } - if (locale.getCountry().length() > 0) { - /* - * Code required because there is no Chinese traditional locale in jdk Locale.java and taiwan and Hong kong are 2 different countries - * We will assume that Hong Kong (HK country code) derive the Traditional Chinese from Taiwan (TW) - * In the future, to define Hong Kong label, a new directory will need to be created zh/HK. - */ - if(language.getLocaleString().equals(LanguageConstants.CHINESE_HK)){ - //adding Taiwan as fallback - list.add(new URL(rootDirectory, locale.getLanguage() + '/'+ Locale.TRADITIONAL_CHINESE.getCountry() +'/'+ basename)); - list.add(new URL(rootDirectory, locale.getLanguage() + '/'+ locale.getCountry() + '/'+ basename)); - }else{ - list.add(new URL(rootDirectory, locale.getLanguage() + '/' + locale.getCountry() + '/' + basename)); - if (locale.getVariant().length() > 0) { - list.add(new URL(rootDirectory, locale.getLanguage() + '/' + locale.getCountry() + '/' + locale.getVariant() + '/' + basename)); - } - } - } } catch (MalformedURLException e) { throw new IllegalArgumentException(e); } - return list; - } + return list; + } + + private static URL getUrl(URL root, String... paths) throws MalformedURLException { + return new URL(root, String.join("/", paths)); + } - private static final Pattern nonalphaPattern = Pattern.compile("\\W"); + private static final Pattern nonalphaPattern = Pattern.compile("\\W"); // TODO: Switch this to splitter. static List tokenize(String input) { @@ -244,7 +261,7 @@ static List tokenize(String input) { * to determine if there should be some "tokenization" of the string. */ public static class Nounifier { - private final static Set EXCLUDED_NOUNS = ImmutableSet.of("Role", "Email", "Address", "{0}"); + private static final Set EXCLUDED_NOUNS = ImmutableSet.of("Role", "Email", "Address", "{0}"); private final GenericTrieMatcher nounMatcher; private final GenericTrieMatcher adjMatcher; diff --git a/src/main/java/com/force/i18n/commons/util/collection/IntHashMap.java b/src/main/java/com/force/i18n/commons/util/collection/IntHashMap.java index c89155d..b6dded7 100644 --- a/src/main/java/com/force/i18n/commons/util/collection/IntHashMap.java +++ b/src/main/java/com/force/i18n/commons/util/collection/IntHashMap.java @@ -8,7 +8,6 @@ package com.force.i18n.commons.util.collection; import java.io.IOException; -import java.io.Serializable; import java.util.*; import com.google.common.annotations.Beta; @@ -77,12 +76,12 @@ * Beta class. Generally use {@link java.util.HashMap} or {@link java.util.EnumMap} instead. * * @author Based on Sun's java.util.HashMap (modified by koliver) - * @see IntMap - * @see java.util.HashMap + * @see IntMap + * @see java.util.HashMap */ @Beta @SuppressWarnings("rawtypes") // TODO Fix -public class IntHashMap extends AbstractIntMap implements Serializable { +public class IntHashMap extends AbstractIntMap { private static final long serialVersionUID = 0L; private static final int DEFAULT_CAPACITY = 101; @@ -186,7 +185,7 @@ public int size() { * * @param value value whose presence in this map is to be tested. */ - @Override + @Override public boolean containsValue(Object value) { IEntry[] tab = this.table; @@ -287,9 +286,9 @@ private void rehash() { * @param key key with which the specified value is to be associated. * @param value value to be associated with the specified key. * @return previous value associated with specified key, or {@code null} - * if there was no mapping for key. A {@code null} return can - * also indicate that the HashMap previously associated - * {@code null} with the specified key. + * if there was no mapping for key. A {@code null} return can + * also indicate that the HashMap previously associated + * {@code null} with the specified key. */ @Override public V put(int key, V value) { @@ -328,9 +327,9 @@ public V put(int key, V value) { * * @param key key whose mapping is to be removed from the map. * @return previous value associated with specified key, or {@code null} - * if there was no mapping for key. A {@code null} return can - * also indicate that the map previously associated {@code null} - * with the specified key. + * if there was no mapping for key. A {@code null} return can + * also indicate that the map previously associated {@code null} + * with the specified key. */ @Override public V remove(int key) { @@ -734,6 +733,20 @@ public int next() { } } + @Override + public int hashCode() { + return super.hashCode(); + } + + @Override + public boolean equals(Object other) { + if (other instanceof IntHashMap) { + // super compares table and count. that may be enough + return super.equals(other); + } + return false; + } + // Serialization private void writeObject(java.io.ObjectOutputStream s) throws IOException { // Write out the threshold, loadfactor, and any hidden stuff diff --git a/src/main/java/com/force/i18n/grammar/LanguageDictionary.java b/src/main/java/com/force/i18n/grammar/LanguageDictionary.java index 2df18ac..4e9fc9f 100644 --- a/src/main/java/com/force/i18n/grammar/LanguageDictionary.java +++ b/src/main/java/com/force/i18n/grammar/LanguageDictionary.java @@ -64,7 +64,7 @@ public class LanguageDictionary implements Serializable { // TODO: These could all be made lists when serialized // map to Noun - protected GrammaticalTermMap nounMap; + protected GrammaticalTermMap nounMap; // map to Noun protected GrammaticalTermMap nounMapByPluralAlias; // map to Adjective @@ -202,9 +202,9 @@ public GrammaticalTermMap getNounByPluralAlias() { public GrammaticalTermMap getAdjectiveMap() { return adjectiveMap; } - + /** - * get termMap of Article + * get termMap of Article */ public GrammaticalTermMap
getArticleMap() { return articleMap; @@ -213,10 +213,10 @@ public GrammaticalTermMap
getArticleMap() { private void forAllTerms (TermType type, BiConsumer f) { switch (type) { - case Noun: + case Noun: for(Map.Entry e : nounMap.entrySet()) f.accept(e.getKey(), e.getValue()); break; - case Adjective: + case Adjective: for(Map.Entry e : adjectiveMap.entrySet()) f.accept(e.getKey(), e.getValue()); break; case Article: @@ -226,14 +226,14 @@ private void forAllTerms (TermType type, BiConsumer f) throw new AssertionError("Invalid term type " + type); } } - + public Set getAllTermNames(TermType type) { switch (type) { - case Noun: + case Noun: return Collections.unmodifiableSet(nounMap.keySet()); - case Adjective: + case Adjective: return Collections.unmodifiableSet(adjectiveMap.keySet()); case Article: return Collections.unmodifiableSet(articleMap.keySet()); @@ -249,8 +249,8 @@ public Set getAllTermNames(TermType type) { public Set getAllInheritedTermNames(TermType type) { Set result = new HashSet(); forAllTerms(type, (k,v) -> { - if (v.isCopiedFromDefault()) result.add(k); - }); + if (v.isCopiedFromDefault()) result.add(k); + }); return result; } @@ -669,12 +669,12 @@ public void writeJson(Appendable appendable, boolean useRenamedNouns, Collection * @throws IOException if an error happens during append */ public void writeJsonTerms(Appendable out, boolean useRenamedNouns, Collection terms) throws IOException { - Collection termsToInclude = - terms == null ? null : + Collection termsToInclude = + terms == null ? null : terms.stream().map((t)->t.getName()).collect(Collectors.toSet()); writeJson(out, useRenamedNouns, termsToInclude); } - + private void writeObject(ObjectOutputStream out) throws IOException { makeSkinny(); @@ -686,7 +686,6 @@ protected void writeObjectInternal(ObjectOutputStream out) throws IOException { // do nothing here - for hook } - @SuppressWarnings("unchecked") private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); @@ -720,9 +719,9 @@ public Noun getNounOverride(Noun n) { } private static class TreeSetSupplier implements Supplier>, Serializable { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - @Override + @Override public SortedSet get() { return new TreeSet(); } diff --git a/src/main/java/com/force/i18n/grammar/impl/ComplexGrammaticalForm.java b/src/main/java/com/force/i18n/grammar/impl/ComplexGrammaticalForm.java index 430f4ca..b220f7e 100644 --- a/src/main/java/com/force/i18n/grammar/impl/ComplexGrammaticalForm.java +++ b/src/main/java/com/force/i18n/grammar/impl/ComplexGrammaticalForm.java @@ -39,6 +39,7 @@ import com.force.i18n.grammar.ModifierForm; import com.force.i18n.grammar.Noun; import com.force.i18n.grammar.NounForm; +import com.google.common.base.Preconditions; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Multimap; @@ -137,7 +138,7 @@ protected Object readResolve() { case Adjective: formList = declension.getAdjectiveForms(); break; case Article: formList = declension.getArticleForms(); break; } - assert formList != null; + Preconditions.checkState(formList != null); return formList.get(this.ordinal); } } @@ -273,7 +274,7 @@ static void serializeFormMap(ObjectOutputStre } else { out.writeByte(values.size()); for (Map.Entry entry : values.entrySet()) { - out.writeByte(entry.getKey().getOrdinal()); + out.writeByte(entry.getKey().getOrdinal()); out.writeUTF(entry.getValue()); // Serialize the "object" because it's been uniquefied } } @@ -292,7 +293,8 @@ static Map deserializeFormMap(Obje case Adjective: formList = (List)declension.getAdjectiveForms(); break; case Article: formList = (List)declension.getArticleForms(); break; } - assert formList != null; + Preconditions.checkState(formList != null); + for (int i = 0; i < size; i++) { int ordinal = in.readByte(); String value = intern(in.readUTF()); diff --git a/src/main/java/com/force/i18n/grammar/impl/EnglishDeclension.java b/src/main/java/com/force/i18n/grammar/impl/EnglishDeclension.java index e6fb691..54fe21b 100644 --- a/src/main/java/com/force/i18n/grammar/impl/EnglishDeclension.java +++ b/src/main/java/com/force/i18n/grammar/impl/EnglishDeclension.java @@ -8,6 +8,7 @@ package com.force.i18n.grammar.impl; import static com.force.i18n.commons.util.settings.IniFileUtil.intern; +import static com.google.common.base.Preconditions.checkArgument; import java.io.IOException; import java.util.*; @@ -25,18 +26,18 @@ * @author stamm */ class EnglishDeclension extends ArticledDeclension { - private static final Logger logger = Logger.getLogger(EnglishDeclension.class.getName()); + private static final Logger logger = Logger.getLogger(EnglishDeclension.class.getName()); - public EnglishDeclension(HumanLanguage language) { - super(language); - assert language.getLocale().getLanguage().equals("en") : "Initializing a language that isn't english"; - } + public EnglishDeclension(HumanLanguage language) { + super(language); + checkArgument(language.getLocale().getLanguage().equals("en"), "Initializing a language that isn't english"); + } /** * The english articles are distinguished by whether the next noun starts with a vowel * sound or not (although the, unlike a/an is spelled the same). */ - public static enum EnglishArticleForm implements ArticleForm { + public enum EnglishArticleForm implements ArticleForm { SINGULAR(LanguageNumber.SINGULAR, LanguageStartsWith.CONSONANT), SINGULAR_V(LanguageNumber.SINGULAR, LanguageStartsWith.VOWEL), PLURAL(LanguageNumber.PLURAL, LanguageStartsWith.CONSONANT) @@ -59,17 +60,17 @@ static EnglishArticleForm getForm(ModifierForm form) { (form.getStartsWith() == LanguageStartsWith.VOWEL ? SINGULAR_V : SINGULAR) : PLURAL; } - @Override - public String getKey() { - return getNumber().getDbValue() + "-" + getStartsWith().getDbValue(); - } - - @Override - public void appendJsFormReplacement(Appendable a, String termFormVar, String genderVar, String startsWithVar) - throws IOException { - // The only variant is in the signular, so we don't want to screw up "the" - a.append(termFormVar+".charAt(0)=='"+LanguageNumber.PLURAL.getDbValue()+"'?"+termFormVar+":'"+LanguageNumber.SINGULAR.getDbValue()+"-'+"+startsWithVar); - } + @Override + public String getKey() { + return getNumber().getDbValue() + "-" + getStartsWith().getDbValue(); + } + + @Override + public void appendJsFormReplacement(Appendable a, String termFormVar, String genderVar, String startsWithVar) + throws IOException { + // The only variant is in the signular, so we don't want to screw up "the" + a.append(termFormVar+".charAt(0)=='"+LanguageNumber.PLURAL.getDbValue()+"'?"+termFormVar+":'"+LanguageNumber.SINGULAR.getDbValue()+"-'+"+startsWithVar); + } } /** diff --git a/src/main/java/com/force/i18n/grammar/impl/HebrewDeclension.java b/src/main/java/com/force/i18n/grammar/impl/HebrewDeclension.java index 4a20ddc..c90b214 100644 --- a/src/main/java/com/force/i18n/grammar/impl/HebrewDeclension.java +++ b/src/main/java/com/force/i18n/grammar/impl/HebrewDeclension.java @@ -34,7 +34,7 @@ public HebrewDeclension(HumanLanguage language) { private static final Logger logger = Logger.getLogger(HebrewDeclension.class.getName()); - public static enum HebrewNounForm implements NounForm { + public enum HebrewNounForm implements NounForm { SINGULAR(LanguageNumber.SINGULAR, LanguageArticle.ZERO), PLURAL(LanguageNumber.PLURAL, LanguageArticle.ZERO), SINGULAR_DEF(LanguageNumber.SINGULAR, LanguageArticle.DEFINITE), @@ -61,7 +61,7 @@ public String getKey() { /** * Adjective form for languages that don't care about "starts with" */ - public static enum HebrewModifierForm implements AdjectiveForm { + public enum HebrewModifierForm implements AdjectiveForm { SINGULAR_MASCULINE(LanguageNumber.SINGULAR, LanguageGender.MASCULINE), SINGULAR_FEMININE(LanguageNumber.SINGULAR, LanguageGender.FEMININE), PLURAL_MASCULINE(LanguageNumber.PLURAL, LanguageGender.MASCULINE), diff --git a/src/main/java/com/force/i18n/grammar/impl/HindiUrduDeclension.java b/src/main/java/com/force/i18n/grammar/impl/HindiUrduDeclension.java index b817d05..6e32375 100644 --- a/src/main/java/com/force/i18n/grammar/impl/HindiUrduDeclension.java +++ b/src/main/java/com/force/i18n/grammar/impl/HindiUrduDeclension.java @@ -43,7 +43,7 @@ class HindiUrduDeclension extends AbstractLanguageDeclension { /** * Adjective form for languages that don't care about "starts with" */ - public static enum HindiUrduModifierForm implements AdjectiveForm { + public enum HindiUrduModifierForm implements AdjectiveForm { SINGULAR_MASCULINE(LanguageNumber.SINGULAR, LanguageGender.MASCULINE, DIRECT_CASE), SINGULAR_FEMININE(LanguageNumber.SINGULAR, LanguageGender.FEMININE, DIRECT_CASE), PLURAL_MASCULINE(LanguageNumber.PLURAL, LanguageGender.MASCULINE, DIRECT_CASE), @@ -80,7 +80,7 @@ public void appendJsFormReplacement(Appendable a, String termFormVar, String gen } } - public static enum HindiUrduNounForm implements NounForm { + public enum HindiUrduNounForm implements NounForm { SINGULAR(LanguageNumber.SINGULAR, DIRECT_CASE), SINGULAR_OBL(LanguageNumber.SINGULAR, OBLIQUE_CASE), PLURAL(LanguageNumber.PLURAL, DIRECT_CASE), diff --git a/src/main/java/com/force/i18n/grammar/impl/MalayoPolynesianDeclension.java b/src/main/java/com/force/i18n/grammar/impl/MalayoPolynesianDeclension.java index 47a6179..e3f29fb 100644 --- a/src/main/java/com/force/i18n/grammar/impl/MalayoPolynesianDeclension.java +++ b/src/main/java/com/force/i18n/grammar/impl/MalayoPolynesianDeclension.java @@ -27,7 +27,7 @@ * @author stamm */ class MalayoPolynesianDeclension extends AbstractLanguageDeclension { - // All the forms you can request + // All the forms you can request static final List ALL_FORMS = ImmutableList.copyOf(EnumSet.allOf(PluralNounForm.class)); // All the forms you can set for "other" forms static final Set OTHER_FORMS = EnumSet.of(PluralNounForm.SINGULAR); @@ -35,8 +35,8 @@ class MalayoPolynesianDeclension extends AbstractLanguageDeclension { static final List ADJECTIVE_FORMS = Collections.singletonList(SimpleModifierForm.SINGULAR); public MalayoPolynesianDeclension(HumanLanguage language) { - super(language); - } + super(language); + } @Override public List< ? extends NounForm> getAllNounForms() { @@ -100,15 +100,14 @@ public Noun createNoun(String name, String pluralAlias, NounType type, String en static class HawaiianDeclension extends ArticledDeclension { public HawaiianDeclension(HumanLanguage language) { - super(language); - } + super(language); + } /** * The hawaiian articles are distinguished by whether the next noun starts with k,e,a,o, * and some changes for starts with ke vs ka. - * */ - public static enum HawaiianArticleForm implements ArticleForm { + public enum HawaiianArticleForm implements ArticleForm { KA(LanguageNumber.SINGULAR, LanguageStartsWith.CONSONANT), KE(LanguageNumber.SINGULAR, LanguageStartsWith.SPECIAL), NA(LanguageNumber.PLURAL, LanguageStartsWith.CONSONANT) @@ -131,16 +130,16 @@ static HawaiianArticleForm getForm(ModifierForm form) { (form.getStartsWith() == LanguageStartsWith.SPECIAL ? KE : KA) : NA; } - @Override - public String getKey() { - return getNumber().getDbValue() + "-" + getStartsWith().getDbValue(); - } - - @Override - public void appendJsFormReplacement(Appendable a, String termFormVar, String genderVar, String startsWithVar) - throws IOException { - a.append(termFormVar+".charAt(0)=='"+LanguageNumber.PLURAL.getDbValue()+"'?"+termFormVar+":'"+LanguageNumber.SINGULAR.getDbValue()+"-'+"+startsWithVar); - } + @Override + public String getKey() { + return getNumber().getDbValue() + "-" + getStartsWith().getDbValue(); + } + + @Override + public void appendJsFormReplacement(Appendable a, String termFormVar, String genderVar, String startsWithVar) + throws IOException { + a.append(termFormVar+".charAt(0)=='"+LanguageNumber.PLURAL.getDbValue()+"'?"+termFormVar+":'"+LanguageNumber.SINGULAR.getDbValue()+"-'+"+startsWithVar); + } } /** diff --git a/src/main/java/com/force/i18n/grammar/impl/UnsupportedLanguageDeclension.java b/src/main/java/com/force/i18n/grammar/impl/UnsupportedLanguageDeclension.java index 7f0b8d1..8a7d106 100644 --- a/src/main/java/com/force/i18n/grammar/impl/UnsupportedLanguageDeclension.java +++ b/src/main/java/com/force/i18n/grammar/impl/UnsupportedLanguageDeclension.java @@ -24,7 +24,7 @@ * @author stamm */ abstract class UnsupportedLanguageDeclension extends ArticledDeclension { - // All the forms you can request + // All the forms you can request static final List ALL_FORMS = ImmutableList.copyOf(EnumSet.allOf(PluralNounForm.class)); // All the forms you can set for "other" forms static final Set OTHER_FORMS = EnumSet.of(SimpleNounForm.SINGULAR); @@ -33,8 +33,8 @@ abstract class UnsupportedLanguageDeclension extends ArticledDeclension { static final List ARTICLE_FORMS = Collections.singletonList(SimpleModifierForm.SINGULAR); public UnsupportedLanguageDeclension(HumanLanguage language) { - super(language); - } + super(language); + } @Override public List< ? extends NounForm> getAllNounForms() { @@ -122,10 +122,10 @@ protected String getDefaultArticleString(ArticleForm form, LanguageArticle artic */ static class CelticDeclension extends UnsupportedLanguageDeclension { public CelticDeclension(HumanLanguage language) { - super(language); - } + super(language); + } - @Override + @Override public boolean hasGender() { return true; } @@ -153,7 +153,8 @@ public IrishDeclension(HumanLanguage language) { } static final List GA_ALL_FORMS = ImmutableList.copyOf(EnumSet.allOf(IrishNounForm.class)); - public static enum IrishNounForm implements NounForm { + + public enum IrishNounForm implements NounForm { SINGULAR(LanguageNumber.SINGULAR, LanguageCase.NOMINATIVE), SINGULAR_GEN(LanguageNumber.SINGULAR, LanguageCase.GENITIVE), PLURAL(LanguageNumber.PLURAL, LanguageCase.NOMINATIVE), @@ -400,7 +401,8 @@ public PersianDeclension(HumanLanguage language) { static final List FA_ALL_FORMS = ImmutableList.copyOf(EnumSet.allOf(PersianNounForm.class)); static final List FA_SING_FORMS = ImmutableList.of(PersianNounForm.SINGULAR); - public static enum PersianNounForm implements NounForm { + + public enum PersianNounForm implements NounForm { SINGULAR(LanguageNumber.SINGULAR, LanguageCase.NOMINATIVE), SINGULAR_ACC(LanguageNumber.SINGULAR, LanguageCase.ACCUSATIVE), PLURAL(LanguageNumber.PLURAL, LanguageCase.NOMINATIVE), diff --git a/src/main/java/com/force/i18n/grammar/parser/AdjectiveRefTag.java b/src/main/java/com/force/i18n/grammar/parser/AdjectiveRefTag.java index ad03d03..c0f948f 100644 --- a/src/main/java/com/force/i18n/grammar/parser/AdjectiveRefTag.java +++ b/src/main/java/com/force/i18n/grammar/parser/AdjectiveRefTag.java @@ -19,7 +19,7 @@ class AdjectiveRefTag extends ModifierRefTag { private static final long serialVersionUID = 173630704208474804L; // Keep the size of serialized maps down to a minimum by reusing tags. - protected static final ConcurrentUniquefy tagMap = new ConcurrentUniquefy(); + protected static final ConcurrentUniquefy tagMap = new ConcurrentUniquefy<>(); private AdjectiveRefTag(String name, NounRefTag nounTag, TermRefTag nextTerm, boolean isCapital, TermAttributes overrides) { diff --git a/src/main/java/com/force/i18n/grammar/parser/ArticleRefTag.java b/src/main/java/com/force/i18n/grammar/parser/ArticleRefTag.java index 58587f5..b8d54ac 100644 --- a/src/main/java/com/force/i18n/grammar/parser/ArticleRefTag.java +++ b/src/main/java/com/force/i18n/grammar/parser/ArticleRefTag.java @@ -17,8 +17,9 @@ * @author stamm */ class ArticleRefTag extends ModifierRefTag { - private static final long serialVersionUID = 1L; - protected static final ConcurrentUniquefy tagMap = new ConcurrentUniquefy(); + private static final long serialVersionUID = 1L; + protected static final ConcurrentUniquefy tagMap = new ConcurrentUniquefy<>(); + private ArticleRefTag(String name, NounRefTag nounTag, TermRefTag nextTermTag, boolean isCapital, TermAttributes overrides) { super(name, nounTag, nextTermTag, isCapital, overrides); } @@ -49,14 +50,14 @@ protected NounModifier resolveModifier(LanguageDictionary dictionary) { return dictionary.getArticle(getName()); } - @Override + @Override public String toJson(LanguageDictionary dictionary, List list) { - // Fallback labels can have articles, but they should be ignored - if (!dictionary.getDeclension().hasArticle()) { - return "\"\""; - } - return super.toJson(dictionary, list); - } + // Fallback labels can have articles, but they should be ignored + if (!dictionary.getDeclension().hasArticle()) { + return "\"\""; + } + return super.toJson(dictionary, list); + } @Override ArticleRefTag unique() { diff --git a/src/main/java/com/force/i18n/grammar/parser/CounterRefTag.java b/src/main/java/com/force/i18n/grammar/parser/CounterRefTag.java index 6539f55..90d3c1a 100644 --- a/src/main/java/com/force/i18n/grammar/parser/CounterRefTag.java +++ b/src/main/java/com/force/i18n/grammar/parser/CounterRefTag.java @@ -1,11 +1,13 @@ -/* +/* * Copyright (c) 2019, salesforce.com, inc. * All rights reserved. - * Licensed under the BSD 3-Clause license. + * Licensed under the BSD 3-Clause license. * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause */ package com.force.i18n.grammar.parser; +import static java.util.Objects.requireNonNull; + import java.util.*; import com.force.i18n.Renameable; @@ -67,7 +69,8 @@ public String toJson(LanguageDictionary dictionary, List list) { associatedNounIndex = i; } } - return "{\"t\":\"c\",\"an\":"+associatedNounIndex.intValue()+"}"; + requireNonNull(associatedNounIndex); + return "{\"t\":\"c\",\"an\":" + associatedNounIndex.intValue() + "}"; } @Override diff --git a/src/main/java/com/force/i18n/grammar/parser/GenderRefTag.java b/src/main/java/com/force/i18n/grammar/parser/GenderRefTag.java index fa06764..2dd683e 100644 --- a/src/main/java/com/force/i18n/grammar/parser/GenderRefTag.java +++ b/src/main/java/com/force/i18n/grammar/parser/GenderRefTag.java @@ -1,11 +1,13 @@ -/* +/* * Copyright (c) 2019, salesforce.com, inc. * All rights reserved. - * Licensed under the BSD 3-Clause license. + * Licensed under the BSD 3-Clause license. * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause */ package com.force.i18n.grammar.parser; +import static java.util.Objects.requireNonNull; + import java.util.*; import com.force.i18n.Renameable; @@ -43,30 +45,31 @@ public int hashCode() { @Override public boolean equals(Object obj) { - return super.equals(obj) + return super.equals(obj) && Objects.equals(when, ((GenderRefTag)obj).when) && Objects.equals(ifDefault, ((GenderRefTag)obj).ifDefault); } - Object getData(LanguageDictionary dictionary, Renameable[] entities) { - if (getAssociatedNounRef() == null) { - return ifDefault; - } - Noun n = getAssociatedNounRef().resolveNoun(dictionary, entities); - if (n == null) { - return ifDefault; - } - Object val = when.get(n.getGender()); - return val != null ? val : ifDefault; - } + Object getData(LanguageDictionary dictionary, Renameable[] entities) { + if (getAssociatedNounRef() == null) { + return ifDefault; + } + Noun n = getAssociatedNounRef().resolveNoun(dictionary, entities); + if (n == null) { + return ifDefault; + } + Object val = when.get(n.getGender()); + return val != null ? val : ifDefault; + } @Override public String toString(LanguageDictionary formatter, boolean overrideForms, Object[] vals, Renameable... entities) { - Object data = getData(formatter, entities); - if (data == null) { - return ""; - } - return formatter.format(getData(formatter, entities), entities, vals, overrideForms, false); // Don't format for message format, since it'll do it again later. + Object data = getData(formatter, entities); + if (data == null) { + return ""; + } + + return formatter.format(getData(formatter, entities), entities, vals, overrideForms, false); } @Override @@ -74,27 +77,31 @@ public GenderRefTag cloneWithResolvedNounTag(NounRefTag nounTag) { return new GenderRefTag(nounTag, this.when, this.ifDefault); } - @Override - public Set getTermsInUse(LanguageDictionary dictionary) { - Set whens = RefTag.getTermsFromLabels(dictionary, when.values()); - return ifDefault != null ? Sets.union(whens, RefTag.getTermsFromLabelValue(dictionary, ifDefault)) : whens; - } - - @Override - public String toJson(LanguageDictionary dictionary, List list) { - // Get associated noun ref - Integer associatedNounIndex = null; - for (int i = 0; i < list.size(); i++) { - Object term = list.get(i); - if (term != null && term.equals(getAssociatedNounRef())) { - associatedNounIndex = i; - } - } - - StringBuilder def = new StringBuilder(); - RefTag.appendJsonLabelValueNoThrow(dictionary, def, ifDefault, null); - StringBuilder forms = new StringBuilder(); - when.entrySet().stream().forEach(e->{forms.append("\""+e.getKey().getDbValue()+"\":");RefTag.appendJsonLabelValueNoThrow(dictionary, forms, e.getValue(), null);}); - return "{\"t\":\"g\",\"an\":"+associatedNounIndex.intValue()+",\"def\":"+def.toString()+",\"v\":{"+forms.toString()+"}}"; - } + @Override + public Set getTermsInUse(LanguageDictionary dictionary) { + Set whens = RefTag.getTermsFromLabels(dictionary, when.values()); + return ifDefault != null ? Sets.union(whens, RefTag.getTermsFromLabelValue(dictionary, ifDefault)) : whens; + } + + @Override + public String toJson(LanguageDictionary dictionary, List list) { + // Get associated noun ref + Integer associatedNounIndex = null; + for (int i = 0; i < list.size(); i++) { + Object term = list.get(i); + if (term != null && term.equals(getAssociatedNounRef())) { + associatedNounIndex = i; + } + } + requireNonNull(associatedNounIndex); + + StringBuilder def = new StringBuilder(); + RefTag.appendJsonLabelValueNoThrow(dictionary, def, ifDefault, null); + StringBuilder forms = new StringBuilder(); + when.entrySet().stream().forEach(e -> { + forms.append("\"" + e.getKey().getDbValue() + "\":"); + RefTag.appendJsonLabelValueNoThrow(dictionary, forms, e.getValue(), null); + }); + return "{\"t\":\"g\",\"an\":" + associatedNounIndex.intValue() + ",\"def\":" + def.toString() + ",\"v\":{" + forms.toString() + "}}"; + } } diff --git a/src/main/java/com/force/i18n/grammar/parser/GrammaticalLabelFileParser.java b/src/main/java/com/force/i18n/grammar/parser/GrammaticalLabelFileParser.java index 16d078b..cfe0054 100644 --- a/src/main/java/com/force/i18n/grammar/parser/GrammaticalLabelFileParser.java +++ b/src/main/java/com/force/i18n/grammar/parser/GrammaticalLabelFileParser.java @@ -434,12 +434,12 @@ private Object resolveAlias(GrammaticalLabelSet labelSet, GrammaticalLabelSetImp } else { // recursive reference. Keep tracking down Set localRefSet = refSet; - if (refSet == null) { + if (localRefSet == null) { // means this is the top level (or maybe middle) of alias chain localRefSet = new HashSet<>(); } else { // recursively called from alias chain. add to the chain list - refSet.add(ap.getKey()); + localRefSet.add(ap.getKey()); } retValue = resolveAlias(labelSet, writeSet, t, localRefSet); @@ -454,7 +454,6 @@ private Object resolveAlias(GrammaticalLabelSet labelSet, GrammaticalLabelSetImp } } } - } writeSet.put(ap.srcSection, ap.srcParam, (retValue == null ? "" : retValue)); diff --git a/src/main/java/com/force/i18n/grammar/parser/ModifierRefTag.java b/src/main/java/com/force/i18n/grammar/parser/ModifierRefTag.java index f425c79..eba2c97 100644 --- a/src/main/java/com/force/i18n/grammar/parser/ModifierRefTag.java +++ b/src/main/java/com/force/i18n/grammar/parser/ModifierRefTag.java @@ -1,13 +1,16 @@ -/* +/* * Copyright (c) 2017, salesforce.com, inc. * All rights reserved. - * Licensed under the BSD 3-Clause license. + * Licensed under the BSD 3-Clause license. * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause */ package com.force.i18n.grammar.parser; +import static java.util.Objects.requireNonNull; + import java.util.List; +import java.util.Objects; import java.util.logging.Logger; import com.force.i18n.Renameable; @@ -19,11 +22,8 @@ * @author yoikawa,stamm */ abstract class ModifierRefTag extends TermRefTag { - /** - * - */ - private static final long serialVersionUID = 1L; - private final boolean isCapital; + private static final long serialVersionUID = 1L; + private final boolean isCapital; private final NounRefTag associatedNounRef; // entity that this modifier associated with. private final TermRefTag nextTermRef; // The term that comes after this one private final TermAttributes overrides; // TODO: Overrides *could* be completely unnecessary @@ -104,8 +104,7 @@ public String toString(LanguageDictionary formatter, boolean overrideForms, Obje logger.fine("Missing modifier " + getName() + " for " + formatter.getLanguage()); return ""; //This is the "legacy" behavior, needed for LabelParserComparisonTest. It should be modifier.getDefaultValue(); } - - assert modifier != null: "Can't find modifier '" + getName() + "'"; + requireNonNull(modifier, () -> "Can't find modifier '" + getName() + "'"); if (getAssociatedNounRef() == null) { return ""; // This is the "legacy" behavior, needed for LabelParserComparisonTest. It should be modifier.getDefaultValue(); @@ -129,7 +128,7 @@ public String toString(LanguageDictionary formatter, boolean overrideForms, Obje String s = modifier.getString(adjForm); if (s == null) { - logger.info("INFORMATIONAL: Invalid modifier: trying to access " + adjForm + " for modifier " + getName() + " and not defined for " + formatter.getLanguage().getLocaleString()); + logger.info("INFORMATIONAL: Invalid modifier: trying to access " + adjForm + " for modifier " + getName() + " and not defined for " + formatter.getLanguage().getLocaleString()); return ""; } if (!isCapital) { @@ -151,24 +150,20 @@ public TermRefTag getNextTerm() { return nextTermRef; } - @Override public int hashCode() { return hashCode; } - @Override protected boolean equalsValue(TermRefTag obj) { ModifierRefTag otherTag = (ModifierRefTag) obj; return this.isCapital == otherTag.isCapital - && (this.associatedNounRef == null ? otherTag.associatedNounRef == null : this.associatedNounRef.equals(otherTag.associatedNounRef)) - && (this.nextTermRef == null ? otherTag.nextTermRef == null : this.nextTermRef.equals(otherTag.nextTermRef)) - && this.overrides.equals(otherTag.overrides); + && Objects.equals(this.associatedNounRef, otherTag.associatedNounRef) + && Objects.equals(this.nextTermRef, otherTag.nextTermRef) + && Objects.equals(this.overrides, otherTag.overrides); } - - public ModifierRefTag fixupModifier(NounRefTag nounTag, TermRefTag nextTermRef) { return fixupModifier(nounTag, nextTermRef, null); } @@ -185,35 +180,35 @@ public ModifierRefTag fixupModifier(NounRefTag nounTag, TermRefTag nextTermRef, return this; } - @Override - String extraJson(LanguageDictionary dictionary, List list) { + @Override + String extraJson(LanguageDictionary dictionary, List list) { if (list == null || list.isEmpty()) return ""; - Integer associatedNounIndex = null; - Integer nextTermIndex = null; - for (int i = 0; i < list.size(); i++) { - Object term = list.get(i); - if (term != null && term.equals(this.associatedNounRef)) { - associatedNounIndex = i; - } - - if (term != null) { - if (term.equals(this.nextTermRef)) { - nextTermIndex = i; - // Since the noun refs have been resolved for modifiers, the associatedNounRef makes the "equalsValue" value false - // But, since the noun has been resolved, we can use that to compare, along with the name of the modifier - } else if (this.nextTermRef instanceof ModifierRefTag && term instanceof ModifierRefTag - && ((ModifierRefTag)this.nextTermRef).getName().equals(((ModifierRefTag)term).getName()) - && (((ModifierRefTag)term).getAssociatedNounRef().equals(this.associatedNounRef))) { - nextTermIndex = i; - } - } - } - StringBuilder json = new StringBuilder(); - if (associatedNounIndex != null) json.append(",\"an\":").append(associatedNounIndex.intValue()); - if (nextTermIndex != null) json.append(",\"nt\":").append(nextTermIndex.intValue()); - return json.toString(); - } - - abstract ModifierRefTag getNewModifierRef(NounRefTag entity, TermRefTag nextTermRef, LanguageArticle override); + Integer associatedNounIndex = null; + Integer nextTermIndex = null; + for (int i = 0; i < list.size(); i++) { + Object term = list.get(i); + if (term != null && term.equals(this.associatedNounRef)) { + associatedNounIndex = i; + } + + if (term != null) { + if (term.equals(this.nextTermRef)) { + nextTermIndex = i; + // Since the noun refs have been resolved for modifiers, the associatedNounRef makes the "equalsValue" value false + // But, since the noun has been resolved, we can use that to compare, along with the name of the modifier + } else if (this.nextTermRef instanceof ModifierRefTag && term instanceof ModifierRefTag + && ((ModifierRefTag)this.nextTermRef).getName().equals(((ModifierRefTag)term).getName()) + && (((ModifierRefTag)term).getAssociatedNounRef().equals(this.associatedNounRef))) { + nextTermIndex = i; + } + } + } + StringBuilder json = new StringBuilder(); + if (associatedNounIndex != null) json.append(",\"an\":").append(associatedNounIndex.intValue()); + if (nextTermIndex != null) json.append(",\"nt\":").append(nextTermIndex.intValue()); + return json.toString(); + } + + abstract ModifierRefTag getNewModifierRef(NounRefTag entity, TermRefTag nextTermRef, LanguageArticle override); } diff --git a/src/main/java/com/force/i18n/grammar/parser/NounRefTag.java b/src/main/java/com/force/i18n/grammar/parser/NounRefTag.java index 693ac9f..c6dd314 100644 --- a/src/main/java/com/force/i18n/grammar/parser/NounRefTag.java +++ b/src/main/java/com/force/i18n/grammar/parser/NounRefTag.java @@ -8,6 +8,8 @@ package com.force.i18n.grammar.parser; +import static com.google.common.base.Preconditions.checkState; + import java.util.List; import java.util.Objects; import java.util.logging.Level; @@ -30,7 +32,7 @@ class NounRefTag extends TermRefTag { private static final Logger logger = Logger.getLogger(NounRefTag.class.getName()); // map for any LabelTag type to reuse. This must be static so all language can share the same entity - protected static final ConcurrentUniquefy tagMap = new ConcurrentUniquefy(); + protected static final ConcurrentUniquefy tagMap = new ConcurrentUniquefy<>(); private final NounForm form; private final boolean isCapital; // capital case @@ -191,7 +193,7 @@ String extraJson(LanguageDictionary dictionary, List terms) { } } - @Override + @Override protected boolean equalsValue(TermRefTag obj) { return Objects.equals(this.form, ((NounRefTag)obj).form) && this.index == ((NounRefTag)obj).index @@ -211,10 +213,10 @@ Noun resolveNoun(LanguageDictionary formatter, Renameable[] entities) { Renameable ei = entities[getReference()]; n = formatter.getDynamicNoun(getName(), ei, true, false); } else { - assert !isDynamic() || I18nJavaUtil.isDebugging() - : "Only allowed in label debug mode, mode: " + I18nJavaUtil.isDebugging() - + " isDynamic: " + isDynamic() + " entities: " + entities.length - + " reference: " + getReference(); + checkState(!isDynamic() || I18nJavaUtil.isDebugging(), + "Only allowed in label debug mode, mode: %s isDynamic: %s entities: %s reference: %s", + I18nJavaUtil.isDebugging(), isDynamic(), + entities == null ? "null" : Integer.toString(entities.length), getReference()); n = formatter.getNoun(getName(), true); } return n; diff --git a/src/main/java/com/force/i18n/grammar/parser/PluralRefTag.java b/src/main/java/com/force/i18n/grammar/parser/PluralRefTag.java index 0ce5ac0..3527e39 100644 --- a/src/main/java/com/force/i18n/grammar/parser/PluralRefTag.java +++ b/src/main/java/com/force/i18n/grammar/parser/PluralRefTag.java @@ -27,20 +27,20 @@ public class PluralRefTag extends RefTag { private static final long serialVersionUID = -1L; - private final int val; - private final Map when; - private final Object ifDefault; + private final int val; + private final Map when; + private final Object ifDefault; - public PluralRefTag(int val, Map when, Object ifDefault) { - this.val = val; - this.when = when; - this.ifDefault = ifDefault != null ? ifDefault : ""; - } + public PluralRefTag(int val, Map when, Object ifDefault) { + this.val = val; + this.when = when; + this.ifDefault = ifDefault != null ? ifDefault : ""; + } - @Override - public String getKey() { - return "Plural" + val + when; - } + @Override + public String getKey() { + return "Plural" + val + when; + } @Override public int hashCode() { @@ -60,49 +60,55 @@ public boolean equals(Object obj) { && Objects.equals(ifDefault, ((PluralRefTag)obj).ifDefault); } - Object getData(LanguageDictionary dictionary, Object[] vals) { - if (vals == null || vals.length <= val) { - return ifDefault; - } - Object toTest = vals[val]; - Number num; - if (toTest == null) { - return ifDefault; - } - if (toTest instanceof Number) { - num = (Number) toTest; - } else { - try { - num = Double.parseDouble(String.valueOf(toTest)); - } catch (NumberFormatException ex) { - return ifDefault; - } - } - // Zero isn't returned for plural rules in CLDR, but you might want it anyway. - PluralCategory category = (num.doubleValue() == 0.0 && when.containsKey(PluralCategory.ZERO)) ? PluralCategory.ZERO : dictionary.getDeclension().getPluralRules().getPluralCategory(num); - Object val = when.get(category); - return val != null ? val : ifDefault; - } + Object getData(LanguageDictionary dictionary, Object[] vals) { + if (vals == null || vals.length <= val) { + return ifDefault; + } + Object toTest = vals[val]; + Number num; + if (toTest == null) { + return ifDefault; + } + if (toTest instanceof Number) { + num = (Number) toTest; + } else { + try { + num = Double.parseDouble(String.valueOf(toTest)); + } catch (NumberFormatException ex) { + return ifDefault; + } + } + // Zero isn't returned for plural rules in CLDR, but you might want it anyway. + PluralCategory category = (num.doubleValue() == 0.0 && when.containsKey(PluralCategory.ZERO)) + ? PluralCategory.ZERO + : dictionary.getDeclension().getPluralRules().getPluralCategory(num); + Object val = when.get(category); + return val != null ? val : ifDefault; + } - @Override - public String toString(LanguageDictionary dictionary, boolean overrideForms, Object[] vals, - Renameable... entities) { - return dictionary.format(getData(dictionary, vals), entities, vals, overrideForms, false); // Don't format for message format, since it'll do it again later. - } + @Override + public String toString(LanguageDictionary dictionary, boolean overrideForms, Object[] vals, + Renameable... entities) { + // Don't format for message format, since it'll do it again later. + return dictionary.format(getData(dictionary, vals), entities, vals, overrideForms, false); + } - @Override - public Set getTermsInUse(LanguageDictionary dictionary) { - Set whens = RefTag.getTermsFromLabels(dictionary, when.values()); - return ifDefault != null ? Sets.union(whens, RefTag.getTermsFromLabelValue(dictionary, ifDefault)) : whens; - } + @Override + public Set getTermsInUse(LanguageDictionary dictionary) { + Set whens = RefTag.getTermsFromLabels(dictionary, when.values()); + return ifDefault != null ? Sets.union(whens, RefTag.getTermsFromLabelValue(dictionary, ifDefault)) : whens; + } - @Override - public String toJson(LanguageDictionary dictionary, List list) { - StringBuilder def = new StringBuilder(); - RefTag.appendJsonLabelValueNoThrow(dictionary, def, ifDefault, null); - StringBuilder forms = new StringBuilder(); - when.entrySet().stream().forEach(e->{forms.append(",\""+e.getKey().getCldrCategory()+"\":");RefTag.appendJsonLabelValueNoThrow(dictionary, forms, e.getValue(), null);}); - String formsVal = forms.length() > 2 ? forms.substring(1) : ""; - return "{\"t\":\"p\",\"i\":"+val+",\"def\":"+def.toString()+",\"v\":{"+formsVal+"}}"; - } + @Override + public String toJson(LanguageDictionary dictionary, List list) { + StringBuilder def = new StringBuilder(); + RefTag.appendJsonLabelValueNoThrow(dictionary, def, ifDefault, null); + StringBuilder forms = new StringBuilder(); + when.entrySet().stream().forEach(e -> { + forms.append(",\"" + e.getKey().getCldrCategory() + "\":"); + RefTag.appendJsonLabelValueNoThrow(dictionary, forms, e.getValue(), null); + }); + String formsVal = forms.length() > 2 ? forms.substring(1) : ""; + return "{\"t\":\"p\",\"i\":" + val + ",\"def\":" + def.toString() + ",\"v\":{" + formsVal + "}}"; + } } diff --git a/src/main/java/com/force/i18n/grammar/parser/RefTag.java b/src/main/java/com/force/i18n/grammar/parser/RefTag.java index 1f4bc93..637ba88 100644 --- a/src/main/java/com/force/i18n/grammar/parser/RefTag.java +++ b/src/main/java/com/force/i18n/grammar/parser/RefTag.java @@ -24,7 +24,7 @@ public abstract class RefTag implements Serializable { private static final long serialVersionUID = 1L; - public RefTag() { + public RefTag() { } /** @@ -114,7 +114,7 @@ public static Set getTermsFromLabels(LanguageDictionary diction /** * Convert a component of a label to a String, either it's a string or a refTag - * @param dictionary the current dictionary of nouns. + * @param dictionary the current dictionary of nouns. * @param o the label value * @param list the list of *all* of the labels to look up, to make sure you get the right reference * @return o as a json value diff --git a/src/main/java/com/force/i18n/grammar/parser/TermAttributes.java b/src/main/java/com/force/i18n/grammar/parser/TermAttributes.java index 1b9e253..d997f48 100644 --- a/src/main/java/com/force/i18n/grammar/parser/TermAttributes.java +++ b/src/main/java/com/force/i18n/grammar/parser/TermAttributes.java @@ -1,7 +1,7 @@ -/* +/* * Copyright (c) 2017, salesforce.com, inc. * All rights reserved. - * Licensed under the BSD 3-Clause license. + * Licensed under the BSD 3-Clause license. * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause */ @@ -99,10 +99,10 @@ public TermAttributes(LanguageDeclension declension, Attributes atts, boolean us if (plural != null) _number = LanguageNumber.fromLabelValue(plural); LanguageStartsWith st = LanguageStartsWith.fromDbValue(atts.getValue(ENDS)); if (st != null) { - _startsWith = st; + _startsWith = st; } else { - st = LanguageStartsWith.fromDbValue(atts.getValue(STARTS)); - if (st != null) _startsWith = st; + st = LanguageStartsWith.fromDbValue(atts.getValue(STARTS)); + if (st != null) _startsWith = st; } LanguageGender g = LanguageGender.fromLabelValue(atts.getValue(GENDER)); if (g != null) _gender = g; @@ -275,20 +275,20 @@ public boolean equals(Object obj) { public String toString() { return "TermAttrs:"+toNullStr(getNumber())+":"+toNullStr(this.getGender())+":"+toNullStr(this.getCase())+":"+toNullStr(this.getStartsWith())+":"+toNullStr(this.getArticle())+":"+toNullStr(this.getPossessive()); } - + public String toJson() { - StringBuilder sw = new StringBuilder(); - sw.append("{"); - if (this.caseType != null) sw.append("\""+LanguageCase.JSON_ATTR_NAME+"\":\"").append(this.caseType.getDbValue()).append("\","); - if (this.article != null) sw.append("\""+LanguageArticle.JSON_ATTR_NAME+"\":\"").append(this.article.getDbValue()).append("\","); - if (this.gender != null) sw.append("\""+LanguageGender.JSON_ATTR_NAME+"\":\"").append(this.gender.getDbValue()).append("\","); - if (this.number != null) sw.append("\""+LanguageNumber.JSON_ATTR_NAME+"\":\"").append(this.number.getDbValue()).append("\","); - if (this.possessive != null) sw.append("\""+LanguagePossessive.JSON_ATTR_NAME+"\":\"").append(this.possessive.getDbValue()).append("\","); - if (this.startsWith != null) sw.append("\""+LanguageStartsWith.JSON_ATTR_NAME+"\":\"").append(this.startsWith.getDbValue()).append("\","); - if (this.position != null) sw.append("\""+LanguagePosition.JSON_ATTR_NAME+"\":\"").append(this.position.getDbValue()).append("\","); - if (sw.length()>1) sw.setLength(sw.length() - 1); // Get rid of the last comma - sw.append("}"); - return sw.toString(); + StringBuilder sw = new StringBuilder(); + sw.append("{"); + if (this.caseType != null) sw.append("\""+LanguageCase.JSON_ATTR_NAME+"\":\"").append(this.caseType.getDbValue()).append("\","); + if (this.article != null) sw.append("\""+LanguageArticle.JSON_ATTR_NAME+"\":\"").append(this.article.getDbValue()).append("\","); + if (this.gender != null) sw.append("\""+LanguageGender.JSON_ATTR_NAME+"\":\"").append(this.gender.getDbValue()).append("\","); + if (this.number != null) sw.append("\""+LanguageNumber.JSON_ATTR_NAME+"\":\"").append(this.number.getDbValue()).append("\","); + if (this.possessive != null) sw.append("\""+LanguagePossessive.JSON_ATTR_NAME+"\":\"").append(this.possessive.getDbValue()).append("\","); + if (this.startsWith != null) sw.append("\""+LanguageStartsWith.JSON_ATTR_NAME+"\":\"").append(this.startsWith.getDbValue()).append("\","); + if (this.position != null) sw.append("\""+LanguagePosition.JSON_ATTR_NAME+"\":\"").append(this.position.getDbValue()).append("\","); + if (sw.length()>1) sw.setLength(sw.length() - 1); // Get rid of the last comma + sw.append("}"); + return sw.toString(); } private static String toNullStr(Object o) { diff --git a/src/main/java/com/force/i18n/grammar/parser/TermRefTag.java b/src/main/java/com/force/i18n/grammar/parser/TermRefTag.java index 9f689ce..cfb6aa7 100644 --- a/src/main/java/com/force/i18n/grammar/parser/TermRefTag.java +++ b/src/main/java/com/force/i18n/grammar/parser/TermRefTag.java @@ -25,9 +25,9 @@ * @author yoikawa */ public abstract class TermRefTag extends RefTag { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - private transient String name; // non-final: see readObject() + private transient String name; // non-final: see readObject() public static final char SEP = '-'; @@ -112,22 +112,22 @@ public String toString() { * @param list the list of the current set of terms being processed (so that for modifiers it can find the associated term by index) */ @Override - public String toJson(LanguageDictionary dictionary, List list) { - // Default implementation uses the key + public String toJson(LanguageDictionary dictionary, List list) { + // Default implementation uses the key return "{\"t\":\"" + getType().getCharId() + "\",\"l\":\"" + getName().toLowerCase() + "\",\"f\":\"" + (getForm(dictionary, true) == null ? "" : getForm(dictionary, true).getKey()) + "\",\"c\":" + isCapital() + extraJson(dictionary, list) + "}"; - } + } - @Override - public Set getTermsInUse(LanguageDictionary dictionary) { - GrammaticalTerm term = dictionary.getTerm(getName()); - //assert term != null : "Reference to invalid term: " + ((TermRefTag)o).getName(); - return (term != null) ? Collections.singleton(term) : Collections.emptySet(); - } + @Override + public Set getTermsInUse(LanguageDictionary dictionary) { + GrammaticalTerm term = dictionary.getTerm(getName()); + //assert term != null : "Reference to invalid term: " + ((TermRefTag)o).getName(); + return (term != null) ? Collections.singleton(term) : Collections.emptySet(); + } - // Extra json for the term - abstract String extraJson(LanguageDictionary dictionary, List list); + // Extra json for the term + abstract String extraJson(LanguageDictionary dictionary, List list); private void writeObject(java.io.ObjectOutputStream s) throws IOException { // Write out the threshold, loadfactor, and any hidden stuff diff --git a/src/main/java/com/force/i18n/settings/MapPropertyFileData.java b/src/main/java/com/force/i18n/settings/MapPropertyFileData.java index 74267d7..7cb104f 100644 --- a/src/main/java/com/force/i18n/settings/MapPropertyFileData.java +++ b/src/main/java/com/force/i18n/settings/MapPropertyFileData.java @@ -1,7 +1,7 @@ -/* +/* * Copyright (c) 2017, salesforce.com, inc. * All rights reserved. - * Licensed under the BSD 3-Clause license. + * Licensed under the BSD 3-Clause license. * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause */ @@ -9,7 +9,6 @@ import static com.force.i18n.commons.util.settings.IniFileUtil.intern; -import java.io.Serializable; import java.util.*; import java.util.Map.Entry; @@ -24,7 +23,7 @@ * @author koliver * @since 146 */ -public class MapPropertyFileData implements PropertyFileData, Serializable { +public class MapPropertyFileData implements PropertyFileData { private static final long serialVersionUID = 1L; protected final Locale locale; diff --git a/src/main/java/com/force/i18n/settings/SharedKeyMapPropertyFileData.java b/src/main/java/com/force/i18n/settings/SharedKeyMapPropertyFileData.java index 73e344a..268a859 100644 --- a/src/main/java/com/force/i18n/settings/SharedKeyMapPropertyFileData.java +++ b/src/main/java/com/force/i18n/settings/SharedKeyMapPropertyFileData.java @@ -1,7 +1,7 @@ -/* +/* * Copyright (c) 2017, salesforce.com, inc. * All rights reserved. - * Licensed under the BSD 3-Clause license. + * Licensed under the BSD 3-Clause license. * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause */ @@ -24,21 +24,18 @@ * * @author koliver */ -public class SharedKeyMapPropertyFileData implements PropertyFileData, Serializable { +public class SharedKeyMapPropertyFileData implements PropertyFileData { - /** - * - */ - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - private static final Logger logger = Logger.getLogger(SharedKeyMapPropertyFileData.class.getName()); + private static final Logger logger = Logger.getLogger(SharedKeyMapPropertyFileData.class.getName()); private static final class SerializableLock implements Serializable { - /** - * - */ - private static final long serialVersionUID = 1L; } + /** + * + */ + private static final long serialVersionUID = 1L; } private final Locale locale; diff --git a/src/test/java/com/force/i18n/LabelDebugTest.java b/src/test/java/com/force/i18n/LabelDebugTest.java index 5cd7d69..c09ecd1 100644 --- a/src/test/java/com/force/i18n/LabelDebugTest.java +++ b/src/test/java/com/force/i18n/LabelDebugTest.java @@ -1,6 +1,10 @@ -/** - * +/* + * Copyright (c) 2024, salesforce.com, inc. + * All rights reserved. + * Licensed under the BSD 3-Clause license. + * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause */ + package com.force.i18n; import java.util.List; @@ -15,81 +19,81 @@ import com.google.common.collect.SetMultimap; /** - * Test Label Debug system, which allows tracking of what labels are displayed, where labels come + * Test Label Debug system, which allows tracking of what labels are displayed, where labels come * from, masking them so that it's easier to see untranslated labels. * @author stamm * @since 1.2.0 */ public class LabelDebugTest extends BaseGrammaticalLabelTest { - /** - * @param name - */ - public LabelDebugTest(String name) { - super(name); - } - + /** + * @param name + */ + public LabelDebugTest(String name) { + super(name); + } + public void testLabelDebug() { - LocalizerProvider oldProvider = LocalizerFactory.get(); - try { - // Set the debug provider to true - LabelDebugProvider.setLabelDebugProviderEnabled(true); + LocalizerProvider oldProvider = LocalizerFactory.get(); + try { + // Set the debug provider to true + LabelDebugProvider.setLabelDebugProviderEnabled(true); LabelDebugProvider debugProvider = LabelDebugProvider.get(); assertFalse(debugProvider.isTrackingLabelUsage()); debugProvider.setLabelHintMode("trace"); debugProvider.setTrackingLabelUsage(true); debugProvider.setLabelHintRequest(true); - - final HumanLanguage ENGLISH_CA = LanguageProviderFactory.get().getLanguage(Locale.CANADA); + + final HumanLanguage ENGLISH_CA = LanguageProviderFactory.get().getLanguage(Locale.CANADA); GrammaticalLabelSetLoader loader = new GrammaticalLabelSetLoader(getDescriptor()); GrammaticalLabelSet set = loader.getSet(ENGLISH_CA); - // Note: LabelHints are done solely through the localizer, not the labelset. + // Note: LabelHints are done solely through the localizer, not the labelset. GrammaticalLocalizer localizer = new GrammaticalLocalizer(Locale.CANADA, Locale.CANADA, null, ENGLISH_CA, set); // You need a default provider factory to call getFilename - LocalizerProvider glf = new GrammaticalLocalizerFactory(GrammaticalLocalizerFactory.getLoader(getDescriptor(), null)); - LocalizerFactory.set(glf); - - assertEquals("click to create a new account now.[#0][#1]", localizer.getLabel("Sample", "click_here_to_create_new_account", "click")); - assertFalse(localizer.labelExists("Sample", "invalid")); - assertFalse(localizer.labelExists("invalid", "invalid")); - try { - localizer.getLabel(new LabelRef("invalid", "invalid", "invalid")); - fail(); - } catch (SettingsSectionNotFoundException ex) {} - assertEquals("__MISSING LABEL__ PropertyFile - val invalid not found in section Sample[#2]", localizer.getLabel(new LabelRef("Sample", "invalid", "invalid"))); - - SetMultimap used = debugProvider.getUsedLabels(); - assertEquals(3, used.size()); - assertTrue(used.containsEntry("Sample", "click_here_to_create_new_account")); - assertTrue(used.containsEntry("invalid", "invalid")); - - List debugs = debugProvider.getLabelDebugs(); - assertEquals(3, debugs.size()); - assertEquals("Sample", debugs.get(0).getSection()); - assertEquals("click_here_to_create_new_account", debugs.get(0).getParameter()); - assertEquals("{0} to create a new account now.", debugs.get(0).getText()); - assertEquals("Sample", debugs.get(1).getSection()); - assertEquals("click_here_to_create_new_account", debugs.get(1).getParameter()); - - assertTrue(debugs.get(1).getStack().contains("com.force.i18n.LabelDebugTest.testLabelDebug")); - - - // The first one is before substitution, the second one is after - Assert.assertNotEquals(debugs.get(0), debugs.get(1)); - Assert.assertNotEquals(debugs.get(0).hashCode(), debugs.get(1).hashCode()); - Assert.assertNotEquals(debugs.get(0).toString(), debugs.get(1).toString()); - - // Now try with mask to visibly see if text leaks through + @SuppressWarnings("deprecation") + LocalizerProvider glf = new GrammaticalLocalizerFactory(GrammaticalLocalizerFactory.getLoader(getDescriptor(), null)); + LocalizerFactory.set(glf); + + assertEquals("click to create a new account now.[#0][#1]", localizer.getLabel("Sample", "click_here_to_create_new_account", "click")); + assertFalse(localizer.labelExists("Sample", "invalid")); + assertFalse(localizer.labelExists("invalid", "invalid")); + try { + localizer.getLabel(new LabelRef("invalid", "invalid", "invalid")); + fail(); + } catch (SettingsSectionNotFoundException ex) {} + assertEquals("__MISSING LABEL__ PropertyFile - val invalid not found in section Sample[#2]", localizer.getLabel(new LabelRef("Sample", "invalid", "invalid"))); + + SetMultimap used = debugProvider.getUsedLabels(); + assertEquals(3, used.size()); + assertTrue(used.containsEntry("Sample", "click_here_to_create_new_account")); + assertTrue(used.containsEntry("invalid", "invalid")); + + List debugs = debugProvider.getLabelDebugs(); + assertEquals(3, debugs.size()); + assertEquals("Sample", debugs.get(0).getSection()); + assertEquals("click_here_to_create_new_account", debugs.get(0).getParameter()); + assertEquals("{0} to create a new account now.", debugs.get(0).getText()); + assertEquals("Sample", debugs.get(1).getSection()); + assertEquals("click_here_to_create_new_account", debugs.get(1).getParameter()); + + assertTrue(debugs.get(1).getStack().contains("com.force.i18n.LabelDebugTest.testLabelDebug")); + + + // The first one is before substitution, the second one is after + Assert.assertNotEquals(debugs.get(0), debugs.get(1)); + Assert.assertNotEquals(debugs.get(0).hashCode(), debugs.get(1).hashCode()); + Assert.assertNotEquals(debugs.get(0).toString(), debugs.get(1).toString()); + + // Now try with mask to visibly see if text leaks through debugProvider.setLabelHintMode("mask"); - assertEquals("################################", localizer.getLabel("Sample", "click_here_to_create_new_account", "click")); + assertEquals("################################", localizer.getLabel("Sample", "click_here_to_create_new_account", "click")); - } finally { - LabelDebugProvider.setLabelDebugProviderEnabled(false); - LocalizerFactory.set(oldProvider); - } - - } + } finally { + LabelDebugProvider.setLabelDebugProviderEnabled(false); + LocalizerFactory.set(oldProvider); + } + } } diff --git a/src/test/java/com/force/i18n/grammar/GrammaticalLocalizerTest.java b/src/test/java/com/force/i18n/grammar/GrammaticalLocalizerTest.java index e2f15c3..759bb96 100644 --- a/src/test/java/com/force/i18n/grammar/GrammaticalLocalizerTest.java +++ b/src/test/java/com/force/i18n/grammar/GrammaticalLocalizerTest.java @@ -1,7 +1,7 @@ -/* +/* * Copyright (c) 2017, salesforce.com, inc. * All rights reserved. - * Licensed under the BSD 3-Clause license. + * Licensed under the BSD 3-Clause license. * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause */ @@ -35,51 +35,53 @@ public class GrammaticalLocalizerTest extends BaseGrammaticalLabelTest { private static final Locale chineseLocale = new Locale("zh", "China"); public GrammaticalLocalizerTest(String name) { - super(name); + super(name); } private LocalizerProvider origProvider; + + @SuppressWarnings("deprecation") + @Override + protected void setUp() throws Exception { + origProvider = LocalizerFactory.get(); + URL sampleJarUrl = getLabelURL(); + GrammaticalLabelSetDescriptor desc = new LabelSetDescriptorImpl(sampleJarUrl, LanguageProviderFactory.get().getBaseLanguage(), "sample"); + LocalizerProvider glf = new GrammaticalLocalizerFactory(GrammaticalLocalizerFactory.getLoader(desc, null)); + assertEquals(sampleJarUrl, glf.getLabelsDirectory()); + LocalizerFactory.set(glf); + super.setUp(); + } + @Override - protected void setUp() throws Exception { - origProvider = LocalizerFactory.get(); - URL sampleJarUrl = getLabelURL(); - GrammaticalLabelSetDescriptor desc = new LabelSetDescriptorImpl(sampleJarUrl, LanguageProviderFactory.get().getBaseLanguage(), "sample"); - LocalizerProvider glf = new GrammaticalLocalizerFactory(GrammaticalLocalizerFactory.getLoader(desc, null)); - assertEquals(sampleJarUrl, glf.getLabelsDirectory()); - LocalizerFactory.set(glf); - super.setUp(); - } - - @Override - protected void tearDown() throws Exception { - LocalizerFactory.set(origProvider); - super.tearDown(); - } - - //@NotThreadSafe + protected void tearDown() throws Exception { + LocalizerFactory.set(origProvider); + super.tearDown(); + } + + // @NotThreadSafe public void testGrammaticalLocalizerFactory() { - GrammaticalLocalizer gl = (GrammaticalLocalizer) LocalizerFactory.get().getLocalizer(Locale.US); - SharedLabelSet ls = gl.getLabelSet(); - assertEquals(new LabelRef("Sample_Entity","created_by"), ls.get("Sample", "created_by")); - assertEquals("Created by...", ls.getString("Sample", "created_by")); - assertEquals("Created by...", gl.getLabel("Sample", "created_by")); - assertEquals("Created by...", gl.getLabel("Sample", "created_by")); - assertEquals("Created by...", gl.getLabel("Sample", "created_by")); - - // Try it in a non-translated language that fallsback to ENGLISH_GB, then ENGLISH - ls = LocalizerFactory.get().getLocalizer(new Locale("en", "IN")).getLabelSet(); - // Fallbacks resolve all aliases immediately. - assertEquals("Created by...", ls.get("Sample", "created_by")); - assertEquals("Created by...", ls.getString("Sample", "created_by")); + GrammaticalLocalizer gl = (GrammaticalLocalizer)LocalizerFactory.get().getLocalizer(Locale.US); + SharedLabelSet ls = gl.getLabelSet(); + assertEquals(new LabelRef("Sample_Entity", "created_by"), ls.get("Sample", "created_by")); + assertEquals("Created by...", ls.getString("Sample", "created_by")); + assertEquals("Created by...", gl.getLabel("Sample", "created_by")); + assertEquals("Created by...", gl.getLabel("Sample", "created_by")); + assertEquals("Created by...", gl.getLabel("Sample", "created_by")); + + // Try it in a non-translated language that fallsback to ENGLISH_GB, then ENGLISH + ls = LocalizerFactory.get().getLocalizer(new Locale("en", "IN")).getLabelSet(); + // Fallbacks resolve all aliases immediately. + assertEquals("Created by...", ls.get("Sample", "created_by")); + assertEquals("Created by...", ls.getString("Sample", "created_by")); } - + public void testLabelThrow() { GrammaticalLocalizer gl = (GrammaticalLocalizer) LocalizerFactory.get().getLocalizer(Locale.US); //Test for valid Label retrieval using LabelThrow Object[] arguments = new Object[] { "1","5" }; assertEquals("Step 1 of 5", gl.getLabelThrow("Sample", "RightHeader", arguments)); - + //Test for invalid Label.An exception should be thrown when invalid label is referenced try { assertEquals("Step 1 of 5", gl.getLabelThrow("Sample", "InvalidLabel", arguments)); @@ -95,7 +97,7 @@ public void testLabelThrow() { public void testSampleLabels() throws Exception { RenamingProvider curProvider = RenamingProviderFactory.get().getProvider(); try { - GrammaticalLocalizer gl = (GrammaticalLocalizer) LocalizerFactory.get().getLocalizer(Locale.US); + GrammaticalLocalizer gl = (GrammaticalLocalizer) LocalizerFactory.get().getLocalizer(Locale.US); Renameable account = getStandardRenameable("Account"); assertEquals("Back to List: Accounts", gl.getLabel("Sample", new Renameable[]{account}, "last_type_list")); assertEquals("Back to Account: foo", gl.getLabel("Sample", new Renameable[]{account}, "back_detail", "foo")); @@ -126,31 +128,31 @@ public void testSampleLabels() throws Exception { public void testSampleLabelsGerman() throws Exception { RenamingProvider curProvider = RenamingProviderFactory.get().getProvider(); try { - GrammaticalLocalizer gl = (GrammaticalLocalizer) LocalizerFactory.get().getLocalizer(Locale.GERMAN); + GrammaticalLocalizer gl = (GrammaticalLocalizer) LocalizerFactory.get().getLocalizer(Locale.GERMAN); assertEquals("Klicken Sie hier, um jetzt einen neuen Account zu erstellen.", gl.getLabel("Sample", "click_here_to_create_new_account", "Klicken Sie hier")); // Account in german is "Account", "Konto", or "Kunde" depending on what you want, like client above. The accusative is used here. LanguageDeclension germanDecl = LanguageDeclensionFactory.get().getDeclension(LanguageProviderFactory.get().getLanguage(Locale.GERMAN)); Map KONTO = ImmutableMap.builder() - .put(germanDecl.getNounForm(LanguageNumber.SINGULAR, LanguageCase.NOMINATIVE), "Konto") - .put(germanDecl.getNounForm(LanguageNumber.SINGULAR, LanguageCase.GENITIVE), "Kontos") - .put(germanDecl.getNounForm(LanguageNumber.SINGULAR, LanguageCase.DATIVE), "Konto") - .put(germanDecl.getNounForm(LanguageNumber.SINGULAR, LanguageCase.ACCUSATIVE), "Konto") - .put(germanDecl.getNounForm(LanguageNumber.PLURAL, LanguageCase.NOMINATIVE), "Konten") // Koni? Kontos? - .put(germanDecl.getNounForm(LanguageNumber.PLURAL, LanguageCase.GENITIVE), "Konten") - .put(germanDecl.getNounForm(LanguageNumber.PLURAL, LanguageCase.DATIVE), "Konten") - .put(germanDecl.getNounForm(LanguageNumber.PLURAL, LanguageCase.ACCUSATIVE), "Konten") - .build(); + .put(germanDecl.getNounForm(LanguageNumber.SINGULAR, LanguageCase.NOMINATIVE), "Konto") + .put(germanDecl.getNounForm(LanguageNumber.SINGULAR, LanguageCase.GENITIVE), "Kontos") + .put(germanDecl.getNounForm(LanguageNumber.SINGULAR, LanguageCase.DATIVE), "Konto") + .put(germanDecl.getNounForm(LanguageNumber.SINGULAR, LanguageCase.ACCUSATIVE), "Konto") + .put(germanDecl.getNounForm(LanguageNumber.PLURAL, LanguageCase.NOMINATIVE), "Konten") // Koni? Kontos? + .put(germanDecl.getNounForm(LanguageNumber.PLURAL, LanguageCase.GENITIVE), "Konten") + .put(germanDecl.getNounForm(LanguageNumber.PLURAL, LanguageCase.DATIVE), "Konten") + .put(germanDecl.getNounForm(LanguageNumber.PLURAL, LanguageCase.ACCUSATIVE), "Konten") + .build(); Map KUNDE = ImmutableMap.builder() - .put(germanDecl.getNounForm(LanguageNumber.SINGULAR, LanguageCase.NOMINATIVE), "Kunde") - .put(germanDecl.getNounForm(LanguageNumber.SINGULAR, LanguageCase.GENITIVE), "Kunden") - .put(germanDecl.getNounForm(LanguageNumber.SINGULAR, LanguageCase.DATIVE), "Kunden") - .put(germanDecl.getNounForm(LanguageNumber.SINGULAR, LanguageCase.ACCUSATIVE), "Kunden") - .put(germanDecl.getNounForm(LanguageNumber.PLURAL, LanguageCase.NOMINATIVE), "Kunde") - .put(germanDecl.getNounForm(LanguageNumber.PLURAL, LanguageCase.GENITIVE), "Kunde") - .put(germanDecl.getNounForm(LanguageNumber.PLURAL, LanguageCase.DATIVE), "Kunde") - .put(germanDecl.getNounForm(LanguageNumber.PLURAL, LanguageCase.ACCUSATIVE), "Kunde") - .build(); + .put(germanDecl.getNounForm(LanguageNumber.SINGULAR, LanguageCase.NOMINATIVE), "Kunde") + .put(germanDecl.getNounForm(LanguageNumber.SINGULAR, LanguageCase.GENITIVE), "Kunden") + .put(germanDecl.getNounForm(LanguageNumber.SINGULAR, LanguageCase.DATIVE), "Kunden") + .put(germanDecl.getNounForm(LanguageNumber.SINGULAR, LanguageCase.ACCUSATIVE), "Kunden") + .put(germanDecl.getNounForm(LanguageNumber.PLURAL, LanguageCase.NOMINATIVE), "Kunde") + .put(germanDecl.getNounForm(LanguageNumber.PLURAL, LanguageCase.GENITIVE), "Kunde") + .put(germanDecl.getNounForm(LanguageNumber.PLURAL, LanguageCase.DATIVE), "Kunde") + .put(germanDecl.getNounForm(LanguageNumber.PLURAL, LanguageCase.ACCUSATIVE), "Kunde") + .build(); Noun konto = gl.getLabelSet().getDictionary().getNoun("account", false).clone(LanguageGender.NEUTER, LanguageStartsWith.CONSONANT, KONTO); @@ -259,7 +261,7 @@ public void testDoParseDate_Exception_DateOutOfRange2() { catch (ParseException expected) {} } - + public void testallowOtherGrammaticalForms() { URL base = GrammaticalLabelFileTest.class.getResource("/sample/labels.xml"); GrammaticalLabelSetLoader baseLoader = new GrammaticalLabelSetLoader(base, "sample", null); @@ -267,7 +269,7 @@ public void testallowOtherGrammaticalForms() { GrammaticalLabelSetLoader labelsLoader = new GrammaticalLabelSetLoader(labels, "test1a", baseLoader); URL overrides = GrammaticalLabelFileTest.class.getResource("/override/override.xml"); GrammaticalLabelSetLoader loader = new GrammaticalLabelSetLoader(overrides, "test2a", labelsLoader); - + HumanLanguage ENGLISH = LanguageProviderFactory.get().getLanguage(Locale.US); HumanLanguage GERMAN = LanguageProviderFactory.get().getLanguage(Locale.GERMAN); GrammaticalLabelSetFallbackImpl set = (GrammaticalLabelSetFallbackImpl) loader.getSet(ENGLISH); @@ -280,12 +282,12 @@ public void testallowOtherGrammaticalForms() { set = (GrammaticalLabelSetFallbackImpl) loader.getSet(GERMAN); assertTrue(set.allowOtherGrammaticalForms()); } - + public void testReloading() { - GrammaticalLocalizerFactory factory = (GrammaticalLocalizerFactory) LocalizerFactory.get(); - factory.resetLabels(); - factory.initEnglishLabelProvider(); - factory.resetLabels(); - factory.initLabelProvider(); + GrammaticalLocalizerFactory factory = (GrammaticalLocalizerFactory) LocalizerFactory.get(); + factory.resetLabels(); + factory.initEnglishLabelProvider(); + factory.resetLabels(); + factory.initLabelProvider(); } } diff --git a/src/test/java/com/force/i18n/grammar/impl/GrammaticalTermMapImplTest.java b/src/test/java/com/force/i18n/grammar/impl/GrammaticalTermMapImplTest.java index 7b38653..87f5af7 100644 --- a/src/test/java/com/force/i18n/grammar/impl/GrammaticalTermMapImplTest.java +++ b/src/test/java/com/force/i18n/grammar/impl/GrammaticalTermMapImplTest.java @@ -12,7 +12,6 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; -import java.util.HashSet; import java.util.Locale; import junit.framework.TestCase; import com.force.i18n.*; @@ -21,7 +20,7 @@ /** * Various sanity test for GrammaticalTermMapImpl - * + * */ public class GrammaticalTermMapImplTest extends TestCase { /** @@ -31,7 +30,7 @@ public class GrammaticalTermMapImplTest extends TestCase { /** * Simple get/ put /isEmpty / sets tests - * + * */ public void testSimpleUpdate() throws Exception{ GrammaticalTermMapImpl map = new GrammaticalTermMapImpl<>(); @@ -81,10 +80,9 @@ public void testMakeSkinny() { fail("no update allowed on skinny map"); } catch (IllegalStateException e) { // expected - } + } } - @SuppressWarnings("unchecked") public void testSerialization() throws Exception { GrammaticalTermMapImpl map = new GrammaticalTermMapImpl<>(); assertSerializedEquals(map); @@ -96,7 +94,7 @@ public void testSerialization() throws Exception { map.put("n1", n1); map.put("n1_a", n1); GrammaticalTermMapImpl serialized = getSerialized(map); - // same noun should be same in serialized map + // same noun should be same in serialized map assertTrue(serialized.get("n1") == serialized.get("n1_a")); } @@ -114,7 +112,7 @@ private void assertSerializedEquals(GrammaticalTermMapImpl orig) throws Ex assertTrue("serialized map doesn't have "+key, serialized.containsKey(key)); assertEquals("serialized map have different noun", orig.get(key), serialized.get(key)); } - assertEquals("The map returns different isSkinny ", orig.isSkinny(), serialized.isSkinny()); + assertEquals("The map returns different isSkinny ", orig.isSkinny(), serialized.isSkinny()); } /** @@ -131,7 +129,7 @@ private GrammaticalTermMapImpl getSerialized(GrammaticalTermMapImpl ObjectOutputStream oos = new ObjectOutputStream(baos)) { oos.writeObject(input); array = baos.toByteArray(); - } + } assertNotNull(array); // Deserialize try ( ByteArrayInputStream bais = new ByteArrayInputStream(array); @@ -139,7 +137,7 @@ private GrammaticalTermMapImpl getSerialized(GrammaticalTermMapImpl return (GrammaticalTermMapImpl) ois.readObject(); } } - + /** * Create a noun for testing */ diff --git a/src/test/java/com/force/i18n/grammar/parser/GrammaticalLabelLSetLoaderOverrideTest.java b/src/test/java/com/force/i18n/grammar/parser/GrammaticalLabelLSetLoaderOverrideTest.java index 2dc6aa7..3161a1a 100644 --- a/src/test/java/com/force/i18n/grammar/parser/GrammaticalLabelLSetLoaderOverrideTest.java +++ b/src/test/java/com/force/i18n/grammar/parser/GrammaticalLabelLSetLoaderOverrideTest.java @@ -13,11 +13,10 @@ import com.force.i18n.*; import com.force.i18n.LanguageLabelSetDescriptor.GrammaticalLabelSetDescriptor; import com.force.i18n.grammar.LanguageDictionary; -import com.force.i18n.grammar.parser.GrammaticalLabelSetLoader; /** - * Test for overriding LabelSetLoader to create another dictionary - * + * Test for overriding LabelSetLoader to create another dictionary + * */ public class GrammaticalLabelLSetLoaderOverrideTest extends BaseGrammaticalLabelTest{ @@ -28,11 +27,11 @@ public GrammaticalLabelLSetLoaderOverrideTest(String name) { /** * Loader for test */ - public static class TestLoader extends GrammaticalLabelSetLoader { + public static class TestLoader extends GrammaticalLabelSetLoader { public TestLoader(GrammaticalLabelSetDescriptor dictDesc) { super(dictDesc); - } - + } + @Override protected LanguageDictionary createNewDictionary(HumanLanguage language) throws IOException { return new TestInMemoryDic(language); @@ -40,12 +39,12 @@ protected LanguageDictionary createNewDictionary(HumanLanguage language) throws @Override protected LanguageDictionary finalizeDictionary(LanguageDictionary dictionary) throws IOException { assertTrue(dictionary instanceof TestInMemoryDic); - return new TestFinalizedDic(dictionary.getLanguage()); - } + return new TestFinalizedDic(dictionary.getLanguage()); + } } /** * Teset for overriding LabelSetLoader to create another dictionary specified in TestLoader - * + * * @throws Exception */ public void testOverride() throws Exception { diff --git a/src/test/java/com/force/i18n/grammar/parser/GrammaticalLabelTest.java b/src/test/java/com/force/i18n/grammar/parser/GrammaticalLabelTest.java index ab6903f..d7994b3 100644 --- a/src/test/java/com/force/i18n/grammar/parser/GrammaticalLabelTest.java +++ b/src/test/java/com/force/i18n/grammar/parser/GrammaticalLabelTest.java @@ -277,10 +277,10 @@ public void testGrammaticalTerms() { try { Renameable pig = makeCustomRenameable("Pig", LanguageStartsWith.CONSONANT, "Pig", "Pigs"); Renameable emu = makeCustomRenameable("Emu", LanguageStartsWith.VOWEL, "Emu", "Emus"); - MockRenamingProvider newProvider = new MockRenamingProvider(pig.getStandardNoun(ENGLISH), emu.getStandardNoun(ENGLISH)); + MockRenamingProvider newProvider = new MockRenamingProvider(pig.getStandardNoun(ENGLISH), emu.getStandardNoun(ENGLISH)); RenamingProviderFactory.get().setProvider(newProvider); - assertEquals("A Pig", set.getString("Global", new Renameable[] {pig}, "aentity")); - assertEquals("An Emu", set.getString("Global", new Renameable[] {emu}, "aentity")); + assertEquals("A Pig", set.getString("Global", new Renameable[] {pig}, "aentity")); + assertEquals("An Emu", set.getString("Global", new Renameable[] {emu}, "aentity")); } finally { RenamingProviderFactory.get().setProvider(curProvider); } @@ -315,7 +315,7 @@ public void testImmutableMapUnion() { * with ImmutableSortableMaps to save on memory */ public void testMultipleOverrides() { - // Go from samples to labels to override. Make sure it loads correctly + // Go from samples to labels to override. Make sure it loads correctly URL base = GrammaticalLabelFileTest.class.getResource("/sample/labels.xml"); GrammaticalLabelSetLoader baseLoader = new GrammaticalLabelSetLoader(base, "sample", null); URL labels = GrammaticalLabelFileTest.class.getResource("/labels/labels.xml"); @@ -540,6 +540,7 @@ public void testLabelSetLoaderConfig() { } @Test + @SuppressWarnings("removal") public void testCacheConfig() throws InterruptedException { HumanLanguage ENGLISH = LanguageProviderFactory.get().getLanguage(Locale.US); HumanLanguage ENGLISH_GB = LanguageProviderFactory.get().getLanguage(LanguageConstants.ENGLISH_GB);