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