1 /*
2  * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.  Oracle designates this
8  * particular file as subject to the "Classpath" exception as provided
9  * by Oracle in the LICENSE file that accompanied this code.
10  *
11  * This code is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14  * version 2 for more details (a copy is included in the LICENSE file that
15  * accompanied this code).
16  *
17  * You should have received a copy of the GNU General Public License version
18  * 2 along with this work; if not, write to the Free Software Foundation,
19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20  *
21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22  * or visit www.oracle.com if you need additional information or have any
23  * questions.
24  */
25 
26 /*
27  * This file is available under and governed by the GNU General Public
28  * License version 2 only, as published by the Free Software Foundation.
29  * However, the following notice accompanied the original version of this
30  * file:
31  *
32  * Copyright (c) 2009-2012, Stephen Colebourne & Michael Nascimento Santos
33  *
34  * All rights reserved.
35  *
36  * Redistribution and use in source and binary forms, with or without
37  * modification, are permitted provided that the following conditions are met:
38  *
39  *  * Redistributions of source code must retain the above copyright notice,
40  *    this list of conditions and the following disclaimer.
41  *
42  *  * Redistributions in binary form must reproduce the above copyright notice,
43  *    this list of conditions and the following disclaimer in the documentation
44  *    and/or other materials provided with the distribution.
45  *
46  *  * Neither the name of JSR-310 nor the names of its contributors
47  *    may be used to endorse or promote products derived from this software
48  *    without specific prior written permission.
49  *
50  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
51  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
52  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
53  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
54  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
55  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
56  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
57  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
58  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
59  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
60  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
61  */
62 package java.time.zone;
63 
64 import java.security.AccessController;
65 import java.security.PrivilegedAction;
66 import java.time.ZoneId;
67 import java.time.ZonedDateTime;
68 import java.util.ArrayList;
69 import java.util.HashSet;
70 import java.util.Iterator;
71 import java.util.List;
72 import java.util.NavigableMap;
73 import java.util.Objects;
74 import java.util.ServiceConfigurationError;
75 import java.util.ServiceLoader;
76 import java.util.Set;
77 import java.util.concurrent.ConcurrentHashMap;
78 import java.util.concurrent.ConcurrentMap;
79 import java.util.concurrent.CopyOnWriteArrayList;
80 import java.util.Collections;
81 
82 /**
83  * Provider of time-zone rules to the system.
84  * <p>
85  * This class manages the configuration of time-zone rules.
86  * The static methods provide the public API that can be used to manage the providers.
87  * The abstract methods provide the SPI that allows rules to be provided.
88  * <p>
89  * ZoneRulesProvider may be installed in an instance of the Java Platform as
90  * extension classes, that is, jar files placed into any of the usual extension
91  * directories. Installed providers are loaded using the service-provider loading
92  * facility defined by the {@link ServiceLoader} class. A ZoneRulesProvider
93  * identifies itself with a provider configuration file named
94  * {@code java.time.zone.ZoneRulesProvider} in the resource directory
95  * {@code META-INF/services}. The file should contain a line that specifies the
96  * fully qualified concrete zonerules-provider class name.
97  * Providers may also be made available by adding them to the class path or by
98  * registering themselves via {@link #registerProvider} method.
99  * <p>
100  * The Java virtual machine has a default provider that provides zone rules
101  * for the time-zones defined by IANA Time Zone Database (TZDB). If the system
102  * property {@systemProperty java.time.zone.DefaultZoneRulesProvider} is defined then
103  * it is taken to be the fully-qualified name of a concrete ZoneRulesProvider
104  * class to be loaded as the default provider, using the system class loader.
105  * If this system property is not defined, a system-default provider will be
106  * loaded to serve as the default provider.
107  * <p>
108  * Rules are looked up primarily by zone ID, as used by {@link ZoneId}.
109  * Only zone region IDs may be used, zone offset IDs are not used here.
110  * <p>
111  * Time-zone rules are political, thus the data can change at any time.
112  * Each provider will provide the latest rules for each zone ID, but they
113  * may also provide the history of how the rules changed.
114  *
115  * @implSpec
116  * This interface is a service provider that can be called by multiple threads.
117  * Implementations must be immutable and thread-safe.
118  * <p>
119  * Providers must ensure that once a rule has been seen by the application, the
120  * rule must continue to be available.
121  * <p>
122  * Providers are encouraged to implement a meaningful {@code toString} method.
123  * <p>
124  * Many systems would like to update time-zone rules dynamically without stopping the JVM.
125  * When examined in detail, this is a complex problem.
126  * Providers may choose to handle dynamic updates, however the default provider does not.
127  *
128  * @since 1.8
129  */
130 public abstract class ZoneRulesProvider {
131 
132     /**
133      * The set of loaded providers.
134      */
135     private static final CopyOnWriteArrayList<ZoneRulesProvider> PROVIDERS = new CopyOnWriteArrayList<>();
136     /**
137      * The lookup from zone ID to provider.
138      */
139     private static final ConcurrentMap<String, ZoneRulesProvider> ZONES = new ConcurrentHashMap<>(512, 0.75f, 2);
140 
141     /**
142      * The zone ID data
143      */
144     private static volatile Set<String> ZONE_IDS;
145 
146     static {
147         // if the property java.time.zone.DefaultZoneRulesProvider is
148         // set then its value is the class name of the default provider
149         final List<ZoneRulesProvider> loaded = new ArrayList<>();
AccessController.doPrivileged(new PrivilegedAction<>() { public Object run() { String prop = System.getProperty(R); if (prop != null) { try { Class<?> c = Class.forName(prop, true, ClassLoader.getSystemClassLoader()); @SuppressWarnings(R) ZoneRulesProvider provider = ZoneRulesProvider.class.cast(c.newInstance()); registerProvider(provider); loaded.add(provider); } catch (Exception x) { throw new Error(x); } } else { registerProvider(new TzdbZoneRulesProvider()); } return null; } })150         AccessController.doPrivileged(new PrivilegedAction<>() {
151             public Object run() {
152                 String prop = System.getProperty("java.time.zone.DefaultZoneRulesProvider");
153                 if (prop != null) {
154                     try {
155                         Class<?> c = Class.forName(prop, true, ClassLoader.getSystemClassLoader());
156                         @SuppressWarnings("deprecation")
157                         ZoneRulesProvider provider = ZoneRulesProvider.class.cast(c.newInstance());
158                         registerProvider(provider);
159                         loaded.add(provider);
160                     } catch (Exception x) {
161                         throw new Error(x);
162                     }
163                 } else {
164                     registerProvider(new TzdbZoneRulesProvider());
165                 }
166                 return null;
167             }
168         });
169 
170         ServiceLoader<ZoneRulesProvider> sl = ServiceLoader.load(ZoneRulesProvider.class, ClassLoader.getSystemClassLoader());
171         Iterator<ZoneRulesProvider> it = sl.iterator();
172         while (it.hasNext()) {
173             ZoneRulesProvider provider;
174             try {
175                 provider = it.next();
176             } catch (ServiceConfigurationError ex) {
177                 if (ex.getCause() instanceof SecurityException) {
178                     continue;  // ignore the security exception, try the next provider
179                 }
180                 throw ex;
181             }
182             boolean found = false;
183             for (ZoneRulesProvider p : loaded) {
184                 if (p.getClass() == provider.getClass()) {
185                     found = true;
186                 }
187             }
188             if (!found) {
189                 registerProvider0(provider);
190                 loaded.add(provider);
191             }
192         }
193         // CopyOnWriteList could be slow if lots of providers and each added individually
194         PROVIDERS.addAll(loaded);
195     }
196 
197     //-------------------------------------------------------------------------
198     /**
199      * Gets the set of available zone IDs.
200      * <p>
201      * These IDs are the string form of a {@link ZoneId}.
202      *
203      * @return the unmodifiable set of zone IDs, not null
204      */
getAvailableZoneIds()205     public static Set<String> getAvailableZoneIds() {
206         return ZONE_IDS;
207     }
208 
209     /**
210      * Gets the rules for the zone ID.
211      * <p>
212      * This returns the latest available rules for the zone ID.
213      * <p>
214      * This method relies on time-zone data provider files that are configured.
215      * These are loaded using a {@code ServiceLoader}.
216      * <p>
217      * The caching flag is designed to allow provider implementations to
218      * prevent the rules being cached in {@code ZoneId}.
219      * Under normal circumstances, the caching of zone rules is highly desirable
220      * as it will provide greater performance. However, there is a use case where
221      * the caching would not be desirable, see {@link #provideRules}.
222      *
223      * @param zoneId the zone ID as defined by {@code ZoneId}, not null
224      * @param forCaching whether the rules are being queried for caching,
225      * true if the returned rules will be cached by {@code ZoneId},
226      * false if they will be returned to the user without being cached in {@code ZoneId}
227      * @return the rules, null if {@code forCaching} is true and this
228      * is a dynamic provider that wants to prevent caching in {@code ZoneId},
229      * otherwise not null
230      * @throws ZoneRulesException if rules cannot be obtained for the zone ID
231      */
getRules(String zoneId, boolean forCaching)232     public static ZoneRules getRules(String zoneId, boolean forCaching) {
233         Objects.requireNonNull(zoneId, "zoneId");
234         return getProvider(zoneId).provideRules(zoneId, forCaching);
235     }
236 
237     /**
238      * Gets the history of rules for the zone ID.
239      * <p>
240      * Time-zones are defined by governments and change frequently.
241      * This method allows applications to find the history of changes to the
242      * rules for a single zone ID. The map is keyed by a string, which is the
243      * version string associated with the rules.
244      * <p>
245      * The exact meaning and format of the version is provider specific.
246      * The version must follow lexicographical order, thus the returned map will
247      * be order from the oldest known rules to the newest available rules.
248      * The default 'TZDB' group uses version numbering consisting of the year
249      * followed by a letter, such as '2009e' or '2012f'.
250      * <p>
251      * Implementations must provide a result for each valid zone ID, however
252      * they do not have to provide a history of rules.
253      * Thus the map will always contain one element, and will only contain more
254      * than one element if historical rule information is available.
255      *
256      * @param zoneId  the zone ID as defined by {@code ZoneId}, not null
257      * @return a modifiable copy of the history of the rules for the ID, sorted
258      *  from oldest to newest, not null
259      * @throws ZoneRulesException if history cannot be obtained for the zone ID
260      */
getVersions(String zoneId)261     public static NavigableMap<String, ZoneRules> getVersions(String zoneId) {
262         Objects.requireNonNull(zoneId, "zoneId");
263         return getProvider(zoneId).provideVersions(zoneId);
264     }
265 
266     /**
267      * Gets the provider for the zone ID.
268      *
269      * @param zoneId  the zone ID as defined by {@code ZoneId}, not null
270      * @return the provider, not null
271      * @throws ZoneRulesException if the zone ID is unknown
272      */
getProvider(String zoneId)273     private static ZoneRulesProvider getProvider(String zoneId) {
274         ZoneRulesProvider provider = ZONES.get(zoneId);
275         if (provider == null) {
276             if (ZONES.isEmpty()) {
277                 throw new ZoneRulesException("No time-zone data files registered");
278             }
279             throw new ZoneRulesException("Unknown time-zone ID: " + zoneId);
280         }
281         return provider;
282     }
283 
284     //-------------------------------------------------------------------------
285     /**
286      * Registers a zone rules provider.
287      * <p>
288      * This adds a new provider to those currently available.
289      * A provider supplies rules for one or more zone IDs.
290      * A provider cannot be registered if it supplies a zone ID that has already been
291      * registered. See the notes on time-zone IDs in {@link ZoneId}, especially
292      * the section on using the concept of a "group" to make IDs unique.
293      * <p>
294      * To ensure the integrity of time-zones already created, there is no way
295      * to deregister providers.
296      *
297      * @param provider  the provider to register, not null
298      * @throws ZoneRulesException if a zone ID is already registered
299      */
registerProvider(ZoneRulesProvider provider)300     public static void registerProvider(ZoneRulesProvider provider) {
301         Objects.requireNonNull(provider, "provider");
302         registerProvider0(provider);
303         PROVIDERS.add(provider);
304     }
305 
306     /**
307      * Registers the provider.
308      *
309      * @param provider  the provider to register, not null
310      * @throws ZoneRulesException if unable to complete the registration
311      */
registerProvider0(ZoneRulesProvider provider)312     private static synchronized void registerProvider0(ZoneRulesProvider provider) {
313         for (String zoneId : provider.provideZoneIds()) {
314             Objects.requireNonNull(zoneId, "zoneId");
315             ZoneRulesProvider old = ZONES.putIfAbsent(zoneId, provider);
316             if (old != null) {
317                 throw new ZoneRulesException(
318                     "Unable to register zone as one already registered with that ID: " + zoneId +
319                     ", currently loading from provider: " + provider);
320             }
321         }
322         Set<String> combinedSet = new HashSet<String>(ZONES.keySet());
323         ZONE_IDS = Collections.unmodifiableSet(combinedSet);
324     }
325 
326     /**
327      * Refreshes the rules from the underlying data provider.
328      * <p>
329      * This method allows an application to request that the providers check
330      * for any updates to the provided rules.
331      * After calling this method, the offset stored in any {@link ZonedDateTime}
332      * may be invalid for the zone ID.
333      * <p>
334      * Dynamic update of rules is a complex problem and most applications
335      * should not use this method or dynamic rules.
336      * To achieve dynamic rules, a provider implementation will have to be written
337      * as per the specification of this class.
338      * In addition, instances of {@code ZoneRules} must not be cached in the
339      * application as they will become stale. However, the boolean flag on
340      * {@link #provideRules(String, boolean)} allows provider implementations
341      * to control the caching of {@code ZoneId}, potentially ensuring that
342      * all objects in the system see the new rules.
343      * Note that there is likely to be a cost in performance of a dynamic rules
344      * provider. Note also that no dynamic rules provider is in this specification.
345      *
346      * @return true if the rules were updated
347      * @throws ZoneRulesException if an error occurs during the refresh
348      */
refresh()349     public static boolean refresh() {
350         boolean changed = false;
351         for (ZoneRulesProvider provider : PROVIDERS) {
352             changed |= provider.provideRefresh();
353         }
354         return changed;
355     }
356 
357     /**
358      * Constructor.
359      */
ZoneRulesProvider()360     protected ZoneRulesProvider() {
361     }
362 
363     //-----------------------------------------------------------------------
364     /**
365      * SPI method to get the available zone IDs.
366      * <p>
367      * This obtains the IDs that this {@code ZoneRulesProvider} provides.
368      * A provider should provide data for at least one zone ID.
369      * <p>
370      * The returned zone IDs remain available and valid for the lifetime of the application.
371      * A dynamic provider may increase the set of IDs as more data becomes available.
372      *
373      * @return the set of zone IDs being provided, not null
374      * @throws ZoneRulesException if a problem occurs while providing the IDs
375      */
provideZoneIds()376     protected abstract Set<String> provideZoneIds();
377 
378     /**
379      * SPI method to get the rules for the zone ID.
380      * <p>
381      * This loads the rules for the specified zone ID.
382      * The provider implementation must validate that the zone ID is valid and
383      * available, throwing a {@code ZoneRulesException} if it is not.
384      * The result of the method in the valid case depends on the caching flag.
385      * <p>
386      * If the provider implementation is not dynamic, then the result of the
387      * method must be the non-null set of rules selected by the ID.
388      * <p>
389      * If the provider implementation is dynamic, then the flag gives the option
390      * of preventing the returned rules from being cached in {@link ZoneId}.
391      * When the flag is true, the provider is permitted to return null, where
392      * null will prevent the rules from being cached in {@code ZoneId}.
393      * When the flag is false, the provider must return non-null rules.
394      *
395      * @param zoneId the zone ID as defined by {@code ZoneId}, not null
396      * @param forCaching whether the rules are being queried for caching,
397      * true if the returned rules will be cached by {@code ZoneId},
398      * false if they will be returned to the user without being cached in {@code ZoneId}
399      * @return the rules, null if {@code forCaching} is true and this
400      * is a dynamic provider that wants to prevent caching in {@code ZoneId},
401      * otherwise not null
402      * @throws ZoneRulesException if rules cannot be obtained for the zone ID
403      */
provideRules(String zoneId, boolean forCaching)404     protected abstract ZoneRules provideRules(String zoneId, boolean forCaching);
405 
406     /**
407      * SPI method to get the history of rules for the zone ID.
408      * <p>
409      * This returns a map of historical rules keyed by a version string.
410      * The exact meaning and format of the version is provider specific.
411      * The version must follow lexicographical order, thus the returned map will
412      * be order from the oldest known rules to the newest available rules.
413      * The default 'TZDB' group uses version numbering consisting of the year
414      * followed by a letter, such as '2009e' or '2012f'.
415      * <p>
416      * Implementations must provide a result for each valid zone ID, however
417      * they do not have to provide a history of rules.
418      * Thus the map will contain at least one element, and will only contain
419      * more than one element if historical rule information is available.
420      * <p>
421      * The returned versions remain available and valid for the lifetime of the application.
422      * A dynamic provider may increase the set of versions as more data becomes available.
423      *
424      * @param zoneId  the zone ID as defined by {@code ZoneId}, not null
425      * @return a modifiable copy of the history of the rules for the ID, sorted
426      *  from oldest to newest, not null
427      * @throws ZoneRulesException if history cannot be obtained for the zone ID
428      */
provideVersions(String zoneId)429     protected abstract NavigableMap<String, ZoneRules> provideVersions(String zoneId);
430 
431     /**
432      * SPI method to refresh the rules from the underlying data provider.
433      * <p>
434      * This method provides the opportunity for a provider to dynamically
435      * recheck the underlying data provider to find the latest rules.
436      * This could be used to load new rules without stopping the JVM.
437      * Dynamic behavior is entirely optional and most providers do not support it.
438      * <p>
439      * This implementation returns false.
440      *
441      * @return true if the rules were updated
442      * @throws ZoneRulesException if an error occurs during the refresh
443      */
provideRefresh()444     protected boolean provideRefresh() {
445         return false;
446     }
447 
448 }
449