1 /*
   2  * Copyright (c) 2012, 2013, 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.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 }