Finish second-to-last commit
[unical.git] / gson / com / google / gson / internal / bind / TimeTypeAdapter.java
CommitLineData
cfd903b6
MG
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
17package com.google.gson.internal.bind;
18
19import com.google.gson.Gson;
20import com.google.gson.JsonSyntaxException;
21import com.google.gson.TypeAdapter;
22import com.google.gson.TypeAdapterFactory;
23import com.google.gson.reflect.TypeToken;
24import com.google.gson.stream.JsonReader;
25import com.google.gson.stream.JsonToken;
26import com.google.gson.stream.JsonWriter;
27import java.io.IOException;
28import java.sql.Time;
29import java.text.DateFormat;
30import java.text.ParseException;
31import java.text.SimpleDateFormat;
32import 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 */
40public 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}
This page took 0.014516 seconds and 4 git commands to generate.