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.mapping;
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  import java.util.regex.Matcher;
33  import java.util.regex.Pattern;
34  
35  import org.codelibs.core.io.CloseableUtil;
36  import org.codelibs.core.lang.StringUtil;
37  import org.codelibs.curl.CurlResponse;
38  import org.codelibs.fess.Constants;
39  import org.codelibs.fess.dict.DictionaryException;
40  import org.codelibs.fess.dict.DictionaryFile;
41  import org.dbflute.optional.OptionalEntity;
42  import org.slf4j.Logger;
43  import org.slf4j.LoggerFactory;
44  
45  public class CharMappingFile extends DictionaryFile<CharMappingItem> {
46      private static final Logger logger = LoggerFactory.getLogger(CharMappingFile.class);
47  
48      private static final String MAPPING = "mapping";
49  
50      List<CharMappingItem> mappingItemList;
51  
52      public CharMappingFile(final String id, final String path, final Date timestamp) {
53          super(id, path, timestamp);
54      }
55  
56      @Override
57      public String getType() {
58          return MAPPING;
59      }
60  
61      @Override
62      public String getPath() {
63          return path;
64      }
65  
66      @Override
67      public OptionalEntity<CharMappingItem> get(final long id) {
68          if (mappingItemList == null) {
69              reload(null);
70          }
71  
72          for (final CharMappingItem mappingItem : mappingItemList) {
73              if (id == mappingItem.getId()) {
74                  return OptionalEntity.of(mappingItem);
75              }
76          }
77          return OptionalEntity.empty();
78      }
79  
80      @Override
81      public synchronized PagingList<CharMappingItem> selectList(final int offset, final int size) {
82          if (mappingItemList == null) {
83              reload(null);
84          }
85  
86          if (offset >= mappingItemList.size() || offset < 0) {
87              return new PagingList<>(Collections.<CharMappingItem> emptyList(), offset, size, mappingItemList.size());
88          }
89  
90          int toIndex = offset + size;
91          if (toIndex > mappingItemList.size()) {
92              toIndex = mappingItemList.size();
93          }
94  
95          return new PagingList<>(mappingItemList.subList(offset, toIndex), offset, size, mappingItemList.size());
96      }
97  
98      @Override
99      public synchronized void insert(final CharMappingItem item) {
100         try (MappingUpdater updater = new MappingUpdater(item)) {
101             reload(updater);
102         }
103     }
104 
105     @Override
106     public synchronized void update(final CharMappingItem item) {
107         try (MappingUpdater updater = new MappingUpdater(item)) {
108             reload(updater);
109         }
110     }
111 
112     @Override
113     public synchronized void delete(final CharMappingItem item) {
114         final CharMappingItem mappingItem = item;
115         mappingItem.setNewInputs(StringUtil.EMPTY_STRINGS);
116         mappingItem.setNewOutput(StringUtil.EMPTY);
117         try (MappingUpdater updater = new MappingUpdater(item)) {
118             reload(updater);
119         }
120     }
121 
122     protected void reload(final MappingUpdater updater) {
123         try (CurlResponse curlResponse = dictionaryManager.getContentResponse(this)) {
124             reload(updater, curlResponse.getContentAsStream());
125         } catch (final IOException e) {
126             throw new DictionaryException("Failed to parse " + path, e);
127         }
128     }
129 
130     protected void reload(final MappingUpdater updater, final InputStream in) {
131         final Pattern parsePattern = Pattern.compile("(.*)\\s*=>\\s*(.*)\\s*$");
132         final List<CharMappingItem> itemList = new ArrayList<>();
133         try (BufferedReader reader = new BufferedReader(new InputStreamReader(in, Constants.UTF_8))) {
134             long id = 0;
135             String line = null;
136             while ((line = reader.readLine()) != null) {
137                 // Remove comments
138                 final String replacedLine = line.replaceAll("#.*$", StringUtil.EMPTY).trim();
139 
140                 // Skip empty lines or comment lines
141                 if (replacedLine.length() == 0) {
142                     if (updater != null) {
143                         updater.write(line);
144                     }
145                     continue;
146                 }
147 
148                 String[] inputs;
149                 String output;
150 
151                 final Matcher m = parsePattern.matcher(replacedLine);
152 
153                 if (!m.find()) {
154                     logger.warn("Failed to parse " + line + " in " + path);
155                     if (updater != null) {
156                         updater.write("# " + line);
157                     }
158                     continue;
159                 }
160 
161                 inputs = m.group(1).trim().split(",");
162                 output = m.group(2).trim();
163 
164                 if (inputs == null || output == null || inputs.length == 0) {
165                     logger.warn("Failed to parse " + line + " in " + path);
166                     if (updater != null) {
167                         updater.write("# " + line);
168                     }
169                     continue;
170                 }
171 
172                 id++;
173                 final CharMappingItemharMappingItem.html#CharMappingItem">CharMappingItem item = new CharMappingItem(id, inputs, output);
174 
175                 if (updater != null) {
176                     final CharMappingItem newItem = updater.write(item);
177                     if (newItem != null) {
178                         itemList.add(newItem);
179                     } else {
180                         id--;
181                     }
182                 } else {
183                     itemList.add(item);
184                 }
185             }
186             if (updater != null) {
187                 final CharMappingItem item = updater.commit();
188                 if (item != null) {
189                     itemList.add(item);
190                 }
191             }
192             mappingItemList = itemList;
193         } catch (final IOException e) {
194             throw new DictionaryException("Failed to parse " + path, e);
195         }
196     }
197 
198     public String getSimpleName() {
199         return new File(path).getName();
200     }
201 
202     public synchronized void update(final InputStream in) throws IOException {
203         try (MappingUpdater updater = new MappingUpdater(null)) {
204             reload(updater, in);
205         }
206     }
207 
208     @Override
209     public String toString() {
210         return "MappingFile [path=" + path + ", mappingItemList=" + mappingItemList + ", id=" + id + "]";
211     }
212 
213     protected class MappingUpdater implements Closeable {
214 
215         protected boolean isCommit = false;
216 
217         protected File newFile;
218 
219         protected Writer writer;
220 
221         protected CharMappingItem item;
222 
223         protected MappingUpdater(final CharMappingItem newItem) {
224             try {
225                 newFile = File.createTempFile(MAPPING, ".txt");
226                 writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(newFile), Constants.UTF_8));
227             } catch (final IOException e) {
228                 if (newFile != null) {
229                     newFile.delete();
230                 }
231                 throw new DictionaryException("Failed to write a userDict file.", e);
232             }
233             item = newItem;
234         }
235 
236         public CharMappingItemarMappingItem.html#CharMappingItem">CharMappingItem write(final CharMappingItem oldItem) {
237             try {
238                 if (item != null && item.getId() == oldItem.getId() && item.isUpdated()) {
239                     if (item.equals(oldItem)) {
240                         try {
241                             if (!item.isDeleted()) {
242                                 // update
243                                 writer.write(item.toLineString());
244                                 writer.write(Constants.LINE_SEPARATOR);
245                                 return new CharMappingItem(item.getId(), item.getNewInputs(), item.getNewOutput());
246                             } else {
247                                 return null;
248                             }
249                         } finally {
250                             item.setNewInputs(null);
251                             item.setNewOutput(null);
252                         }
253                     } else {
254                         throw new DictionaryException("Mapping file was updated: old=" + oldItem + " : new=" + item);
255                     }
256                 } else {
257                     writer.write(oldItem.toLineString());
258                     writer.write(Constants.LINE_SEPARATOR);
259                     return oldItem;
260                 }
261             } catch (final IOException e) {
262                 throw new DictionaryException("Failed to write: " + oldItem + " -> " + item, e);
263             }
264         }
265 
266         public void write(final String line) {
267             try {
268                 writer.write(line);
269                 writer.write(Constants.LINE_SEPARATOR);
270             } catch (final IOException e) {
271                 throw new DictionaryException("Failed to write: " + line, e);
272             }
273         }
274 
275         public CharMappingItem commit() {
276             isCommit = true;
277             if (item != null && item.isUpdated()) {
278                 try {
279                     writer.write(item.toLineString());
280                     writer.write(Constants.LINE_SEPARATOR);
281                     return item;
282                 } catch (final IOException e) {
283                     throw new DictionaryException("Failed to write: " + item, e);
284                 }
285             }
286             return null;
287         }
288 
289         @Override
290         public void close() {
291             try {
292                 writer.flush();
293             } catch (final IOException e) {
294                 // ignore
295             }
296             CloseableUtil.closeQuietly(writer);
297 
298             if (isCommit) {
299                 try {
300                     dictionaryManager.store(CharMappingFile.this, newFile);
301                 } finally {
302                     newFile.delete();
303                 }
304             } else {
305                 newFile.delete();
306             }
307         }
308     }
309 
310 }