package fi.nls.oskari.mybatis;

import fi.nls.oskari.log.LogFactory;
import fi.nls.oskari.log.Logger;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.json.JSONException;
import org.json.JSONObject;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@MappedTypes({JSONObject.class})
@MappedJdbcTypes({JdbcType.VARCHAR, JdbcType.NULL})
public class JSONObjectMybatisTypeHandler extends BaseTypeHandler<JSONObject> {
	private final static Logger log = LogFactory.getLogger(JSONObjectMybatisTypeHandler.class);

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, JSONObject parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, parameter.toString());
    }

    @Override
    public JSONObject getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return valueOf(rs.getString(columnName));
    }

    @Override
    public JSONObject getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return valueOf(rs.getString(columnIndex));
    }

    @Override
    public JSONObject getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return valueOf(cs.getString(columnIndex));
    }

    public JSONObject valueOf(String s) {
        try {
            return new JSONObject(s);
        } catch (JSONException e) {
            log.error("Couldn't parse DB string to JSONObject:", s, e);
            return new JSONObject();
        }
    }
}

@@ -91,24 +91,74 @@
 log.Logger;%0A
+import org.apache.commons.text.StringEscapeUtils;%0A
 import org.a
@@ -1507,24 +1507,96 @@
 String s) %7B%0A
+        if (s == null) %7B%0A            return new JSONObject();%0A        %7D%0A
         try 
@@ -1687,17 +1687,335 @@
     
-log.error
+if (s.startsWith(%22%5C%22%7B%22) && s.endsWith(%22%7D%5C%22%22) && s.length() %3E 5) %7B%0A                // H2 DB wraps a stringified json to quotes and escapes the content%0A                String unwrapped = s.substring(1, s.length()  - 1);%0A                return valueOf(StringEscapeUtils.unescapeJava(unwrapped));%0A            %7D%0A            log.info
 (%22Co

Make an effort unwrapping stringified JSON to an object before failing