| 1 | /* |
| 2 | * Copyright (C) 2011 Google Inc. |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | package com.google.gson.internal.bind; |
| 18 | |
| 19 | import com.google.gson.Gson; |
| 20 | import com.google.gson.JsonSyntaxException; |
| 21 | import com.google.gson.TypeAdapter; |
| 22 | import com.google.gson.TypeAdapterFactory; |
| 23 | import com.google.gson.reflect.TypeToken; |
| 24 | import com.google.gson.stream.JsonReader; |
| 25 | import com.google.gson.stream.JsonToken; |
| 26 | import com.google.gson.stream.JsonWriter; |
| 27 | import java.io.IOException; |
| 28 | import java.sql.Time; |
| 29 | import java.text.DateFormat; |
| 30 | import java.text.ParseException; |
| 31 | import java.text.SimpleDateFormat; |
| 32 | import java.util.Date; |
| 33 | |
| 34 | /** |
| 35 | * Adapter for Time. Although this class appears stateless, it is not. |
| 36 | * DateFormat captures its time zone and locale when it is created, which gives |
| 37 | * this class state. DateFormat isn't thread safe either, so this class has |
| 38 | * to synchronize its read and write methods. |
| 39 | */ |
| 40 | public final class TimeTypeAdapter extends TypeAdapter<Time> { |
| 41 | public static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() { |
| 42 | @SuppressWarnings("unchecked") // we use a runtime check to make sure the 'T's equal |
| 43 | public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) { |
| 44 | return typeToken.getRawType() == Time.class ? (TypeAdapter<T>) new TimeTypeAdapter() : null; |
| 45 | } |
| 46 | }; |
| 47 | |
| 48 | private final DateFormat format = new SimpleDateFormat("hh:mm:ss a"); |
| 49 | |
| 50 | @Override public synchronized Time read(JsonReader in) throws IOException { |
| 51 | if (in.peek() == JsonToken.NULL) { |
| 52 | in.nextNull(); |
| 53 | return null; |
| 54 | } |
| 55 | try { |
| 56 | Date date = format.parse(in.nextString()); |
| 57 | return new Time(date.getTime()); |
| 58 | } catch (ParseException e) { |
| 59 | throw new JsonSyntaxException(e); |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | @Override public synchronized void write(JsonWriter out, Time value) throws IOException { |
| 64 | out.value(value == null ? null : format.format(value)); |
| 65 | } |
| 66 | } |