Project

General

Profile

Download (8.08 KB) Statistics
| Branch: | Tag: | Revision:
1
/**
2
* Copyright (C) 2007 EDIT
3
* European Distributed Institute of Taxonomy
4
* http://www.e-taxonomy.eu
5
*
6
* The contents of this file are subject to the Mozilla Public License Version 1.1
7
* See LICENSE.TXT at the top of this package for the full license terms.
8
*/
9

    
10
package eu.etaxonomy.cdm.io.common.mapping.out;
11

    
12
import java.sql.PreparedStatement;
13
import java.sql.ResultSet;
14
import java.sql.SQLException;
15
import java.sql.Types;
16

    
17
import org.apache.logging.log4j.LogManager;import org.apache.logging.log4j.Logger;
18
import org.joda.time.DateTime;
19

    
20
import eu.etaxonomy.cdm.common.CdmUtils;
21
import eu.etaxonomy.cdm.io.common.DbExportStateBase;
22
import eu.etaxonomy.cdm.io.common.ImportHelper;
23
import eu.etaxonomy.cdm.io.common.Source;
24
import eu.etaxonomy.cdm.io.common.mapping.CdmSingleAttributeMapperBase;
25
import eu.etaxonomy.cdm.model.common.CdmBase;
26

    
27
/**
28
 * @author a.mueller
29
 * @since 12.05.2009
30
 */
31
public abstract class DbSingleAttributeExportMapperBase<STATE extends DbExportStateBase<?, IExportTransformer>>
32
        extends CdmSingleAttributeMapperBase
33
        implements IDbExportMapper<STATE, IExportTransformer>  {
34

    
35
    private static final Logger logger = LogManager.getLogger(DbSingleAttributeExportMapperBase.class);
36

    
37
	protected DbExportMapperBase<STATE> exportMapperHelper = new DbExportMapperBase<>();
38
	private Integer precision = null;
39
	//if the source attribute (not the value) is obligatory, currently results in error logging only
40
	protected boolean obligatory = true;
41
	protected boolean notNull = false;
42

    
43
	protected DbSingleAttributeExportMapperBase(String cdmAttributeString, String dbAttributString, Object defaultValue) {
44
		super(cdmAttributeString, dbAttributString, defaultValue);
45
	}
46

    
47
	/**
48
     * @param cdmAttributeString source attribute (CDM)
49
     * @param dbAttributString target attribute (export DB)
50
     * @param defaultValue default value if source value is <code>null</code>
51
     * @param obligatory if the source attribute is obligatory, but value may be <code>null</code>
52
     */
53
    protected DbSingleAttributeExportMapperBase(String cdmAttributeString, String dbAttributString, Object defaultValue, boolean obligatory, boolean notNull) {
54
        super(cdmAttributeString, dbAttributString, defaultValue);
55
        this.notNull = notNull;
56
        this.obligatory = obligatory;
57
    }
58

    
59
	@Override
60
    public void initialize(PreparedStatement stmt, IndexCounter index, STATE state, String tableName) {
61
		exportMapperHelper.initialize(stmt, index, state, tableName);
62
		this.precision = getDbColumnIntegerInfo("c.prec");
63
	}
64

    
65
	@Override
66
    public boolean invoke(CdmBase cdmBase) throws SQLException {
67
		if (exportMapperHelper.preparedStatement == null){
68
			logger.warn("PreparedStatement is null");
69
			return false;
70
		}else{
71
			return doInvoke(cdmBase);
72
		}
73
	}
74

    
75
	protected boolean doInvoke(CdmBase cdmBase) throws SQLException {
76
		try {
77
			Object value = getValue(cdmBase);
78
			int sqlType = getSqlType();
79
			//use default value if necessary
80
			if (value == null && defaultValue != null){
81
				value = defaultValue;
82
			}
83
			if (value == null){
84
			    if (notNull){
85
			        logger.error("Value for '"+this.getSourceAttribute()+"' is null but a value is required. Object: " + cdmBase.toString());
86
			        return false;
87
			    }else{
88
			        getPreparedStatement().setNull(getIndex(), sqlType);
89
			    }
90
			}else{
91
				if (sqlType == Types.INTEGER){
92
					try{
93
						getPreparedStatement().setInt(getIndex(), (Integer)value);
94
					}catch (Exception e) {
95
						logger.error("Exception: " + e.getLocalizedMessage() + ": " + cdmBase.toString());
96
						value = getValue(cdmBase);
97
						throw new RuntimeException( e);
98
					}
99
				}else if (sqlType == Types.CLOB){
100
					getPreparedStatement().setString(getIndex(), (String)value);
101
				}else if (sqlType == Types.VARCHAR){
102
					String strValue = (String)value;
103
//					if (strValue.length() > 255){
104
//						logger.debug("String to long (" + strValue.length() + ") for object " + cdmBase.toString() + ": " + value);
105
//					}
106
					int precision = getPrecision();
107
					if (strValue.length() > 450){
108
						logger.debug(">450");
109
					}
110

    
111
					if (strValue.length() > precision && precision > 0 ){
112
						logger.warn("The length of the string to save ("+ getDestinationAttribute() + ") is longer than the database columns precision ("+precision+"). String will be truncated: " + strValue);
113
						if (precision >= 4) {
114
							strValue = strValue.substring(0, precision - 4 )+" ...";
115
						} else {
116
							strValue = strValue.substring(0, precision);
117
						}
118
					}
119
					getPreparedStatement().setString(getIndex(), strValue);
120
				}else if (sqlType == Types.BOOLEAN){
121
					getPreparedStatement().setBoolean(getIndex(), (Boolean)value);
122
				}else if (sqlType == Types.DATE){
123
				    java.sql.Timestamp sqlTimestamp;
124
				    if(value instanceof String){
125
				        String strDate = (String)value;
126
				        sqlTimestamp = java.sql.Timestamp.valueOf(strDate);
127
				    }else{
128
				        DateTime dateTime = (DateTime)value;
129
				        java.util.Date date = dateTime.toDate();
130
				        long t = date.getTime();
131
				        sqlTimestamp = new java.sql.Timestamp(t);
132
				    }
133
					getPreparedStatement().setTimestamp(getIndex(), sqlTimestamp);
134
				}else{
135
					throw new IllegalArgumentException("SqlType not yet supported yet: " + sqlType);
136
				}
137
			}
138
			return true;
139
		} catch (SQLException e) {
140
			logger.warn("SQL Exception: " + e.getLocalizedMessage());
141
			throw e;
142
		} catch (IllegalArgumentException e) {
143
			logger.error("IllegalArgumentException: " + e.getLocalizedMessage() + ": " + cdmBase.toString());
144
			return false;
145
		} catch (Exception e) {
146
			logger.error("Exception: " + e.getLocalizedMessage() + ": " + cdmBase.toString());
147
			throw new RuntimeException( e);
148
		}
149
	}
150

    
151
	protected Object getValue(CdmBase cdmBase){
152
		boolean isBoolean = (this.getTypeClass() == boolean.class || this.getTypeClass() == Boolean.class);
153
		return ImportHelper.getValue(cdmBase, this.getSourceAttribute(), isBoolean, obligatory);
154
	}
155

    
156
	protected abstract int getSqlType();
157

    
158
	public PreparedStatement getPreparedStatement() {
159
		return exportMapperHelper.getPreparedStatement();
160
	}
161

    
162
	public int getIndex() {
163
		return exportMapperHelper.getIndex();
164
	}
165

    
166
	public STATE getState() {
167
		return exportMapperHelper.getState();
168
	}
169

    
170
	public String getTableName() {
171
		return exportMapperHelper.getTableName();
172
	}
173

    
174
	protected boolean checkSqlServerColumnExists(){
175
		Source source = getState().getConfig().getDestination();
176
		String strQuery = "SELECT  Count(t.id) as n " +
177
				" FROM sysobjects AS t " +
178
				" INNER JOIN syscolumns AS c ON t.id = c.id " +
179
				" WHERE (t.xtype = 'U') AND " +
180
				" (t.name = '" + getTableName() + "') AND " +
181
				" (c.name = '" + getDestinationAttribute() + "')";
182
		ResultSet rs = source.getResultSet(strQuery) ;
183
		int n;
184
		try {
185
			rs.next();
186
			n = rs.getInt("n");
187
			return n>0;
188
		} catch (SQLException e) {
189
			e.printStackTrace();
190
			return false;
191
		}
192
	}
193

    
194
	protected int getPrecision(){
195
		return this.precision;
196
	}
197

    
198
	protected int getDbColumnIntegerInfo(String selectPart){
199
		Source source = getState().getConfig().getDestination();
200
		String strQuery = "SELECT  " + selectPart + " as result" +
201
				" FROM sysobjects AS t " +
202
				" INNER JOIN syscolumns AS c ON t.id = c.id " +
203
				" WHERE (t.xtype = 'U') AND " +
204
				" (t.name = '" + getTableName() + "') AND " +
205
				" (c.name = '" + getDestinationAttribute() + "')";
206
		ResultSet rs = source.getResultSet(strQuery) ;
207
		int n;
208
		try {
209
			rs.next();
210
			n = rs.getInt("result");
211
			return n;
212
		} catch (Exception e) {
213
			System.out.println(strQuery);
214
		    logger.error(e.getMessage() + ", selectPart: " + CdmUtils.Nz(selectPart) + ", table: " + CdmUtils.Nz(getTableName()) +", destination: " + CdmUtils.Nz(getDestinationAttribute()));
215
			e.printStackTrace();
216
			return -1;
217
		}
218
	}
219

    
220
	@Override
221
    public String toString(){
222
		String sourceAtt = CdmUtils.Nz(getSourceAttribute());
223
		String destAtt = CdmUtils.Nz(getDestinationAttribute());
224
		return this.getClass().getSimpleName() +"[" + sourceAtt + "->" + destAtt + "]";
225
	}
226
}
(30-30/44)