src/share/classes/java/time/zone/TzdbZoneRulesProvider.java

Print this page




  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.io.ByteArrayInputStream;
  65 import java.io.DataInputStream;
  66 import java.io.File;
  67 import java.io.IOException;
  68 import java.io.StreamCorruptedException;
  69 import java.nio.file.FileSystems;
  70 import java.security.AccessController;
  71 import java.security.PrivilegedExceptionAction;
  72 import java.time.DateTimeException;
  73 import java.util.Arrays;
  74 import java.util.HashSet;


  75 import java.util.NavigableMap;
  76 import java.util.Objects;
  77 import java.util.Set;
  78 import java.util.TreeMap;
  79 import java.util.concurrent.ConcurrentNavigableMap;
  80 import java.util.concurrent.ConcurrentSkipListMap;
  81 import java.util.concurrent.CopyOnWriteArraySet;
  82 import java.util.concurrent.atomic.AtomicReferenceArray;
  83 import java.util.zip.ZipFile;
  84 
  85 /**
  86  * Loads time-zone rules for 'TZDB'.
  87  * <p>
  88  * This class is public for the service loader to access.
  89  *
  90  * <h3>Specification for implementors</h3>
  91  * This class is immutable and thread-safe.
  92  *
  93  * @since 1.8
  94  */
  95 final class TzdbZoneRulesProvider extends ZoneRulesProvider {
  96     // service loader seems to need it to be public
  97 
  98     /**
  99      * All the regions that are available.
 100      */
 101     private final Set<String> regionIds = new CopyOnWriteArraySet<>();




 102     /**
 103      * All the versions that are available.
 104      */
 105     private final ConcurrentNavigableMap<String, Version> versions = new ConcurrentSkipListMap<>();
 106 
 107     /**
 108      * Creates an instance.
 109      * Created by the {@code ServiceLoader}.
 110      *
 111      * @throws ZoneRulesException if unable to load
 112      */
 113     public TzdbZoneRulesProvider() {
 114         super();
 115         if (load(ClassLoader.getSystemClassLoader()) == false) {
 116             throw new ZoneRulesException("No time-zone rules found for 'TZDB'");







 117         }
 118     }
 119 
 120     //-----------------------------------------------------------------------
 121     @Override
 122     protected Set<String> provideZoneIds() {
 123         return new HashSet<>(regionIds);
 124     }
 125 
 126     @Override
 127     protected ZoneRules provideRules(String zoneId) {
 128         Objects.requireNonNull(zoneId, "zoneId");
 129         ZoneRules rules = versions.lastEntry().getValue().getRules(zoneId);
 130         if (rules == null) {
 131             throw new ZoneRulesException("Unknown time-zone ID: " + zoneId);
 132         }
 133         return rules;










 134     }
 135 
 136     @Override
 137     protected NavigableMap<String, ZoneRules> provideVersions(String zoneId) {
 138         TreeMap<String, ZoneRules> map = new TreeMap<>();
 139         for (Version version : versions.values()) {
 140             ZoneRules rules = version.getRules(zoneId);
 141             if (rules != null) {
 142                 map.put(version.versionId, rules);
 143             }
 144         }
 145         return map;
 146     }
 147 
 148     //-------------------------------------------------------------------------
 149     /**
 150      * Loads the rules.
 151      *
 152      * @param classLoader  the class loader to use, not null
 153      * @return true if updated
 154      * @throws ZoneRulesException if unable to load
 155      */
 156     private boolean load(ClassLoader classLoader) {
 157         Object updated = Boolean.FALSE;
 158         try {
 159             updated = AccessController.doPrivileged(new PrivilegedExceptionAction() {
 160                 public Object run() throws IOException, ClassNotFoundException {
 161                     File tzdbJar = null;
 162                     // TBD: workaround for now, so test/java/time tests can be
 163                     //      run against Java runtime that does not have tzdb
 164                     String tzdbProp = System.getProperty("java.time.zone.tzdbjar");
 165                     if (tzdbProp != null) {
 166                         tzdbJar = new File(tzdbProp);
 167                     } else {
 168                         String libDir = System.getProperty("java.home") + File.separator + "lib";
 169                         try {
 170                             libDir = FileSystems.getDefault().getPath(libDir).toRealPath().toString();
 171                         } catch(Exception e) {}
 172                         tzdbJar = new File(libDir, "tzdb.jar");
 173                     }
 174                     try (ZipFile zf = new ZipFile(tzdbJar);
 175                          DataInputStream dis = new DataInputStream(
 176                              zf.getInputStream(zf.getEntry("TZDB.dat")))) {
 177                         Iterable<Version> loadedVersions = load(dis);
 178                         for (Version loadedVersion : loadedVersions) {
 179                             if (versions.putIfAbsent(loadedVersion.versionId, loadedVersion) != null) {
 180                                 throw new DateTimeException(
 181                                     "Data already loaded for TZDB time-zone rules version: " +
 182                                     loadedVersion.versionId);
 183                             }
 184                         }
 185                     }
 186                     return Boolean.TRUE;
 187                 }
 188             });
 189         } catch (Exception ex) {
 190             throw new ZoneRulesException("Unable to load TZDB time-zone rules", ex);
 191         }
 192         return updated == Boolean.TRUE;
 193     }
 194 
 195     /**
 196      * Loads the rules from a DateInputStream, often in a jar file.
 197      *
 198      * @param dis  the DateInputStream to load, not null
 199      * @throws Exception if an error occurs
 200      */
 201     private Iterable<Version> load(DataInputStream dis) throws ClassNotFoundException, IOException {
 202         if (dis.readByte() != 1) {
 203             throw new StreamCorruptedException("File format not recognised");
 204         }
 205         // group
 206         String groupId = dis.readUTF();
 207         if ("TZDB".equals(groupId) == false) {
 208             throw new StreamCorruptedException("File format not recognised");
 209         }
 210         // versions
 211         int versionCount = dis.readShort();
 212         String[] versionArray = new String[versionCount];
 213         for (int i = 0; i < versionCount; i++) {
 214             versionArray[i] = dis.readUTF();
 215         }
 216         // regions
 217         int regionCount = dis.readShort();
 218         String[] regionArray = new String[regionCount];
 219         for (int i = 0; i < regionCount; i++) {
 220             regionArray[i] = dis.readUTF();
 221         }
 222         regionIds.addAll(Arrays.asList(regionArray));
 223         // rules
 224         int ruleCount = dis.readShort();
 225         Object[] ruleArray = new Object[ruleCount];
 226         for (int i = 0; i < ruleCount; i++) {
 227             byte[] bytes = new byte[dis.readShort()];
 228             dis.readFully(bytes);
 229             ruleArray[i] = bytes;
 230         }
 231         AtomicReferenceArray<Object> ruleData = new AtomicReferenceArray<>(ruleArray);
 232         // link version-region-rules
 233         Set<Version> versionSet = new HashSet<Version>(versionCount);
 234         for (int i = 0; i < versionCount; i++) {
 235             int versionRegionCount = dis.readShort();
 236             String[] versionRegionArray = new String[versionRegionCount];
 237             short[] versionRulesArray = new short[versionRegionCount];
 238             for (int j = 0; j < versionRegionCount; j++) {
 239                 versionRegionArray[j] = regionArray[dis.readShort()];
 240                 versionRulesArray[j] = dis.readShort();

 241             }
 242             versionSet.add(new Version(versionArray[i], versionRegionArray, versionRulesArray, ruleData));
 243         }
 244         return versionSet;
 245     }
 246 
 247     @Override
 248     public String toString() {
 249         return "TZDB";
 250     }
 251 
 252     //-----------------------------------------------------------------------
 253     /**
 254      * A version of the TZDB rules.
 255      */
 256     static class Version {
 257         private final String versionId;
 258         private final String[] regionArray;
 259         private final short[] ruleIndices;
 260         private final AtomicReferenceArray<Object> ruleData;
 261 
 262         Version(String versionId, String[] regionIds, short[] ruleIndices, AtomicReferenceArray<Object> ruleData) {
 263             this.ruleData = ruleData;
 264             this.versionId = versionId;
 265             this.regionArray = regionIds;
 266             this.ruleIndices = ruleIndices;
 267         }
 268 
 269         ZoneRules getRules(String regionId) {
 270             int regionIndex = Arrays.binarySearch(regionArray, regionId);
 271             if (regionIndex < 0) {
 272                 return null;
 273             }
 274             try {
 275                 return createRule(ruleIndices[regionIndex]);
 276             } catch (Exception ex) {
 277                 throw new ZoneRulesException("Invalid binary time-zone data: TZDB:" + regionId + ", version: " + versionId, ex);
 278             }
 279         }
 280 
 281         ZoneRules createRule(short index) throws Exception {
 282             Object obj = ruleData.get(index);
 283             if (obj instanceof byte[]) {
 284                 byte[] bytes = (byte[]) obj;
 285                 DataInputStream dis = new DataInputStream(new ByteArrayInputStream(bytes));
 286                 obj = Ser.read(dis);
 287                 ruleData.set(index, obj);
 288             }
 289             return (ZoneRules) obj;
 290         }
 291 
 292         @Override
 293         public String toString() {
 294             return versionId;
 295         }
 296     }
 297 
 298 }


  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.io.ByteArrayInputStream;
  65 import java.io.DataInputStream;
  66 import java.io.File;
  67 import java.io.IOException;
  68 import java.io.StreamCorruptedException;




  69 import java.util.Arrays;
  70 import java.util.HashSet;
  71 import java.util.List;
  72 import java.util.Map;
  73 import java.util.NavigableMap;
  74 import java.util.Objects;
  75 import java.util.Set;
  76 import java.util.TreeMap;
  77 import java.util.concurrent.ConcurrentHashMap;



  78 import java.util.zip.ZipFile;
  79 
  80 /**
  81  * Loads time-zone rules for 'TZDB'.





  82  *
  83  * @since 1.8
  84  */
  85 final class TzdbZoneRulesProvider extends ZoneRulesProvider {

  86 
  87     /**
  88      * All the regions that are available.
  89      */
  90     private List<String> regionIds;
  91     /**
  92      * Version Id of this tzdb rules
  93      */
  94     private String versionId;
  95     /**
  96      * Region to rules mapping
  97      */
  98     private final Map<String, Object> regionToRules = new ConcurrentHashMap<>();
  99 
 100     /**
 101      * Creates an instance.
 102      * Created by the {@code ServiceLoader}.
 103      *
 104      * @throws ZoneRulesException if unable to load
 105      */
 106     public TzdbZoneRulesProvider() {
 107         try {
 108             String libDir = System.getProperty("java.home") + File.separator + "lib";
 109             File tzdbJar = new File(libDir, "tzdb.jar");
 110             try (ZipFile zf = new ZipFile(tzdbJar);
 111                  DataInputStream dis = new DataInputStream(
 112                      zf.getInputStream(zf.getEntry("TZDB.dat")))) {
 113                 load(dis);
 114             }
 115         } catch (Exception ex) {
 116             throw new ZoneRulesException("Unable to load TZDB time-zone rules", ex);
 117         }
 118     }
 119 

 120     @Override
 121     protected Set<String> provideZoneIds() {
 122         return new HashSet<>(regionIds);
 123     }
 124 
 125     @Override
 126     protected ZoneRules provideRules(String zoneId, boolean forCaching) {
 127         // forCaching flag is ignored because this is not a dynamic provider
 128         Object obj = regionToRules.get(zoneId);
 129         if (obj == null) {
 130             throw new ZoneRulesException("Unknown time-zone ID: " + zoneId);
 131         }
 132         try {
 133             if (obj instanceof byte[]) {
 134                 byte[] bytes = (byte[]) obj;
 135                 DataInputStream dis = new DataInputStream(new ByteArrayInputStream(bytes));
 136                 obj = Ser.read(dis);
 137                 regionToRules.put(zoneId, obj);
 138             }
 139             return (ZoneRules) obj;
 140         } catch (Exception ex) {
 141             throw new ZoneRulesException("Invalid binary time-zone data: TZDB:" + zoneId + ", version: " + versionId, ex);
 142         }
 143     }
 144 
 145     @Override
 146     protected NavigableMap<String, ZoneRules> provideVersions(String zoneId) {
 147         TreeMap<String, ZoneRules> map = new TreeMap<>();
 148         ZoneRules rules = getRules(zoneId, false);

 149         if (rules != null) {
 150             map.put(versionId, rules);

 151         }
 152         return map;
 153     }
 154 















































 155     /**
 156      * Loads the rules from a DateInputStream, often in a jar file.
 157      *
 158      * @param dis  the DateInputStream to load, not null
 159      * @throws Exception if an error occurs
 160      */
 161     private void load(DataInputStream dis) throws Exception {
 162         if (dis.readByte() != 1) {
 163             throw new StreamCorruptedException("File format not recognised");
 164         }
 165         // group
 166         String groupId = dis.readUTF();
 167         if ("TZDB".equals(groupId) == false) {
 168             throw new StreamCorruptedException("File format not recognised");
 169         }
 170         // versions
 171         int versionCount = dis.readShort();

 172         for (int i = 0; i < versionCount; i++) {
 173             versionId = dis.readUTF();
 174         }
 175         // regions
 176         int regionCount = dis.readShort();
 177         String[] regionArray = new String[regionCount];
 178         for (int i = 0; i < regionCount; i++) {
 179             regionArray[i] = dis.readUTF();
 180         }
 181         regionIds = Arrays.asList(regionArray);
 182         // rules
 183         int ruleCount = dis.readShort();
 184         Object[] ruleArray = new Object[ruleCount];
 185         for (int i = 0; i < ruleCount; i++) {
 186             byte[] bytes = new byte[dis.readShort()];
 187             dis.readFully(bytes);
 188             ruleArray[i] = bytes;
 189         }

 190         // link version-region-rules

 191         for (int i = 0; i < versionCount; i++) {
 192             int versionRegionCount = dis.readShort();
 193             regionToRules.clear();

 194             for (int j = 0; j < versionRegionCount; j++) {
 195                 String region = regionArray[dis.readShort()];
 196                 Object rule = ruleArray[dis.readShort() & 0xffff];
 197                 regionToRules.put(region, rule);
 198             }

 199         }

 200     }
 201 
 202     @Override
 203     public String toString() {
 204         return "TZDB[" + versionId + "]";




























 205     }



















 206 }