Project

General

Profile

Download (12.7 KB) Statistics
| Branch: | Tag: | Revision:
1
/**
2
* Copyright (C) 2009 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
package eu.etaxonomy.cdm.database.update;
10

    
11
import java.sql.ResultSet;
12
import java.sql.SQLException;
13
import java.util.UUID;
14

    
15
import org.apache.log4j.Logger;
16

    
17
import eu.etaxonomy.cdm.common.monitor.IProgressMonitor;
18
import eu.etaxonomy.cdm.database.ICdmDataSource;
19
import eu.etaxonomy.cdm.model.common.TermType;
20
import eu.etaxonomy.cdm.model.description.Feature;
21
import eu.etaxonomy.cdm.model.name.Rank;
22
import eu.etaxonomy.cdm.model.name.RankClass;
23

    
24
/**
25
 * Creates a new term if a term with the same given uuid does not exist yet
26
 * @author a.mueller
27
 * @since 10.09.2010
28
 *
29
 */
30
public class SingleTermUpdater extends SchemaUpdaterStepBase {
31
	@SuppressWarnings("unused")
32
	private static final Logger logger = Logger.getLogger(SingleTermUpdater.class);
33

    
34
	/**
35
	 * @Deprecated use {@link #NewInstance(String, TermType, UUID, String, String, String, String, UUID, UUID, boolean, UUID)} instead
36
	 */
37
	@Deprecated
38
	public static final SingleTermUpdater NewInstance(String stepName, UUID uuidTerm, String description,  String label, String abbrev, String dtype, UUID uuidVocabulary, UUID uuidLanguage, boolean isOrdered, UUID uuidAfterTerm){
39
		return new SingleTermUpdater(stepName, null, uuidTerm, null, description, label, abbrev, dtype, uuidVocabulary, uuidLanguage, isOrdered, uuidAfterTerm);
40
	}
41

    
42
	public static final SingleTermUpdater NewInstance(String stepName, TermType termType, UUID uuidTerm, String idInVocabulary, String description,  String label, String abbrev, String dtype, UUID uuidVocabulary, UUID uuidLanguage, boolean isOrdered, UUID uuidAfterTerm){
43
		return new SingleTermUpdater(stepName, termType, uuidTerm, idInVocabulary, description, label, abbrev, dtype, uuidVocabulary, uuidLanguage, isOrdered, uuidAfterTerm);
44
	}
45

    
46

    
47
	private final UUID uuidTerm ;
48
	private final String description;
49
	private final String label;
50
	private final String abbrev;
51
	private final String dtype;
52
	private final UUID uuidVocabulary;
53
	private final boolean isOrdered;
54
	private final UUID uuidAfterTerm;
55
	private final UUID uuidLanguage;
56
	private String reverseDescription;
57
	private String reverseLabel;
58
	private String reverseAbbrev;
59
	private RankClass rankClass;
60
	private final TermType termType;
61
	private final String idInVocabulary;
62
	private boolean symmetric = false;
63
	private boolean transitive = false;
64

    
65

    
66

    
67
	private SingleTermUpdater(String stepName, TermType termType, UUID uuidTerm, String idInVocabulary, String description, String label, String abbrev, String dtype, UUID uuidVocabulary, UUID uuidLanguage, boolean isOrdered, UUID uuidAfterTerm) {
68
		super(stepName);
69
		this.termType = termType;
70
		this.idInVocabulary = idInVocabulary;
71
		this.abbrev = abbrev;
72
		this.description = description;
73
		this.dtype = dtype;
74
		this.label = label;
75
		this.isOrdered = isOrdered;
76
		this.uuidTerm = uuidTerm;
77
		this.uuidVocabulary = uuidVocabulary;
78
		this.uuidAfterTerm = uuidAfterTerm;
79
		this.uuidLanguage = uuidLanguage;
80
	}
81

    
82
    @Override
83
    public void invoke(ICdmDataSource datasource, IProgressMonitor monitor,
84
            CaseType caseType, SchemaUpdateResult result) throws SQLException {
85
		String sqlCheckTermExists = " SELECT count(*) as n " +
86
 				" FROM " + caseType.transformTo("DefinedTermBase") +
87
 				" WHERE uuid = '" + uuidTerm + "'";
88
		Long n = (Long)datasource.getSingleValue(sqlCheckTermExists);
89
		if (n != 0){
90
		    String message ="Term already exists: " + label + "(" + uuidTerm + ")";
91
			monitor.warning(message);
92
			result.addWarning(message, (String)null, getStepName());
93
			return;
94
		}
95

    
96
		//vocabulary id
97
		int vocId;
98
		String sqlVocId = " SELECT id " +
99
				" FROM  " + caseType.transformTo("TermVocabulary") +
100
				" WHERE uuid = '" + uuidVocabulary + "'";
101
		ResultSet rs = datasource.executeQuery(sqlVocId);
102
		if (rs.next()){
103
			vocId = rs.getInt("id");
104
		}else{
105
			String message = "Vocabulary ( "+ uuidVocabulary +" ) for term does not exist!";
106
			monitor.warning(message);
107
			result.addError(message, getStepName() + ", SingleTermUpdater.invoke");
108
            return;
109
		}
110

    
111
		Integer termId;
112
		String sqlMaxId = " SELECT max(id)+1 as maxId FROM " + caseType.transformTo("DefinedTermBase");
113
		rs = datasource.executeQuery(sqlMaxId);
114
		if (rs.next()){
115
			termId = rs.getInt("maxId");
116
		}else{
117
			String message = "No defined terms do exist yet. Can't update terms!";
118
			monitor.warning(message);
119
			result.addError(message, getStepName() + ", SingleTermUpdater.invoke");
120
            return;
121
		}
122

    
123
		String id = Integer.toString(termId);
124
		String created = getNowString();
125
		String defaultColor = "null";
126
		String protectedTitleCache = getBoolean(false, datasource);
127
		String orderIndex;
128
		if (isOrdered){
129
			orderIndex = getOrderIndex(datasource, vocId, monitor, caseType);
130
		}else{
131
			orderIndex = "null";
132
		}
133
		String titleCache = label != null ? label : (abbrev != null ? abbrev : description );
134
		String idInVocStr = idInVocabulary == null ? "NULL" : "'" + idInVocabulary + "'";
135
		String sqlInsertTerm = " INSERT INTO @@DefinedTermBase@@ (DTYPE, id, uuid, created, termtype, idInVocabulary, protectedtitlecache, titleCache, orderindex, defaultcolor, vocabulary_id)" +
136
				"VALUES ('" + dtype + "', " + id + ", '" + uuidTerm + "', '" + created + "', '" + termType.getKey() + "', " + idInVocStr +  ", " + protectedTitleCache + ", '" + titleCache + "', " + orderIndex + ", " + defaultColor + ", " + vocId + ")";
137

    
138
		datasource.executeUpdate(caseType.replaceTableNames(sqlInsertTerm));
139

    
140
		updateFeatureTerms(termId, datasource, monitor, caseType);
141
		updateRelationshipTerms(termId, datasource, monitor, caseType);
142
		updateRanks(termId, datasource, monitor, caseType);
143

    
144
//
145
//		INSERT INTO DefinedTermBase (DTYPE, id, uuid, created, protectedtitlecache, titleCache, orderindex, defaultcolor, vocabulary_id)
146
//		SELECT 'ReferenceSystem' ,  (@defTermId := max(id)+1)  as maxId , '1bb67042-2814-4b09-9e76-c8c1e68aa281', '2010-06-01 10:15:00', b'0', 'Google Earth', null, null, @refSysVocId
147
//		FROM DefinedTermBase ;
148
//
149

    
150
		//language id
151
		Integer langId = getLanguageId(uuidLanguage, datasource, monitor, caseType);
152
		if (langId == null){
153
			String message = "LangId is null";
154
			result.addWarning(message);
155
		    return;
156
		}
157

    
158
		//representation
159
		int repId;
160
		sqlMaxId = " SELECT max(id)+1 as maxId FROM " + caseType.transformTo("Representation");
161
		rs = datasource.executeQuery(sqlMaxId);
162
		if (rs.next()){
163
			repId = rs.getInt("maxId");
164
		}else{
165
			String message = "No representations do exist yet. Can't update terms!";
166
			monitor.warning(message);
167
			result.addError(message, this, "invoke");
168
			return;
169
		}
170

    
171
		//standard representation
172
		UUID uuidRepresentation = UUID.randomUUID();
173
		String sqlInsertRepresentation = " INSERT INTO @@Representation@@ (id, created, uuid, text, label, abbreviatedlabel, language_id) " +
174
				"VALUES (" + repId + ", '" + created + "', '" + uuidRepresentation + "', " + nullSafeStr(description) +  ", " +nullSafeStr( label) +  ", " + nullSafeStr(abbrev) +  ", " + langId + ")";
175

    
176
		datasource.executeUpdate(caseType.replaceTableNames(sqlInsertRepresentation));
177

    
178
		String sqlInsertMN = "INSERT INTO @@DefinedTermBase_Representation@@ (DefinedTermBase_id, representations_id) " +
179
				" VALUES ("+ termId +"," +repId+ " )";
180

    
181
		datasource.executeUpdate(caseType.replaceTableNames(sqlInsertMN));
182

    
183
		//reverse representation
184
		if (hasReverseRepresentation()){
185
			int reverseRepId = repId + 1;
186
			UUID uuidReverseRepresentation = UUID.randomUUID();
187
			String sqlInsertReverseRepresentation = " INSERT INTO @@Representation@@ (id, created, uuid, text, label, abbreviatedlabel, language_id) " +
188
					"VALUES (" + reverseRepId + ", '" + created + "', '" + uuidReverseRepresentation + "', " + nullSafeStr(reverseDescription) +  ", " + nullSafeStr(reverseLabel) +  ",  " + nullSafeStr(reverseAbbrev) +  ", " + langId + ")";
189

    
190
			datasource.executeUpdate(caseType.replaceTableNames(sqlInsertReverseRepresentation));
191

    
192
			String sqlReverseInsertMN = "INSERT INTO @@RelationshipTermBase_inverseRepresentation@@ (DefinedTermBase_id, inverserepresentations_id) " +
193
					" VALUES ("+ termId +"," +reverseRepId+ " )";
194

    
195
			datasource.executeUpdate(caseType.replaceTableNames(sqlReverseInsertMN));
196
		}
197

    
198
		return;
199
	}
200

    
201
	private String nullSafeStr(String str) {
202
		if (str == null){
203
			return " NULL ";
204
		}else{
205
			return "'" + str + "'";
206
		}
207
	}
208

    
209
	private void updateFeatureTerms(Integer termId, ICdmDataSource datasource, IProgressMonitor monitor, CaseType caseType) throws SQLException {
210
		if (dtype.equals(Feature.class.getSimpleName())){
211
			String sqlUpdate = "UPDATE  " + caseType.transformTo("DefinedTermBase") +
212
				" SET " +
213
				" supportscategoricaldata = " + getBoolean(false, datasource) + ", " +
214
				" supportscommontaxonname = " + getBoolean(false, datasource) + ", " +
215
				" supportsdistribution = " + getBoolean(false, datasource) + ", " +
216
				" supportsindividualassociation = " + getBoolean(false, datasource) + ", " +
217
				" supportsquantitativedata = " + getBoolean(false, datasource) + ", " +
218
				" supportstaxoninteraction = " + getBoolean(false, datasource) + ", " +
219
				" supportstextdata = " + getBoolean(true, datasource) +  " " +
220
				" WHERE id = " + termId;
221
			datasource.executeUpdate(sqlUpdate);
222
		}
223
	}
224

    
225
	private void updateRelationshipTerms(Integer termId, ICdmDataSource datasource, IProgressMonitor monitor, CaseType caseType) throws SQLException {
226
		if (dtype.contains("Relationship")){
227
			String sqlUpdate = "UPDATE "  + caseType.transformTo("DefinedTermBase") +
228
				" SET " +
229
				" symmetrical = " + getBoolean(symmetric, datasource) + ", " +
230
				" transitive = " + getBoolean(transitive, datasource) + " " +
231
				" WHERE id = " + termId;
232
			datasource.executeUpdate(sqlUpdate);
233
		}
234
	}
235

    
236
	private void updateRanks(Integer termId, ICdmDataSource datasource, IProgressMonitor monitor, CaseType caseType) throws SQLException {
237
		if (dtype.equals(Rank.class.getSimpleName())){
238
			String sqlUpdate = "UPDATE " + caseType.transformTo("DefinedTermBase") +
239
				" SET rankClass = '" + rankClass.getKey() + "'" +
240
				" WHERE id = " + termId;
241
			datasource.executeUpdate(sqlUpdate);
242
		}
243
	}
244

    
245
	public SingleTermUpdater setRankClass(RankClass rankClass) {
246
		this.rankClass = rankClass;
247
		return this;
248
	}
249

    
250

    
251

    
252
	/**
253
	 * @param datasource
254
	 * @param vocId
255
	 * @param monitor
256
	 * @param caseType
257
	 * @return
258
	 * @throws SQLException
259
	 */
260
	private String getOrderIndex(ICdmDataSource datasource, int vocId, IProgressMonitor monitor, CaseType caseType) throws SQLException {
261
		ResultSet rs;
262
		Integer intOrderIndex = null;
263
		if (uuidAfterTerm == null){
264
			return "1";
265
		}
266
		String sqlOrderIndex = " SELECT orderindex FROM %s WHERE uuid = '%s' AND vocabulary_id = %d ";
267
		sqlOrderIndex = String.format(sqlOrderIndex, caseType.transformTo("DefinedTermBase"), uuidAfterTerm.toString(), vocId);
268
		rs = datasource.executeQuery(sqlOrderIndex);
269
		if (rs.next()){
270
			intOrderIndex = rs.getInt("orderindex") + 1;
271

    
272
			String sqlUpdateLowerTerms = "UPDATE %s SET orderindex = orderindex + 1 WHERE vocabulary_id = %d AND orderindex >= %d ";
273
			sqlUpdateLowerTerms = String.format(sqlUpdateLowerTerms, caseType.transformTo("DefinedTermBase"), vocId, intOrderIndex );
274
			datasource.executeUpdate(sqlUpdateLowerTerms);
275
		}else{
276
			String warning = "The previous term has not been found in vocabulary. Put term to the end";
277
			monitor.warning(warning);
278
		}
279
		if (intOrderIndex == null){
280
			String sqlMaxOrderIndex = " SELECT max(orderindex) FROM %s WHERE vocabulary_id = %d";
281
			sqlMaxOrderIndex = String.format(sqlMaxOrderIndex, caseType.transformTo("DefinedTermBase"), vocId);
282
			intOrderIndex = (Integer)datasource.getSingleValue(sqlMaxOrderIndex);
283
			if (intOrderIndex != null){
284
				intOrderIndex++;
285
			}else{
286
				String warning = "No term was found in vocabulary or vocabulary does not exist. Use order index '0'.";
287
				monitor.warning(warning);
288
				intOrderIndex =0;
289
			}
290
		}
291

    
292
		return intOrderIndex.toString();
293
	}
294

    
295

    
296
	private boolean hasReverseRepresentation() {
297
		return  reverseLabel != null ||  reverseDescription != null ||  reverseAbbrev != null;
298
	}
299

    
300
	public SingleTermUpdater setReverseRepresentation(String reverseDescription, String reverseLabel, String reverseAbbrev) {
301
		this.reverseLabel = reverseLabel;
302
		this.reverseDescription = reverseDescription;
303
		this.reverseAbbrev = reverseAbbrev;
304
		return this;
305
	}
306

    
307
	public SingleTermUpdater setSymmetricTransitiv(boolean symmetric, boolean transitive){
308
		this.symmetric = symmetric;
309
		this.transitive = transitive;
310
		return this;
311
	}
312

    
313
}
(25-25/35)