package com.cedarsoft.business.contact.postal;
import com.cedarsoft.business.AbstractCodesProvider;
import com.cedarsoft.business.contact.City;
import com.cedarsoft.business.contact.CityCodeProvider;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.LineIterator;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.net.URL;
import java.util.Locale;
import java.util.Collection;
/**
* A special class that is able to parse German postal codes
*/
public class GermanPostalCodesProvider extends AbstractCodesProvider implements CityCodeProvider {
@NonNls
private static final String RESOURCE_NAME_DE_PLZ_TXT = "de_plz.txt";
public GermanPostalCodesProvider() throws IOException {
URL resource = getClass().getResource( RESOURCE_NAME_DE_PLZ_TXT );
if ( resource == null ) {
throw new IOException( "Resource \"" + RESOURCE_NAME_DE_PLZ_TXT + "\" not found" );
}
LineIterator iterator = IOUtils.lineIterator( resource.openStream(), "UTF-8" );
while ( iterator.hasNext() ) {
String line = iterator.nextLine();
String[] parts = line.split( "\t" );
if ( parts.length == 0 ) {
continue;
}
code2names.put( parts[0], parts[1] );
name2codes.put( parts[1], parts[0] );
}
}
/**
* Returns the first city for the given postal code
*
* @param postalCode the postal code
* @return the first city for the given postal code
*/
@NotNull
public City getCity( @NotNull @NonNls String postalCode ) {
String cityName = getCityNames( postalCode ).iterator().next();
return new City( postalCode, cityName );
}
@NotNull
@NonNls
public Collection<String> getCityNames( @NotNull @NonNls String code ) {
return getNames( code );
}
@NotNull
@NonNls
public String getCountryCode() {
return Locale.GERMANY.getCountry();
}
}