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.kuromoji;
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.codelibs.fess.util.KuromojiCSVUtil;
40  import org.dbflute.optional.OptionalEntity;
41  
42  public class KuromojiFile extends DictionaryFile<KuromojiItem> {
43      private static final String KUROMOJI = "kuromoji";
44  
45      List<KuromojiItem> kuromojiItemList;
46  
47      public KuromojiFile(final String id, final String path, final Date timestamp) {
48          super(id, path, timestamp);
49      }
50  
51      @Override
52      public String getType() {
53          return KUROMOJI;
54      }
55  
56      @Override
57      public String getPath() {
58          return path;
59      }
60  
61      @Override
62      public synchronized OptionalEntity<KuromojiItem> get(final long id) {
63          if (kuromojiItemList == null) {
64              reload(null);
65          }
66  
67          for (final KuromojiItem kuromojiItem : kuromojiItemList) {
68              if (id == kuromojiItem.getId()) {
69                  return OptionalEntity.of(kuromojiItem);
70              }
71          }
72          return OptionalEntity.empty();
73      }
74  
75      @Override
76      public synchronized PagingList<KuromojiItem> selectList(final int offset, final int size) {
77          if (kuromojiItemList == null) {
78              reload(null);
79          }
80  
81          if (offset >= kuromojiItemList.size() || offset < 0) {
82              return new PagingList<>(Collections.<KuromojiItem> emptyList(), offset, size, kuromojiItemList.size());
83          }
84  
85          int toIndex = offset + size;
86          if (toIndex > kuromojiItemList.size()) {
87              toIndex = kuromojiItemList.size();
88          }
89  
90          return new PagingList<>(kuromojiItemList.subList(offset, toIndex), offset, size, kuromojiItemList.size());
91      }
92  
93      @Override
94      public synchronized void insert(final KuromojiItem item) {
95          try (KuromojiUpdater updater = new KuromojiUpdater(item)) {
96              reload(updater);
97          }
98      }
99  
100     @Override
101     public synchronized void update(final KuromojiItem item) {
102         try (KuromojiUpdater updater = new KuromojiUpdater(item)) {
103             reload(updater);
104         }
105     }
106 
107     @Override
108     public synchronized void delete(final KuromojiItem item) {
109         final KuromojiItem kuromojiItem = item;
110         kuromojiItem.setNewToken(StringUtil.EMPTY);
111         try (KuromojiUpdater updater = new KuromojiUpdater(item)) {
112             reload(updater);
113         }
114     }
115 
116     protected void reload(final KuromojiUpdater 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 KuromojiUpdater updater, final InputStream in) {
125         final List<KuromojiItem> 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                 // Remove comments
131                 final String replacedLine = line.replaceAll("#.*$", StringUtil.EMPTY).trim();
132 
133                 // Skip empty lines or comment lines
134                 if (replacedLine.length() == 0) {
135                     if (updater != null) {
136                         updater.write(line);
137                     }
138                     continue;
139                 }
140 
141                 final String[] values = KuromojiCSVUtil.parse(replacedLine);
142                 String token = null;
143                 String segmentation = null;
144                 String reading = null;
145                 String pos = null;
146                 switch (values.length) {
147                 case 4:
148                     pos = values[3];
149                 case 3:
150                     reading = values[2];
151                 case 2:
152                     segmentation = values[1];
153                 case 1:
154                     token = values[0];
155                 default:
156                     break;
157                 }
158 
159                 id++;
160                 final KuromojiItemji/KuromojiItem.html#KuromojiItem">KuromojiItem item = new KuromojiItem(id, token, segmentation, reading, pos);
161                 if (updater != null) {
162                     final KuromojiItem newItem = updater.write(item);
163                     if (newItem != null) {
164                         itemList.add(newItem);
165                     } else {
166                         id--;
167                     }
168                 } else {
169                     itemList.add(item);
170                 }
171             }
172             if (updater != null) {
173                 final KuromojiItem item = updater.commit();
174                 if (item != null) {
175                     itemList.add(item);
176                 }
177             }
178             kuromojiItemList = itemList;
179         } catch (final IOException e) {
180             throw new DictionaryException("Failed to parse " + path, e);
181         }
182     }
183 
184     public String getSimpleName() {
185         return new File(path).getName();
186     }
187 
188     public synchronized void update(final InputStream in) throws IOException {
189         try (KuromojiUpdater updater = new KuromojiUpdater(null)) {
190             reload(updater, in);
191         }
192     }
193 
194     @Override
195     public String toString() {
196         return "KuromojiFile [path=" + path + ", kuromojiItemList=" + kuromojiItemList + ", id=" + id + "]";
197     }
198 
199     protected class KuromojiUpdater implements Closeable {
200 
201         protected boolean isCommit = false;
202 
203         protected File newFile;
204 
205         protected Writer writer;
206 
207         protected KuromojiItem item;
208 
209         protected KuromojiUpdater(final KuromojiItem newItem) {
210             try {
211                 newFile = File.createTempFile(KUROMOJI, ".txt");
212                 writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(newFile), Constants.UTF_8));
213             } catch (final IOException e) {
214                 if (newFile != null) {
215                     newFile.delete();
216                 }
217                 throw new DictionaryException("Failed to write a userDict file.", e);
218             }
219             item = newItem;
220         }
221 
222         public KuromojiItemi/KuromojiItem.html#KuromojiItem">KuromojiItem write(final KuromojiItem oldItem) {
223             try {
224                 if (item != null && item.getId() == oldItem.getId() && item.isUpdated()) {
225                     if (item.equals(oldItem)) {
226                         try {
227                             if (!item.isDeleted()) {
228                                 // update
229                                 writer.write(item.toLineString());
230                                 writer.write(Constants.LINE_SEPARATOR);
231                                 return new KuromojiItem(item.getId(), item.getNewToken(), item.getNewSegmentation(), item.getNewReading(),
232                                         item.getNewPos());
233                             } else {
234                                 return null;
235                             }
236                         } finally {
237                             item.setNewToken(null);
238                         }
239                     } else {
240                         throw new DictionaryException("Kuromoji file was updated: old=" + oldItem + " : new=" + item);
241                     }
242                 } else {
243                     writer.write(oldItem.toLineString());
244                     writer.write(Constants.LINE_SEPARATOR);
245                     return oldItem;
246                 }
247             } catch (final IOException e) {
248                 throw new DictionaryException("Failed to write: " + oldItem + " -> " + item, e);
249             }
250         }
251 
252         public void write(final String line) {
253             try {
254                 writer.write(line);
255                 writer.write(Constants.LINE_SEPARATOR);
256             } catch (final IOException e) {
257                 throw new DictionaryException("Failed to write: " + line, e);
258             }
259         }
260 
261         public KuromojiItem commit() {
262             isCommit = true;
263             if (item != null && item.isUpdated()) {
264                 try {
265                     writer.write(item.toLineString());
266                     writer.write(Constants.LINE_SEPARATOR);
267                     return item;
268                 } catch (final IOException e) {
269                     throw new DictionaryException("Failed to write: " + item, e);
270                 }
271             }
272             return null;
273         }
274 
275         @Override
276         public void close() {
277             try {
278                 writer.flush();
279             } catch (final IOException e) {
280                 // ignore
281             }
282             CloseableUtil.closeQuietly(writer);
283 
284             if (isCommit) {
285                 try {
286                     dictionaryManager.store(KuromojiFile.this, newFile);
287                 } finally {
288                     newFile.delete();
289                 }
290             } else {
291                 newFile.delete();
292             }
293         }
294     }
295 
296 }