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         USE_OLDMAPPING = AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
 249             public Boolean run() {
 250                 try {
 251                     String libDir = System.getProperty("java.home") + File.separator + "lib";
 252                     try (DataInputStream dis = new DataInputStream(
 253                              new BufferedInputStream(new FileInputStream(
 254                                  new File(libDir, "tzdb.dat"))))) {
 255                         load(dis);
 256                     }
 257                 } catch (Exception x) {
 258                     throw new Error(x);
 259                 }
 260                 String oldmapping = System.getProperty("sun.timezone.ids.oldmapping", "false")
 261                     .toLowerCase(Locale.ROOT);
 262                 return (oldmapping.equals("yes") || oldmapping.equals("true"));
 263             }
 264         });
 265     }
 266 
 267     private static void addOldMapping() {
 268         for (String[] alias : oldMappings) {
 269             aliases.put(alias[0], alias[1]);
 270         }
 271         if (USE_OLDMAPPING) {
 272             aliases.put("EST", "America/New_York");
 273             aliases.put("MST", "America/Denver");
 274             aliases.put("HST", "Pacific/Honolulu");
 275         } else {
 276             zones.put("EST", new ZoneInfo("EST", -18000000));
 277             zones.put("MST", new ZoneInfo("MST", -25200000));
 278             zones.put("HST", new ZoneInfo("HST", -36000000));
 279         }
 280     }
 281 
 282     public static boolean useOldMapping() {
 283        return USE_OLDMAPPING;
 284     }
 285 
 286     /**
 287      * Loads the rules from a DateInputStream
 288      *
 289      * @param dis  the DateInputStream to load, not null
 290      * @throws Exception if an error occurs
 291      */
 292     private static void load(DataInputStream dis) throws ClassNotFoundException, IOException {
 293         if (dis.readByte() != 1) {
 294             throw new StreamCorruptedException("File format not recognised");
 295         }
 296         // group
 297         String groupId = dis.readUTF();
 298         if ("TZDB".equals(groupId) == false) {
 299             throw new StreamCorruptedException("File format not recognised");
 300         }
 301         // versions, only keep the last one
 302         int versionCount = dis.readShort();
 303         for (int i = 0; i < versionCount; i++) {
 304             versionId = dis.readUTF();
 305 
 306         }
 307         // regions
 308         int regionCount = dis.readShort();
 309         String[] regionArray = new String[regionCount];
 310         for (int i = 0; i < regionCount; i++) {
 311             regionArray[i] = dis.readUTF();
 312         }
 313         // rules
 314         int ruleCount = dis.readShort();
 315         ruleArray = new byte[ruleCount][];
 316         for (int i = 0; i < ruleCount; i++) {
 317             byte[] bytes = new byte[dis.readShort()];
 318             dis.readFully(bytes);
 319             ruleArray[i] = bytes;
 320         }
 321         // link version-region-rules, only keep the last version, if more than one
 322         for (int i = 0; i < versionCount; i++) {
 323             regionCount = dis.readShort();
 324             regions = new String[regionCount];
 325             indices = new int[regionCount];
 326             for (int j = 0; j < regionCount; j++) {
 327                 regions[j] = regionArray[dis.readShort()];
 328                 indices[j] = dis.readShort();
 329             }
 330         }
 331         // remove the following ids from the map, they
 332         // are exclued from the "old" ZoneInfo
 333         zones.remove("ROC");
 334         for (int i = 0; i < versionCount; i++) {
 335             int aliasCount = dis.readShort();
 336             aliases.clear();
 337             for (int j = 0; j < aliasCount; j++) {
 338                 String alias = regionArray[dis.readShort()];
 339                 String region = regionArray[dis.readShort()];
 340                 aliases.put(alias, region);
 341             }
 342         }
 343         // old us time-zone names
 344         addOldMapping();
 345     }
 346 
 347     /////////////////////////Ser/////////////////////////////////
 348     public static ZoneInfo getZoneInfo(DataInput in, String zoneId) throws Exception {
 349         byte type = in.readByte();
 350         // TBD: assert ZRULES:
 351         int stdSize = in.readInt();
 352         long[] stdTrans = new long[stdSize];
 353         for (int i = 0; i < stdSize; i++) {
 354             stdTrans[i] = readEpochSec(in);
 355         }
 356         int [] stdOffsets = new int[stdSize + 1];
 357         for (int i = 0; i < stdOffsets.length; i++) {
 358             stdOffsets[i] = readOffset(in);
 359         }
 360         int savSize = in.readInt();
 361         long[] savTrans = new long[savSize];
 362         for (int i = 0; i < savSize; i++) {
 363             savTrans[i] = readEpochSec(in);
 364         }
 365         int[] savOffsets = new int[savSize + 1];
 366         for (int i = 0; i < savOffsets.length; i++) {
 367             savOffsets[i] = readOffset(in);
 368         }
 369         int ruleSize = in.readByte();
 370         ZoneOffsetTransitionRule[] rules = new ZoneOffsetTransitionRule[ruleSize];
 371         for (int i = 0; i < ruleSize; i++) {
 372             rules[i] = new ZoneOffsetTransitionRule(in);
 373         }
 374         return getZoneInfo(zoneId, stdTrans, stdOffsets, savTrans, savOffsets, rules);
 375     }
 376 
 377     public static int readOffset(DataInput in) throws IOException {
 378         int offsetByte = in.readByte();
 379         return offsetByte == 127 ? in.readInt() : offsetByte * 900;
 380     }
 381 
 382     static long readEpochSec(DataInput in) throws IOException {
 383         int hiByte = in.readByte() & 255;
 384         if (hiByte == 255) {
 385             return in.readLong();
 386         } else {
 387             int midByte = in.readByte() & 255;
 388             int loByte = in.readByte() & 255;
 389             long tot = ((hiByte << 16) + (midByte << 8) + loByte);
 390             return (tot * 900) - 4575744000L;
 391         }
 392     }
 393 
 394     /////////////////////////ZoneRules --> ZoneInfo/////////////////////////////////
 395 
 396     // ZoneInfo starts with UTC1900
 397     private static final long UTC1900 = -2208988800L;
 398 
 399     // ZoneInfo ends with   UTC2037
 400     // LocalDateTime.of(2038, 1, 1, 0, 0, 0).toEpochSecond(ZoneOffset.UTC) - 1;
 401     private static final long UTC2037 = 2145916799L;
 402 
 403     // ZoneInfo has an ending entry for 2037, this need to be offset by
 404     // a "rawOffset"
 405     // LocalDateTime.of(2037, 1, 1, 0, 0, 0).toEpochSecond(ZoneOffset.UTC));
 406     private static final long LDT2037 = 2114380800L;
 407 
 408     //Current time. Used to determine future GMToffset transitions
 409     private static final long CURRT = System.currentTimeMillis()/1000;
 410 
 411     /* Get a ZoneInfo instance.
 412      *
 413      * @param standardTransitions  the standard transitions, not null
 414      * @param standardOffsets  the standard offsets, not null
 415      * @param savingsInstantTransitions  the standard transitions, not null
 416      * @param wallOffsets  the wall offsets, not null
 417      * @param lastRules  the recurring last rules, size 15 or less, not null
 418      */
 419     private static ZoneInfo getZoneInfo(String zoneId,
 420                                         long[] standardTransitions,
 421                                         int[] standardOffsets,
 422                                         long[] savingsInstantTransitions,
 423                                         int[] wallOffsets,
 424                                         ZoneOffsetTransitionRule[] lastRules) {
 425         int rawOffset = 0;
 426         int dstSavings = 0;
 427         int checksum = 0;
 428         int[] params = null;
 429         boolean willGMTOffsetChange = false;
 430 
 431         // rawOffset, pick the last one
 432         if (standardTransitions.length > 0) {
 433             rawOffset = standardOffsets[standardOffsets.length - 1] * 1000;
 434             willGMTOffsetChange = standardTransitions[standardTransitions.length - 1] > CURRT;
 435         }
 436         else
 437             rawOffset = standardOffsets[0] * 1000;
 438 
 439         // transitions, offsets;
 440         long[] transitions = null;
 441         int[]  offsets = null;
 442         int    nOffsets = 0;
 443         int    nTrans = 0;
 444 
 445         if (savingsInstantTransitions.length != 0) {
 446             transitions = new long[250];
 447             offsets = new int[100];    // TBD: ZoneInfo actually can't handle
 448                                        // offsets.length > 16 (4-bit index limit)
 449             // last year in trans table
 450             // It should not matter to use before or after offset for year
 451             int lastyear = getYear(savingsInstantTransitions[savingsInstantTransitions.length - 1],
 452                                    wallOffsets[savingsInstantTransitions.length - 1]);
 453             int i = 0, k = 1;
 454             while (i < savingsInstantTransitions.length &&
 455                    savingsInstantTransitions[i] < UTC1900) {
 456                 i++;     // skip any date before UTC1900
 457             }
 458             if (i < savingsInstantTransitions.length) {
 459                 // javazic writes the last GMT offset into index 0!
 460                 if (i < savingsInstantTransitions.length) {
 461                     offsets[0] = standardOffsets[standardOffsets.length - 1] * 1000;
 462                     nOffsets = 1;
 463                 }
 464                 // ZoneInfo has a beginning entry for 1900.
 465                 // Only add it if this is not the only one in table
 466                 nOffsets = addTrans(transitions, nTrans++,
 467                                     offsets, nOffsets,
 468                                     UTC1900,
 469                                     wallOffsets[i],
 470                                     getStandardOffset(standardTransitions, standardOffsets, UTC1900));
 471             }
 472 
 473             for (; i < savingsInstantTransitions.length; i++) {
 474                 long trans = savingsInstantTransitions[i];
 475                 if (trans > UTC2037) {
 476                     // no trans beyond LASTYEAR
 477                     lastyear = LASTYEAR;
 478                     break;
 479                 }
 480                 while (k < standardTransitions.length) {
 481                     // some standard offset transitions don't exist in
 482                     // savingInstantTrans, if the offset "change" doesn't
 483                     // really change the "effectiveWallOffset". For example
 484                     // the 1999/2000 pair in Zone Arg/Buenos_Aires, in which
 485                     // the daylightsaving "happened" but it actually does
 486                     // not result in the timezone switch. ZoneInfo however
 487                     // needs them in its transitions table
 488                     long trans_s = standardTransitions[k];
 489                     if (trans_s >= UTC1900) {
 490                         if (trans_s > trans)
 491                             break;
 492                         if (trans_s < trans) {
 493                             if (nOffsets + 2 >= offsets.length) {
 494                                 offsets = Arrays.copyOf(offsets, offsets.length + 100);
 495                             }
 496                             if (nTrans + 1 >= transitions.length) {
 497                                 transitions = Arrays.copyOf(transitions, transitions.length + 100);
 498                             }
 499                             nOffsets = addTrans(transitions, nTrans++, offsets, nOffsets,
 500                                                 trans_s,
 501                                                 wallOffsets[i],
 502                                                 standardOffsets[k+1]);
 503 
 504                         }
 505                     }
 506                     k++;
 507                 }
 508                 if (nOffsets + 2 >= offsets.length) {
 509                     offsets = Arrays.copyOf(offsets, offsets.length + 100);
 510                 }
 511                 if (nTrans + 1 >= transitions.length) {
 512                     transitions = Arrays.copyOf(transitions, transitions.length + 100);
 513                 }
 514                 nOffsets = addTrans(transitions, nTrans++, offsets, nOffsets,
 515                                     trans,
 516                                     wallOffsets[i + 1],
 517                                     getStandardOffset(standardTransitions, standardOffsets, trans));
 518 
 519             }
 520             // append any leftover standard trans
 521             while (k < standardTransitions.length) {
 522                 long trans = standardTransitions[k];
 523                 if (trans >= UTC1900) {
 524                     int offset = wallOffsets[i];
 525                     int offsetIndex = indexOf(offsets, 0, nOffsets, offset);
 526                     if (offsetIndex == nOffsets)
 527                         nOffsets++;
 528                     transitions[nTrans++] = ((trans * 1000) << TRANSITION_NSHIFT) |
 529                                             (offsetIndex & OFFSET_MASK);
 530                 }
 531                 k++;
 532             }
 533             if (lastRules.length > 1) {
 534                 // fill the gap between the last trans until LASTYEAR
 535                 while (lastyear++ < LASTYEAR) {
 536                     for (ZoneOffsetTransitionRule zotr : lastRules) {
 537                         long trans = zotr.getTransitionEpochSecond(lastyear);
 538                         if (nOffsets + 2 >= offsets.length) {
 539                             offsets = Arrays.copyOf(offsets, offsets.length + 100);
 540                         }
 541                         if (nTrans + 1 >= transitions.length) {
 542                             transitions = Arrays.copyOf(transitions, transitions.length + 100);
 543                         }
 544                         nOffsets = addTrans(transitions, nTrans++,
 545                                             offsets, nOffsets,
 546                                             trans,
 547                                             zotr.offsetAfter,
 548                                             zotr.standardOffset);
 549                     }
 550                 }
 551                 ZoneOffsetTransitionRule startRule =  lastRules[lastRules.length - 2];
 552                 ZoneOffsetTransitionRule endRule =  lastRules[lastRules.length - 1];
 553                 params = new int[10];
 554                 if (startRule.offsetAfter - startRule.offsetBefore < 0 &&
 555                     endRule.offsetAfter - endRule.offsetBefore > 0) {
 556                     ZoneOffsetTransitionRule tmp;
 557                     tmp = startRule;
 558                     startRule = endRule;
 559                     endRule = tmp;
 560                 }
 561                 params[0] = startRule.month - 1;
 562                 int dom = startRule.dom;
 563                 int dow = startRule.dow;
 564                 if (dow == -1) {
 565                     params[1] = dom;
 566                     params[2] = 0;
 567                 } else {
 568                     // ZoneRulesBuilder adjusts < 0 case (-1, for last, don't have
 569                     // "<=" case yet) to positive value if not February (it appears
 570                     // we don't have February cutoff in tzdata table yet)
 571                     // Ideally, if JSR310 can just pass in the nagative and
 572                     // we can then pass in the dom = -1, dow > 0 into ZoneInfo
 573                     //
 574                     // hacking, assume the >=24 is the result of ZRB optimization for
 575                     // "last", it works for now.
 576                     if (dom < 0 || dom >= 24) {
 577                         params[1] = -1;
 578                         params[2] = toCalendarDOW[dow];
 579                     } else {
 580                         params[1] = dom;
 581                         // To specify a day of week on or after an exact day of month,
 582                         // set the month to an exact month value, day-of-month to the
 583                         // day on or after which the rule is applied, and day-of-week
 584                         // to a negative Calendar.DAY_OF_WEEK DAY_OF_WEEK field value.
 585                         params[2] = -toCalendarDOW[dow];
 586                     }
 587                 }
 588                 params[3] = startRule.secondOfDay * 1000;
 589                 params[4] = toSTZTime[startRule.timeDefinition];
 590                 params[5] = endRule.month - 1;
 591                 dom = endRule.dom;
 592                 dow = endRule.dow;
 593                 if (dow == -1) {
 594                     params[6] = dom;
 595                     params[7] = 0;
 596                 } else {
 597                     // hacking: see comment above
 598                     if (dom < 0 || dom >= 24) {
 599                         params[6] = -1;
 600                         params[7] = toCalendarDOW[dow];
 601                     } else {
 602                         params[6] = dom;
 603                         params[7] = -toCalendarDOW[dow];
 604                     }
 605                 }
 606                 params[8] = endRule.secondOfDay * 1000;
 607                 params[9] = toSTZTime[endRule.timeDefinition];
 608                 dstSavings = (startRule.offsetAfter - startRule.offsetBefore) * 1000;
 609 
 610                 // Note: known mismatching -> Asia/Amman
 611                 //                            Asia/Gaza
 612                 //                            Asia/Hebron
 613                 // ZoneInfo :      startDayOfWeek=5     <= Thursday
 614                 //                 startTime=86400000   <= 24 hours
 615                 // This:           startDayOfWeek=6
 616                 //                 startTime=0
 617                 // Similar workaround needs to be applied to Africa/Cairo and
 618                 // its endDayOfWeek and endTime
 619                 // Below is the workarounds, it probably slows down everyone a little
 620                 if (params[2] == 6 && params[3] == 0 &&
 621                     (zoneId.equals("Asia/Amman") ||
 622                      zoneId.equals("Asia/Gaza") ||
 623                      zoneId.equals("Asia/Hebron"))) {
 624                     params[2] = 5;
 625                     params[3] = 86400000;
 626                 }
 627                 // Additional check for startDayOfWeek=6 and starTime=86400000
 628                 // is needed for Asia/Amman; Asia/Gasa and Asia/Hebron
 629                 if (params[2] == 7 && params[3] == 0 &&
 630                      (zoneId.equals("Asia/Amman") ||
 631                       zoneId.equals("Asia/Gaza") ||
 632                       zoneId.equals("Asia/Hebron"))) {
 633                     params[2] = 6;        // Friday
 634                     params[3] = 86400000; // 24h
 635                 }
 636                 //endDayOfWeek and endTime workaround
 637                 if (params[7] == 6 && params[8] == 0 &&
 638                     (zoneId.equals("Africa/Cairo"))) {
 639                     params[7] = 5;
 640                     params[8] = 86400000;
 641                 }
 642 
 643             } else if (nTrans > 0) {  // only do this if there is something in table already
 644                 if (lastyear < LASTYEAR) {
 645                     // ZoneInfo has an ending entry for 2037
 646                     //long trans = OffsetDateTime.of(LASTYEAR, 1, 1, 0, 0, 0, 0,
 647                     //                               ZoneOffset.ofTotalSeconds(rawOffset/1000))
 648                     //                           .toEpochSecond();
 649                     long trans = LDT2037 - rawOffset/1000;
 650 
 651                     int offsetIndex = indexOf(offsets, 0, nOffsets, rawOffset/1000);
 652                     if (offsetIndex == nOffsets)
 653                         nOffsets++;
 654                     transitions[nTrans++] = (trans * 1000) << TRANSITION_NSHIFT |
 655                                        (offsetIndex & OFFSET_MASK);
 656 
 657                 } else if (savingsInstantTransitions.length > 2) {
 658                     // Workaround: create the params based on the last pair for
 659                     // zones like Israel and Iran which have trans defined
 660                     // up until 2037, but no "transition rule" defined
 661                     //
 662                     // Note: Known mismatching for Israel, Asia/Jerusalem/Tel Aviv
 663                     // ZoneInfo:        startMode=3
 664                     //                  startMonth=2
 665                     //                  startDay=26
 666                     //                  startDayOfWeek=6
 667                     //
 668                     // This:            startMode=1
 669                     //                  startMonth=2
 670                     //                  startDay=27
 671                     //                  startDayOfWeek=0
 672                     // these two are actually the same for 2037, the SimpleTimeZone
 673                     // for the last "known" year
 674                     int m = savingsInstantTransitions.length;
 675                     long startTrans = savingsInstantTransitions[m - 2];
 676                     int startOffset = wallOffsets[m - 2 + 1];
 677                     int startStd = getStandardOffset(standardTransitions, standardOffsets, startTrans);
 678                     long endTrans =  savingsInstantTransitions[m - 1];
 679                     int endOffset = wallOffsets[m - 1 + 1];
 680                     int endStd = getStandardOffset(standardTransitions, standardOffsets, endTrans);
 681                     if (startOffset > startStd && endOffset == endStd) {
 682                         // last - 1 trans
 683                         m = savingsInstantTransitions.length - 2;
 684                         ZoneOffset before = ZoneOffset.ofTotalSeconds(wallOffsets[m]);
 685                         ZoneOffset after = ZoneOffset.ofTotalSeconds(wallOffsets[m + 1]);
 686                         LocalDateTime ldt = LocalDateTime.ofEpochSecond(savingsInstantTransitions[m], 0, before);
 687                         LocalDateTime startLDT;
 688                         if (after.getTotalSeconds() > before.getTotalSeconds()) {  // isGap()
 689                             startLDT = ldt;
 690                         } else {
 691                             startLDT = ldt.plusSeconds(wallOffsets[m + 1] - wallOffsets[m]);
 692                         }
 693                         // last trans
 694                         m = savingsInstantTransitions.length - 1;
 695                         before = ZoneOffset.ofTotalSeconds(wallOffsets[m]);
 696                         after = ZoneOffset.ofTotalSeconds(wallOffsets[m + 1]);
 697                         ldt = LocalDateTime.ofEpochSecond(savingsInstantTransitions[m], 0, before);
 698                         LocalDateTime endLDT;
 699                         if (after.getTotalSeconds() > before.getTotalSeconds()) {  // isGap()
 700                             endLDT = ldt.plusSeconds(wallOffsets[m + 1] - wallOffsets[m]);
 701                         } else {
 702                             endLDT = ldt;
 703                         }
 704                         params = new int[10];
 705                         params[0] = startLDT.getMonthValue() - 1;
 706                         params[1] = startLDT.getDayOfMonth();
 707                         params[2] = 0;
 708                         params[3] = startLDT.toLocalTime().toSecondOfDay() * 1000;
 709                         params[4] = SimpleTimeZone.WALL_TIME;
 710                         params[5] = endLDT.getMonthValue() - 1;
 711                         params[6] = endLDT.getDayOfMonth();
 712                         params[7] = 0;
 713                         params[8] = endLDT.toLocalTime().toSecondOfDay() * 1000;
 714                         params[9] = SimpleTimeZone.WALL_TIME;
 715                         dstSavings = (startOffset - startStd) * 1000;
 716                     }
 717                 }
 718             }
 719             if (transitions != null && transitions.length != nTrans) {
 720                 if (nTrans == 0) {
 721                     transitions = null;
 722                 } else {
 723                     transitions = Arrays.copyOf(transitions, nTrans);
 724                 }
 725             }
 726             if (offsets != null && offsets.length != nOffsets) {
 727                 if (nOffsets == 0) {
 728                     offsets = null;
 729                 } else {
 730                     offsets = Arrays.copyOf(offsets, nOffsets);
 731                 }
 732             }
 733             if (transitions != null) {
 734                 Checksum sum = new Checksum();
 735                 for (i = 0; i < transitions.length; i++) {
 736                     long val = transitions[i];
 737                     int dst = (int)((val >>> DST_NSHIFT) & 0xfL);
 738                     int saving = (dst == 0) ? 0 : offsets[dst];
 739                     int index = (int)(val & OFFSET_MASK);
 740                     int offset = offsets[index];
 741                     long second = (val >> TRANSITION_NSHIFT);
 742                     // javazic uses "index of the offset in offsets",
 743                     // instead of the real offset value itself to
 744                     // calculate the checksum. Have to keep doing
 745                     // the same thing, checksum is part of the
 746                     // ZoneInfo serialization form.
 747                     sum.update(second + index);
 748                     sum.update(index);
 749                     sum.update(dst == 0 ? -1 : dst);
 750                 }
 751                 checksum = (int)sum.getValue();
 752             }
 753         }
 754         return new ZoneInfo(zoneId, rawOffset, dstSavings, checksum, transitions,
 755                             offsets, params, willGMTOffsetChange);
 756     }
 757 
 758     private static int getStandardOffset(long[] standardTransitions,
 759                                          int[] standardOffsets,
 760                                          long epochSec) {
 761         // The size of stdOffsets is [0..9], with most are
 762         // [1..4] entries , simple loop search is faster
 763         //
 764         // int index  = Arrays.binarySearch(standardTransitions, epochSec);
 765         // if (index < 0) {
 766         //    // switch negative insert position to start of matched range
 767         //    index = -index - 2;
 768         // }
 769         // return standardOffsets[index + 1];
 770         int index = 0;
 771         for (; index < standardTransitions.length; index++) {
 772             if (epochSec < standardTransitions[index]) {
 773                 break;
 774             }
 775         }
 776         return standardOffsets[index];
 777     }
 778 
 779     static final int SECONDS_PER_DAY = 86400;
 780     static final int DAYS_PER_CYCLE = 146097;
 781     static final long DAYS_0000_TO_1970 = (DAYS_PER_CYCLE * 5L) - (30L * 365L + 7L);
 782 
 783     private static int getYear(long epochSecond, int offset) {
 784         long second = epochSecond + offset;  // overflow caught later
 785         long epochDay = Math.floorDiv(second, SECONDS_PER_DAY);
 786         long zeroDay = epochDay + DAYS_0000_TO_1970;
 787         // find the march-based year
 788         zeroDay -= 60;  // adjust to 0000-03-01 so leap day is at end of four year cycle
 789         long adjust = 0;
 790         if (zeroDay < 0) {
 791             // adjust negative years to positive for calculation
 792             long adjustCycles = (zeroDay + 1) / DAYS_PER_CYCLE - 1;
 793             adjust = adjustCycles * 400;
 794             zeroDay += -adjustCycles * DAYS_PER_CYCLE;
 795         }
 796         long yearEst = (400 * zeroDay + 591) / DAYS_PER_CYCLE;
 797         long doyEst = zeroDay - (365 * yearEst + yearEst / 4 - yearEst / 100 + yearEst / 400);
 798         if (doyEst < 0) {
 799             // fix estimate
 800             yearEst--;
 801             doyEst = zeroDay - (365 * yearEst + yearEst / 4 - yearEst / 100 + yearEst / 400);
 802         }
 803         yearEst += adjust;  // reset any negative year
 804         int marchDoy0 = (int) doyEst;
 805         // convert march-based values back to january-based
 806         int marchMonth0 = (marchDoy0 * 5 + 2) / 153;
 807         int month = (marchMonth0 + 2) % 12 + 1;
 808         int dom = marchDoy0 - (marchMonth0 * 306 + 5) / 10 + 1;
 809         yearEst += marchMonth0 / 10;
 810         return (int)yearEst;
 811     }
 812 
 813     private static final int toCalendarDOW[] = new int[] {
 814         -1,
 815         Calendar.MONDAY,
 816         Calendar.TUESDAY,
 817         Calendar.WEDNESDAY,
 818         Calendar.THURSDAY,
 819         Calendar.FRIDAY,
 820         Calendar.SATURDAY,
 821         Calendar.SUNDAY
 822     };
 823 
 824     private static final int toSTZTime[] = new int[] {
 825         SimpleTimeZone.UTC_TIME,
 826         SimpleTimeZone.WALL_TIME,
 827         SimpleTimeZone.STANDARD_TIME,
 828     };
 829 
 830     private static final long OFFSET_MASK = 0x0fL;
 831     private static final long DST_MASK = 0xf0L;
 832     private static final int  DST_NSHIFT = 4;
 833     private static final int  TRANSITION_NSHIFT = 12;
 834     private static final int  LASTYEAR = 2037;
 835 
 836     // from: 0 for offset lookup, 1 for dstsvings lookup
 837     private static int indexOf(int[] offsets, int from, int nOffsets, int offset) {
 838         offset *= 1000;
 839         for (; from < nOffsets; from++) {
 840             if (offsets[from] == offset)
 841                 return from;
 842         }
 843         offsets[from] = offset;
 844         return from;
 845     }
 846 
 847     // return updated nOffsets
 848     private static int addTrans(long transitions[], int nTrans,
 849                                 int offsets[], int nOffsets,
 850                                 long trans, int offset, int stdOffset) {
 851         int offsetIndex = indexOf(offsets, 0, nOffsets, offset);
 852         if (offsetIndex == nOffsets)
 853             nOffsets++;
 854         int dstIndex = 0;
 855         if (offset != stdOffset) {
 856             dstIndex = indexOf(offsets, 1, nOffsets, offset - stdOffset);
 857             if (dstIndex == nOffsets)
 858                 nOffsets++;
 859         }
 860         transitions[nTrans] = ((trans * 1000) << TRANSITION_NSHIFT) |
 861                               ((dstIndex << DST_NSHIFT) & DST_MASK) |
 862                               (offsetIndex & OFFSET_MASK);
 863         return nOffsets;
 864     }
 865 
 866     // ZoneInfo checksum, copy/pasted from javazic
 867     private static class Checksum extends CRC32 {
 868         public void update(int val) {
 869             byte[] b = new byte[4];
 870             b[0] = (byte)(val >>> 24);
 871             b[1] = (byte)(val >>> 16);
 872             b[2] = (byte)(val >>> 8);
 873             b[3] = (byte)(val);
 874             update(b);
 875         }
 876         void update(long val) {
 877             byte[] b = new byte[8];
 878             b[0] = (byte)(val >>> 56);
 879             b[1] = (byte)(val >>> 48);
 880             b[2] = (byte)(val >>> 40);
 881             b[3] = (byte)(val >>> 32);
 882             b[4] = (byte)(val >>> 24);
 883             b[5] = (byte)(val >>> 16);
 884             b[6] = (byte)(val >>> 8);
 885             b[7] = (byte)(val);
 886             update(b);
 887         }
 888     }
 889 
 890     // A simple/raw version of j.t.ZoneOffsetTransitionRule
 891     private static class ZoneOffsetTransitionRule {
 892         private final int month;
 893         private final byte dom;
 894         private final int dow;
 895         private final int secondOfDay;
 896         private final boolean timeEndOfDay;
 897         private final int timeDefinition;
 898         private final int standardOffset;
 899         private final int offsetBefore;
 900         private final int offsetAfter;
 901 
 902         ZoneOffsetTransitionRule(DataInput in) throws IOException {
 903             int data = in.readInt();
 904             int dowByte = (data & (7 << 19)) >>> 19;
 905             int timeByte = (data & (31 << 14)) >>> 14;
 906             int stdByte = (data & (255 << 4)) >>> 4;
 907             int beforeByte = (data & (3 << 2)) >>> 2;
 908             int afterByte = (data & 3);
 909 
 910             this.month = data >>> 28;
 911             this.dom = (byte)(((data & (63 << 22)) >>> 22) - 32);
 912             this.dow = dowByte == 0 ? -1 : dowByte;
 913             this.secondOfDay = timeByte == 31 ? in.readInt() : timeByte * 3600;
 914             this.timeEndOfDay = timeByte == 24;
 915             this.timeDefinition = (data & (3 << 12)) >>> 12;
 916 
 917             this.standardOffset = stdByte == 255 ? in.readInt() : (stdByte - 128) * 900;
 918             this.offsetBefore = beforeByte == 3 ? in.readInt() : standardOffset + beforeByte * 1800;
 919             this.offsetAfter = afterByte == 3 ? in.readInt() : standardOffset + afterByte * 1800;
 920         }
 921 
 922         long getTransitionEpochSecond(int year) {
 923             long epochDay = 0;
 924             if (dom < 0) {
 925                 epochDay = toEpochDay(year, month, lengthOfMonth(year, month) + 1 + dom);
 926                 if (dow != -1) {
 927                     epochDay = previousOrSame(epochDay, dow);
 928                 }
 929             } else {
 930                 epochDay = toEpochDay(year, month, dom);
 931                 if (dow != -1) {
 932                     epochDay = nextOrSame(epochDay, dow);
 933                 }
 934             }
 935             if (timeEndOfDay) {
 936                 epochDay += 1;
 937             }
 938             int difference = 0;
 939             switch (timeDefinition) {
 940                 case 0:    // UTC
 941                     difference = 0;
 942                     break;
 943                 case 1:    // WALL
 944                     difference = -offsetBefore;
 945                     break;
 946                 case 2:    //STANDARD
 947                     difference = -standardOffset;
 948                     break;
 949             }
 950             return epochDay * 86400 + secondOfDay + difference;
 951         }
 952 
 953         static final boolean isLeapYear(int year) {
 954             return ((year & 3) == 0) && ((year % 100) != 0 || (year % 400) == 0);
 955         }
 956 
 957         static final int lengthOfMonth(int year, int month) {
 958             switch (month) {
 959                 case 2:        //FEBRUARY:
 960                     return isLeapYear(year)? 29 : 28;
 961                 case 4:        //APRIL:
 962                 case 6:        //JUNE:
 963                 case 9:        //SEPTEMBER:
 964                 case 11:       //NOVEMBER:
 965                     return 30;
 966                 default:
 967                     return 31;
 968             }
 969         }
 970 
 971         static final long toEpochDay(int year, int month, int day) {
 972             long y = year;
 973             long m = month;
 974             long total = 0;
 975             total += 365 * y;
 976             if (y >= 0) {
 977                 total += (y + 3) / 4 - (y + 99) / 100 + (y + 399) / 400;
 978             } else {
 979                 total -= y / -4 - y / -100 + y / -400;
 980             }
 981             total += ((367 * m - 362) / 12);
 982             total += day - 1;
 983             if (m > 2) {
 984                 total--;
 985                 if (!isLeapYear(year)) {
 986                     total--;
 987                 }
 988             }
 989             return total - DAYS_0000_TO_1970;
 990         }
 991 
 992         static final long previousOrSame(long epochDay, int dayOfWeek) {
 993             return adjust(epochDay, dayOfWeek, 1);
 994         }
 995 
 996         static final long nextOrSame(long epochDay, int dayOfWeek) {
 997            return adjust(epochDay, dayOfWeek, 0);
 998         }
 999 
1000         static final long adjust(long epochDay, int dow, int relative) {
1001             int calDow = (int)Math.floorMod(epochDay + 3, 7L) + 1;
1002             if (relative < 2 && calDow == dow) {
1003                 return epochDay;
1004             }
1005             if ((relative & 1) == 0) {
1006                 int daysDiff = calDow - dow;
1007                 return epochDay + (daysDiff >= 0 ? 7 - daysDiff : -daysDiff);
1008             } else {
1009                 int daysDiff = dow - calDow;
1010                 return epochDay - (daysDiff >= 0 ? 7 - daysDiff : -daysDiff);
1011             }
1012         }
1013     }
1014 }