]> gitweb.fperrin.net Git - Dictionary.git/blob - src/com/hughes/android/dictionary/engine/Dictionary.java
Make more robust by catching some exceptions.
[Dictionary.git] / src / com / hughes / android / dictionary / engine / Dictionary.java
1 // Copyright 2011 Google Inc. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package com.hughes.android.dictionary.engine;
16
17 import java.io.DataInput;
18 import java.io.DataOutput;
19 import java.io.File;
20 import java.io.IOException;
21 import java.io.PrintStream;
22 import java.io.RandomAccessFile;
23 import java.nio.BufferUnderflowException;
24 import java.nio.MappedByteBuffer;
25 import java.nio.channels.FileChannel;
26 import java.util.ArrayList;
27 import java.util.Collections;
28 import java.util.List;
29
30 import com.hughes.android.dictionary.DictionaryInfo;
31 import com.hughes.util.CachingList;
32 import com.hughes.util.DataInputBuffer;
33 import com.hughes.util.raf.RAFList;
34 import com.hughes.util.raf.RAFListSerializer;
35
36 public class Dictionary {
37
38     private static final int CACHE_SIZE = 5000;
39
40     private static final int CURRENT_DICT_VERSION = 7;
41     private static final String END_OF_DICTIONARY = "END OF DICTIONARY";
42
43     // persisted
44     final int dictFileVersion;
45     public final long creationMillis;
46     public final String dictInfo;
47     public final List<PairEntry> pairEntries;
48     public final List<TextEntry> textEntries;
49     public final List<HtmlEntry> htmlEntries;
50     public final List<DataInputBuffer> htmlData;
51     public final List<EntrySource> sources;
52     public final List<Index> indices;
53     // Could be a local variable in constructor, but
54     // this way avoids a native-image VM bug.
55     private final MappedByteBuffer wholefile;
56
57     /**
58      * dictFileVersion 1 adds: <li>links to sources? dictFileVersion 2 adds: <li>
59      * counts of tokens in indices.
60      */
61
62     public Dictionary(final String dictInfo) {
63         this.dictFileVersion = CURRENT_DICT_VERSION;
64         this.creationMillis = System.currentTimeMillis();
65         this.dictInfo = dictInfo;
66         pairEntries = new ArrayList<>();
67         textEntries = new ArrayList<>();
68         htmlEntries = new ArrayList<>();
69         htmlData = null;
70         sources = new ArrayList<>();
71         indices = new ArrayList<>();
72         wholefile = null;
73     }
74
75     public Dictionary(final FileChannel ch) throws IOException {
76         wholefile = ch.map(FileChannel.MapMode.READ_ONLY, 0, ch.size());
77         DataInputBuffer in = new DataInputBuffer(wholefile, 0);
78         dictFileVersion = in.readInt();
79         if (dictFileVersion < 0 || dictFileVersion > CURRENT_DICT_VERSION) {
80             throw new IOException("Invalid dictionary version: " + dictFileVersion);
81         }
82         creationMillis = in.readLong();
83         dictInfo = in.readUTF();
84
85         // Load the sources, then seek past them, because reading them later
86         // disrupts the offset.
87         try {
88             final RAFList<EntrySource> rafSources = RAFList.create(in, new EntrySource.Serializer(
89                     this), dictFileVersion, dictInfo + " sources: ");
90             sources = new ArrayList<>(rafSources);
91             ch.position(rafSources.getEndOffset());
92
93             pairEntries = CachingList.create(
94                               RAFList.create(in, new PairEntry.Serializer(this), dictFileVersion, dictInfo + " pairs: "),
95                               CACHE_SIZE, false);
96             textEntries = CachingList.create(
97                               RAFList.create(in, new TextEntry.Serializer(this), dictFileVersion, dictInfo + " text: "),
98                               CACHE_SIZE, true);
99             if (dictFileVersion >= 5) {
100                 htmlEntries = CachingList.create(
101                                   RAFList.create(in, new HtmlEntry.Serializer(this), dictFileVersion, dictInfo + " html: "),
102                                   CACHE_SIZE, false);
103             } else {
104                 htmlEntries = Collections.emptyList();
105             }
106             if (dictFileVersion >= 7) {
107                 htmlData = RAFList.create(in, new HtmlEntry.DataDeserializer(), dictFileVersion, dictInfo + " html: ");
108             } else {
109                 htmlData = null;
110             }
111             indices = CachingList.createFullyCached(RAFList.create(in, new IndexSerializer(),
112                                                     dictFileVersion, dictInfo + " index: "));
113         } catch (RuntimeException e) {
114             throw new IOException("RuntimeException loading dictionary", e);
115         }
116         final String end = in.readUTF();
117         if (!end.equals(END_OF_DICTIONARY)) {
118             throw new IOException("Dictionary seems corrupt: " + end);
119         }
120     }
121
122     public void write(DataOutput out) throws IOException {
123         RandomAccessFile raf = (RandomAccessFile)out;
124         if (dictFileVersion < 7) throw new RuntimeException("write function cannot write formats older than v7!");
125         raf.writeInt(dictFileVersion);
126         raf.writeLong(creationMillis);
127         raf.writeUTF(dictInfo);
128         System.out.println("sources start: " + raf.getFilePointer());
129         RAFList.write(raf, sources, new EntrySource.Serializer(this));
130         System.out.println("pair start: " + raf.getFilePointer());
131         RAFList.write(raf, pairEntries, new PairEntry.Serializer(this), 64, true);
132         System.out.println("text start: " + raf.getFilePointer());
133         RAFList.write(raf, textEntries, new TextEntry.Serializer(this));
134         System.out.println("html index start: " + raf.getFilePointer());
135         RAFList.write(raf, htmlEntries, new HtmlEntry.Serializer(this), 64, true);
136         System.out.println("html data start: " + raf.getFilePointer());
137         assert htmlData == null;
138         RAFList.write(raf, htmlEntries, new HtmlEntry.DataSerializer(), 128, true);
139         System.out.println("indices start: " + raf.getFilePointer());
140         RAFList.write(raf, indices, new IndexSerializer());
141         System.out.println("end: " + raf.getFilePointer());
142         raf.writeUTF(END_OF_DICTIONARY);
143     }
144
145     private final class IndexSerializer implements RAFListSerializer<Index> {
146         @Override
147         public Index read(DataInput raf, final int readIndex) throws IOException {
148             return new Index(Dictionary.this, (DataInputBuffer)raf);
149         }
150
151         @Override
152         public void write(DataOutput raf, Index t) throws IOException {
153             t.write(raf);
154         }
155     }
156
157     final RAFListSerializer<HtmlEntry> htmlEntryIndexSerializer = new RAFListSerializer<HtmlEntry>() {
158         @Override
159         public void write(DataOutput raf, HtmlEntry t) {
160             assert false;
161         }
162
163         @Override
164         public HtmlEntry read(DataInput raf, int readIndex) throws IOException {
165             return htmlEntries.get(raf.readInt());
166         }
167     };
168
169     public void print(final PrintStream out) {
170         out.println("dictInfo=" + dictInfo);
171         for (final EntrySource entrySource : sources) {
172             out.printf("EntrySource: %s %d\n", entrySource.name, entrySource.numEntries);
173         }
174         out.println();
175         for (final Index index : indices) {
176             out.printf("Index: %s %s\n", index.shortName, index.longName);
177             index.print(out);
178             out.println();
179         }
180     }
181
182     public DictionaryInfo getDictionaryInfo() {
183         final DictionaryInfo result = new DictionaryInfo();
184         result.creationMillis = this.creationMillis;
185         result.dictInfo = this.dictInfo;
186         for (final Index index : indices) {
187             result.indexInfos.add(index.getIndexInfo());
188         }
189         return result;
190     }
191
192     // get DictionaryInfo for case when Dictionary cannot be opened
193     private static DictionaryInfo getErrorDictionaryInfo(final File file) {
194         final DictionaryInfo dictionaryInfo = new DictionaryInfo();
195         dictionaryInfo.uncompressedFilename = file.getName();
196         dictionaryInfo.uncompressedBytes = file.length();
197         return dictionaryInfo;
198     }
199
200     public static DictionaryInfo getDictionaryInfo(final File file) {
201         RandomAccessFile raf = null;
202         try {
203             raf = new RandomAccessFile(file, "r");
204             final Dictionary dict = new Dictionary(raf.getChannel());
205             final DictionaryInfo dictionaryInfo = dict.getDictionaryInfo();
206             dictionaryInfo.uncompressedFilename = file.getName();
207             dictionaryInfo.uncompressedBytes = file.length();
208             raf.close();
209             return dictionaryInfo;
210         } catch (IOException e) {
211             return getErrorDictionaryInfo(file);
212         } catch (IllegalArgumentException e) {
213             // Most likely due to a Buffer.limit beyond size of file,
214             // do not crash just because of a truncated dictionary file
215             return getErrorDictionaryInfo(file);
216         } catch (BufferUnderflowException e) {
217             // Most likely due to a read beyond the buffer limit set,
218             // do not crash just because of a truncated or corrupt dictionary file
219             return getErrorDictionaryInfo(file);
220         } finally {
221             if (raf != null) {
222                 try {
223                     raf.close();
224                 } catch (IOException e) {
225                     e.printStackTrace();
226                 }
227             }
228         }
229     }
230
231 }