/* * ReadOnceStrategy.java * Copyright (C) 2006 Amin Ahmad * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.ahmadsoft.postal; import java.io.File; import java.io.RandomAccessFile; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; /** * A retrieval strategy that looks up from disk the first time * and subsequently reads from cache. The Read-Once strategy * is quite acceptable for day to day usage, its main problem * being that memory usage limits cannot be enforced. * * @author Amin Ahmad */ public class ReadOnceStrategy implements PostalRetrievalStrategy { private RandomAccessFile dataFile; private RandomAccessFile indexFile; private static Map cache = Collections.synchronizedMap(new HashMap()); /** * @inheritDoc */ public void initialize(File _indexFile, File _dataFile) throws Exception { dataFile = new RandomAccessFile(_dataFile, "r"); indexFile = new RandomAccessFile(_indexFile, "r"); } private synchronized List diskLookup(int postalCode) { List result = new ArrayList(); try { indexFile.seek((postalCode-1) * 8); indexFile.readInt(); int loc = indexFile.readInt(); dataFile.seek(loc); short type=0; while (0 != (type=dataFile.readShort())) { String state = dataFile.readUTF(); String city = dataFile.readUTF(); result.add(new PostalCodeEntry(postalCode,city,state,type)); } } catch (Exception e) { throw new RuntimeException(e); } return result; } /** * @inheritDoc */ public List getCandidates(int postalCode) { if (postalCode < 1 || postalCode > 99999) { return new ArrayList(); } List candidates = null; if (!cache.containsKey(new Integer(postalCode))) { candidates = Collections.unmodifiableList(diskLookup(postalCode)); cache.put(new Integer(postalCode), candidates); } else { candidates = (List) cache.get(new Integer(postalCode)); } return candidates; } /** * @inheritDoc */ public void dispose() throws Exception { dataFile.close(); indexFile.close(); cache = null; } }