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