1/* 2 * DiskStrategy.java 3 * Copyright (C) 2006 Amin Ahmad 4 * 5 * This program is free software; you can redistribute it and/or modify 6 * it under the terms of the GNU General Public License as published by 7 * the Free Software Foundation; either version 2 of the License, or 8 * any later version. 9 * 10 * This program is distributed in the hope that it will be useful, 11 * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 * GNU General Public License for more details. 14 * 15 * You should have received a copy of the GNU General Public License 16 * along with this program; if not, write to the Free Software 17 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 18 */ 19 20package org.ahmadsoft.postal; 21 22import java.io.File; 23import java.io.RandomAccessFile; 24import java.util.ArrayList; 25import java.util.List; 26 27/** 28 * A retrieval strategy that looks up from disk every time. There is 29 * almost no reason to use this strategy except in an interactive program 30 * because, due to the fact that lookups are synchronized, and that every 31 * lookup results in a disk access, its time characteristics are very poor. 32 * However, its space requirements are constant. 33 * 34 * @author Amin Ahmad 35 */ 36public class DiskStrategy implements PostalRetrievalStrategy { 37 38 private RandomAccessFile dataFile; 39 private RandomAccessFile indexFile; 40 41 public void initialize(File _indexFile, File _dataFile) throws Exception { 42 dataFile = new RandomAccessFile(_dataFile, "r"); 43 indexFile = new RandomAccessFile(_indexFile, "r"); 44 } 45 46 public synchronized List getCandidates(int postalCode) { 47 if (postalCode < 1 || postalCode > 99999) { 48 return new ArrayList(); 49 } 50 51 List result = new ArrayList(); 52 53 try { 54 indexFile.seek((postalCode-1) * 8); 55 indexFile.readInt(); 56 int loc = indexFile.readInt(); 57 58 dataFile.seek(loc); 59 short type=0; 60 while (0 != (type=dataFile.readShort())) { 61 String state = dataFile.readUTF(); 62 String city = dataFile.readUTF(); 63 64 result.add(new PostalCodeEntry(postalCode,city,state,type)); 65 } 66 } catch (Exception e) { 67 throw new RuntimeException(e); 68 } 69 70 71 return result; 72 } 73 74 public void dispose() throws Exception { 75 dataFile.close(); 76 indexFile.close(); 77 } 78 79} 80