/** * @author Hyacinthe MENIET * Created on 21 août 07 */ package net.dotmyself.weatherws; import java.util.HashMap; import java.util.Map; /** * Data Access Object which allows to Create, Retrieve, Update and Delete {@link City}. */ public class CityMemory { private Map mapCities = new HashMap(); private long nextId = 0; /** * Inserts the given {@link City}. * @param item * The {@link City} to insert. * @return * The key associated with the {@link City}. */ public Long create(City item) { Long key = nextKey(); item.setId(key); mapCities.put(key, item); return key; } /** * Gets a {@link City}. * @param key * The key associated with the {@link City}. * @return * The {@link City} or null if * no {@link City} could be found. */ public City retrieve(Long key) { return mapCities.get(key); } /** * Updates an existing {@link City}. * @param key * The key associated with the {@link City}. * @param item * The {@link City}. */ public void update(Long key,City item) { if (mapCities.containsKey(key)) { item.setId(key); mapCities.put(key, item); } else { throw new IllegalArgumentException("There is no City with key=" + key); } } /** * Removes the {@link City} for this key if present. * @param key * The key associated with the {@link City}. */ public void delete(Long key) { mapCities.remove(key); } /** * Searches for the given {@link City}, testing for equality using the equals method. * @param item * The {@link City}. * @return * The key or null if no key could be found. */ public Long getKey(City item) { for (Map.Entry entry : mapCities.entrySet()) { if (entry.getValue().equals(item)) { return entry.getKey(); } } return null; } /** * Returns the next key available. * @return * The next key available. */ protected Long nextKey() { return new Long(++nextId); } }