001/* 002 * Copyright 2021 Anyware Services 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package org.ametys.plugins.contentio.synchronize.impl.typehandler; 017 018import java.sql.CallableStatement; 019import java.sql.PreparedStatement; 020import java.sql.ResultSet; 021import java.sql.SQLException; 022import java.sql.Timestamp; 023import java.time.ZoneId; 024import java.time.ZonedDateTime; 025 026import org.apache.ibatis.type.BaseTypeHandler; 027import org.apache.ibatis.type.InstantTypeHandler; 028import org.apache.ibatis.type.JdbcType; 029 030import org.ametys.core.util.DateUtils; 031 032/** 033 * Inspired from {@link InstantTypeHandler} 034 */ 035public class ZonedDateTimeTypeHandler extends BaseTypeHandler<ZonedDateTime> 036{ 037 @Override 038 public void setNonNullParameter(PreparedStatement ps, int i, ZonedDateTime parameter, JdbcType jdbcType) throws SQLException 039 { 040 ps.setTimestamp(i, Timestamp.from(parameter.toInstant())); 041 } 042 043 @Override 044 public ZonedDateTime getNullableResult(ResultSet rs, String columnName) throws SQLException 045 { 046 Timestamp timestamp = rs.getTimestamp(columnName); 047 return _getZonedDateTime(timestamp); 048 } 049 050 @Override 051 public ZonedDateTime getNullableResult(ResultSet rs, int columnIndex) throws SQLException 052 { 053 Timestamp timestamp = rs.getTimestamp(columnIndex); 054 return _getZonedDateTime(timestamp); 055 } 056 057 @Override 058 public ZonedDateTime getNullableResult(CallableStatement cs, int columnIndex) throws SQLException 059 { 060 Timestamp timestamp = cs.getTimestamp(columnIndex); 061 return _getZonedDateTime(timestamp); 062 } 063 064 private ZonedDateTime _getZonedDateTime(Timestamp timestamp) 065 { 066 if (timestamp != null) 067 { 068 // In most cases, the database and the web server are on the same timezone 069 // Force the zone ID is useful for date only, there is no changes to date time 070 return DateUtils.asZonedDateTime(timestamp.toInstant(), ZoneId.systemDefault()); 071 } 072 return null; 073 } 074}