001/* 002 * (C) Copyright 2006-2014 Nuxeo SA (http://nuxeo.com/) and contributors. 003 * 004 * All rights reserved. This program and the accompanying materials 005 * are made available under the terms of the GNU Lesser General Public License 006 * (LGPL) version 2.1 which accompanies this distribution, and is available at 007 * http://www.gnu.org/licenses/lgpl-2.1.html 008 * 009 * This library is distributed in the hope that it will be useful, 010 * but WITHOUT ANY WARRANTY; without even the implied warranty of 011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 012 * Lesser General Public License for more details. 013 * 014 * Contributors: 015 * Nuxeo - initial API and implementation 016 * Michaƫl Vachette 017 * 018 */ 019package org.nuxeo.ecm.platform.importer.random; 020 021import org.apache.commons.logging.Log; 022import org.apache.commons.logging.LogFactory; 023 024import java.io.BufferedReader; 025import java.io.IOException; 026import java.io.InputStream; 027import java.io.InputStreamReader; 028import java.net.URL; 029import java.util.ArrayList; 030import java.util.List; 031import java.util.Random; 032 033/** 034 * @author Thierry Delprat 035 */ 036public class HunspellDictionaryHolder implements DictionaryHolder { 037 038 protected static final int INITIAL_SIZE = 100000; 039 040 protected List<String> words = new ArrayList<>(INITIAL_SIZE); 041 042 protected Random generator; 043 044 protected int wordCount; 045 046 protected String dicName; 047 048 public static final Log log = LogFactory.getLog(HunspellDictionaryHolder.class); 049 050 public HunspellDictionaryHolder(String dicName) { 051 generator = new Random(System.currentTimeMillis()); 052 this.dicName = dicName; 053 } 054 055 @Override 056 public void init() throws IOException { 057 loadDic(); 058 wordCount = words.size(); 059 } 060 061 /** 062 * @deprecated since 6.0 063 */ 064 @Deprecated 065 protected void loadDic(String dicName) throws IOException { 066 this.dicName = dicName; 067 loadDic(); 068 } 069 070 /** 071 * @since 6.0 072 */ 073 protected void loadDic() throws IOException { 074 URL url = Thread.currentThread().getContextClassLoader().getResource(dicName); 075 if (url == null) { 076 log.error("not found: " + dicName); 077 return; 078 } 079 try (InputStream in = url.openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in))) { 080 String line; 081 while ((line = reader.readLine()) != null) { 082 int idx = line.indexOf("/"); 083 if (idx > 0) { 084 String word = line.substring(0, idx); 085 words.add(word + " "); 086 } else { 087 words.add(line + " "); 088 } 089 } 090 } 091 } 092 093 @Override 094 public int getWordCount() { 095 return wordCount; 096 } 097 098 @Override 099 public String getRandomWord() { 100 int idx = generator.nextInt(wordCount); 101 return words.get(idx); 102 } 103}