001/* 002 * Copyright 2001-2005 Stephen Colebourne 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package org.joda.time.tz; 017 018import java.text.DateFormatSymbols; 019import java.util.HashMap; 020import java.util.Locale; 021 022/** 023 * The default name provider acquires localized names from 024 * {@link DateFormatSymbols java.text.DateFormatSymbols}. 025 * <p> 026 * DefaultNameProvider is thread-safe and immutable. 027 * 028 * @author Brian S O'Neill 029 * @since 1.0 030 */ 031public class DefaultNameProvider implements NameProvider { 032 // locale -> (id -> (nameKey -> [shortName, name])) 033 private HashMap iByLocaleCache = createCache(); 034 035 public DefaultNameProvider() { 036 } 037 038 public String getShortName(Locale locale, String id, String nameKey) { 039 String[] nameSet = getNameSet(locale, id, nameKey); 040 return nameSet == null ? null : nameSet[0]; 041 } 042 043 public String getName(Locale locale, String id, String nameKey) { 044 String[] nameSet = getNameSet(locale, id, nameKey); 045 return nameSet == null ? null : nameSet[1]; 046 } 047 048 private synchronized String[] getNameSet(Locale locale, String id, String nameKey) { 049 if (locale == null || id == null || nameKey == null) { 050 return null; 051 } 052 053 HashMap byIdCache = (HashMap)iByLocaleCache.get(locale); 054 if (byIdCache == null) { 055 iByLocaleCache.put(locale, byIdCache = createCache()); 056 } 057 058 HashMap byNameKeyCache = (HashMap)byIdCache.get(id); 059 if (byNameKeyCache == null) { 060 byIdCache.put(id, byNameKeyCache = createCache()); 061 String[][] zoneStrings = new DateFormatSymbols(locale).getZoneStrings(); 062 for (int i=0; i<zoneStrings.length; i++) { 063 String[] set = zoneStrings[i]; 064 if (set != null && set.length == 5 && id.equals(set[0])) { 065 byNameKeyCache.put(set[2], new String[] {set[2], set[1]}); 066 // need to handle case where summer and winter have the same 067 // abbreviation, such as EST in Australia [1716305] 068 // we handle this by appending "-Summer", cf ZoneInfoCompiler 069 if (set[2].equals(set[4])) { 070 byNameKeyCache.put(set[4] + "-Summer", new String[] {set[4], set[3]}); 071 } else { 072 byNameKeyCache.put(set[4], new String[] {set[4], set[3]}); 073 } 074 break; 075 } 076 } 077 } 078 079 return (String[])byNameKeyCache.get(nameKey); 080 } 081 082 private HashMap createCache() { 083 return new HashMap(7); 084 } 085}