aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/org/onap/music/conductor/conditionals/MusicConditional.java
blob: d5e9e4d5ce0bc72da33f2851ffad2935d5af39f5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
/*
 * ============LICENSE_START==========================================
 * org.onap.music
 * ===================================================================
 *  Copyright (c) 2017 AT&T Intellectual Property
 * ===================================================================
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 * 
 * ============LICENSE_END=============================================
 * ====================================================================
 */
package org.onap.music.conductor.conditionals;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import org.codehaus.jettison.json.JSONObject;
import org.onap.music.datastore.PreparedQueryObject;
import org.onap.music.eelf.logging.EELFLoggerDelegate;
import org.onap.music.eelf.logging.format.AppMessages;
import org.onap.music.eelf.logging.format.ErrorSeverity;
import org.onap.music.eelf.logging.format.ErrorTypes;
import org.onap.music.lockingservice.MusicLockState;
import org.onap.music.main.MusicCore;
import org.onap.music.main.MusicUtil;
import org.onap.music.main.ResultType;
import org.onap.music.main.ReturnType;
import org.onap.music.rest.RestMusicDataAPI;

import com.datastax.driver.core.ColumnDefinitions;
import com.datastax.driver.core.DataType;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.TableMetadata;

public class MusicConditional {
	private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestMusicDataAPI.class);
	private static final String CRITICAL = "critical";

	public static ReturnType conditionalInsert(String keyspace, String tablename, String casscadeColumnName,
			Map<String, Object> casscadeColumnData, String primaryKey, Map<String, Object> valuesMap,
			Map<String, String> status) throws Exception {

		Map<String, PreparedQueryObject> queryBank = new HashMap<>();
		TableMetadata tableInfo = null;
		tableInfo = MusicCore.returnColumnMetadata(keyspace, tablename);
		DataType primaryIdType = tableInfo.getPrimaryKey().get(0).getType();
		String primaryId = tableInfo.getPrimaryKey().get(0).getName();
		DataType casscadeColumnType = tableInfo.getColumn(casscadeColumnName).getType();
		String vector = String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis());

		PreparedQueryObject select = new PreparedQueryObject();
		select.appendQueryString("SELECT * FROM " + keyspace + "." + tablename + " where " + primaryId + " = ?");
		select.addValue(MusicUtil.convertToActualDataType(primaryIdType, primaryKey));
		queryBank.put(MusicUtil.SELECT, select);

		PreparedQueryObject update = new PreparedQueryObject();
		Map<String, String> updateColumnvalues = new HashMap<>(); //casscade column values
		updateColumnvalues = getValues(true, casscadeColumnData, status);
		Object formatedValues = MusicUtil.convertToActualDataType(casscadeColumnType, updateColumnvalues);
		update.appendQueryString("UPDATE " + keyspace + "." + tablename + " SET " + casscadeColumnName + " ="
				+ casscadeColumnName + " + ? , vector_ts = ?" + " WHERE " + primaryId + " = ? ");
		update.addValue(formatedValues);
		update.addValue(MusicUtil.convertToActualDataType(DataType.text(), vector));
		update.addValue(MusicUtil.convertToActualDataType(primaryIdType, primaryKey));
		queryBank.put(MusicUtil.UPDATE, update);


		Map<String, String> insertColumnvalues = new HashMap<>();//casscade column values
		insertColumnvalues = getValues(false, casscadeColumnData, status);
		formatedValues = MusicUtil.convertToActualDataType(casscadeColumnType, insertColumnvalues);
		PreparedQueryObject insert = extractQuery(valuesMap, tableInfo, tablename, keyspace, primaryId, primaryKey,casscadeColumnName,formatedValues);
		queryBank.put(MusicUtil.INSERT, insert);
		
		
		String key = keyspace + "." + tablename + "." + primaryKey;
		String lockId = MusicCore.createLockReference(key);
		long leasePeriod = MusicUtil.getDefaultLockLeasePeriod();
		ReturnType lockAcqResult = MusicCore.acquireLockWithLease(key, lockId, leasePeriod);

		try {
			if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) {
				ReturnType criticalPutResult = conditionalInsertAtomic(lockId, keyspace, tablename, primaryKey,
						queryBank);
				MusicCore.destroyLockRef(lockId);
				if (criticalPutResult.getMessage().contains("insert"))
					criticalPutResult
							.setMessage("Insert values: ");
				else if (criticalPutResult.getMessage().contains("update"))
					criticalPutResult
							.setMessage("Update values: " + updateColumnvalues);
				return criticalPutResult;

			} else {
				MusicCore.destroyLockRef(lockId);
				return lockAcqResult;
			}
		} catch (Exception e) {
			logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED);
			MusicCore.destroyLockRef(lockId);
			return new ReturnType(ResultType.FAILURE, e.getMessage());
		}

	}

	public static ReturnType conditionalInsertAtomic(String lockId, String keyspace, String tableName,
			String primaryKey, Map<String, PreparedQueryObject> queryBank) {

		ResultSet results = null;

		try {

			MusicLockState mls = MusicCore.getLockingServiceHandle()
					.getLockState(keyspace + "." + tableName + "." + primaryKey);
			if (mls.getLockHolder().equals(lockId)) {
				try {
					results = MusicCore.getDSHandle().executeCriticalGet(queryBank.get(MusicUtil.SELECT));
				} catch (Exception e) {
					return new ReturnType(ResultType.FAILURE, e.getMessage());
				}
				if (results.all().isEmpty()) {
					MusicCore.getDSHandle().executePut(queryBank.get(MusicUtil.INSERT), CRITICAL);
					return new ReturnType(ResultType.SUCCESS, "insert");
				} else {
					MusicCore.getDSHandle().executePut(queryBank.get(MusicUtil.UPDATE), CRITICAL);
					return new ReturnType(ResultType.SUCCESS, "update");
				}
			} else {
				return new ReturnType(ResultType.FAILURE,
						"Cannot perform operation since you are the not the lock holder");
			}

		} catch (Exception e) {
			StringWriter sw = new StringWriter();
			e.printStackTrace(new PrintWriter(sw));
			logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
			String exceptionAsString = sw.toString();
			return new ReturnType(ResultType.FAILURE,
					"Exception thrown while doing the critical put, check sanctity of the row/conditions:\n"
							+ exceptionAsString);
		}

	}

	public static ReturnType update(Map<String,PreparedQueryObject> queryBank, String keyspace, String tableName, String primaryKey,String primaryKeyValue,String planId,String cascadeColumnName,Map<String,String> cascadeColumnValues) {

		String key = keyspace + "." + tableName + "." + primaryKeyValue;
		String lockId = MusicCore.createLockReference(key);
		long leasePeriod = MusicUtil.getDefaultLockLeasePeriod();
		ReturnType lockAcqResult = MusicCore.acquireLockWithLease(key, lockId, leasePeriod);

		try {

			if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) {
				return updateAtomic(lockId, keyspace, tableName, primaryKey,primaryKeyValue, queryBank,planId,cascadeColumnValues,cascadeColumnName);

			} else {
				MusicCore.destroyLockRef(lockId);
				return lockAcqResult;
			}

		} catch (Exception e) {
			logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
			MusicCore.destroyLockRef(lockId);
			return new ReturnType(ResultType.FAILURE, e.getMessage());

		}
	}

	public static ReturnType updateAtomic(String lockId, String keyspace, String tableName, String primaryKey,String primaryKeyValue,
			Map<String,PreparedQueryObject> queryBank,String planId,Map<String,String> cascadeColumnValues,String casscadeColumnName) {
		try {

			MusicLockState mls = MusicCore.getLockingServiceHandle()
					.getLockState(keyspace + "." + tableName + "." + primaryKeyValue);
			if (mls.getLockHolder().equals(lockId)) {
				Row row  = MusicCore.getDSHandle().executeCriticalGet(queryBank.get(MusicUtil.SELECT)).one();
				
				if(row != null) {
					Map<String, String> updatedValues = cascadeColumnUpdateSpecific(row, cascadeColumnValues, casscadeColumnName, planId);
					JSONObject json = new JSONObject(updatedValues);
					PreparedQueryObject update = new PreparedQueryObject();
					String vector_ts = String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis());
					update.appendQueryString("UPDATE " + keyspace + "." + tableName + " SET " + casscadeColumnName + "['" + planId
							+ "'] = ?, vector_ts = ? WHERE " + primaryKey + " = ?");
					update.addValue(MusicUtil.convertToActualDataType(DataType.text(), json.toString()));
					update.addValue(MusicUtil.convertToActualDataType(DataType.text(), vector_ts));
					update.addValue(MusicUtil.convertToActualDataType(DataType.text(), primaryKeyValue));
					try {
						MusicCore.getDSHandle().executePut(update, CRITICAL);
					} catch (Exception ex) {
						return new ReturnType(ResultType.FAILURE, ex.getMessage());
					}
				}else {
					return new ReturnType(ResultType.FAILURE,"Cannot find data related to key: "+primaryKey);
				}
				MusicCore.getDSHandle().executePut(queryBank.get(MusicUtil.UPSERT), CRITICAL);
				return new ReturnType(ResultType.SUCCESS, "update success");

			} else {
				return new ReturnType(ResultType.FAILURE,
						"Cannot perform operation since you are the not the lock holder");
			}

		} catch (Exception e) {
			logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
			StringWriter sw = new StringWriter();
			e.printStackTrace(new PrintWriter(sw));
			String exceptionAsString = sw.toString();
			return new ReturnType(ResultType.FAILURE,
					"Exception thrown while doing the critical put, check sanctity of the row/conditions:\n"
							+ exceptionAsString);
		}

	}

	@SuppressWarnings("unchecked")
	public static Map<String, String> getValues(boolean isExists, Map<String, Object> casscadeColumnData,
			Map<String, String> status) {

		Map<String, String> value = new HashMap<>();
		Map<String, String> returnMap = new HashMap<>();
		Object key = casscadeColumnData.get("key");
		String setStatus = "";
		value = (Map<String, String>) casscadeColumnData.get("value");

		if (isExists)
			setStatus = status.get("exists");
		else
			setStatus = status.get("nonexists");

		value.put("status", setStatus);
		JSONObject valueJson = new JSONObject(value);
		returnMap.put(key.toString(), valueJson.toString());
		return returnMap;

	}
	
	public static PreparedQueryObject extractQuery(Map<String, Object> valuesMap, TableMetadata tableInfo, String tableName,
			String keySpaceName,String primaryKeyName,String primaryKey,String casscadeColumn,Object casscadeColumnValues) throws Exception {

		PreparedQueryObject queryObject = new PreparedQueryObject();
		StringBuilder fieldsString = new StringBuilder("(vector_ts"+",");
		StringBuilder valueString = new StringBuilder("(" + "?" + ",");
		String vector = String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis());
		queryObject.addValue(vector);
		if(casscadeColumn!=null && casscadeColumnValues!=null) {
			fieldsString.append("" +casscadeColumn+" ," );
		  valueString.append("?,");
		  queryObject.addValue(casscadeColumnValues);
		}
		
		int counter = 0;
		for (Map.Entry<String, Object> entry : valuesMap.entrySet()) {
            
			fieldsString.append("" + entry.getKey());
            Object valueObj = entry.getValue();
            if (primaryKeyName.equals(entry.getKey())) {
                primaryKey = entry.getValue() + "";
                primaryKey = primaryKey.replace("'", "''");
            }
            DataType colType = null;
            try {
                colType = tableInfo.getColumn(entry.getKey()).getType();
            } catch(NullPointerException ex) {
                logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage() +" Invalid column name : "+entry.getKey(), AppMessages.INCORRECTDATA  ,ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
               
            }

            Object formattedValue = null;
            try {
              formattedValue = MusicUtil.convertToActualDataType(colType, valueObj);
            } catch (Exception e) {
              logger.error(EELFLoggerDelegate.errorLogger,e.getMessage());
          }
            
			valueString.append("?");
            queryObject.addValue(formattedValue);

            
			if (counter == valuesMap.size() - 1) {
                fieldsString.append(")");
                valueString.append(")");
            } else {
                fieldsString.append(",");
                valueString.append(",");
            }
            counter = counter + 1;
        }
        queryObject.appendQueryString("INSERT INTO " + keySpaceName + "." + tableName + " "
                + fieldsString + " VALUES " + valueString);
		return queryObject;
	}
	
	public static Object getColValue(Row row, String colName, DataType colType) {
		switch (colType.getName()) {
		case VARCHAR:
			return row.getString(colName);
		case UUID:
			return row.getUUID(colName);
		case VARINT:
			return row.getVarint(colName);
		case BIGINT:
			return row.getLong(colName);
		case INT:
			return row.getInt(colName);
		case FLOAT:
			return row.getFloat(colName);
		case DOUBLE:
			return row.getDouble(colName);
		case BOOLEAN:
			return row.getBool(colName);
		case MAP:
			return row.getMap(colName, String.class, String.class);
		default:
			return null;
		}
	}
	
	@SuppressWarnings("unchecked")
	public static Map<String, String> cascadeColumnUpdateSpecific(Row row, Map<String, String> changeOfStatus,
			String cascadeColumnName, String planId) {

		ColumnDefinitions colInfo = row.getColumnDefinitions();
		DataType colType = colInfo.getType(cascadeColumnName);
		Map<String, String> values = new HashMap<>();
		Object columnValue = getColValue(row, cascadeColumnName, colType);

		Map<String, String> finalValues = new HashMap<>();
		values = (Map<String, String>) columnValue;
		if (values != null && values.keySet().contains(planId)) {
			String valueString = values.get(planId);
			String tempValueString = valueString.replaceAll("\\{", "").replaceAll("\"", "").replaceAll("\\}", "");
			String[] elements = tempValueString.split(",");
			for (String str : elements) {
				String[] keyValue = str.split(":");
				if ((changeOfStatus.keySet().contains(keyValue[0].replaceAll("\\s", ""))))
				keyValue[1] = changeOfStatus.get(keyValue[0].replaceAll("\\s", ""));
				finalValues.put(keyValue[0], keyValue[1]);
			}
		}
		return finalValues;

	}

}