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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
|
/*
* SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license. See terms of license at gnu.org.
*/
package net.java.sip.communicator.plugin.spellcheck;
import java.io.*;
import java.net.*;
import java.util.*;
import net.java.sip.communicator.service.fileaccess.*;
import net.java.sip.communicator.service.gui.*;
import net.java.sip.communicator.service.gui.event.*;
import net.java.sip.communicator.util.Logger;
import org.dts.spell.dictionary.*;
import org.osgi.framework.*;
/**
* Model for spell checking capabilities. This allows for the on-demand
* retrieval of dictionaries in other languages which are cached with the user's
* configurations.
*
* @author Damian Johnson
*/
class SpellChecker
implements ChatListener
{
private static final Logger logger = Logger.getLogger(SpellChecker.class);
private static final String LOCALE_CONFIG_PARAM =
"net.java.sip.communicator.plugin.spellchecker.LOCALE";
// default bundled dictionary
private static final String DEFAULT_DICT_PATH =
"/resources/config/spellcheck/";
// location where dictionaries are stored
private static final String DICT_DIR = "spellingDictionaries/";
// filename of custom dictionary (added words)
private static final String PERSONAL_DICT_NAME = "custom.per";
/*-
* Dictionary resources.
* Note: Dictionary needs to be created with input streams that AREN'T CLOSED
* (dictionaries will handle it). Closing the stream or creating with a file
* will cause an internal NullPointerException in the spell checker.
*/
private File personalDictLocation;
private File dictLocation;
private SpellDictionary dict;
private Parameters.Locale locale; // dictionary locale
// chat instances the spell checker is currently attached to
private ArrayList<ChatAttachments> attachedChats =
new ArrayList<ChatAttachments>();
private boolean isEnabled = true;
/**
* Associates spell checking capabilities with all chats. This doesn't do
* anything if this is already running.
*
* @param bc execution context of the bundle
*/
synchronized void start(BundleContext bc) throws Exception
{
FileAccessService faService =
SpellCheckActivator.getFileAccessService();
// checks if DICT_DIR exists to see if this is the first run
File dictionaryDir = faService.getPrivatePersistentFile(DICT_DIR);
if (!dictionaryDir.exists())
{
dictionaryDir.mkdir();
// copy default dictionaries so they don't need to be downloaded
@SuppressWarnings ("unchecked")
Enumeration<URL> dictUrls
= SpellCheckActivator.bundleContext.getBundle()
.findEntries(DEFAULT_DICT_PATH,
"*.zip",
false);
if (dictUrls != null)
{
while (dictUrls.hasMoreElements())
{
URL dictUrl = dictUrls.nextElement();
InputStream source = dictUrl.openStream();
int filenameStart = dictUrl.getPath().lastIndexOf('/') + 1;
String filename = dictUrl.getPath().substring(filenameStart);
File dictLocation =
faService.getPrivatePersistentFile(DICT_DIR + filename);
copyDictionary(source, dictLocation);
}
}
}
// gets resource for personal dictionary
this.personalDictLocation =
faService.getPrivatePersistentFile(DICT_DIR + PERSONAL_DICT_NAME);
if (!personalDictLocation.exists())
personalDictLocation.createNewFile();
// gets dictionary locale
String localeIso =
SpellCheckActivator.getConfigService().getString(
LOCALE_CONFIG_PARAM);
if (localeIso == null)
{
// sets locale to be the default
localeIso = Parameters.getDefault(Parameters.Default.LOCALE);
if (localeIso == null)
throw new Exception(
"No default locale provided for spell checker");
}
Parameters.Locale tmp = Parameters.getLocale(localeIso);
if (tmp == null)
throw new Exception("No dictionary resources defined for locale: "
+ localeIso);
this.locale = tmp; // needed for synchronization lock
setLocale(tmp); // initializes dictionary and saves locale config
// attaches to uiService so this'll be attached to future chats
synchronized (this.attachedChats)
{
SpellCheckActivator.getUIService().addChatListener(this);
for (Chat chat : SpellCheckActivator.getUIService().getAllChats())
{
ChatAttachments wrapper = new ChatAttachments(chat, this.dict);
wrapper.attachListeners();
this.attachedChats.add(wrapper);
}
}
if (logger.isInfoEnabled())
logger.info("Spell Checker loaded.");
}
/**
* Removes the spell checking capabilities from all chats. This doesn't do
* anything if this isn't running.
*/
synchronized void stop()
{
// removes spell checker listeners from chats
synchronized (this.attachedChats)
{
for (ChatAttachments chat : this.attachedChats)
{
chat.detachListeners();
}
this.attachedChats.clear();
SpellCheckActivator.getUIService().removeChatListener(this);
}
}
// attaches listeners to new chats
public void chatCreated(Chat chat)
{
synchronized (this.attachedChats)
{
ChatAttachments wrapper = new ChatAttachments(chat, this.dict);
wrapper.setEnabled(this.isEnabled);
wrapper.attachListeners();
this.attachedChats.add(wrapper);
}
}
/**
* Provides the user's list of words to be ignored by the spell checker.
*
* @return user's word list
*/
ArrayList<String> getPersonalWords()
{
synchronized (this.personalDictLocation)
{
try
{
// Retrieves contents of the custom dictionary
ArrayList<String> customWords = new ArrayList<String>();
Scanner customDictScanner =
new Scanner(this.personalDictLocation);
while (customDictScanner.hasNextLine())
{
customWords.add(customDictScanner.nextLine());
}
customDictScanner.close();
return customWords;
}
catch (FileNotFoundException exc)
{
logger.error("Unable to read custom dictionary", exc);
return new ArrayList<String>();
}
}
}
/**
* Writes custom dictionary and updates spell checker to utilize new
* listing.
*
* @param words words to be ignored by the spell checker
*/
void setPersonalWords(List<String> words)
{
synchronized (this.personalDictLocation)
{
try
{
// writes new word list
BufferedWriter writer =
new BufferedWriter(
new FileWriter(this.personalDictLocation));
for (String customWord : words)
{
writer.append(customWord);
writer.newLine();
}
writer.flush();
writer.close();
// resets dictionary being used to include changes
synchronized (this.attachedChats)
{
InputStream dictInput =
new FileInputStream(this.dictLocation);
this.dict =
new OpenOfficeSpellDictionary(dictInput,
this.personalDictLocation);
// updates chats
for (ChatAttachments chat : this.attachedChats)
{
chat.setDictionary(this.dict);
}
}
}
catch (IOException exc)
{
logger.error("Unable to access personal spelling dictionary",
exc);
}
}
}
/**
* Provides the locale of the dictionary currently being used by the spell
* checker.
*
* @return locale of current dictionary
*/
Parameters.Locale getLocale()
{
synchronized (this.locale)
{
return this.locale;
}
}
/**
* Resets spell checker to use a different locale's dictionary. This uses
* the local copy of the dictionary if available, otherwise it's downloaded
* and saved for future use.
*
* @param locale locale of dictionary to be used
* @throws Exception problem occurring in utilizing locale's dictionary
*/
void setLocale(Parameters.Locale locale) throws Exception
{
synchronized (this.locale)
{
String path = locale.getDictUrl().getFile();
int filenameStart = path.lastIndexOf('/') + 1;
String filename = path.substring(filenameStart);
File dictLocation =
SpellCheckActivator.getFileAccessService()
.getPrivatePersistentFile(DICT_DIR + filename);
// downloads dictionary if unavailable (not cached)
if (!dictLocation.exists())
copyDictionary(locale.getDictUrl().openStream(), dictLocation);
// resets dictionary being used to include changes
synchronized (this.attachedChats)
{
InputStream dictInput = new FileInputStream(dictLocation);
SpellDictionary dict =
new OpenOfficeSpellDictionary(dictInput,
this.personalDictLocation);
this.dict = dict;
this.dictLocation = dictLocation;
this.locale = locale;
// saves locale choice to configuration properties
SpellCheckActivator.getConfigService().setProperty(
LOCALE_CONFIG_PARAM, locale.getIsoCode());
// updates chats
for (ChatAttachments chat : this.attachedChats)
{
chat.setDictionary(this.dict);
}
}
}
}
/**
* Determines if locale's dictionary is locally available or not.
*
* @param locale locale to be checked
* @return true if local resources for dictionary are available and
* accessible, false otherwise
*/
boolean isLocaleAvailable(Parameters.Locale locale)
{
String path = locale.getDictUrl().getFile();
int filenameStart = path.lastIndexOf('/') + 1;
String filename = path.substring(filenameStart);
try
{
File dictLocation =
SpellCheckActivator.getFileAccessService()
.getPrivatePersistentFile(DICT_DIR + filename);
return dictLocation.exists();
}
catch (Exception exc)
{
return false;
}
}
boolean isEnabled()
{
synchronized (this.attachedChats)
{
return this.isEnabled;
}
}
void setEnabled(boolean enable)
{
if (enable != this.isEnabled)
{
synchronized (this.attachedChats)
{
this.isEnabled = enable;
for (ChatAttachments chatAttachment : this.attachedChats)
{
chatAttachment.setEnabled(enable);
}
}
}
}
// copies dictionary to appropriate location, closing the stream afterward
private void copyDictionary(InputStream input, File dest)
throws IOException,
FileNotFoundException
{
byte[] buf = new byte[1024];
FileOutputStream output = new FileOutputStream(dest);
int len;
while ((len = input.read(buf)) > 0)
{
output.write(buf, 0, len);
}
input.close();
output.close();
}
/**
* Determines if spell checker dictionary works. Backend API often fails
* when used so this tests that the current dictionary is able to process
* words.
*
* @return true if current dictionary can check words, false otherwise
*/
private boolean isDictionaryValid(SpellDictionary dict)
{
try
{
// spell checker API often works until used
dict.isCorrect("foo");
return true;
}
catch (Exception exc)
{
logger.error("Dictionary validation failed", exc);
return false;
}
}
}
|