1 // Copyright 2011 Google Inc. All Rights Reserved.
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
7 // http://www.apache.org/licenses/LICENSE-2.0
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.
15 package com.hughes.android.dictionary.engine;
17 import com.hughes.android.dictionary.DictionaryInfo;
18 import com.hughes.util.CachingList;
19 import com.hughes.util.raf.RAFList;
20 import com.hughes.util.raf.RAFListSerializer;
21 import com.hughes.util.raf.RAFSerializable;
23 import java.io.ByteArrayOutputStream;
24 import java.io.DataInput;
25 import java.io.DataInputStream;
26 import java.io.DataOutput;
28 import java.io.IOException;
29 import java.io.ObjectOutputStream;
30 import java.io.PrintStream;
31 import java.io.RandomAccessFile;
32 import java.nio.channels.Channels;
33 import java.nio.channels.FileChannel;
34 import java.util.ArrayList;
35 import java.util.Collections;
36 import java.util.List;
37 import java.util.zip.GZIPOutputStream;
39 public class Dictionary implements RAFSerializable<Dictionary> {
41 private static final int CACHE_SIZE = 5000;
43 private static final int CURRENT_DICT_VERSION = 7;
44 private static final String END_OF_DICTIONARY = "END OF DICTIONARY";
47 final int dictFileVersion;
48 private final long creationMillis;
49 public final String dictInfo;
50 public final List<PairEntry> pairEntries;
51 public final List<TextEntry> textEntries;
52 public final List<HtmlEntry> htmlEntries;
53 public final List<byte[]> htmlData;
54 public final List<EntrySource> sources;
55 public final List<Index> indices;
58 * dictFileVersion 1 adds: <li>links to sources? dictFileVersion 2 adds: <li>
59 * counts of tokens in indices.
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<>();
70 sources = new ArrayList<>();
71 indices = new ArrayList<>();
74 public Dictionary(final FileChannel ch) throws IOException {
75 DataInput raf = new DataInputStream(Channels.newInputStream(ch));
76 dictFileVersion = raf.readInt();
77 if (dictFileVersion < 0 || dictFileVersion > CURRENT_DICT_VERSION) {
78 throw new IOException("Invalid dictionary version: " + dictFileVersion);
80 creationMillis = raf.readLong();
81 dictInfo = raf.readUTF();
83 // Load the sources, then seek past them, because reading them later
84 // disrupts the offset.
86 final RAFList<EntrySource> rafSources = RAFList.create(ch, new EntrySource.Serializer(
87 this), ch.position(), dictFileVersion, dictInfo + " sources: ");
88 sources = new ArrayList<>(rafSources);
89 ch.position(rafSources.getEndOffset());
91 pairEntries = CachingList.create(
92 RAFList.create(ch, new PairEntry.Serializer(this), ch.position(), dictFileVersion, dictInfo + " pairs: "),
94 textEntries = CachingList.create(
95 RAFList.create(ch, new TextEntry.Serializer(this), ch.position(), dictFileVersion, dictInfo + " text: "),
97 if (dictFileVersion >= 5) {
98 htmlEntries = CachingList.create(
99 RAFList.create(ch, new HtmlEntry.Serializer(this, ch), ch.position(), dictFileVersion, dictInfo + " html: "),
102 htmlEntries = Collections.emptyList();
104 if (dictFileVersion >= 7) {
105 htmlData = RAFList.create(ch, new HtmlEntry.DataDeserializer(), ch.position(), dictFileVersion, dictInfo + " html: ");
109 indices = CachingList.createFullyCached(RAFList.create(ch, new IndexSerializer(ch),
110 ch.position(), dictFileVersion, dictInfo + " index: "));
111 } catch (RuntimeException e) {
112 throw new IOException("RuntimeException loading dictionary", e);
114 final String end = raf.readUTF();
115 if (!end.equals(END_OF_DICTIONARY)) {
116 throw new IOException("Dictionary seems corrupt: " + end);
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, null), 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(null));
140 System.out.println("end: " + raf.getFilePointer());
141 raf.writeUTF(END_OF_DICTIONARY);
144 private void writev6Sources(RandomAccessFile out) throws IOException {
145 out.writeInt(sources.size());
146 long tocPos = out.getFilePointer();
147 out.seek(tocPos + sources.size() * 8 + 8);
148 for (EntrySource s : sources) {
149 long dataPos = out.getFilePointer();
151 out.writeLong(dataPos);
154 out.writeUTF(s.getName());
155 out.writeInt(s.getNumEntries());
157 long dataPos = out.getFilePointer();
159 out.writeLong(dataPos);
163 private void writev6PairEntries(RandomAccessFile out) throws IOException {
164 out.writeInt(pairEntries.size());
165 long tocPos = out.getFilePointer();
166 out.seek(tocPos + pairEntries.size() * 8 + 8);
167 for (PairEntry pe : pairEntries) {
168 long dataPos = out.getFilePointer();
170 out.writeLong(dataPos);
173 out.writeShort(pe.entrySource.index());
174 out.writeInt(pe.pairs.size());
175 for (PairEntry.Pair p : pe.pairs) {
176 out.writeUTF(p.lang1);
177 out.writeUTF(p.lang2);
180 long dataPos = out.getFilePointer();
182 out.writeLong(dataPos);
186 private void writev6TextEntries(RandomAccessFile out) throws IOException {
187 out.writeInt(textEntries.size());
188 long tocPos = out.getFilePointer();
189 out.seek(tocPos + textEntries.size() * 8 + 8);
190 for (TextEntry t : textEntries) {
191 long dataPos = out.getFilePointer();
193 out.writeLong(dataPos);
196 out.writeShort(t.entrySource.index());
197 out.writeUTF(t.text);
199 long dataPos = out.getFilePointer();
201 out.writeLong(dataPos);
205 private void writev6HtmlEntries(RandomAccessFile out) throws IOException {
206 out.writeInt(htmlEntries.size());
207 long tocPos = out.getFilePointer();
208 out.seek(tocPos + htmlEntries.size() * 8 + 8);
209 for (HtmlEntry h : htmlEntries) {
210 long dataPos = out.getFilePointer();
212 out.writeLong(dataPos);
215 out.writeShort(h.entrySource.index());
216 out.writeUTF(h.title);
217 byte[] data = h.getHtml().getBytes("UTF-8");
218 out.writeInt(data.length);
219 ByteArrayOutputStream baos = new ByteArrayOutputStream();
220 GZIPOutputStream gzout = new GZIPOutputStream(baos);
223 out.writeInt(baos.size());
224 out.write(baos.toByteArray());
226 long dataPos = out.getFilePointer();
228 out.writeLong(dataPos);
232 private void writev6HtmlIndices(RandomAccessFile out, List<HtmlEntry> entries) throws IOException {
233 out.writeInt(entries.size());
234 long tocPos = out.getFilePointer();
235 out.seek(tocPos + entries.size() * 8 + 8);
236 for (HtmlEntry e : entries) {
237 long dataPos = out.getFilePointer();
239 out.writeLong(dataPos);
242 out.writeInt(e.index());
244 long dataPos = out.getFilePointer();
246 out.writeLong(dataPos);
250 private void writev6IndexEntries(RandomAccessFile out, List<Index.IndexEntry> entries) throws IOException {
251 out.writeInt(entries.size());
252 long tocPos = out.getFilePointer();
253 out.seek(tocPos + entries.size() * 8 + 8);
254 for (Index.IndexEntry e : entries) {
255 long dataPos = out.getFilePointer();
257 out.writeLong(dataPos);
260 out.writeUTF(e.token);
261 out.writeInt(e.startRow);
262 out.writeInt(e.numRows);
263 final boolean hasNormalizedForm = !e.token.equals(e.normalizedToken());
264 out.writeBoolean(hasNormalizedForm);
265 if (hasNormalizedForm) out.writeUTF(e.normalizedToken());
266 writev6HtmlIndices(out, e.htmlEntries);
268 long dataPos = out.getFilePointer();
270 out.writeLong(dataPos);
274 private void writev6Index(RandomAccessFile out) throws IOException {
275 out.writeInt(indices.size());
276 long tocPos = out.getFilePointer();
277 out.seek(tocPos + indices.size() * 8 + 8);
278 for (Index idx : indices) {
279 long dataPos = out.getFilePointer();
281 out.writeLong(dataPos);
284 out.writeUTF(idx.shortName);
285 out.writeUTF(idx.longName);
286 out.writeUTF(idx.sortLanguage.getIsoCode());
287 out.writeUTF(idx.normalizerRules);
288 out.writeBoolean(idx.swapPairEntries);
289 out.writeInt(idx.mainTokenCount);
290 writev6IndexEntries(out, idx.sortedIndexEntries);
292 // write stoplist, serializing the whole Set *shudder*
293 final ByteArrayOutputStream baos = new ByteArrayOutputStream();
294 final ObjectOutputStream oos = new ObjectOutputStream(baos);
295 oos.writeObject(idx.stoplist);
297 final byte[] bytes = baos.toByteArray();
298 out.writeInt(bytes.length);
301 out.writeInt(idx.rows.size());
303 for (RowBase r : idx.rows) {
305 if (r instanceof PairEntry.Row) {
307 } else if (r instanceof TokenRow) {
308 final TokenRow tokenRow = (TokenRow)r;
309 type = tokenRow.hasMainEntry ? 1 : 3;
310 } else if (r instanceof TextEntry.Row) {
312 } else if (r instanceof HtmlEntry.Row) {
315 throw new RuntimeException("Row type not supported for v6");
318 out.writeInt(r.referenceIndex);
321 long dataPos = out.getFilePointer();
323 out.writeLong(dataPos);
327 public void writev6(DataOutput out) throws IOException {
328 RandomAccessFile raf = (RandomAccessFile)out;
330 raf.writeLong(creationMillis);
331 raf.writeUTF(dictInfo);
332 System.out.println("sources start: " + raf.getFilePointer());
334 System.out.println("pair start: " + raf.getFilePointer());
335 writev6PairEntries(raf);
336 System.out.println("text start: " + raf.getFilePointer());
337 writev6TextEntries(raf);
338 System.out.println("html index start: " + raf.getFilePointer());
339 writev6HtmlEntries(raf);
340 System.out.println("indices start: " + raf.getFilePointer());
342 System.out.println("end: " + raf.getFilePointer());
343 raf.writeUTF(END_OF_DICTIONARY);
346 private final class IndexSerializer implements RAFListSerializer<Index> {
347 private final FileChannel ch;
349 IndexSerializer(FileChannel ch) {
354 public Index read(DataInput raf, final int readIndex) throws IOException {
355 return new Index(Dictionary.this, ch, raf);
359 public void write(DataOutput raf, Index t) throws IOException {
364 final RAFListSerializer<HtmlEntry> htmlEntryIndexSerializer = new RAFListSerializer<HtmlEntry>() {
366 public void write(DataOutput raf, HtmlEntry t) {
371 public HtmlEntry read(DataInput raf, int readIndex) throws IOException {
372 return htmlEntries.get(raf.readInt());
376 public void print(final PrintStream out) {
377 out.println("dictInfo=" + dictInfo);
378 for (final EntrySource entrySource : sources) {
379 out.printf("EntrySource: %s %d\n", entrySource.name, entrySource.numEntries);
382 for (final Index index : indices) {
383 out.printf("Index: %s %s\n", index.shortName, index.longName);
389 public DictionaryInfo getDictionaryInfo() {
390 final DictionaryInfo result = new DictionaryInfo();
391 result.creationMillis = this.creationMillis;
392 result.dictInfo = this.dictInfo;
393 for (final Index index : indices) {
394 result.indexInfos.add(index.getIndexInfo());
399 public static DictionaryInfo getDictionaryInfo(final File file) {
400 RandomAccessFile raf = null;
402 raf = new RandomAccessFile(file, "r");
403 final Dictionary dict = new Dictionary(raf.getChannel());
404 final DictionaryInfo dictionaryInfo = dict.getDictionaryInfo();
405 dictionaryInfo.uncompressedFilename = file.getName();
406 dictionaryInfo.uncompressedBytes = file.length();
408 return dictionaryInfo;
409 } catch (IOException e) {
410 final DictionaryInfo dictionaryInfo = new DictionaryInfo();
411 dictionaryInfo.uncompressedFilename = file.getName();
412 dictionaryInfo.uncompressedBytes = file.length();
413 return dictionaryInfo;
418 } catch (IOException e) {