/** * Gets the size of the provided area code map storage. The map storage passed-in will be filled * as a result. */ private static int getSizeOfAreaCodeMapStorage(AreaCodeMapStorageStrategy mapStorage, SortedMap <Integer, String> areaCodeMap) { mapStorage.readFromSortedMap(areaCodeMap); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); mapStorage.writeExternal(objectOutputStream); objectOutputStream.flush(); int sizeOfStorage = byteArrayOutputStream.size(); objectOutputStream.close(); return(sizeOfStorage); }
/** * Supports Java Serialization. */ public override void readExternal(ObjectInput objectInput) { // Read the area code map storage strategy flag. boolean useFlyweightMapStorage = objectInput.readBoolean(); if (useFlyweightMapStorage) { areaCodeMapStorage = new FlyweightMapStorage(); } else { areaCodeMapStorage = new DefaultMapStorage(); } areaCodeMapStorage.readExternal(objectInput); }
/** * Gets the smaller area code map storage strategy according to the provided area code map. It * actually uses (outputs the data to a stream) both strategies and retains the best one which * make this method quite expensive. */ // @VisibleForTesting internal AreaCodeMapStorageStrategy getSmallerMapStorage(SortedMap <Integer, String> areaCodeMap) { try { AreaCodeMapStorageStrategy flyweightMapStorage = createFlyweightMapStorage(); int sizeOfFlyweightMapStorage = getSizeOfAreaCodeMapStorage(flyweightMapStorage, areaCodeMap); AreaCodeMapStorageStrategy defaultMapStorage = createDefaultMapStorage(); int sizeOfDefaultMapStorage = getSizeOfAreaCodeMapStorage(defaultMapStorage, areaCodeMap); return(sizeOfFlyweightMapStorage < sizeOfDefaultMapStorage ? flyweightMapStorage : defaultMapStorage); } catch (IOException e) { LOGGER.severe(e.getMessage()); return(createFlyweightMapStorage()); } }
/** * Creates an {@link AreaCodeMap} initialized with {@code sortedAreaCodeMap}. Note that the * underlying implementation of this method is expensive thus should not be called by * time-critical applications. * * @param sortedAreaCodeMap a map from phone number prefixes to descriptions of corresponding * geographical areas, sorted in ascending order of the phone number prefixes as integers. */ public void readAreaCodeMap(SortedMap <Integer, String> sortedAreaCodeMap) { areaCodeMapStorage = getSmallerMapStorage(sortedAreaCodeMap); }