001package ball.game.scrabble; 002/*- 003 * ########################################################################## 004 * Game Applications and Utilities 005 * $Id: WordList.java 6143 2020-06-12 16:21:29Z ball $ 006 * $HeadURL: svn+ssh://svn.hcf.dev/var/spool/scm/repository.svn/ball-game/trunk/src/main/java/ball/game/scrabble/WordList.java $ 007 * %% 008 * Copyright (C) 2010 - 2020 Allen D. Ball 009 * %% 010 * Licensed under the Apache License, Version 2.0 (the "License"); 011 * you may not use this file except in compliance with the License. 012 * You may obtain a copy of the License at 013 * 014 * http://www.apache.org/licenses/LICENSE-2.0 015 * 016 * Unless required by applicable law or agreed to in writing, software 017 * distributed under the License is distributed on an "AS IS" BASIS, 018 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 019 * See the License for the specific language governing permissions and 020 * limitations under the License. 021 * ########################################################################## 022 */ 023import ball.annotation.CompileTimeCheck; 024import java.text.Collator; 025import java.util.LinkedHashSet; 026import java.util.Locale; 027import java.util.Map; 028import java.util.ResourceBundle; 029import java.util.Set; 030import java.util.TreeMap; 031import java.util.regex.Matcher; 032import java.util.regex.Pattern; 033import org.apache.commons.lang3.StringUtils; 034 035/** 036 * Abstract Word List base class. 037 * 038 * @author {@link.uri mailto:ball@hcf.dev Allen D. Ball} 039 * @version $Revision: 6143 $ 040 */ 041public abstract class WordList extends TreeMap<CharSequence,Set<String>> { 042 private static final long serialVersionUID = -2777411476474325653L; 043 044 @CompileTimeCheck 045 private static final Pattern BRACKETED = Pattern.compile("\\[[^]]+\\]"); 046 @CompileTimeCheck 047 private static final Pattern ALTERNATIVES = Pattern.compile("-?[\\p{Upper}]+"); 048 049 /** 050 * Sole constructor. 051 * 052 * @param locale The {@link Locale}. 053 */ 054 protected WordList(Locale locale) { 055 super(Collator.getInstance(locale)); 056 057 ResourceBundle bundle = 058 ResourceBundle.getBundle(getClass().getName(), locale); 059 060 for (String key : bundle.keySet()) { 061 String value = bundle.getString(key); 062 String root = key.toUpperCase(); 063 String line = String.join(" ", root, value).trim(); 064 065 add(root, line); 066 067 Matcher bracketed = BRACKETED.matcher(value); 068 069 while (bracketed.find()) { 070 Matcher alternatives = ALTERNATIVES.matcher(bracketed.group()); 071 072 while (alternatives.find()) { 073 String word = alternatives.group(); 074 075 if (word.startsWith("-")) { 076 word = root + word.replace("-", ""); 077 } 078 079 add(word, line); 080 } 081 } 082 } 083 } 084 085 private void add(String word, String source) { 086 computeIfAbsent(word, k -> new LinkedHashSet<>()).add(source); 087 } 088}