001/* 002 * Copyright 2018 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.io.IOException; 019import java.sql.CallableStatement; 020import java.sql.Clob; 021import java.sql.PreparedStatement; 022import java.sql.ResultSet; 023import java.sql.SQLException; 024 025import org.apache.commons.io.IOUtils; 026import org.apache.ibatis.type.BaseTypeHandler; 027import org.apache.ibatis.type.JdbcType; 028import org.slf4j.Logger; 029import org.slf4j.LoggerFactory; 030 031import com.google.common.base.CharMatcher; 032 033/** 034 * Handle Clob SQL type to return string value 035 */ 036public class SQLClobTypeHandler extends BaseTypeHandler<Object> 037{ 038 private static Logger __logger = LoggerFactory.getLogger(SQLClobTypeHandler.class); 039 040 @Override 041 public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException 042 { 043 ps.setObject(i, parameter); 044 } 045 046 @Override 047 public Object getNullableResult(ResultSet rs, String columnName) throws SQLException 048 { 049 Clob clob = rs.getClob(columnName); 050 return _transformClobToString(clob); 051 } 052 053 @Override 054 public Object getNullableResult(ResultSet rs, int columnIndex) throws SQLException 055 { 056 Clob clob = rs.getClob(columnIndex); 057 return _transformClobToString(clob); 058 059 } 060 061 @Override 062 public Object getNullableResult(CallableStatement cs, int columnIndex) throws SQLException 063 { 064 Clob clob = cs.getClob(columnIndex); 065 return _transformClobToString(clob); 066 } 067 068 /** 069 * Transform CLOB value to String value. 070 * @param clob the clob 071 * @return the CLOB transformed to String. 072 * @throws SQLException if an error occurred 073 */ 074 protected String _transformClobToString(Clob clob) throws SQLException 075 { 076 try 077 { 078 String strValue = IOUtils.toString(clob.getCharacterStream()); 079 return CharMatcher.javaIsoControl().and(CharMatcher.anyOf("\r\n\t").negate()).removeFrom(strValue); 080 } 081 catch (IOException e) 082 { 083 __logger.warn("Can't transform clob to string", e); 084 return null; 085 } 086 finally 087 { 088 clob.free(); 089 } 090 } 091}