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 package sun.util.calendar;
  27 
  28 import java.io.ByteArrayInputStream;
  29 import java.io.BufferedInputStream;
  30 import java.io.DataInput;
  31 import java.io.DataInputStream;
  32 import java.io.File;
  33 import java.io.FileInputStream;
  34 import java.io.IOException;
  35 import java.io.StreamCorruptedException;
  36 import java.security.AccessController;
  37 import java.security.PrivilegedAction;
  38 import java.time.LocalDateTime;
  39 import java.time.ZoneOffset;
  40 import java.util.ArrayList;
  41 import java.util.Arrays;
  42 import java.util.Calendar;
  43 import java.util.Collections;
  44 import java.util.HashMap;
  45 import java.util.List;
  46 import java.util.Locale;
  47 import java.util.Map;
  48 import java.util.Map.Entry;
  49 import java.util.Objects;
  50 import java.util.Set;
  51 import java.util.SimpleTimeZone;
  52 import java.util.concurrent.ConcurrentHashMap;
  53 import java.util.zip.CRC32;
  54 import sun.security.action.GetPropertyAction;
  55 
  56 /**
  57  * Loads TZDB time-zone rules for j.u.TimeZone
  58  * <p>
  59  * @since 1.8
  60  */
  61 public final class ZoneInfoFile {
  62 
  63     /**
  64      * Gets all available IDs supported in the Java run-time.
  65      *
  66      * @return a set of time zone IDs.
  67      */
  68     public static String[] getZoneIds() {
  69         int len = regions.length + oldMappings.length;
  70         if (!USE_OLDMAPPING) {
  71             len += 3;    // EST/HST/MST not in tzdb.dat
  72         }
  73         String[] ids = Arrays.copyOf(regions, len);
  74         int i = regions.length;
  75         if (!USE_OLDMAPPING) {
  76             ids[i++] = "EST";
  77             ids[i++] = "HST";
  78             ids[i++] = "MST";
  79         }
  80         for (int j = 0; j < oldMappings.length; j++) {
  81             ids[i++] = oldMappings[j][0];
  82         }
  83         return ids;
  84     }
  85 
  86     /**
  87      * Gets all available IDs that have the same value as the
  88      * specified raw GMT offset.
  89      *
  90      * @param rawOffset  the GMT offset in milliseconds. This
  91      *                   value should not include any daylight saving time.
  92      * @return an array of time zone IDs.
  93      */
  94     public static String[] getZoneIds(int rawOffset) {
  95         List<String> ids = new ArrayList<>();
  96         for (String id : getZoneIds()) {
  97             ZoneInfo zi = getZoneInfo(id);
  98             if (zi.getRawOffset() == rawOffset) {
  99                 ids.add(id);
 100             }
 101         }
 102         // It appears the "zi" implementation returns the
 103         // sorted list, though the specification does not
 104         // specify it. Keep the same behavior for better
 105         // compatibility.
 106         String[] list = ids.toArray(new String[ids.size()]);
 107         Arrays.sort(list);
 108         return list;
 109     }
 110 
 111     public static ZoneInfo getZoneInfo(String zoneId) {
 112         if (zoneId == null) {
 113             return null;
 114         }
 115         ZoneInfo zi = getZoneInfo0(zoneId);
 116         if (zi != null) {
 117             zi = (ZoneInfo)zi.clone();
 118             zi.setID(zoneId);
 119         }
 120         return zi;
 121     }
 122 
 123     private static ZoneInfo getZoneInfo0(String zoneId) {
 124         try {
 125             ZoneInfo zi = zones.get(zoneId);
 126             if (zi != null) {
 127                 return zi;
 128             }
 129             String zid = zoneId;
 130             if (aliases.containsKey(zoneId)) {
 131                 zid = aliases.get(zoneId);
 132             }
 133             int index = Arrays.binarySearch(regions, zid);
 134             if (index < 0) {
 135                 return null;
 136             }
 137             byte[] bytes = ruleArray[indices[index]];
 138             DataInputStream dis = new DataInputStream(new ByteArrayInputStream(bytes));
 139             zi = getZoneInfo(dis, zid);
 140             zones.put(zoneId, zi);
 141             return zi;
 142         } catch (Exception ex) {
 143             throw new RuntimeException("Invalid binary time-zone data: TZDB:" +
 144                 zoneId + ", version: " + versionId, ex);
 145         }
 146     }
 147 
 148     /**
 149      * Returns a Map from alias time zone IDs to their standard
 150      * time zone IDs.
 151      *
 152      * @return an unmodified alias mapping
 153      */
 154     public static Map<String, String> getAliasMap() {
 155         return Collections.unmodifiableMap(aliases);
 156     }
 157 
 158     /**
 159      * Gets the version of this tz data.
 160      *
 161      * @return the tzdb version
 162      */
 163     public static String getVersion() {
 164         return versionId;
 165     }
 166 
 167     /**
 168      * Gets a ZoneInfo with the given GMT offset. The object
 169      * has its ID in the format of GMT{+|-}hh:mm.
 170      *
 171      * @param originalId  the given custom id (before normalized such as "GMT+9")
 172      * @param gmtOffset   GMT offset <em>in milliseconds</em>
 173      * @return a ZoneInfo constructed with the given GMT offset
 174      */
 175     public static ZoneInfo getCustomTimeZone(String originalId, int gmtOffset) {
 176         String id = toCustomID(gmtOffset);
 177         return new ZoneInfo(id, gmtOffset);
 178     }
 179 
 180     public static String toCustomID(int gmtOffset) {
 181         char sign;
 182         int offset = gmtOffset / 60000;
 183         if (offset >= 0) {
 184             sign = '+';
 185         } else {
 186             sign = '-';
 187             offset = -offset;
 188         }
 189         int hh = offset / 60;
 190         int mm = offset % 60;
 191 
 192         char[] buf = new char[] { 'G', 'M', 'T', sign, '0', '0', ':', '0', '0' };
 193         if (hh >= 10) {
 194             buf[4] += hh / 10;
 195         }
 196         buf[5] += hh % 10;
 197         if (mm != 0) {
 198             buf[7] += mm / 10;
 199             buf[8] += mm % 10;
 200         }
 201         return new String(buf);
 202     }
 203 
 204     ///////////////////////////////////////////////////////////
 205     private ZoneInfoFile() {
 206     }
 207 
 208     private static String versionId;
 209     private static final Map<String, ZoneInfo> zones = new ConcurrentHashMap<>();
 210     private static Map<String, String> aliases = new HashMap<>();
 211 
 212     private static byte[][] ruleArray;
 213     private static String[] regions;
 214     private static int[] indices;
 215 
 216     // Flag for supporting JDK backward compatible IDs, such as "EST".
 217     private static final boolean USE_OLDMAPPING;
 218 
 219     private static String[][] oldMappings = new String[][] {
 220         { "ACT", "Australia/Darwin" },
 221         { "AET", "Australia/Sydney" },
 222         { "AGT", "America/Argentina/Buenos_Aires" },
 223         { "ART", "Africa/Cairo" },
 224         { "AST", "America/Anchorage" },
 225         { "BET", "America/Sao_Paulo" },
 226         { "BST", "Asia/Dhaka" },
 227         { "CAT", "Africa/Harare" },
 228         { "CNT", "America/St_Johns" },
 229         { "CST", "America/Chicago" },
 230         { "CTT", "Asia/Shanghai" },
 231         { "EAT", "Africa/Addis_Ababa" },
 232         { "ECT", "Europe/Paris" },
 233         { "IET", "America/Indiana/Indianapolis" },
 234         { "IST", "Asia/Kolkata" },
 235         { "JST", "Asia/Tokyo" },
 236         { "MIT", "Pacific/Apia" },
 237         { "NET", "Asia/Yerevan" },
 238         { "NST", "Pacific/Auckland" },
 239         { "PLT", "Asia/Karachi" },
 240         { "PNT", "America/Phoenix" },
 241         { "PRT", "America/Puerto_Rico" },
 242         { "PST", "America/Los_Angeles" },
 243         { "SST", "Pacific/Guadalcanal" },
 244         { "VST", "Asia/Ho_Chi_Minh" },
 245     };
 246 
 247     static {
 248         String oldmapping = GetPropertyAction
 249                 .privilegedGetProperty("sun.timezone.ids.oldmapping", "false")
 250                 .toLowerCase(Locale.ROOT);
 251         USE_OLDMAPPING = (oldmapping.equals("yes") || oldmapping.equals("true"));
 252         AccessController.doPrivileged(new PrivilegedAction<Void>() {
 253             public Void run() {
 254                 try {
 255                     String pathToRules = System.getProperty("jdk.time.tzdbfile");
 256                     if (pathToRules == null) {
 257                         pathToRules = System.getProperty("java.home") + File.separator +
 258                             "lib" +  File.separator + "tzdb.dat";
 259             }
 260                     try (DataInputStream dis = new DataInputStream(
 261                              new BufferedInputStream(new FileInputStream(
 262                                  new File(pathToRules))))) {
 263                         load(dis);
 264                     }
 265                 } catch (Exception x) {
 266                     throw new Error(x);
 267                 }
 268                 return null;
 269             }
 270         });
 271     }
 272 
 273     private static void addOldMapping() {
 274         for (String[] alias : oldMappings) {
 275             aliases.put(alias[0], alias[1]);
 276         }
 277         if (USE_OLDMAPPING) {
 278             aliases.put("EST", "America/New_York");
 279             aliases.put("MST", "America/Denver");
 280             aliases.put("HST", "Pacific/Honolulu");
 281         } else {
 282             zones.put("EST", new ZoneInfo("EST", -18000000));
 283             zones.put("MST", new ZoneInfo("MST", -25200000));
 284             zones.put("HST", new ZoneInfo("HST", -36000000));
 285         }
 286     }
 287 
 288     public static boolean useOldMapping() {
 289        return USE_OLDMAPPING;
 290     }
 291 
 292     /**
 293      * Loads the rules from a DateInputStream
 294      *
 295      * @param dis  the DateInputStream to load, not null
 296      * @throws Exception if an error occurs
 297      */
 298     private static void load(DataInputStream dis) throws ClassNotFoundException, IOException {
 299         if (dis.readByte() != 1) {
 300             throw new StreamCorruptedException("File format not recognised");
 301         }
 302         // group
 303         String groupId = dis.readUTF();
 304         if ("TZDB".equals(groupId) == false) {
 305             throw new StreamCorruptedException("File format not recognised");
 306         }
 307         // versions, only keep the last one
 308         int versionCount = dis.readShort();
 309         for (int i = 0; i < versionCount; i++) {
 310             versionId = dis.readUTF();
 311 
 312         }
 313         // regions
 314         int regionCount = dis.readShort();
 315         String[] regionArray = new String[regionCount];
 316         for (int i = 0; i < regionCount; i++) {
 317             regionArray[i] = dis.readUTF();
 318         }
 319         // rules
 320         int ruleCount = dis.readShort();
 321         ruleArray = new byte[ruleCount][];
 322         for (int i = 0; i < ruleCount; i++) {
 323             byte[] bytes = new byte[dis.readShort()];
 324             dis.readFully(bytes);
 325             ruleArray[i] = bytes;
 326         }
 327         // link version-region-rules, only keep the last version, if more than one
 328         for (int i = 0; i < versionCount; i++) {
 329             regionCount = dis.readShort();
 330             regions = new String[regionCount];
 331             indices = new int[regionCount];
 332             for (int j = 0; j < regionCount; j++) {
 333                 regions[j] = regionArray[dis.readShort()];
 334                 indices[j] = dis.readShort();
 335             }
 336         }
 337         // remove the following ids from the map, they
 338         // are exclued from the "old" ZoneInfo
 339         zones.remove("ROC");
 340         for (int i = 0; i < versionCount; i++) {
 341             int aliasCount = dis.readShort();
 342             aliases.clear();
 343             for (int j = 0; j < aliasCount; j++) {
 344                 String alias = regionArray[dis.readShort()];
 345                 String region = regionArray[dis.readShort()];
 346                 aliases.put(alias, region);
 347             }
 348         }
 349         // old us time-zone names
 350         addOldMapping();
 351     }
 352 
 353     /////////////////////////Ser/////////////////////////////////
 354     public static ZoneInfo getZoneInfo(DataInput in, String zoneId) throws Exception {
 355         byte type = in.readByte();
 356         // TBD: assert ZRULES:
 357         int stdSize = in.readInt();
 358         long[] stdTrans = new long[stdSize];
 359         for (int i = 0; i < stdSize; i++) {
 360             stdTrans[i] = readEpochSec(in);
 361         }
 362         int [] stdOffsets = new int[stdSize + 1];
 363         for (int i = 0; i < stdOffsets.length; i++) {
 364             stdOffsets[i] = readOffset(in);
 365         }
 366         int savSize = in.readInt();
 367         long[] savTrans = new long[savSize];
 368         for (int i = 0; i < savSize; i++) {
 369             savTrans[i] = readEpochSec(in);
 370         }
 371         int[] savOffsets = new int[savSize + 1];
 372         for (int i = 0; i < savOffsets.length; i++) {
 373             savOffsets[i] = readOffset(in);
 374         }
 375         int ruleSize = in.readByte();
 376         ZoneOffsetTransitionRule[] rules = new ZoneOffsetTransitionRule[ruleSize];
 377         for (int i = 0; i < ruleSize; i++) {
 378             rules[i] = new ZoneOffsetTransitionRule(in);
 379         }
 380         return getZoneInfo(zoneId, stdTrans, stdOffsets, savTrans, savOffsets, rules);
 381     }
 382 
 383     public static int readOffset(DataInput in) throws IOException {
 384         int offsetByte = in.readByte();
 385         return offsetByte == 127 ? in.readInt() : offsetByte * 900;
 386     }
 387 
 388     static long readEpochSec(DataInput in) throws IOException {
 389         int hiByte = in.readByte() & 255;
 390         if (hiByte == 255) {
 391             return in.readLong();
 392         } else {
 393             int midByte = in.readByte() & 255;
 394             int loByte = in.readByte() & 255;
 395             long tot = ((hiByte << 16) + (midByte << 8) + loByte);
 396             return (tot * 900) - 4575744000L;
 397         }
 398     }
 399 
 400     /////////////////////////ZoneRules --> ZoneInfo/////////////////////////////////
 401 
 402     // ZoneInfo starts with UTC1900
 403     private static final long UTC1900 = -2208988800L;
 404 
 405     // ZoneInfo ends with   UTC2037
 406     // LocalDateTime.of(2038, 1, 1, 0, 0, 0).toEpochSecond(ZoneOffset.UTC) - 1;
 407     private static final long UTC2037 = 2145916799L;
 408 
 409     // ZoneInfo has an ending entry for 2037, this need to be offset by
 410     // a "rawOffset"
 411     // LocalDateTime.of(2037, 1, 1, 0, 0, 0).toEpochSecond(ZoneOffset.UTC));
 412     private static final long LDT2037 = 2114380800L;
 413 
 414     //Current time. Used to determine future GMToffset transitions
 415     private static final long CURRT = System.currentTimeMillis()/1000;
 416 
 417     /* Get a ZoneInfo instance.
 418      *
 419      * @param standardTransitions  the standard transitions, not null
 420      * @param standardOffsets  the standard offsets, not null
 421      * @param savingsInstantTransitions  the standard transitions, not null
 422      * @param wallOffsets  the wall offsets, not null
 423      * @param lastRules  the recurring last rules, size 15 or less, not null
 424      */
 425     private static ZoneInfo getZoneInfo(String zoneId,
 426                                         long[] standardTransitions,
 427                                         int[] standardOffsets,
 428                                         long[] savingsInstantTransitions,
 429                                         int[] wallOffsets,
 430                                         ZoneOffsetTransitionRule[] lastRules) {
 431         int rawOffset = 0;
 432         int dstSavings = 0;
 433         int checksum = 0;
 434         int[] params = null;
 435         boolean willGMTOffsetChange = false;
 436 
 437         // rawOffset, pick the last one
 438         if (standardTransitions.length > 0) {
 439             rawOffset = standardOffsets[standardOffsets.length - 1] * 1000;
 440             willGMTOffsetChange = standardTransitions[standardTransitions.length - 1] > CURRT;
 441         }
 442         else
 443             rawOffset = standardOffsets[0] * 1000;
 444 
 445         // transitions, offsets;
 446         long[] transitions = null;
 447         int[]  offsets = null;
 448         int    nOffsets = 0;
 449         int    nTrans = 0;
 450 
 451         if (savingsInstantTransitions.length != 0) {
 452             transitions = new long[250];
 453             offsets = new int[100];    // TBD: ZoneInfo actually can't handle
 454                                        // offsets.length > 16 (4-bit index limit)
 455             // last year in trans table
 456             // It should not matter to use before or after offset for year
 457             int lastyear = getYear(savingsInstantTransitions[savingsInstantTransitions.length - 1],
 458                                    wallOffsets[savingsInstantTransitions.length - 1]);
 459             int i = 0, k = 1;
 460             while (i < savingsInstantTransitions.length &&
 461                    savingsInstantTransitions[i] < UTC1900) {
 462                 i++;     // skip any date before UTC1900
 463             }
 464             if (i < savingsInstantTransitions.length) {
 465                 // javazic writes the last GMT offset into index 0!
 466                 if (i < savingsInstantTransitions.length) {
 467                     offsets[0] = standardOffsets[standardOffsets.length - 1] * 1000;
 468                     nOffsets = 1;
 469                 }
 470                 // ZoneInfo has a beginning entry for 1900.
 471                 // Only add it if this is not the only one in table
 472                 nOffsets = addTrans(transitions, nTrans++,
 473                                     offsets, nOffsets,
 474                                     UTC1900,
 475                                     wallOffsets[i],
 476                                     getStandardOffset(standardTransitions, standardOffsets, UTC1900));
 477             }
 478 
 479             for (; i < savingsInstantTransitions.length; i++) {
 480                 long trans = savingsInstantTransitions[i];
 481                 if (trans > UTC2037) {
 482                     // no trans beyond LASTYEAR
 483                     lastyear = LASTYEAR;
 484                     break;
 485                 }
 486                 while (k < standardTransitions.length) {
 487                     // some standard offset transitions don't exist in
 488                     // savingInstantTrans, if the offset "change" doesn't
 489                     // really change the "effectiveWallOffset". For example
 490                     // the 1999/2000 pair in Zone Arg/Buenos_Aires, in which
 491                     // the daylightsaving "happened" but it actually does
 492                     // not result in the timezone switch. ZoneInfo however
 493                     // needs them in its transitions table
 494                     long trans_s = standardTransitions[k];
 495                     if (trans_s >= UTC1900) {
 496                         if (trans_s > trans)
 497                             break;
 498                         if (trans_s < trans) {
 499                             if (nOffsets + 2 >= offsets.length) {
 500                                 offsets = Arrays.copyOf(offsets, offsets.length + 100);
 501                             }
 502                             if (nTrans + 1 >= transitions.length) {
 503                                 transitions = Arrays.copyOf(transitions, transitions.length + 100);
 504                             }
 505                             nOffsets = addTrans(transitions, nTrans++, offsets, nOffsets,
 506                                                 trans_s,
 507                                                 wallOffsets[i],
 508                                                 standardOffsets[k+1]);
 509 
 510                         }
 511                     }
 512                     k++;
 513                 }
 514                 if (nOffsets + 2 >= offsets.length) {
 515                     offsets = Arrays.copyOf(offsets, offsets.length + 100);
 516                 }
 517                 if (nTrans + 1 >= transitions.length) {
 518                     transitions = Arrays.copyOf(transitions, transitions.length + 100);
 519                 }
 520                 nOffsets = addTrans(transitions, nTrans++, offsets, nOffsets,
 521                                     trans,
 522                                     wallOffsets[i + 1],
 523                                     getStandardOffset(standardTransitions, standardOffsets, trans));
 524 
 525             }
 526             // append any leftover standard trans
 527             while (k < standardTransitions.length) {
 528                 long trans = standardTransitions[k];
 529                 if (trans >= UTC1900) {
 530                     int offset = wallOffsets[i];
 531                     int offsetIndex = indexOf(offsets, 0, nOffsets, offset);
 532                     if (offsetIndex == nOffsets)
 533                         nOffsets++;
 534                     transitions[nTrans++] = ((trans * 1000) << TRANSITION_NSHIFT) |
 535                                             (offsetIndex & OFFSET_MASK);
 536                 }
 537                 k++;
 538             }
 539             if (lastRules.length > 1) {
 540                 // fill the gap between the last trans until LASTYEAR
 541                 while (lastyear++ < LASTYEAR) {
 542                     for (ZoneOffsetTransitionRule zotr : lastRules) {
 543                         long trans = zotr.getTransitionEpochSecond(lastyear);
 544                         if (nOffsets + 2 >= offsets.length) {
 545                             offsets = Arrays.copyOf(offsets, offsets.length + 100);
 546                         }
 547                         if (nTrans + 1 >= transitions.length) {
 548                             transitions = Arrays.copyOf(transitions, transitions.length + 100);
 549                         }
 550                         nOffsets = addTrans(transitions, nTrans++,
 551                                             offsets, nOffsets,
 552                                             trans,
 553                                             zotr.offsetAfter,
 554                                             zotr.standardOffset);
 555                     }
 556                 }
 557                 ZoneOffsetTransitionRule startRule =  lastRules[lastRules.length - 2];
 558                 ZoneOffsetTransitionRule endRule =  lastRules[lastRules.length - 1];
 559                 params = new int[10];
 560                 if (startRule.offsetAfter - startRule.offsetBefore < 0 &&
 561                     endRule.offsetAfter - endRule.offsetBefore > 0) {
 562                     ZoneOffsetTransitionRule tmp;
 563                     tmp = startRule;
 564                     startRule = endRule;
 565                     endRule = tmp;
 566                 }
 567                 params[0] = startRule.month - 1;
 568                 int dom = startRule.dom;
 569                 int dow = startRule.dow;
 570                 if (dow == -1) {
 571                     params[1] = dom;
 572                     params[2] = 0;
 573                 } else {
 574                     // ZoneRulesBuilder adjusts < 0 case (-1, for last, don't have
 575                     // "<=" case yet) to positive value if not February (it appears
 576                     // we don't have February cutoff in tzdata table yet)
 577                     // Ideally, if JSR310 can just pass in the nagative and
 578                     // we can then pass in the dom = -1, dow > 0 into ZoneInfo
 579                     //
 580                     // hacking, assume the >=24 is the result of ZRB optimization for
 581                     // "last", it works for now.
 582                     if (dom < 0 || dom >= 24) {
 583                         params[1] = -1;
 584                         params[2] = toCalendarDOW[dow];
 585                     } else {
 586                         params[1] = dom;
 587                         // To specify a day of week on or after an exact day of month,
 588                         // set the month to an exact month value, day-of-month to the
 589                         // day on or after which the rule is applied, and day-of-week
 590                         // to a negative Calendar.DAY_OF_WEEK DAY_OF_WEEK field value.
 591                         params[2] = -toCalendarDOW[dow];
 592                     }
 593                 }
 594                 params[3] = startRule.secondOfDay * 1000;
 595                 params[4] = toSTZTime[startRule.timeDefinition];
 596                 params[5] = endRule.month - 1;
 597                 dom = endRule.dom;
 598                 dow = endRule.dow;
 599                 if (dow == -1) {
 600                     params[6] = dom;
 601                     params[7] = 0;
 602                 } else {
 603                     // hacking: see comment above
 604                     if (dom < 0 || dom >= 24) {
 605                         params[6] = -1;
 606                         params[7] = toCalendarDOW[dow];
 607                     } else {
 608                         params[6] = dom;
 609                         params[7] = -toCalendarDOW[dow];
 610                     }
 611                 }
 612                 params[8] = endRule.secondOfDay * 1000;
 613                 params[9] = toSTZTime[endRule.timeDefinition];
 614                 dstSavings = (startRule.offsetAfter - startRule.offsetBefore) * 1000;
 615 
 616                 // Note: known mismatching -> Asia/Amman
 617                 //                            Asia/Gaza
 618                 //                            Asia/Hebron
 619                 // ZoneInfo :      startDayOfWeek=5     <= Thursday
 620                 //                 startTime=86400000   <= 24 hours
 621                 // This:           startDayOfWeek=6
 622                 //                 startTime=0
 623                 // Similar workaround needs to be applied to Africa/Cairo and
 624                 // its endDayOfWeek and endTime
 625                 // Below is the workarounds, it probably slows down everyone a little
 626                 if (params[2] == 6 && params[3] == 0 &&
 627                     (zoneId.equals("Asia/Amman") ||
 628                      zoneId.equals("Asia/Gaza") ||
 629                      zoneId.equals("Asia/Hebron"))) {
 630                     params[2] = 5;
 631                     params[3] = 86400000;
 632                 }
 633                 // Additional check for startDayOfWeek=6 and starTime=86400000
 634                 // is needed for Asia/Amman; Asia/Gasa and Asia/Hebron
 635                 if (params[2] == 7 && params[3] == 0 &&
 636                      (zoneId.equals("Asia/Amman") ||
 637                       zoneId.equals("Asia/Gaza") ||
 638                       zoneId.equals("Asia/Hebron"))) {
 639                     params[2] = 6;        // Friday
 640                     params[3] = 86400000; // 24h
 641                 }
 642                 //endDayOfWeek and endTime workaround
 643                 if (params[7] == 6 && params[8] == 0 &&
 644                     (zoneId.equals("Africa/Cairo"))) {
 645                     params[7] = 5;
 646                     params[8] = 86400000;
 647                 }
 648 
 649             } else if (nTrans > 0) {  // only do this if there is something in table already
 650                 if (lastyear < LASTYEAR) {
 651                     // ZoneInfo has an ending entry for 2037
 652                     //long trans = OffsetDateTime.of(LASTYEAR, 1, 1, 0, 0, 0, 0,
 653                     //                               ZoneOffset.ofTotalSeconds(rawOffset/1000))
 654                     //                           .toEpochSecond();
 655                     long trans = LDT2037 - rawOffset/1000;
 656 
 657                     int offsetIndex = indexOf(offsets, 0, nOffsets, rawOffset/1000);
 658                     if (offsetIndex == nOffsets)
 659                         nOffsets++;
 660                     transitions[nTrans++] = (trans * 1000) << TRANSITION_NSHIFT |
 661                                        (offsetIndex & OFFSET_MASK);
 662 
 663                 } else if (savingsInstantTransitions.length > 2) {
 664                     // Workaround: create the params based on the last pair for
 665                     // zones like Israel and Iran which have trans defined
 666                     // up until 2037, but no "transition rule" defined
 667                     //
 668                     // Note: Known mismatching for Israel, Asia/Jerusalem/Tel Aviv
 669                     // ZoneInfo:        startMode=3
 670                     //                  startMonth=2
 671                     //                  startDay=26
 672                     //                  startDayOfWeek=6
 673                     //
 674                     // This:            startMode=1
 675                     //                  startMonth=2
 676                     //                  startDay=27
 677                     //                  startDayOfWeek=0
 678                     // these two are actually the same for 2037, the SimpleTimeZone
 679                     // for the last "known" year
 680                     int m = savingsInstantTransitions.length;
 681                     long startTrans = savingsInstantTransitions[m - 2];
 682                     int startOffset = wallOffsets[m - 2 + 1];
 683                     int startStd = getStandardOffset(standardTransitions, standardOffsets, startTrans);
 684                     long endTrans =  savingsInstantTransitions[m - 1];
 685                     int endOffset = wallOffsets[m - 1 + 1];
 686                     int endStd = getStandardOffset(standardTransitions, standardOffsets, endTrans);
 687                     if (startOffset > startStd && endOffset == endStd) {
 688                         // last - 1 trans
 689                         m = savingsInstantTransitions.length - 2;
 690                         ZoneOffset before = ZoneOffset.ofTotalSeconds(wallOffsets[m]);
 691                         ZoneOffset after = ZoneOffset.ofTotalSeconds(wallOffsets[m + 1]);
 692                         LocalDateTime ldt = LocalDateTime.ofEpochSecond(savingsInstantTransitions[m], 0, before);
 693                         LocalDateTime startLDT;
 694                         if (after.getTotalSeconds() > before.getTotalSeconds()) {  // isGap()
 695                             startLDT = ldt;
 696                         } else {
 697                             startLDT = ldt.plusSeconds(wallOffsets[m + 1] - wallOffsets[m]);
 698                         }
 699                         // last trans
 700                         m = savingsInstantTransitions.length - 1;
 701                         before = ZoneOffset.ofTotalSeconds(wallOffsets[m]);
 702                         after = ZoneOffset.ofTotalSeconds(wallOffsets[m + 1]);
 703                         ldt = LocalDateTime.ofEpochSecond(savingsInstantTransitions[m], 0, before);
 704                         LocalDateTime endLDT;
 705                         if (after.getTotalSeconds() > before.getTotalSeconds()) {  // isGap()
 706                             endLDT = ldt.plusSeconds(wallOffsets[m + 1] - wallOffsets[m]);
 707                         } else {
 708                             endLDT = ldt;
 709                         }
 710                         params = new int[10];
 711                         params[0] = startLDT.getMonthValue() - 1;
 712                         params[1] = startLDT.getDayOfMonth();
 713                         params[2] = 0;
 714                         params[3] = startLDT.toLocalTime().toSecondOfDay() * 1000;
 715                         params[4] = SimpleTimeZone.WALL_TIME;
 716                         params[5] = endLDT.getMonthValue() - 1;
 717                         params[6] = endLDT.getDayOfMonth();
 718                         params[7] = 0;
 719                         params[8] = endLDT.toLocalTime().toSecondOfDay() * 1000;
 720                         params[9] = SimpleTimeZone.WALL_TIME;
 721                         dstSavings = (startOffset - startStd) * 1000;
 722                     }
 723                 }
 724             }
 725             if (transitions != null && transitions.length != nTrans) {
 726                 if (nTrans == 0) {
 727                     transitions = null;
 728                 } else {
 729                     transitions = Arrays.copyOf(transitions, nTrans);
 730                 }
 731             }
 732             if (offsets != null && offsets.length != nOffsets) {
 733                 if (nOffsets == 0) {
 734                     offsets = null;
 735                 } else {
 736                     offsets = Arrays.copyOf(offsets, nOffsets);
 737                 }
 738             }
 739             if (transitions != null) {
 740                 Checksum sum = new Checksum();
 741                 for (i = 0; i < transitions.length; i++) {
 742                     long val = transitions[i];
 743                     int dst = (int)((val >>> DST_NSHIFT) & 0xfL);
 744                     int saving = (dst == 0) ? 0 : offsets[dst];
 745                     int index = (int)(val & OFFSET_MASK);
 746                     int offset = offsets[index];
 747                     long second = (val >> TRANSITION_NSHIFT);
 748                     // javazic uses "index of the offset in offsets",
 749                     // instead of the real offset value itself to
 750                     // calculate the checksum. Have to keep doing
 751                     // the same thing, checksum is part of the
 752                     // ZoneInfo serialization form.
 753                     sum.update(second + index);
 754                     sum.update(index);
 755                     sum.update(dst == 0 ? -1 : dst);
 756                 }
 757                 checksum = (int)sum.getValue();
 758             }
 759         }
 760         return new ZoneInfo(zoneId, rawOffset, dstSavings, checksum, transitions,
 761                             offsets, params, willGMTOffsetChange);
 762     }
 763 
 764     private static int getStandardOffset(long[] standardTransitions,
 765                                          int[] standardOffsets,
 766                                          long epochSec) {
 767         // The size of stdOffsets is [0..9], with most are
 768         // [1..4] entries , simple loop search is faster
 769         //
 770         // int index  = Arrays.binarySearch(standardTransitions, epochSec);
 771         // if (index < 0) {
 772         //    // switch negative insert position to start of matched range
 773         //    index = -index - 2;
 774         // }
 775         // return standardOffsets[index + 1];
 776         int index = 0;
 777         for (; index < standardTransitions.length; index++) {
 778             if (epochSec < standardTransitions[index]) {
 779                 break;
 780             }
 781         }
 782         return standardOffsets[index];
 783     }
 784 
 785     static final int SECONDS_PER_DAY = 86400;
 786     static final int DAYS_PER_CYCLE = 146097;
 787     static final long DAYS_0000_TO_1970 = (DAYS_PER_CYCLE * 5L) - (30L * 365L + 7L);
 788 
 789     private static int getYear(long epochSecond, int offset) {
 790         long second = epochSecond + offset;  // overflow caught later
 791         long epochDay = Math.floorDiv(second, SECONDS_PER_DAY);
 792         long zeroDay = epochDay + DAYS_0000_TO_1970;
 793         // find the march-based year
 794         zeroDay -= 60;  // adjust to 0000-03-01 so leap day is at end of four year cycle
 795         long adjust = 0;
 796         if (zeroDay < 0) {
 797             // adjust negative years to positive for calculation
 798             long adjustCycles = (zeroDay + 1) / DAYS_PER_CYCLE - 1;
 799             adjust = adjustCycles * 400;
 800             zeroDay += -adjustCycles * DAYS_PER_CYCLE;
 801         }
 802         long yearEst = (400 * zeroDay + 591) / DAYS_PER_CYCLE;
 803         long doyEst = zeroDay - (365 * yearEst + yearEst / 4 - yearEst / 100 + yearEst / 400);
 804         if (doyEst < 0) {
 805             // fix estimate
 806             yearEst--;
 807             doyEst = zeroDay - (365 * yearEst + yearEst / 4 - yearEst / 100 + yearEst / 400);
 808         }
 809         yearEst += adjust;  // reset any negative year
 810         int marchDoy0 = (int) doyEst;
 811         // convert march-based values back to january-based
 812         int marchMonth0 = (marchDoy0 * 5 + 2) / 153;
 813         int month = (marchMonth0 + 2) % 12 + 1;
 814         int dom = marchDoy0 - (marchMonth0 * 306 + 5) / 10 + 1;
 815         yearEst += marchMonth0 / 10;
 816         return (int)yearEst;
 817     }
 818 
 819     private static final int toCalendarDOW[] = new int[] {
 820         -1,
 821         Calendar.MONDAY,
 822         Calendar.TUESDAY,
 823         Calendar.WEDNESDAY,
 824         Calendar.THURSDAY,
 825         Calendar.FRIDAY,
 826         Calendar.SATURDAY,
 827         Calendar.SUNDAY
 828     };
 829 
 830     private static final int toSTZTime[] = new int[] {
 831         SimpleTimeZone.UTC_TIME,
 832         SimpleTimeZone.WALL_TIME,
 833         SimpleTimeZone.STANDARD_TIME,
 834     };
 835 
 836     private static final long OFFSET_MASK = 0x0fL;
 837     private static final long DST_MASK = 0xf0L;
 838     private static final int  DST_NSHIFT = 4;
 839     private static final int  TRANSITION_NSHIFT = 12;
 840     private static final int  LASTYEAR = 2037;
 841 
 842     // from: 0 for offset lookup, 1 for dstsvings lookup
 843     private static int indexOf(int[] offsets, int from, int nOffsets, int offset) {
 844         offset *= 1000;
 845         for (; from < nOffsets; from++) {
 846             if (offsets[from] == offset)
 847                 return from;
 848         }
 849         offsets[from] = offset;
 850         return from;
 851     }
 852 
 853     // return updated nOffsets
 854     private static int addTrans(long transitions[], int nTrans,
 855                                 int offsets[], int nOffsets,
 856                                 long trans, int offset, int stdOffset) {
 857         int offsetIndex = indexOf(offsets, 0, nOffsets, offset);
 858         if (offsetIndex == nOffsets)
 859             nOffsets++;
 860         int dstIndex = 0;
 861         if (offset != stdOffset) {
 862             dstIndex = indexOf(offsets, 1, nOffsets, offset - stdOffset);
 863             if (dstIndex == nOffsets)
 864                 nOffsets++;
 865         }
 866         transitions[nTrans] = ((trans * 1000) << TRANSITION_NSHIFT) |
 867                               ((dstIndex << DST_NSHIFT) & DST_MASK) |
 868                               (offsetIndex & OFFSET_MASK);
 869         return nOffsets;
 870     }
 871 
 872     // ZoneInfo checksum, copy/pasted from javazic
 873     private static class Checksum extends CRC32 {
 874         public void update(int val) {
 875             byte[] b = new byte[4];
 876             b[0] = (byte)(val >>> 24);
 877             b[1] = (byte)(val >>> 16);
 878             b[2] = (byte)(val >>> 8);
 879             b[3] = (byte)(val);
 880             update(b);
 881         }
 882         void update(long val) {
 883             byte[] b = new byte[8];
 884             b[0] = (byte)(val >>> 56);
 885             b[1] = (byte)(val >>> 48);
 886             b[2] = (byte)(val >>> 40);
 887             b[3] = (byte)(val >>> 32);
 888             b[4] = (byte)(val >>> 24);
 889             b[5] = (byte)(val >>> 16);
 890             b[6] = (byte)(val >>> 8);
 891             b[7] = (byte)(val);
 892             update(b);
 893         }
 894     }
 895 
 896     // A simple/raw version of j.t.ZoneOffsetTransitionRule
 897     private static class ZoneOffsetTransitionRule {
 898         private final int month;
 899         private final byte dom;
 900         private final int dow;
 901         private final int secondOfDay;
 902         private final boolean timeEndOfDay;
 903         private final int timeDefinition;
 904         private final int standardOffset;
 905         private final int offsetBefore;
 906         private final int offsetAfter;
 907 
 908         ZoneOffsetTransitionRule(DataInput in) throws IOException {
 909             int data = in.readInt();
 910             int dowByte = (data & (7 << 19)) >>> 19;
 911             int timeByte = (data & (31 << 14)) >>> 14;
 912             int stdByte = (data & (255 << 4)) >>> 4;
 913             int beforeByte = (data & (3 << 2)) >>> 2;
 914             int afterByte = (data & 3);
 915 
 916             this.month = data >>> 28;
 917             this.dom = (byte)(((data & (63 << 22)) >>> 22) - 32);
 918             this.dow = dowByte == 0 ? -1 : dowByte;
 919             this.secondOfDay = timeByte == 31 ? in.readInt() : timeByte * 3600;
 920             this.timeEndOfDay = timeByte == 24;
 921             this.timeDefinition = (data & (3 << 12)) >>> 12;
 922 
 923             this.standardOffset = stdByte == 255 ? in.readInt() : (stdByte - 128) * 900;
 924             this.offsetBefore = beforeByte == 3 ? in.readInt() : standardOffset + beforeByte * 1800;
 925             this.offsetAfter = afterByte == 3 ? in.readInt() : standardOffset + afterByte * 1800;
 926         }
 927 
 928         long getTransitionEpochSecond(int year) {
 929             long epochDay = 0;
 930             if (dom < 0) {
 931                 epochDay = toEpochDay(year, month, lengthOfMonth(year, month) + 1 + dom);
 932                 if (dow != -1) {
 933                     epochDay = previousOrSame(epochDay, dow);
 934                 }
 935             } else {
 936                 epochDay = toEpochDay(year, month, dom);
 937                 if (dow != -1) {
 938                     epochDay = nextOrSame(epochDay, dow);
 939                 }
 940             }
 941             if (timeEndOfDay) {
 942                 epochDay += 1;
 943             }
 944             int difference = 0;
 945             switch (timeDefinition) {
 946                 case 0:    // UTC
 947                     difference = 0;
 948                     break;
 949                 case 1:    // WALL
 950                     difference = -offsetBefore;
 951                     break;
 952                 case 2:    //STANDARD
 953                     difference = -standardOffset;
 954                     break;
 955             }
 956             return epochDay * 86400 + secondOfDay + difference;
 957         }
 958 
 959         static final boolean isLeapYear(int year) {
 960             return ((year & 3) == 0) && ((year % 100) != 0 || (year % 400) == 0);
 961         }
 962 
 963         static final int lengthOfMonth(int year, int month) {
 964             switch (month) {
 965                 case 2:        //FEBRUARY:
 966                     return isLeapYear(year)? 29 : 28;
 967                 case 4:        //APRIL:
 968                 case 6:        //JUNE:
 969                 case 9:        //SEPTEMBER:
 970                 case 11:       //NOVEMBER:
 971                     return 30;
 972                 default:
 973                     return 31;
 974             }
 975         }
 976 
 977         static final long toEpochDay(int year, int month, int day) {
 978             long y = year;
 979             long m = month;
 980             long total = 0;
 981             total += 365 * y;
 982             if (y >= 0) {
 983                 total += (y + 3) / 4 - (y + 99) / 100 + (y + 399) / 400;
 984             } else {
 985                 total -= y / -4 - y / -100 + y / -400;
 986             }
 987             total += ((367 * m - 362) / 12);
 988             total += day - 1;
 989             if (m > 2) {
 990                 total--;
 991                 if (!isLeapYear(year)) {
 992                     total--;
 993                 }
 994             }
 995             return total - DAYS_0000_TO_1970;
 996         }
 997 
 998         static final long previousOrSame(long epochDay, int dayOfWeek) {
 999             return adjust(epochDay, dayOfWeek, 1);
1000         }
1001 
1002         static final long nextOrSame(long epochDay, int dayOfWeek) {
1003            return adjust(epochDay, dayOfWeek, 0);
1004         }
1005 
1006         static final long adjust(long epochDay, int dow, int relative) {
1007             int calDow = (int)Math.floorMod(epochDay + 3, 7L) + 1;
1008             if (relative < 2 && calDow == dow) {
1009                 return epochDay;
1010             }
1011             if ((relative & 1) == 0) {
1012                 int daysDiff = calDow - dow;
1013                 return epochDay + (daysDiff >= 0 ? 7 - daysDiff : -daysDiff);
1014             } else {
1015                 int daysDiff = dow - calDow;
1016                 return epochDay - (daysDiff >= 0 ? 7 - daysDiff : -daysDiff);
1017             }
1018         }
1019     }
1020 }