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.protwords;
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 ProtwordsFile extends DictionaryFile<ProtwordsItem> {
42      private static final String PROTWORDS = "protwords";
43  
44      List<ProtwordsItem> protwordsItemList;
45  
46      public ProtwordsFile(final String id, final String path, final Date timestamp) {
47          super(id, path, timestamp);
48      }
49  
50      @Override
51      public String getType() {
52          return PROTWORDS;
53      }
54  
55      @Override
56      public String getPath() {
57          return path;
58      }
59  
60      @Override
61      public synchronized OptionalEntity<ProtwordsItem> get(final long id) {
62          if (protwordsItemList == null) {
63              reload(null);
64          }
65  
66          for (final ProtwordsItemf="../../../../../org/codelibs/fess/dict/protwords/ProtwordsItem.html#ProtwordsItem">ProtwordsItem ProtwordsItem : protwordsItemList) {
67              if (id == ProtwordsItem.getId()) {
68                  return OptionalEntity.of(ProtwordsItem);
69              }
70          }
71          return OptionalEntity.empty();
72      }
73  
74      @Override
75      public synchronized PagingList<ProtwordsItem> selectList(final int offset, final int size) {
76          if (protwordsItemList == null) {
77              reload(null);
78          }
79  
80          if (offset >= protwordsItemList.size() || offset < 0) {
81              return new PagingList<>(Collections.<ProtwordsItem> emptyList(), offset, size, protwordsItemList.size());
82          }
83  
84          int toIndex = offset + size;
85          if (toIndex > protwordsItemList.size()) {
86              toIndex = protwordsItemList.size();
87          }
88  
89          return new PagingList<>(protwordsItemList.subList(offset, toIndex), offset, size, protwordsItemList.size());
90      }
91  
92      @Override
93      public synchronized void insert(final ProtwordsItem item) {
94          try (ProtwordsUpdater updater = new ProtwordsUpdater(item)) {
95              reload(updater);
96          }
97      }
98  
99      @Override
100     public synchronized void update(final ProtwordsItem item) {
101         try (ProtwordsUpdater updater = new ProtwordsUpdater(item)) {
102             reload(updater);
103         }
104     }
105 
106     @Override
107     public synchronized void delete(final ProtwordsItem item) {
108         final ProtwordsItemf="../../../../../org/codelibs/fess/dict/protwords/ProtwordsItem.html#ProtwordsItem">ProtwordsItem ProtwordsItem = item;
109         ProtwordsItem.setNewInput(StringUtil.EMPTY);
110         try (ProtwordsUpdater updater = new ProtwordsUpdater(item)) {
111             reload(updater);
112         }
113     }
114 
115     protected void reload(final ProtwordsUpdater updater) {
116         try (CurlResponse curlResponse = dictionaryManager.getContentResponse(this)) {
117             reload(updater, curlResponse.getContentAsStream());
118         } catch (final IOException e) {
119             throw new DictionaryException("Failed to parse " + path, e);
120         }
121     }
122 
123     protected void reload(final ProtwordsUpdater updater, final InputStream in) {
124         final List<ProtwordsItem> itemList = new ArrayList<>();
125         try (BufferedReader reader = new BufferedReader(new InputStreamReader(in, Constants.UTF_8))) {
126             long id = 0;
127             String line = null;
128             while ((line = reader.readLine()) != null) {
129                 if (line.length() == 0 || line.charAt(0) == '#') {
130                     if (updater != null) {
131                         updater.write(line);
132                     }
133                     continue; // ignore empty lines and comments
134                 }
135 
136                 final String inputStrings = line;
137                 final String input = unescape(inputStrings);
138 
139                 if (input.length() > 0) {
140                     id++;
141                     final ProtwordsItemds/ProtwordsItem.html#ProtwordsItem">ProtwordsItem item = new ProtwordsItem(id, input);
142                     if (updater != null) {
143                         final ProtwordsItem newItem = updater.write(item);
144                         if (newItem != null) {
145                             itemList.add(newItem);
146                         } else {
147                             id--;
148                         }
149                     } else {
150                         itemList.add(item);
151                     }
152                 }
153             }
154             if (updater != null) {
155                 final ProtwordsItem item = updater.commit();
156                 if (item != null) {
157                     itemList.add(item);
158                 }
159             }
160             protwordsItemList = itemList;
161         } catch (final IOException e) {
162             throw new DictionaryException("Failed to parse " + path, e);
163         }
164     }
165 
166     private String unescape(final String s) {
167         if (s.indexOf('\\') >= 0) {
168             final StringBuilder sb = new StringBuilder();
169             for (int i = 0; i < s.length(); i++) {
170                 final char ch = s.charAt(i);
171                 if (ch == '\\' && i < s.length() - 1) {
172                     sb.append(s.charAt(++i));
173                 } else {
174                     sb.append(ch);
175                 }
176             }
177             return sb.toString();
178         }
179         return s;
180     }
181 
182     public String getSimpleName() {
183         return new File(path).getName();
184     }
185 
186     public synchronized void update(final InputStream in) throws IOException {
187         try (ProtwordsUpdater updater = new ProtwordsUpdater(null)) {
188             reload(updater, in);
189         }
190     }
191 
192     @Override
193     public String toString() {
194         return "ProtwordsFile [path=" + path + ", protwordsItemList=" + protwordsItemList + ", id=" + id + "]";
195     }
196 
197     protected class ProtwordsUpdater implements Closeable {
198 
199         protected boolean isCommit = false;
200 
201         protected File newFile;
202 
203         protected Writer writer;
204 
205         protected ProtwordsItem item;
206 
207         protected ProtwordsUpdater(final ProtwordsItem newItem) {
208             try {
209                 newFile = File.createTempFile(PROTWORDS, ".txt");
210                 writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(newFile), Constants.UTF_8));
211             } catch (final IOException e) {
212                 if (newFile != null) {
213                     newFile.delete();
214                 }
215                 throw new DictionaryException("Failed to write a userDict file.", e);
216             }
217             item = newItem;
218         }
219 
220         public ProtwordsItems/ProtwordsItem.html#ProtwordsItem">ProtwordsItem write(final ProtwordsItem oldItem) {
221             try {
222                 if (item != null && item.getId() == oldItem.getId() && item.isUpdated()) {
223                     if (item.equals(oldItem)) {
224                         try {
225                             if (!item.isDeleted()) {
226                                 // update
227                                 writer.write(item.toLineString());
228                                 writer.write(Constants.LINE_SEPARATOR);
229                                 return new ProtwordsItem(item.getId(), item.getNewInput());
230                             } else {
231                                 return null;
232                             }
233                         } finally {
234                             item.setNewInput(null);
235                         }
236                     } else {
237                         throw new DictionaryException("Protwords file was updated: old=" + oldItem + " : new=" + item);
238                     }
239                 } else {
240                     writer.write(oldItem.toLineString());
241                     writer.write(Constants.LINE_SEPARATOR);
242                     return oldItem;
243                 }
244             } catch (final IOException e) {
245                 throw new DictionaryException("Failed to write: " + oldItem + " -> " + item, e);
246             }
247         }
248 
249         public void write(final String line) {
250             try {
251                 writer.write(line);
252                 writer.write(Constants.LINE_SEPARATOR);
253             } catch (final IOException e) {
254                 throw new DictionaryException("Failed to write: " + line, e);
255             }
256         }
257 
258         public ProtwordsItem commit() {
259             isCommit = true;
260             if (item != null && item.isUpdated()) {
261                 try {
262                     writer.write(item.toLineString());
263                     writer.write(Constants.LINE_SEPARATOR);
264                     return item;
265                 } catch (final IOException e) {
266                     throw new DictionaryException("Failed to write: " + item, e);
267                 }
268             }
269             return null;
270         }
271 
272         @Override
273         public void close() {
274             try {
275                 writer.flush();
276             } catch (final IOException e) {
277                 // ignore
278             }
279             CloseableUtil.closeQuietly(writer);
280 
281             if (isCommit) {
282                 try {
283                     dictionaryManager.store(ProtwordsFile.this, newFile);
284                 } finally {
285                     newFile.delete();
286                 }
287             } else {
288                 newFile.delete();
289             }
290         }
291     }
292 }