Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/time/zone/ZoneRulesProvider.java
38918 views
/*1* Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425/*26* This file is available under and governed by the GNU General Public27* License version 2 only, as published by the Free Software Foundation.28* However, the following notice accompanied the original version of this29* file:30*31* Copyright (c) 2009-2012, Stephen Colebourne & Michael Nascimento Santos32*33* All rights reserved.34*35* Redistribution and use in source and binary forms, with or without36* modification, are permitted provided that the following conditions are met:37*38* * Redistributions of source code must retain the above copyright notice,39* this list of conditions and the following disclaimer.40*41* * Redistributions in binary form must reproduce the above copyright notice,42* this list of conditions and the following disclaimer in the documentation43* and/or other materials provided with the distribution.44*45* * Neither the name of JSR-310 nor the names of its contributors46* may be used to endorse or promote products derived from this software47* without specific prior written permission.48*49* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS50* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT51* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR52* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR53* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,54* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,55* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR56* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF57* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING58* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS59* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.60*/61package java.time.zone;6263import java.security.AccessController;64import java.security.PrivilegedAction;65import java.time.ZoneId;66import java.time.ZonedDateTime;67import java.util.ArrayList;68import java.util.HashSet;69import java.util.Iterator;70import java.util.List;71import java.util.NavigableMap;72import java.util.Objects;73import java.util.ServiceConfigurationError;74import java.util.ServiceLoader;75import java.util.Set;76import java.util.concurrent.ConcurrentHashMap;77import java.util.concurrent.ConcurrentMap;78import java.util.concurrent.CopyOnWriteArrayList;7980/**81* Provider of time-zone rules to the system.82* <p>83* This class manages the configuration of time-zone rules.84* The static methods provide the public API that can be used to manage the providers.85* The abstract methods provide the SPI that allows rules to be provided.86* <p>87* ZoneRulesProvider may be installed in an instance of the Java Platform as88* extension classes, that is, jar files placed into any of the usual extension89* directories. Installed providers are loaded using the service-provider loading90* facility defined by the {@link ServiceLoader} class. A ZoneRulesProvider91* identifies itself with a provider configuration file named92* {@code java.time.zone.ZoneRulesProvider} in the resource directory93* {@code META-INF/services}. The file should contain a line that specifies the94* fully qualified concrete zonerules-provider class name.95* Providers may also be made available by adding them to the class path or by96* registering themselves via {@link #registerProvider} method.97* <p>98* The Java virtual machine has a default provider that provides zone rules99* for the time-zones defined by IANA Time Zone Database (TZDB). If the system100* property {@code java.time.zone.DefaultZoneRulesProvider} is defined then101* it is taken to be the fully-qualified name of a concrete ZoneRulesProvider102* class to be loaded as the default provider, using the system class loader.103* If this system property is not defined, a system-default provider will be104* loaded to serve as the default provider.105* <p>106* Rules are looked up primarily by zone ID, as used by {@link ZoneId}.107* Only zone region IDs may be used, zone offset IDs are not used here.108* <p>109* Time-zone rules are political, thus the data can change at any time.110* Each provider will provide the latest rules for each zone ID, but they111* may also provide the history of how the rules changed.112*113* @implSpec114* This interface is a service provider that can be called by multiple threads.115* Implementations must be immutable and thread-safe.116* <p>117* Providers must ensure that once a rule has been seen by the application, the118* rule must continue to be available.119* <p>120* Providers are encouraged to implement a meaningful {@code toString} method.121* <p>122* Many systems would like to update time-zone rules dynamically without stopping the JVM.123* When examined in detail, this is a complex problem.124* Providers may choose to handle dynamic updates, however the default provider does not.125*126* @since 1.8127*/128public abstract class ZoneRulesProvider {129130/**131* The set of loaded providers.132*/133private static final CopyOnWriteArrayList<ZoneRulesProvider> PROVIDERS = new CopyOnWriteArrayList<>();134/**135* The lookup from zone ID to provider.136*/137private static final ConcurrentMap<String, ZoneRulesProvider> ZONES = new ConcurrentHashMap<>(512, 0.75f, 2);138139static {140// if the property java.time.zone.DefaultZoneRulesProvider is141// set then its value is the class name of the default provider142final List<ZoneRulesProvider> loaded = new ArrayList<>();143AccessController.doPrivileged(new PrivilegedAction<Object>() {144public Object run() {145String prop = System.getProperty("java.time.zone.DefaultZoneRulesProvider");146if (prop != null) {147try {148Class<?> c = Class.forName(prop, true, ClassLoader.getSystemClassLoader());149ZoneRulesProvider provider = ZoneRulesProvider.class.cast(c.newInstance());150registerProvider(provider);151loaded.add(provider);152} catch (Exception x) {153throw new Error(x);154}155} else {156registerProvider(new TzdbZoneRulesProvider());157}158return null;159}160});161162ServiceLoader<ZoneRulesProvider> sl = ServiceLoader.load(ZoneRulesProvider.class, ClassLoader.getSystemClassLoader());163Iterator<ZoneRulesProvider> it = sl.iterator();164while (it.hasNext()) {165ZoneRulesProvider provider;166try {167provider = it.next();168} catch (ServiceConfigurationError ex) {169if (ex.getCause() instanceof SecurityException) {170continue; // ignore the security exception, try the next provider171}172throw ex;173}174boolean found = false;175for (ZoneRulesProvider p : loaded) {176if (p.getClass() == provider.getClass()) {177found = true;178}179}180if (!found) {181registerProvider0(provider);182loaded.add(provider);183}184}185// CopyOnWriteList could be slow if lots of providers and each added individually186PROVIDERS.addAll(loaded);187}188189//-------------------------------------------------------------------------190/**191* Gets the set of available zone IDs.192* <p>193* These IDs are the string form of a {@link ZoneId}.194*195* @return a modifiable copy of the set of zone IDs, not null196*/197public static Set<String> getAvailableZoneIds() {198return new HashSet<>(ZONES.keySet());199}200201/**202* Gets the rules for the zone ID.203* <p>204* This returns the latest available rules for the zone ID.205* <p>206* This method relies on time-zone data provider files that are configured.207* These are loaded using a {@code ServiceLoader}.208* <p>209* The caching flag is designed to allow provider implementations to210* prevent the rules being cached in {@code ZoneId}.211* Under normal circumstances, the caching of zone rules is highly desirable212* as it will provide greater performance. However, there is a use case where213* the caching would not be desirable, see {@link #provideRules}.214*215* @param zoneId the zone ID as defined by {@code ZoneId}, not null216* @param forCaching whether the rules are being queried for caching,217* true if the returned rules will be cached by {@code ZoneId},218* false if they will be returned to the user without being cached in {@code ZoneId}219* @return the rules, null if {@code forCaching} is true and this220* is a dynamic provider that wants to prevent caching in {@code ZoneId},221* otherwise not null222* @throws ZoneRulesException if rules cannot be obtained for the zone ID223*/224public static ZoneRules getRules(String zoneId, boolean forCaching) {225Objects.requireNonNull(zoneId, "zoneId");226return getProvider(zoneId).provideRules(zoneId, forCaching);227}228229/**230* Gets the history of rules for the zone ID.231* <p>232* Time-zones are defined by governments and change frequently.233* This method allows applications to find the history of changes to the234* rules for a single zone ID. The map is keyed by a string, which is the235* version string associated with the rules.236* <p>237* The exact meaning and format of the version is provider specific.238* The version must follow lexicographical order, thus the returned map will239* be order from the oldest known rules to the newest available rules.240* The default 'TZDB' group uses version numbering consisting of the year241* followed by a letter, such as '2009e' or '2012f'.242* <p>243* Implementations must provide a result for each valid zone ID, however244* they do not have to provide a history of rules.245* Thus the map will always contain one element, and will only contain more246* than one element if historical rule information is available.247*248* @param zoneId the zone ID as defined by {@code ZoneId}, not null249* @return a modifiable copy of the history of the rules for the ID, sorted250* from oldest to newest, not null251* @throws ZoneRulesException if history cannot be obtained for the zone ID252*/253public static NavigableMap<String, ZoneRules> getVersions(String zoneId) {254Objects.requireNonNull(zoneId, "zoneId");255return getProvider(zoneId).provideVersions(zoneId);256}257258/**259* Gets the provider for the zone ID.260*261* @param zoneId the zone ID as defined by {@code ZoneId}, not null262* @return the provider, not null263* @throws ZoneRulesException if the zone ID is unknown264*/265private static ZoneRulesProvider getProvider(String zoneId) {266ZoneRulesProvider provider = ZONES.get(zoneId);267if (provider == null) {268if (ZONES.isEmpty()) {269throw new ZoneRulesException("No time-zone data files registered");270}271throw new ZoneRulesException("Unknown time-zone ID: " + zoneId);272}273return provider;274}275276//-------------------------------------------------------------------------277/**278* Registers a zone rules provider.279* <p>280* This adds a new provider to those currently available.281* A provider supplies rules for one or more zone IDs.282* A provider cannot be registered if it supplies a zone ID that has already been283* registered. See the notes on time-zone IDs in {@link ZoneId}, especially284* the section on using the concept of a "group" to make IDs unique.285* <p>286* To ensure the integrity of time-zones already created, there is no way287* to deregister providers.288*289* @param provider the provider to register, not null290* @throws ZoneRulesException if a zone ID is already registered291*/292public static void registerProvider(ZoneRulesProvider provider) {293Objects.requireNonNull(provider, "provider");294registerProvider0(provider);295PROVIDERS.add(provider);296}297298/**299* Registers the provider.300*301* @param provider the provider to register, not null302* @throws ZoneRulesException if unable to complete the registration303*/304private static void registerProvider0(ZoneRulesProvider provider) {305for (String zoneId : provider.provideZoneIds()) {306Objects.requireNonNull(zoneId, "zoneId");307ZoneRulesProvider old = ZONES.putIfAbsent(zoneId, provider);308if (old != null) {309throw new ZoneRulesException(310"Unable to register zone as one already registered with that ID: " + zoneId +311", currently loading from provider: " + provider);312}313}314}315316/**317* Refreshes the rules from the underlying data provider.318* <p>319* This method allows an application to request that the providers check320* for any updates to the provided rules.321* After calling this method, the offset stored in any {@link ZonedDateTime}322* may be invalid for the zone ID.323* <p>324* Dynamic update of rules is a complex problem and most applications325* should not use this method or dynamic rules.326* To achieve dynamic rules, a provider implementation will have to be written327* as per the specification of this class.328* In addition, instances of {@code ZoneRules} must not be cached in the329* application as they will become stale. However, the boolean flag on330* {@link #provideRules(String, boolean)} allows provider implementations331* to control the caching of {@code ZoneId}, potentially ensuring that332* all objects in the system see the new rules.333* Note that there is likely to be a cost in performance of a dynamic rules334* provider. Note also that no dynamic rules provider is in this specification.335*336* @return true if the rules were updated337* @throws ZoneRulesException if an error occurs during the refresh338*/339public static boolean refresh() {340boolean changed = false;341for (ZoneRulesProvider provider : PROVIDERS) {342changed |= provider.provideRefresh();343}344return changed;345}346347/**348* Constructor.349*/350protected ZoneRulesProvider() {351}352353//-----------------------------------------------------------------------354/**355* SPI method to get the available zone IDs.356* <p>357* This obtains the IDs that this {@code ZoneRulesProvider} provides.358* A provider should provide data for at least one zone ID.359* <p>360* The returned zone IDs remain available and valid for the lifetime of the application.361* A dynamic provider may increase the set of IDs as more data becomes available.362*363* @return the set of zone IDs being provided, not null364* @throws ZoneRulesException if a problem occurs while providing the IDs365*/366protected abstract Set<String> provideZoneIds();367368/**369* SPI method to get the rules for the zone ID.370* <p>371* This loads the rules for the specified zone ID.372* The provider implementation must validate that the zone ID is valid and373* available, throwing a {@code ZoneRulesException} if it is not.374* The result of the method in the valid case depends on the caching flag.375* <p>376* If the provider implementation is not dynamic, then the result of the377* method must be the non-null set of rules selected by the ID.378* <p>379* If the provider implementation is dynamic, then the flag gives the option380* of preventing the returned rules from being cached in {@link ZoneId}.381* When the flag is true, the provider is permitted to return null, where382* null will prevent the rules from being cached in {@code ZoneId}.383* When the flag is false, the provider must return non-null rules.384*385* @param zoneId the zone ID as defined by {@code ZoneId}, not null386* @param forCaching whether the rules are being queried for caching,387* true if the returned rules will be cached by {@code ZoneId},388* false if they will be returned to the user without being cached in {@code ZoneId}389* @return the rules, null if {@code forCaching} is true and this390* is a dynamic provider that wants to prevent caching in {@code ZoneId},391* otherwise not null392* @throws ZoneRulesException if rules cannot be obtained for the zone ID393*/394protected abstract ZoneRules provideRules(String zoneId, boolean forCaching);395396/**397* SPI method to get the history of rules for the zone ID.398* <p>399* This returns a map of historical rules keyed by a version string.400* The exact meaning and format of the version is provider specific.401* The version must follow lexicographical order, thus the returned map will402* be order from the oldest known rules to the newest available rules.403* The default 'TZDB' group uses version numbering consisting of the year404* followed by a letter, such as '2009e' or '2012f'.405* <p>406* Implementations must provide a result for each valid zone ID, however407* they do not have to provide a history of rules.408* Thus the map will contain at least one element, and will only contain409* more than one element if historical rule information is available.410* <p>411* The returned versions remain available and valid for the lifetime of the application.412* A dynamic provider may increase the set of versions as more data becomes available.413*414* @param zoneId the zone ID as defined by {@code ZoneId}, not null415* @return a modifiable copy of the history of the rules for the ID, sorted416* from oldest to newest, not null417* @throws ZoneRulesException if history cannot be obtained for the zone ID418*/419protected abstract NavigableMap<String, ZoneRules> provideVersions(String zoneId);420421/**422* SPI method to refresh the rules from the underlying data provider.423* <p>424* This method provides the opportunity for a provider to dynamically425* recheck the underlying data provider to find the latest rules.426* This could be used to load new rules without stopping the JVM.427* Dynamic behavior is entirely optional and most providers do not support it.428* <p>429* This implementation returns false.430*431* @return true if the rules were updated432* @throws ZoneRulesException if an error occurs during the refresh433*/434protected boolean provideRefresh() {435return false;436}437438}439440441