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