View Javadoc
1   /*
2    * Copyright 2012-2019 CodeLibs Project and the Others.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
13   * either express or implied. See the License for the specific language
14   * governing permissions and limitations under the License.
15   */
16  package org.codelibs.fess.dict.synonym;
17  
18  import java.io.BufferedReader;
19  import java.io.BufferedWriter;
20  import java.io.Closeable;
21  import java.io.File;
22  import java.io.FileOutputStream;
23  import java.io.IOException;
24  import java.io.InputStream;
25  import java.io.InputStreamReader;
26  import java.io.OutputStreamWriter;
27  import java.io.Writer;
28  import java.util.ArrayList;
29  import java.util.Collections;
30  import java.util.Date;
31  import java.util.List;
32  
33  import org.codelibs.core.io.CloseableUtil;
34  import org.codelibs.core.lang.StringUtil;
35  import org.codelibs.curl.CurlResponse;
36  import org.codelibs.fess.Constants;
37  import org.codelibs.fess.dict.DictionaryException;
38  import org.codelibs.fess.dict.DictionaryFile;
39  import org.dbflute.optional.OptionalEntity;
40  
41  public class SynonymFile extends DictionaryFile<SynonymItem> {
42      private static final String SYNONYM = "synonym";
43  
44      List<SynonymItem> synonymItemList;
45  
46      public SynonymFile(final String id, final String path, final Date timestamp) {
47          super(id, path, timestamp);
48      }
49  
50      @Override
51      public String getType() {
52          return SYNONYM;
53      }
54  
55      @Override
56      public String getPath() {
57          return path;
58      }
59  
60      @Override
61      public synchronized OptionalEntity<SynonymItem> get(final long id) {
62          if (synonymItemList == null) {
63              reload(null);
64          }
65  
66          for (final SynonymItem synonymItem : synonymItemList) {
67              if (id == synonymItem.getId()) {
68                  return OptionalEntity.of(synonymItem);
69              }
70          }
71          return OptionalEntity.empty();
72      }
73  
74      @Override
75      public synchronized PagingList<SynonymItem> selectList(final int offset, final int size) {
76          if (synonymItemList == null) {
77              reload(null);
78          }
79  
80          if (offset >= synonymItemList.size() || offset < 0) {
81              return new PagingList<>(Collections.<SynonymItem> emptyList(), offset, size, synonymItemList.size());
82          }
83  
84          int toIndex = offset + size;
85          if (toIndex > synonymItemList.size()) {
86              toIndex = synonymItemList.size();
87          }
88  
89          return new PagingList<>(synonymItemList.subList(offset, toIndex), offset, size, synonymItemList.size());
90      }
91  
92      @Override
93      public synchronized void insert(final SynonymItem item) {
94          try (SynonymUpdater updater = new SynonymUpdater(item)) {
95              reload(updater);
96          }
97      }
98  
99      @Override
100     public synchronized void update(final SynonymItem item) {
101         try (SynonymUpdater updater = new SynonymUpdater(item)) {
102             reload(updater);
103         }
104     }
105 
106     @Override
107     public synchronized void delete(final SynonymItem item) {
108         final SynonymItem synonymItem = item;
109         synonymItem.setNewInputs(StringUtil.EMPTY_STRINGS);
110         synonymItem.setNewOutputs(StringUtil.EMPTY_STRINGS);
111         try (SynonymUpdater updater = new SynonymUpdater(item)) {
112             reload(updater);
113         }
114     }
115 
116     protected void reload(final SynonymUpdater updater) {
117         try (CurlResponse curlResponse = dictionaryManager.getContentResponse(this)) {
118             reload(updater, curlResponse.getContentAsStream());
119         } catch (final IOException e) {
120             throw new DictionaryException("Failed to parse " + path, e);
121         }
122     }
123 
124     protected void reload(final SynonymUpdater updater, final InputStream in) {
125         final List<SynonymItem> itemList = new ArrayList<>();
126         try (BufferedReader reader = new BufferedReader(new InputStreamReader(in, Constants.UTF_8))) {
127             long id = 0;
128             String line = null;
129             while ((line = reader.readLine()) != null) {
130                 if (line.length() == 0 || line.charAt(0) == '#') {
131                     if (updater != null) {
132                         updater.write(line);
133                     }
134                     continue; // ignore empty lines and comments
135                 }
136 
137                 String[] inputs;
138                 String[] outputs;
139 
140                 final List<String> sides = split(line, "=>");
141                 if (sides.size() > 1) { // explicit mapping
142                     if (sides.size() != 2) {
143                         throw new DictionaryException("more than one explicit mapping specified on the same line");
144                     }
145                     final List<String> inputStrings = split(sides.get(0), ",");
146                     inputs = new String[inputStrings.size()];
147                     for (int i = 0; i < inputs.length; i++) {
148                         inputs[i] = unescape(inputStrings.get(i)).trim();
149                     }
150 
151                     final List<String> outputStrings = split(sides.get(1), ",");
152                     outputs = new String[outputStrings.size()];
153                     for (int i = 0; i < outputs.length; i++) {
154                         outputs[i] = unescape(outputStrings.get(i)).trim();
155                     }
156 
157                     if (inputs.length > 0 && outputs.length > 0) {
158                         id++;
159                         final SynonymItemym/SynonymItem.html#SynonymItem">SynonymItem item = new SynonymItem(id, inputs, outputs);
160                         if (updater != null) {
161                             final SynonymItem newItem = updater.write(item);
162                             if (newItem != null) {
163                                 itemList.add(newItem);
164                             } else {
165                                 id--;
166                             }
167                         } else {
168                             itemList.add(item);
169                         }
170                     }
171                 } else {
172                     final List<String> inputStrings = split(line, ",");
173                     inputs = new String[inputStrings.size()];
174                     for (int i = 0; i < inputs.length; i++) {
175                         inputs[i] = unescape(inputStrings.get(i)).trim();
176                     }
177 
178                     if (inputs.length > 0) {
179                         id++;
180                         final SynonymItemym/SynonymItem.html#SynonymItem">SynonymItem item = new SynonymItem(id, inputs, inputs);
181                         if (updater != null) {
182                             final SynonymItem newItem = updater.write(item);
183                             if (newItem != null) {
184                                 itemList.add(newItem);
185                             } else {
186                                 id--;
187                             }
188                         } else {
189                             itemList.add(item);
190                         }
191                     }
192                 }
193             }
194             if (updater != null) {
195                 final SynonymItem item = updater.commit();
196                 if (item != null) {
197                     itemList.add(item);
198                 }
199             }
200             synonymItemList = itemList;
201         } catch (final IOException e) {
202             throw new DictionaryException("Failed to parse " + path, e);
203         }
204     }
205 
206     private static List<String> split(final String s, final String separator) {
207         final List<String> list = new ArrayList<>(2);
208         StringBuilder sb = new StringBuilder();
209         int pos = 0;
210         final int end = s.length();
211         while (pos < end) {
212             if (s.startsWith(separator, pos)) {
213                 if (sb.length() > 0) {
214                     list.add(sb.toString());
215                     sb = new StringBuilder();
216                 }
217                 pos += separator.length();
218                 continue;
219             }
220 
221             char ch = s.charAt(pos++);
222             if (ch == '\\') {
223                 sb.append(ch);
224                 if (pos >= end) {
225                     break; // ERROR, or let it go?
226                 }
227                 ch = s.charAt(pos++);
228             }
229 
230             sb.append(ch);
231         }
232 
233         if (sb.length() > 0) {
234             list.add(sb.toString());
235         }
236 
237         return list;
238     }
239 
240     private String unescape(final String s) {
241         if (s.indexOf('\\') >= 0) {
242             final StringBuilder sb = new StringBuilder();
243             for (int i = 0; i < s.length(); i++) {
244                 final char ch = s.charAt(i);
245                 if (ch == '\\' && i < s.length() - 1) {
246                     sb.append(s.charAt(++i));
247                 } else {
248                     sb.append(ch);
249                 }
250             }
251             return sb.toString();
252         }
253         return s;
254     }
255 
256     public String getSimpleName() {
257         return new File(path).getName();
258     }
259 
260     public synchronized void update(final InputStream in) throws IOException {
261         try (SynonymUpdater updater = new SynonymUpdater(null)) {
262             reload(updater, in);
263         }
264     }
265 
266     @Override
267     public String toString() {
268         return "SynonymFile [path=" + path + ", synonymItemList=" + synonymItemList + ", id=" + id + "]";
269     }
270 
271     protected class SynonymUpdater implements Closeable {
272 
273         protected boolean isCommit = false;
274 
275         protected File newFile;
276 
277         protected Writer writer;
278 
279         protected SynonymItem item;
280 
281         protected SynonymUpdater(final SynonymItem newItem) {
282             try {
283                 newFile = File.createTempFile(SYNONYM, ".txt");
284                 writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(newFile), Constants.UTF_8));
285             } catch (final IOException e) {
286                 if (newFile != null) {
287                     newFile.delete();
288                 }
289                 throw new DictionaryException("Failed to write a userDict file.", e);
290             }
291             item = newItem;
292         }
293 
294         public SynonymItemm/SynonymItem.html#SynonymItem">SynonymItem write(final SynonymItem oldItem) {
295             try {
296                 if (item != null && item.getId() == oldItem.getId() && item.isUpdated()) {
297                     if (item.equals(oldItem)) {
298                         try {
299                             if (!item.isDeleted()) {
300                                 // update
301                                 writer.write(item.toLineString());
302                                 writer.write(Constants.LINE_SEPARATOR);
303                                 return new SynonymItem(item.getId(), item.getNewInputs(), item.getNewOutputs());
304                             } else {
305                                 return null;
306                             }
307                         } finally {
308                             item.setNewInputs(null);
309                             item.setNewOutputs(null);
310                         }
311                     } else {
312                         throw new DictionaryException("Synonym file was updated: old=" + oldItem + " : new=" + item);
313                     }
314                 } else {
315                     writer.write(oldItem.toLineString());
316                     writer.write(Constants.LINE_SEPARATOR);
317                     return oldItem;
318                 }
319             } catch (final IOException e) {
320                 throw new DictionaryException("Failed to write: " + oldItem + " -> " + item, e);
321             }
322         }
323 
324         public void write(final String line) {
325             try {
326                 writer.write(line);
327                 writer.write(Constants.LINE_SEPARATOR);
328             } catch (final IOException e) {
329                 throw new DictionaryException("Failed to write: " + line, e);
330             }
331         }
332 
333         public SynonymItem commit() {
334             isCommit = true;
335             if (item != null && item.isUpdated()) {
336                 try {
337                     writer.write(item.toLineString());
338                     writer.write(Constants.LINE_SEPARATOR);
339                     return item;
340                 } catch (final IOException e) {
341                     throw new DictionaryException("Failed to write: " + item, e);
342                 }
343             }
344             return null;
345         }
346 
347         @Override
348         public void close() {
349             try {
350                 writer.flush();
351             } catch (final IOException e) {
352                 // ignore
353             }
354             CloseableUtil.closeQuietly(writer);
355 
356             if (isCommit) {
357                 try {
358                     dictionaryManager.store(SynonymFile.this, newFile);
359                 } finally {
360                     newFile.delete();
361                 }
362             } else {
363                 newFile.delete();
364             }
365         }
366     }
367 
368 }