Project

General

Profile

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

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

    
16
import org.apache.log4j.Logger;
17

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

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

    
35
	/**
36
	 * @Deprecated use {@link #NewInstance(String, TermType, UUID, String, String, String, String, UUID, UUID, boolean, UUID)} instead
37
	 */
38
	@Deprecated
39
	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){
40
		return new SingleTermUpdater(stepName, null, uuidTerm, null, description, label, abbrev, dtype, uuidVocabulary, uuidLanguage, isOrdered, uuidAfterTerm);
41
	}
42

    
43
	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){
44
		return new SingleTermUpdater(stepName, termType, uuidTerm, idInVocabulary, description, label, abbrev, dtype, uuidVocabulary, uuidLanguage, isOrdered, uuidAfterTerm);
45
	}
46

    
47

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

    
66

    
67

    
68
	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) {
69
		super(stepName);
70
		this.termType = termType;
71
		this.idInVocabulary = idInVocabulary;
72
		this.abbrev = abbrev;
73
		this.description = description;
74
		this.dtype = dtype;
75
		this.label = label;
76
		this.isOrdered = isOrdered;
77
		this.uuidTerm = uuidTerm;
78
		this.uuidVocabulary = uuidVocabulary;
79
		this.uuidAfterTerm = uuidAfterTerm;
80
		this.uuidLanguage = uuidLanguage;
81
	}
82

    
83
	@Override
84
	public Integer invoke(ICdmDataSource datasource, IProgressMonitor monitor, CaseType caseType) 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
			monitor.warning("Term already exists: " + label + "(" + uuidTerm + ")");
91
			return -1;
92
		}
93

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

    
108
		Integer termId;
109
		String sqlMaxId = " SELECT max(id)+1 as maxId FROM " + caseType.transformTo("DefinedTermBase");
110
		rs = datasource.executeQuery(sqlMaxId);
111
		if (rs.next()){
112
			termId = rs.getInt("maxId");
113
		}else{
114
			String warning = "No defined terms do exist yet. Can't update terms!";
115
			monitor.warning(warning);
116
			return null;
117
		}
118

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

    
134
		datasource.executeUpdate(caseType.replaceTableNames(sqlInsertTerm));
135

    
136
		updateFeatureTerms(termId, datasource, monitor, caseType);
137
		updateRelationshipTerms(termId, datasource, monitor, caseType);
138
		updateRanks(termId, datasource, monitor, caseType);
139

    
140
//
141
//		INSERT INTO DefinedTermBase (DTYPE, id, uuid, created, protectedtitlecache, titleCache, orderindex, defaultcolor, vocabulary_id)
142
//		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
143
//		FROM DefinedTermBase ;
144
//
145

    
146
		//language id
147
		Integer langId = getLanguageId(uuidLanguage, datasource, monitor, caseType);
148
		if (langId == null){
149
			return null;
150
		}
151

    
152
		//representation
153
		int repId;
154
		sqlMaxId = " SELECT max(id)+1 as maxId FROM " + caseType.transformTo("Representation");
155
		rs = datasource.executeQuery(sqlMaxId);
156
		if (rs.next()){
157
			repId = rs.getInt("maxId");
158
		}else{
159
			String warning = "No representations do exist yet. Can't update terms!";
160
			monitor.warning(warning);
161
			return null;
162
		}
163

    
164
		//standard representation
165
		UUID uuidRepresentation = UUID.randomUUID();
166
		String sqlInsertRepresentation = " INSERT INTO @@Representation@@ (id, created, uuid, text, label, abbreviatedlabel, language_id) " +
167
				"VALUES (" + repId + ", '" + created + "', '" + uuidRepresentation + "', " + nullSafeStr(description) +  ", " +nullSafeStr( label) +  ", " + nullSafeStr(abbrev) +  ", " + langId + ")";
168

    
169
		datasource.executeUpdate(caseType.replaceTableNames(sqlInsertRepresentation));
170

    
171
		String sqlInsertMN = "INSERT INTO @@DefinedTermBase_Representation@@ (DefinedTermBase_id, representations_id) " +
172
				" VALUES ("+ termId +"," +repId+ " )";
173

    
174
		datasource.executeUpdate(caseType.replaceTableNames(sqlInsertMN));
175

    
176
		//reverse representation
177
		if (hasReverseRepresentation()){
178
			int reverseRepId = repId + 1;
179
			UUID uuidReverseRepresentation = UUID.randomUUID();
180
			String sqlInsertReverseRepresentation = " INSERT INTO @@Representation@@ (id, created, uuid, text, label, abbreviatedlabel, language_id) " +
181
					"VALUES (" + reverseRepId + ", '" + created + "', '" + uuidReverseRepresentation + "', " + nullSafeStr(reverseDescription) +  ", " + nullSafeStr(reverseLabel) +  ",  " + nullSafeStr(reverseAbbrev) +  ", " + langId + ")";
182

    
183
			datasource.executeUpdate(caseType.replaceTableNames(sqlInsertReverseRepresentation));
184

    
185
			String sqlReverseInsertMN = "INSERT INTO @@RelationshipTermBase_inverseRepresentation@@ (DefinedTermBase_id, inverserepresentations_id) " +
186
					" VALUES ("+ termId +"," +reverseRepId+ " )";
187

    
188
			datasource.executeUpdate(caseType.replaceTableNames(sqlReverseInsertMN));
189
		}
190

    
191
		return termId;
192
	}
193

    
194
	private String nullSafeStr(String str) {
195
		if (str == null){
196
			return " NULL ";
197
		}else{
198
			return "'" + str + "'";
199
		}
200
	}
201

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

    
218
	private void updateRelationshipTerms(Integer termId, ICdmDataSource datasource, IProgressMonitor monitor, CaseType caseType) throws SQLException {
219
		if (dtype.contains("Relationship")){
220
			String sqlUpdate = "UPDATE "  + caseType.transformTo("DefinedTermBase") +
221
				" SET " +
222
				" symmetrical = " + getBoolean(symmetric, datasource) + ", " +
223
				" transitive = " + getBoolean(transitive, datasource) + " " +
224
				" WHERE id = " + termId;
225
			datasource.executeUpdate(sqlUpdate);
226
		}
227
	}
228

    
229
	private void updateRanks(Integer termId, ICdmDataSource datasource, IProgressMonitor monitor, CaseType caseType) throws SQLException {
230
		if (dtype.equals(Rank.class.getSimpleName())){
231
			String sqlUpdate = "UPDATE " + caseType.transformTo("DefinedTermBase") +
232
				" SET rankClass = '" + rankClass.getKey() + "'" +
233
				" WHERE id = " + termId;
234
			datasource.executeUpdate(sqlUpdate);
235
		}
236
	}
237

    
238
	public SingleTermUpdater setRankClass(RankClass rankClass) {
239
		this.rankClass = rankClass;
240
		return this;
241
	}
242

    
243

    
244

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

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

    
285
		return intOrderIndex.toString();
286
	}
287

    
288

    
289
	private boolean hasReverseRepresentation() {
290
		return  reverseLabel != null ||  reverseDescription != null ||  reverseAbbrev != null;
291
	}
292

    
293
	public SingleTermUpdater setReverseRepresentation(String reverseDescription, String reverseLabel, String reverseAbbrev) {
294
		this.reverseLabel = reverseLabel;
295
		this.reverseDescription = reverseDescription;
296
		this.reverseAbbrev = reverseAbbrev;
297
		return this;
298
	}
299

    
300
	public SingleTermUpdater setSymmetricTransitiv(boolean symmetric, boolean transitive){
301
		this.symmetric = symmetric;
302
		this.transitive = transitive;
303
		return this;
304
	}
305

    
306
}
(23-23/34)