Source code for PhoneRegionList.java

package PhoneApp.Data;

import java.util.HashMap;

/**
 * Provides a mapping of phone area codes to specific regions.
 * This should be tied into the OODB, but for the sake of simplicity
 * has remained as a HashMap-based implementation.
 *
 * @version $Date: 2001/06/25 $
 * @author  Steve Franklin
 * @since   jdk 1.3.1
 */

class PhoneRegionList extends DataObject {

 /**
  * Initializes the list based on known mappings of area codes to regions.
  */

  public PhoneRegionList() {
    map = new HashMap();
    initialize();
  }

 /**
  * Returns a PhoneRegion object corresponding to a specific phone number.
  * This method does not test for phone number validity (obviously important
  * in a real application) and assumes the format ###-###-####.
  */

  public void addRegion(PhoneRegion region) {
    map.put(region.getAreaCode(),region);
  }
  
  public PhoneRegion getRegion(String phoneNumber) {
    String areaCode = getAreaCode(phoneNumber);
    PhoneRegion region = (PhoneRegion)map.get(areaCode);
    return region;
  }

 /**
  * Sets up the hash map with a set of area-code/region mappings.
  */
  private void initialize() {
    map.put(new String("555"),new PhoneRegion("555","NowhereLand","NoSuchState","USA"));
    map.put(new String("562"),new PhoneRegion("562","Long Beach","California","USA"));
    map.put(new String("818"),new PhoneRegion("818","Los Angeles","California","USA"));
    map.put(new String("213"),new PhoneRegion("213","Los Angeles","California","USA"));
    map.put(new String("858"),new PhoneRegion("858","San Diego","California","USA"));
    map.put(new String("415"),new PhoneRegion("415","San Francisco","California","USA"));
  }

 /**
  * Extracts the area code from a phone number. This code is very naive in its
  * parsing and validation
  */
  private String getAreaCode(String phoneNumber) {
    String result = "";
    if ( testString(phoneNumber,VERIFY_PHONENUMBER, VERIFY_MANDATORY, 50) ) { 
      try {
        result = phoneNumber.substring(0,3);
      } catch (Exception e) {
        // Substring failed
      }
    }
    return result;
  }
  
 /**
  * Provides the map between the phone area code (key) and the
  * associated regional info (value) */
  HashMap map = null;
}