TimeUtil.java 19.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
/*
  Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved.

  The MySQL Connector/J is licensed under the terms of the GPLv2
  <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most MySQL Connectors.
  There are special exceptions to the terms and conditions of the GPLv2 as it is applied to
  this software, see the FOSS License Exception
  <http://www.mysql.com/about/legal/licensing/foss-exception.html>.

  This program is free software; you can redistribute it and/or modify it under the terms
  of the GNU General Public License as published by the Free Software Foundation; version 2
  of the License.

  This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
  without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  See the GNU General Public License for more details.

  You should have received a copy of the GNU General Public License along with this
  program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth
  Floor, Boston, MA 02110-1301  USA

 */

package com.mysql.jdbc;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Date;
import java.sql.SQLException;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Properties;
import java.util.TimeZone;

/**
 * Timezone conversion routines and other time related methods
 */
public class TimeUtil {
    static final TimeZone GMT_TIMEZONE = TimeZone.getTimeZone("GMT");

    // cache this ourselves, as the method call is statically-synchronized in all but JDK6!
    private static final TimeZone DEFAULT_TIMEZONE = TimeZone.getDefault();

    // Mappings from TimeZone identifications (prefixed by type: Windows, TZ name, MetaZone, TZ alias, ...), to standard TimeZone Ids
    private static final String TIME_ZONE_MAPPINGS_RESOURCE = "/com/mysql/jdbc/TimeZoneMapping.properties";

    private static Properties timeZoneMappings = null;

    protected final static Method systemNanoTimeMethod;

    static {
        Method aMethod;

        try {
            aMethod = System.class.getMethod("nanoTime", (Class[]) null);
        } catch (SecurityException e) {
            aMethod = null;
        } catch (NoSuchMethodException e) {
            aMethod = null;
        }

        systemNanoTimeMethod = aMethod;
    }

    public static boolean nanoTimeAvailable() {
        return systemNanoTimeMethod != null;
    }

    public static final TimeZone getDefaultTimeZone(boolean useCache) {
        return (TimeZone) (useCache ? DEFAULT_TIMEZONE.clone() : TimeZone.getDefault().clone());
    }

    public static long getCurrentTimeNanosOrMillis() {
        if (systemNanoTimeMethod != null) {
            try {
                return ((Long) systemNanoTimeMethod.invoke(null, (Object[]) null)).longValue();
            } catch (IllegalArgumentException e) {
                // ignore - fall through to currentTimeMillis()
            } catch (IllegalAccessException e) {
                // ignore - fall through to currentTimeMillis()
            } catch (InvocationTargetException e) {
                // ignore - fall through to currentTimeMillis()
            }
        }

        return System.currentTimeMillis();
    }

    /**
     * Change the given times from one timezone to another
     * 
     * @param conn
     *            the current connection to the MySQL server
     * @param t
     *            the times to change
     * @param fromTz
     *            the timezone to change from
     * @param toTz
     *            the timezone to change to
     * 
     * @return the times changed to the timezone 'toTz'
     */
    public static Time changeTimezone(MySQLConnection conn, Calendar sessionCalendar, Calendar targetCalendar, Time t, TimeZone fromTz, TimeZone toTz,
            boolean rollForward) {
        if ((conn != null)) {
            if (conn.getUseTimezone() && !conn.getNoTimezoneConversionForTimeType()) {
                // Convert the timestamp from GMT to the server's timezone
                Calendar fromCal = Calendar.getInstance(fromTz);
                fromCal.setTime(t);

                int fromOffset = fromCal.get(Calendar.ZONE_OFFSET) + fromCal.get(Calendar.DST_OFFSET);
                Calendar toCal = Calendar.getInstance(toTz);
                toCal.setTime(t);

                int toOffset = toCal.get(Calendar.ZONE_OFFSET) + toCal.get(Calendar.DST_OFFSET);
                int offsetDiff = fromOffset - toOffset;
                long toTime = toCal.getTime().getTime();

                if (rollForward) {
                    toTime += offsetDiff;
                } else {
                    toTime -= offsetDiff;
                }

                Time changedTime = new Time(toTime);

                return changedTime;
            } else if (conn.getUseJDBCCompliantTimezoneShift()) {
                if (targetCalendar != null) {

                    Time adjustedTime = new Time(jdbcCompliantZoneShift(sessionCalendar, targetCalendar, t));

                    return adjustedTime;
                }
            }
        }

        return t;
    }

    /**
     * Change the given timestamp from one timezone to another
     * 
     * @param conn
     *            the current connection to the MySQL server
     * @param tstamp
     *            the timestamp to change
     * @param fromTz
     *            the timezone to change from
     * @param toTz
     *            the timezone to change to
     * 
     * @return the timestamp changed to the timezone 'toTz'
     */
    public static Timestamp changeTimezone(MySQLConnection conn, Calendar sessionCalendar, Calendar targetCalendar, Timestamp tstamp, TimeZone fromTz,
            TimeZone toTz, boolean rollForward) {
        if ((conn != null)) {
            if (conn.getUseTimezone()) {
                // Convert the timestamp from GMT to the server's timezone
                Calendar fromCal = Calendar.getInstance(fromTz);
                fromCal.setTime(tstamp);

                int fromOffset = fromCal.get(Calendar.ZONE_OFFSET) + fromCal.get(Calendar.DST_OFFSET);
                Calendar toCal = Calendar.getInstance(toTz);
                toCal.setTime(tstamp);

                int toOffset = toCal.get(Calendar.ZONE_OFFSET) + toCal.get(Calendar.DST_OFFSET);
                int offsetDiff = fromOffset - toOffset;
                long toTime = toCal.getTime().getTime();

                if (rollForward) {
                    toTime += offsetDiff;
                } else {
                    toTime -= offsetDiff;
                }

                Timestamp changedTimestamp = new Timestamp(toTime);

                return changedTimestamp;
            } else if (conn.getUseJDBCCompliantTimezoneShift()) {
                if (targetCalendar != null) {

                    Timestamp adjustedTimestamp = new Timestamp(jdbcCompliantZoneShift(sessionCalendar, targetCalendar, tstamp));

                    adjustedTimestamp.setNanos(tstamp.getNanos());

                    return adjustedTimestamp;
                }
            }
        }

        return tstamp;
    }

    private static long jdbcCompliantZoneShift(Calendar sessionCalendar, Calendar targetCalendar, java.util.Date dt) {
        if (sessionCalendar == null) {
            sessionCalendar = new GregorianCalendar();
        }

        synchronized (sessionCalendar) {
            // JDBC spec is not clear whether or not this calendar should be immutable, so let's treat it like it is, for safety

            java.util.Date origCalDate = targetCalendar.getTime();
            java.util.Date origSessionDate = sessionCalendar.getTime();

            try {
                sessionCalendar.setTime(dt);

                targetCalendar.set(Calendar.YEAR, sessionCalendar.get(Calendar.YEAR));
                targetCalendar.set(Calendar.MONTH, sessionCalendar.get(Calendar.MONTH));
                targetCalendar.set(Calendar.DAY_OF_MONTH, sessionCalendar.get(Calendar.DAY_OF_MONTH));

                targetCalendar.set(Calendar.HOUR_OF_DAY, sessionCalendar.get(Calendar.HOUR_OF_DAY));
                targetCalendar.set(Calendar.MINUTE, sessionCalendar.get(Calendar.MINUTE));
                targetCalendar.set(Calendar.SECOND, sessionCalendar.get(Calendar.SECOND));
                targetCalendar.set(Calendar.MILLISECOND, sessionCalendar.get(Calendar.MILLISECOND));

                return targetCalendar.getTime().getTime();

            } finally {
                sessionCalendar.setTime(origSessionDate);
                targetCalendar.setTime(origCalDate);
            }
        }
    }

    final static Date fastDateCreate(boolean useGmtConversion, Calendar gmtCalIfNeeded, Calendar cal, int year, int month, int day) {

        Calendar dateCal = cal;

        if (useGmtConversion) {

            if (gmtCalIfNeeded == null) {
                gmtCalIfNeeded = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
            }

            dateCal = gmtCalIfNeeded;
        }

        synchronized (dateCal) {
            java.util.Date origCalDate = dateCal.getTime();
            try {
                dateCal.clear();
                dateCal.set(Calendar.MILLISECOND, 0);

                // why-oh-why is this different than java.util.date, in the year part, but it still keeps the silly '0' for the start month????
                dateCal.set(year, month - 1, day, 0, 0, 0);

                long dateAsMillis = dateCal.getTimeInMillis();

                return new Date(dateAsMillis);
            } finally {
                dateCal.setTime(origCalDate);
            }
        }

    }

    final static Date fastDateCreate(int year, int month, int day, Calendar targetCalendar) {

        Calendar dateCal = (targetCalendar == null) ? new GregorianCalendar() : targetCalendar;

        synchronized (dateCal) {
            java.util.Date origCalDate = dateCal.getTime();
            try {
                dateCal.clear();

                // why-oh-why is this different than java.util.date, in the year part, but it still keeps the silly '0' for the start month????
                dateCal.set(year, month - 1, day, 0, 0, 0);
                dateCal.set(Calendar.MILLISECOND, 0);

                long dateAsMillis = dateCal.getTimeInMillis();

                return new Date(dateAsMillis);
            } finally {
                dateCal.setTime(origCalDate);
            }
        }
    }

    final static Time fastTimeCreate(Calendar cal, int hour, int minute, int second, ExceptionInterceptor exceptionInterceptor) throws SQLException {
        if (hour < 0 || hour > 24) {
            throw SQLError.createSQLException(
                    "Illegal hour value '" + hour + "' for java.sql.Time type in value '" + timeFormattedString(hour, minute, second) + ".",
                    SQLError.SQL_STATE_ILLEGAL_ARGUMENT, exceptionInterceptor);
        }

        if (minute < 0 || minute > 59) {
            throw SQLError.createSQLException(
                    "Illegal minute value '" + minute + "' for java.sql.Time type in value '" + timeFormattedString(hour, minute, second) + ".",
                    SQLError.SQL_STATE_ILLEGAL_ARGUMENT, exceptionInterceptor);
        }

        if (second < 0 || second > 59) {
            throw SQLError.createSQLException(
                    "Illegal minute value '" + second + "' for java.sql.Time type in value '" + timeFormattedString(hour, minute, second) + ".",
                    SQLError.SQL_STATE_ILLEGAL_ARGUMENT, exceptionInterceptor);
        }

        synchronized (cal) {
            java.util.Date origCalDate = cal.getTime();
            try {
                cal.clear();

                // Set 'date' to epoch of Jan 1, 1970
                cal.set(1970, 0, 1, hour, minute, second);

                long timeAsMillis = cal.getTimeInMillis();

                return new Time(timeAsMillis);
            } finally {
                cal.setTime(origCalDate);
            }
        }
    }

    final static Time fastTimeCreate(int hour, int minute, int second, Calendar targetCalendar, ExceptionInterceptor exceptionInterceptor) throws SQLException {
        if (hour < 0 || hour > 23) {
            throw SQLError.createSQLException(
                    "Illegal hour value '" + hour + "' for java.sql.Time type in value '" + timeFormattedString(hour, minute, second) + ".",
                    SQLError.SQL_STATE_ILLEGAL_ARGUMENT, exceptionInterceptor);
        }

        if (minute < 0 || minute > 59) {
            throw SQLError.createSQLException(
                    "Illegal minute value '" + minute + "' for java.sql.Time type in value '" + timeFormattedString(hour, minute, second) + ".",
                    SQLError.SQL_STATE_ILLEGAL_ARGUMENT, exceptionInterceptor);
        }

        if (second < 0 || second > 59) {
            throw SQLError.createSQLException(
                    "Illegal minute value '" + second + "' for java.sql.Time type in value '" + timeFormattedString(hour, minute, second) + ".",
                    SQLError.SQL_STATE_ILLEGAL_ARGUMENT, exceptionInterceptor);
        }

        Calendar cal = (targetCalendar == null) ? new GregorianCalendar() : targetCalendar;

        synchronized (cal) {
            java.util.Date origCalDate = cal.getTime();
            try {
                cal.clear();

                // Set 'date' to epoch of Jan 1, 1970
                cal.set(1970, 0, 1, hour, minute, second);

                long timeAsMillis = cal.getTimeInMillis();

                return new Time(timeAsMillis);
            } finally {
                cal.setTime(origCalDate);
            }
        }
    }

    final static Timestamp fastTimestampCreate(boolean useGmtConversion, Calendar gmtCalIfNeeded, Calendar cal, int year, int month, int day, int hour,
            int minute, int seconds, int secondsPart) {

        synchronized (cal) {
            java.util.Date origCalDate = cal.getTime();
            try {
                cal.clear();

                // why-oh-why is this different than java.util.date, in the year part, but it still keeps the silly '0' for the start month????
                cal.set(year, month - 1, day, hour, minute, seconds);

                int offsetDiff = 0;

                if (useGmtConversion) {
                    int fromOffset = cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET);

                    if (gmtCalIfNeeded == null) {
                        gmtCalIfNeeded = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
                    }
                    gmtCalIfNeeded.clear();

                    gmtCalIfNeeded.setTimeInMillis(cal.getTimeInMillis());

                    int toOffset = gmtCalIfNeeded.get(Calendar.ZONE_OFFSET) + gmtCalIfNeeded.get(Calendar.DST_OFFSET);
                    offsetDiff = fromOffset - toOffset;
                }

                if (secondsPart != 0) {
                    cal.set(Calendar.MILLISECOND, secondsPart / 1000000);
                }

                long tsAsMillis = cal.getTimeInMillis();

                Timestamp ts = new Timestamp(tsAsMillis + offsetDiff);

                ts.setNanos(secondsPart);

                return ts;
            } finally {
                cal.setTime(origCalDate);
            }
        }
    }

    final static Timestamp fastTimestampCreate(TimeZone tz, int year, int month, int day, int hour, int minute, int seconds, int secondsPart) {
        Calendar cal = (tz == null) ? new GregorianCalendar() : new GregorianCalendar(tz);
        cal.clear();

        // why-oh-why is this different than java.util.date, in the year part, but it still keeps the silly '0' for the start month????
        cal.set(year, month - 1, day, hour, minute, seconds);

        long tsAsMillis = cal.getTimeInMillis();

        Timestamp ts = new Timestamp(tsAsMillis);
        ts.setNanos(secondsPart);

        return ts;
    }

    /**
     * Returns the 'official' Java timezone name for the given timezone
     * 
     * @param timezoneStr
     *            the 'common' timezone name
     * 
     * @return the Java timezone name for the given timezone
     * @throws SQLException
     * 
     * @throws IllegalArgumentException
     */
    public static String getCanonicalTimezone(String timezoneStr, ExceptionInterceptor exceptionInterceptor) throws SQLException {
        if (timezoneStr == null) {
            return null;
        }

        timezoneStr = timezoneStr.trim();

        // handle '+/-hh:mm' form ...
        if (timezoneStr.length() > 2) {
            if ((timezoneStr.charAt(0) == '+' || timezoneStr.charAt(0) == '-') && Character.isDigit(timezoneStr.charAt(1))) {
                return "GMT" + timezoneStr;
            }
        }

        synchronized (TimeUtil.class) {
            if (timeZoneMappings == null) {
                loadTimeZoneMappings(exceptionInterceptor);
            }
        }

        String canonicalTz;
        if ((canonicalTz = timeZoneMappings.getProperty(timezoneStr)) != null) {
            return canonicalTz;
        }

        throw SQLError.createSQLException(Messages.getString("TimeUtil.UnrecognizedTimezoneId", new Object[] { timezoneStr }),
                SQLError.SQL_STATE_INVALID_CONNECTION_ATTRIBUTE, exceptionInterceptor);
    }

    // we could use SimpleDateFormat, but it won't work when the time values are out-of-bounds, and we're using this for error messages for exactly  that case

    private static String timeFormattedString(int hours, int minutes, int seconds) {
        StringBuilder buf = new StringBuilder(8);
        if (hours < 10) {
            buf.append("0");
        }

        buf.append(hours);
        buf.append(":");

        if (minutes < 10) {
            buf.append("0");
        }

        buf.append(minutes);
        buf.append(":");

        if (seconds < 10) {
            buf.append("0");
        }

        buf.append(seconds);

        return buf.toString();
    }

    public static String formatNanos(int nanos, boolean serverSupportsFracSecs, boolean usingMicros) {

        // get only last 9 digits
        if (nanos > 999999999) {
            nanos %= 100000000;
        }

        if (usingMicros) {
            nanos /= 1000;
        }

        if (!serverSupportsFracSecs || nanos == 0) {
            return "0";
        }

        final int digitCount = usingMicros ? 6 : 9;

        String nanosString = Integer.toString(nanos);
        final String zeroPadding = usingMicros ? "000000" : "000000000";

        nanosString = zeroPadding.substring(0, (digitCount - nanosString.length())) + nanosString;

        int pos = digitCount - 1; // the end, we're padded to the end by the code above

        while (nanosString.charAt(pos) == '0') {
            pos--;
        }

        nanosString = nanosString.substring(0, pos + 1);

        return nanosString;
    }

    /**
     * Loads a properties file that contains all kinds of time zone mappings.
     * 
     * @param exceptionInterceptor
     * @throws SQLException
     */
    private static void loadTimeZoneMappings(ExceptionInterceptor exceptionInterceptor) throws SQLException {
        timeZoneMappings = new Properties();
        try {
            timeZoneMappings.load(TimeUtil.class.getResourceAsStream(TIME_ZONE_MAPPINGS_RESOURCE));
        } catch (IOException e) {
            throw SQLError.createSQLException(Messages.getString("TimeUtil.LoadTimeZoneMappingError"), SQLError.SQL_STATE_INVALID_CONNECTION_ATTRIBUTE,
                    exceptionInterceptor);
        }
        // bridge all Time Zone ids known by Java
        for (String tz : TimeZone.getAvailableIDs()) {
            if (!timeZoneMappings.containsKey(tz)) {
                timeZoneMappings.put(tz, tz);
            }
        }
    }

    public static Timestamp truncateFractionalSeconds(Timestamp timestamp) {
        Timestamp truncatedTimestamp = new Timestamp(timestamp.getTime());
        truncatedTimestamp.setNanos(0);
        return truncatedTimestamp;
    }
}