1 /* 2 * Copyright (C) 2013 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.inputmethod.latin.makedict; 18 19 import com.android.inputmethod.annotations.UsedForTesting; 20 import com.android.inputmethod.latin.makedict.FusionDictionary.WeightedString; 21 22 import java.io.File; 23 import java.io.FileNotFoundException; 24 import java.io.FileOutputStream; 25 import java.io.IOException; 26 import java.io.OutputStream; 27 import java.util.ArrayList; 28 29 /** 30 * An implementation of DictUpdater for version 3 binary dictionary. 31 */ 32 @UsedForTesting 33 public class Ver3DictUpdater extends Ver3DictDecoder implements DictUpdater { 34 private OutputStream mOutStream; 35 36 @UsedForTesting 37 public Ver3DictUpdater(final File dictFile, final int factoryType) { 38 // DictUpdater must have an updatable DictBuffer. 39 super(dictFile, ((factoryType & MASK_DICTBUFFER) == USE_BYTEARRAY) 40 ? USE_BYTEARRAY : USE_WRITABLE_BYTEBUFFER); 41 mOutStream = null; 42 } 43 44 private void openStreamAndBuffer() throws FileNotFoundException, IOException { 45 super.openDictBuffer(); 46 mOutStream = new FileOutputStream(mDictionaryBinaryFile, true /* append */); 47 } 48 49 private void close() throws IOException { 50 if (mOutStream != null) { 51 mOutStream.close(); 52 mOutStream = null; 53 } 54 } 55 56 @Override @UsedForTesting 57 public void deleteWord(final String word) throws IOException, UnsupportedFormatException { 58 if (mOutStream == null) openStreamAndBuffer(); 59 mDictBuffer.position(0); 60 readHeader(); 61 final int wordPos = getTerminalPosition(word); 62 if (wordPos != FormatSpec.NOT_VALID_WORD) { 63 mDictBuffer.position(wordPos); 64 final int flags = mDictBuffer.readUnsignedByte(); 65 mDictBuffer.position(wordPos); 66 mDictBuffer.put((byte) DynamicBinaryDictIOUtils.markAsDeleted(flags)); 67 } 68 close(); 69 } 70 71 @Override @UsedForTesting 72 public void insertWord(final String word, final int frequency, 73 final ArrayList<WeightedString> bigramStrings, 74 final ArrayList<WeightedString> shortcuts, 75 final boolean isNotAWord, final boolean isBlackListEntry) 76 throws IOException, UnsupportedFormatException { 77 if (mOutStream == null) openStreamAndBuffer(); 78 DynamicBinaryDictIOUtils.insertWord(this, mOutStream, word, frequency, bigramStrings, 79 shortcuts, isNotAWord, isBlackListEntry); 80 close(); 81 } 82 } 83