1/*
2 *  InMemoryStrategy.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 */
19package org.ahmadsoft.postal;
20
21import java.io.DataInputStream;
22import java.io.File;
23import java.io.FileInputStream;
24import java.io.RandomAccessFile;
25import java.util.ArrayList;
26import java.util.Arrays;
27import java.util.Collections;
28import java.util.HashMap;
29import java.util.List;
30
31/**
32 * A retrieval strategy that loads the entire file into memory. This
33 * strategy may be acceptable if you are running this library as a
34 * service (e.g. a servlet-based HTTP service). It occupies roughly
35 * 23 megabytes of RAM under Windows XP running Java 5.
36 *
37 * @author Amin Ahmad
38 */
39public class InMemoryStrategy implements PostalRetrievalStrategy {
40
41	private static HashMap map = new HashMap();
42
43	/**
44	 * @inheritDoc
45	 */
46	public void initialize(File indexFile, File dataFile) throws Exception {
47		DataInputStream dis = new DataInputStream(new FileInputStream(indexFile));
48		RandomAccessFile dfRan = new RandomAccessFile(dataFile, "r");
49
50		int pc = 99999;
51		while (99999 != (pc=dis.readInt())) {
52			int loc = dis.readInt();
53
54			dfRan.seek(loc);
55
56			List postalCodes = new ArrayList();
57			short type=0;
58			while (0 != (type=dfRan.readShort())) {
59				String state = dfRan.readUTF();
60				String city = dfRan.readUTF();
61
62				postalCodes.add(new PostalCodeEntry(pc,city,state,type));
63			}
64
65			map.put(new Integer(pc), postalCodes);
66		}
67
68		dis.close();
69		dfRan.close();
70	}
71
72	/**
73	 * @inheritDoc
74	 */
75	public List getCandidates(int postalCode) {
76		if (map.containsKey(new Integer(postalCode))) {
77			return Collections.unmodifiableList((List) map.get(new Integer(postalCode)));
78		} else {
79			return Arrays.asList(new PostalCodeEntry[] {});
80		}
81	}
82
83	/**
84	 * @inheritDoc
85	 */
86	public void dispose() throws Exception {
87		map = null;
88	}
89
90}
91