/* * InMemoryStrategy.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.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.RandomAccessFile; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; /** * A retrieval strategy that loads the entire file into memory. This * strategy may be acceptable if you are running this library as a * service (e.g. a servlet-based HTTP service). It occupies roughly * 23 megabytes of RAM under Windows XP running Java 5. * * @author Amin Ahmad */ public class InMemoryStrategy implements PostalRetrievalStrategy { private static HashMap map = new HashMap(); /** * @inheritDoc */ public void initialize(File indexFile, File dataFile) throws Exception { DataInputStream dis = new DataInputStream(new FileInputStream(indexFile)); RandomAccessFile dfRan = new RandomAccessFile(dataFile, "r"); int pc = 99999; while (99999 != (pc=dis.readInt())) { int loc = dis.readInt(); dfRan.seek(loc); List postalCodes = new ArrayList(); short type=0; while (0 != (type=dfRan.readShort())) { String state = dfRan.readUTF(); String city = dfRan.readUTF(); postalCodes.add(new PostalCodeEntry(pc,city,state,type)); } map.put(new Integer(pc), postalCodes); } dis.close(); dfRan.close(); } /** * @inheritDoc */ public List getCandidates(int postalCode) { if (map.containsKey(new Integer(postalCode))) { return Collections.unmodifiableList((List) map.get(new Integer(postalCode))); } else { return Arrays.asList(new PostalCodeEntry[] {}); } } /** * @inheritDoc */ public void dispose() throws Exception { map = null; } }