Line data Source code
1 : // Copyright 2008 Google Inc. 2 : // 3 : // Licensed under the Apache License, Version 2.0 (the "License"); 4 : // you may not use this file except in compliance with the License. 5 : // You may obtain a copy of the License at 6 : // 7 : // http://www.apache.org/licenses/LICENSE-2.0 8 : // 9 : // Unless required by applicable law or agreed to in writing, software 10 : // distributed under the License is distributed on an "AS IS" BASIS, 11 : // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 : // See the License for the specific language governing permissions and 13 : // limitations under the License. 14 : 15 : package com.google.gerrit.json; 16 : 17 : import com.google.gerrit.common.Nullable; 18 : import com.google.gson.JsonDeserializationContext; 19 : import com.google.gson.JsonDeserializer; 20 : import com.google.gson.JsonElement; 21 : import com.google.gson.JsonNull; 22 : import com.google.gson.JsonParseException; 23 : import com.google.gson.JsonPrimitive; 24 : import com.google.gson.JsonSerializationContext; 25 : import com.google.gson.JsonSerializer; 26 : import java.lang.reflect.Type; 27 : import java.sql.Timestamp; 28 : import java.text.SimpleDateFormat; 29 : import java.util.TimeZone; 30 : 31 157 : class SqlTimestampDeserializer implements JsonDeserializer<Timestamp>, JsonSerializer<Timestamp> { 32 157 : private static final TimeZone UTC = TimeZone.getTimeZone("UTC"); 33 : 34 : @Nullable 35 : @Override 36 : public Timestamp deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) 37 : throws JsonParseException { 38 9 : if (json.isJsonNull()) { 39 0 : return null; 40 : } 41 9 : if (!json.isJsonPrimitive()) { 42 0 : throw new JsonParseException("Expected string for timestamp type"); 43 : } 44 9 : JsonPrimitive p = (JsonPrimitive) json; 45 9 : if (!p.isString()) { 46 0 : throw new JsonParseException("Expected string for timestamp type"); 47 : } 48 : 49 9 : String input = p.getAsString(); 50 9 : if (input.trim().isEmpty()) { 51 : // Magic timestamp to indicate no timestamp. (-> null object) 52 : // Always create a new object as timestamps are mutable. Don't use TimeUtil.never() to not 53 : // introduce an undesired dependency. 54 1 : return new Timestamp(0); 55 : } 56 : 57 8 : return JavaSqlTimestampHelper.parseTimestamp(input); 58 : } 59 : 60 : @Override 61 : public JsonElement serialize(Timestamp src, Type typeOfSrc, JsonSerializationContext context) { 62 15 : if (src == null) { 63 0 : return JsonNull.INSTANCE; 64 : } 65 15 : return new JsonPrimitive(newFormat().format(src) + "000000"); 66 : } 67 : 68 : private static SimpleDateFormat newFormat() { 69 15 : SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); 70 15 : f.setTimeZone(UTC); 71 15 : f.setLenient(true); 72 15 : return f; 73 : } 74 : }