java-commons/commons-serialize-databind-sql/src/main/java/io/gitlab/jfronny/commons/serialize/databind/sql/SqlTimestampTypeAdapter.java

58 lines
2.4 KiB
Java

/*
* Copyright (C) 2020 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.gitlab.jfronny.commons.serialize.databind.sql;
import io.gitlab.jfronny.commons.serialize.databind.ObjectMapper;
import io.gitlab.jfronny.commons.serialize.databind.api.TypeAdapter;
import io.gitlab.jfronny.commons.serialize.databind.TypeAdapterFactory;
import io.gitlab.jfronny.commons.serialize.databind.api.TypeToken;
import io.gitlab.jfronny.commons.serialize.MalformedDataException;
import io.gitlab.jfronny.commons.serialize.SerializeReader;
import io.gitlab.jfronny.commons.serialize.SerializeWriter;
import java.sql.Timestamp;
import java.util.Date;
@SuppressWarnings("JavaUtilDate")
class SqlTimestampTypeAdapterFactory implements TypeAdapterFactory {
@Override
public <T> TypeAdapter<T> create(ObjectMapper mapper, TypeToken<T> type) {
if (type.getRawType() != Timestamp.class) return null;
TypeAdapter<Date> dateTypeAdapter = mapper.getAdapter(Date.class);
return (TypeAdapter) new TimestampTypeAdapter(dateTypeAdapter);
}
private static class TimestampTypeAdapter extends TypeAdapter<Timestamp> {
private final TypeAdapter<Date> dateTypeAdapter;
public TimestampTypeAdapter(TypeAdapter<Date> dateTypeAdapter) {
this.dateTypeAdapter = dateTypeAdapter;
}
@Override
public <TEx extends Exception, Writer extends SerializeWriter<TEx, Writer>> void serialize(Timestamp value, Writer writer) throws TEx, MalformedDataException {
dateTypeAdapter.serialize(value, writer);
}
@Override
public <TEx extends Exception, Reader extends SerializeReader<TEx, Reader>> Timestamp deserialize(Reader reader) throws TEx, MalformedDataException {
Date date = dateTypeAdapter.deserialize(reader);
return date != null ? new Timestamp(date.getTime()) : null;
}
}
}