1 package com.google.gson.internal.sql; 2 3 import java.sql.Timestamp; 4 import java.util.Date; 5 6 import com.google.gson.TypeAdapterFactory; 7 import com.google.gson.internal.bind.DefaultDateTypeAdapter.DateType; 8 9 /** 10 * Encapsulates access to {@code java.sql} types, to allow Gson to 11 * work without the {@code java.sql} module being present. 12 * No {@link ClassNotFoundException}s will be thrown in case 13 * the {@code java.sql} module is not present. 14 * 15 * <p>If {@link #SUPPORTS_SQL_TYPES} is {@code true}, all other 16 * constants of this class will be non-{@code null}. However, if 17 * it is {@code false} all other constants will be {@code null} and 18 * there will be no support for {@code java.sql} types. 19 */ 20 public final class SqlTypesSupport { 21 /** 22 * {@code true} if {@code java.sql} types are supported, 23 * {@code false} otherwise 24 */ 25 public static final boolean SUPPORTS_SQL_TYPES; 26 27 public static final DateType<? extends Date> DATE_DATE_TYPE; 28 public static final DateType<? extends Date> TIMESTAMP_DATE_TYPE; 29 30 public static final TypeAdapterFactory DATE_FACTORY; 31 public static final TypeAdapterFactory TIME_FACTORY; 32 public static final TypeAdapterFactory TIMESTAMP_FACTORY; 33 34 static { 35 boolean sqlTypesSupport; 36 try { 37 Class.forName("java.sql.Date"); 38 sqlTypesSupport = true; 39 } catch (ClassNotFoundException classNotFoundException) { 40 sqlTypesSupport = false; 41 } 42 SUPPORTS_SQL_TYPES = sqlTypesSupport; 43 44 if (SUPPORTS_SQL_TYPES) { 45 DATE_DATE_TYPE = new DateType<java.sql.Date>(java.sql.Date.class) { 46 @Override protected java.sql.Date deserialize(Date date) { 47 return new java.sql.Date(date.getTime()); 48 } 49 }; 50 TIMESTAMP_DATE_TYPE = new DateType<Timestamp>(Timestamp.class) { 51 @Override protected Timestamp deserialize(Date date) { 52 return new Timestamp(date.getTime()); 53 } 54 }; 55 56 DATE_FACTORY = SqlDateTypeAdapter.FACTORY; 57 TIME_FACTORY = SqlTimeTypeAdapter.FACTORY; 58 TIMESTAMP_FACTORY = SqlTimestampTypeAdapter.FACTORY; 59 } else { 60 DATE_DATE_TYPE = null; 61 TIMESTAMP_DATE_TYPE = null; 62 63 DATE_FACTORY = null; 64 TIME_FACTORY = null; 65 TIMESTAMP_FACTORY = null; 66 } 67 } 68 SqlTypesSupport()69 private SqlTypesSupport() { 70 } 71 } 72