aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/org/onap/music/prom/musicinterface/MusicHandle.java
blob: cc7a875fd91e0b09769984fa8409115433a7744b (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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
/*
 * ============LICENSE_START==========================================
 * org.onap.music.prom
 * ===================================================================
 *  Copyright (c) 2018 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.prom.musicinterface;
import java.net.ConnectException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.ws.rs.core.MediaType;

import org.onap.music.prom.eelf.logging.EELFLoggerDelegate;
import org.onap.music.prom.main.ConfigReader;
import org.onap.music.prom.main.PromUtil;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.WebResource.Builder;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;
import java.util.Base64;

public class MusicHandle {
	private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicHandle.class);


	/**
	 * Adds MUSIC's authentication headers into the webresource
	 * @param webResource
	 */
	private static Builder addMusicHeaders(WebResource webResource) {
		String aid = PromUtil.getAid();
		String namespace = PromUtil.getAppNamespace();
		String userId = PromUtil.getUserId();
		String password = PromUtil.getPassword();
		Builder builder = webResource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON);
		if (!aid.equals("")) {
			builder.header("aid", aid);
		}
		if (!namespace.equals("")) {
			builder.header("ns", namespace);
		}
		if (!userId.equals("") && !password.equals("")) {
			String authString = Base64.getEncoder().encodeToString((userId + ":" + password).getBytes());
			builder.header("Authorization", "Basic " + authString);
		}
		return builder;
	}
	
	private static WebResource createMusicWebResource(String musicAPIurl) {
		ClientConfig clientConfig = new DefaultClientConfig();

		clientConfig.getFeatures().put(
				JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
		int timeout = getMaxConnectionTimeout();
		clientConfig.getProperties().put(ClientConfig.PROPERTY_CONNECT_TIMEOUT, timeout);
		clientConfig.getProperties().put(ClientConfig.PROPERTY_READ_TIMEOUT, timeout);

		Client client = Client.create(clientConfig);
		return client.resource(musicAPIurl);
	}
	
	public static void createKeyspaceEventual(String keyspaceName){
		logger.info(EELFLoggerDelegate.applicationLogger, "createKeyspaceEventual "+keyspaceName);
		
		ArrayList<String> musicUrls = PromUtil.getMusicNodeURL();
		for (String musicUrl: musicUrls) {
			try {
				createKeyspaceEventual(musicUrl, keyspaceName);
				return;
			} catch (ClientHandlerException che) {
				logger.warn(EELFLoggerDelegate.applicationLogger, "Timed out connection to MUSIC. Consider setting"
						+ " 'music-connection-timeout-ms' in the configuration");
			} catch (RuntimeException e) {
				logger.warn(EELFLoggerDelegate.applicationLogger, e.getMessage());
			}
			logger.warn(EELFLoggerDelegate.applicationLogger, "Could not reach music at '" + musicUrl +"'");
		}
		logger.error(EELFLoggerDelegate.errorLogger, "Unable to create keyspace."
							+ "Could not successfully reach any music instance to create keyspace.");
		return;
	}
	
	private static void createKeyspaceEventual(String musicUrl, String keyspaceName){
		Map<String,Object> replicationInfo = new HashMap<String, Object>();
		replicationInfo.put("class", "SimpleStrategy");
		replicationInfo.put("replication_factor", 3);
		String durabilityOfWrites="true";
		Map<String,String> consistencyInfo= new HashMap<String, String>();
		consistencyInfo.put("type", "eventual");
		JsonKeySpace jsonKp = new JsonKeySpace();
		jsonKp.setConsistencyInfo(consistencyInfo);
		jsonKp.setDurabilityOfWrites(durabilityOfWrites);
		jsonKp.setReplicationInfo(replicationInfo);

		WebResource webResource = createMusicWebResource(musicUrl+"/keyspaces/"+keyspaceName);

		Builder b = addMusicHeaders(webResource);
		logger.error("music handle create keyspace eventual: " + b);
		ClientResponse response = addMusicHeaders(webResource)
									.post(ClientResponse.class, jsonKp);
		
		Map<String,Object> output = response.getEntity(Map.class);
		if (!output.containsKey("status") || !output.get("status").equals("SUCCESS")) {
			if (output.containsKey("error")) {
				String errorMsg = String.valueOf(output.get("error"));
				if (errorMsg.equals("err:Keyspace prom_sdnc already exists")) {
					logger.warn(EELFLoggerDelegate.applicationLogger, 
							"Not creating keyspace " + keyspaceName + " because it already exists. Continuing.");
					//assume keyspace is already created and continue
				}
				else { //unhandled/unknown exception
					logger.error(EELFLoggerDelegate.errorLogger,
							"Failed to createKeySpaceEventual : Status Code "+ output.toString());
					throw new RuntimeException("Failed: MUSIC Response " + output.toString());
				}
			} else { //no exception message
				logger.error(EELFLoggerDelegate.errorLogger,
						"Failed to createKeySpaceEventual : Status Code "+ output.toString());
				throw new RuntimeException("Failed: MUSIC Response " + output.toString());
			}
		}
	}

	public static void createTableEventual(String keyspaceName, String tableName, Map<String,String> fields) {
		logger.info(EELFLoggerDelegate.applicationLogger,
				"createKeyspaceEventual "+keyspaceName+" tableName "+tableName);
		
		ArrayList<String> musicUrls = PromUtil.getMusicNodeURL();
		for (String musicUrl: musicUrls) {
			try {
				createTableEventual(musicUrl, keyspaceName, tableName, fields);
				return;
			} catch (ClientHandlerException che) {
				logger.warn(EELFLoggerDelegate.applicationLogger, "Timed out connection to MUSIC. Consider setting"
						+ " 'music-connection-timeout-ms' in the configuration");
			} catch (RuntimeException e) {
				logger.warn(EELFLoggerDelegate.applicationLogger, e.getMessage());
			}
			logger.warn(EELFLoggerDelegate.applicationLogger, "Could not reach music at '" + musicUrl +"'");

		}
		logger.error(EELFLoggerDelegate.errorLogger, "Unable to create table. "
						+ "Could not successfully reach any music instance.");
		return;
	}
	
	private static void createTableEventual(String musicUrl, String keyspaceName,
										String tableName, Map<String,String> fields) {
		Map<String,String> consistencyInfo= new HashMap<String, String>();
		consistencyInfo.put("type", "eventual");

		JsonTable jtab = new JsonTable();
		jtab.setFields(fields);
		jtab.setConsistencyInfo(consistencyInfo);

		WebResource webResource = createMusicWebResource(musicUrl+"/keyspaces/"+keyspaceName+"/tables/"+tableName);

		ClientResponse response = addMusicHeaders(webResource).post(ClientResponse.class, jtab);

		Map<String,Object> output = response.getEntity(Map.class);
		if (!output.containsKey("status") || !output.get("status").equals("SUCCESS")) {
			if (output.containsKey("error")) {
				String error = String.valueOf(output.get("error"));
				if (error.equalsIgnoreCase("Table " + keyspaceName + "." + tableName + " already exists")) {
					logger.warn(EELFLoggerDelegate.applicationLogger, 
							"Not creating table " + tableName + " because it already exists. Continuing.");
				} else { //unhandled exception message
					logger.error(EELFLoggerDelegate.errorLogger,
							"Failed to createTableEventual : Status Code "+ output.toString());
					throw new RuntimeException("Failed: MUSIC Response " + output.toString());
				}
			} else { //no exception message, MUSIC should give more info if failure
				logger.error(EELFLoggerDelegate.errorLogger, 
						"Failed to createTableEventual : Status Code "+ output.toString());
				throw new RuntimeException("Failed: MUSIC Response " + output.toString());
			}
		}
	}

	public static void createIndexInTable(String keyspaceName, String tableName, String colName) {
		logger.info(EELFLoggerDelegate.applicationLogger,
				"createIndexInTable "+keyspaceName+" tableName "+tableName + " colName" + colName);
		
		ArrayList<String> musicUrls = PromUtil.getMusicNodeURL();
		for (String musicUrl: musicUrls) {
			try {
				createIndexInTable(musicUrl, keyspaceName, tableName, colName);
				return;
			} catch (ClientHandlerException che) {
				logger.warn(EELFLoggerDelegate.applicationLogger, "Timed out connection to MUSIC. Consider setting"
						+ " 'music-connection-timeout-ms' in the configuration");
			} catch (RuntimeException e) {
				logger.warn(EELFLoggerDelegate.applicationLogger, e.getMessage());
			}
			logger.warn(EELFLoggerDelegate.applicationLogger, "Could not reach music at '" + musicUrl +"'");
		}
		logger.error(EELFLoggerDelegate.errorLogger, "Unable to create index in table. "
									+ "Could not successfully reach any music instance.");
		return;
	}
	
	private static void createIndexInTable(String musicUrl, String keyspaceName, String tableName, String colName) {
		WebResource webResource = createMusicWebResource(musicUrl +
							"/keyspaces/"+keyspaceName+"/tables/"+tableName+"/index/"+colName);

		ClientResponse response = addMusicHeaders(webResource).post(ClientResponse.class);

		if (response.getStatus() != 200 && response.getStatus() != 204) {
			logger.error(EELFLoggerDelegate.errorLogger,
					"Failed to createIndexInTable : Status Code " + response.getStatus());
			throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
		}

	}

	public static void insertIntoTableEventual(String keyspaceName, String tableName, Map<String,Object> values) {
		logger.info(EELFLoggerDelegate.applicationLogger,
				"insertIntoTableEventual "+keyspaceName+" tableName "+tableName);
		
		ArrayList<String> musicUrls = PromUtil.getMusicNodeURL();
		for (String musicUrl: musicUrls) {
			try {
				insertIntoTableEventual(musicUrl, keyspaceName, tableName, values);
				return;
			} catch (ClientHandlerException che) {
				logger.warn(EELFLoggerDelegate.applicationLogger, "Timed out connection to MUSIC. Consider setting"
						+ " 'music-connection-timeout-ms' in the configuration");
			} catch (RuntimeException e) {
				logger.warn(EELFLoggerDelegate.applicationLogger, e.getMessage());
			}
			logger.warn(EELFLoggerDelegate.applicationLogger, "Could not reach music at '" + musicUrl +"'");
		}
		logger.error(EELFLoggerDelegate.errorLogger, "Unable to insert into table."
								+ " Could not successfully reach any music instance.");
		return;
	}
	
	private static void insertIntoTableEventual(String musicUrl, String keyspaceName,
											String tableName, Map<String,Object> values) {
		Map<String,String> consistencyInfo= new HashMap<String, String>();
		consistencyInfo.put("type", "eventual");

		JsonInsert jIns = new JsonInsert();
		jIns.setValues(values);
		jIns.setConsistencyInfo(consistencyInfo);

		WebResource webResource = createMusicWebResource(musicUrl+"/keyspaces/"+keyspaceName+"/tables/"+tableName+"/rows");

		ClientResponse response = addMusicHeaders(webResource).post(ClientResponse.class, jIns);

		if (response.getStatus() < 200 || response.getStatus() > 299) {
			logger.error(EELFLoggerDelegate.errorLogger,
					"Failed to insertIntoTableEventual : Status Code " + response.getStatus());
			throw new RuntimeException("Failed : HTTP error code : "+ response.getStatus());
		}

		Map<String,Object> output = response.getEntity(Map.class);
		if (!output.containsKey("status") || !output.get("status").equals("SUCCESS")) {
			logger.error(EELFLoggerDelegate.errorLogger, "Failed to createKeySpaceEventual : Status Code "+ output.toString());
			throw new RuntimeException("Failed: MUSIC Response " + output.toString());
		}
	}

	public static void updateTableEventual(String keyspaceName, String tableName, String keyName,
													String keyValue, Map<String,Object> values) {
		logger.info(EELFLoggerDelegate.applicationLogger, "updateTableEventual "+keyspaceName+" tableName "+tableName);
		
		ArrayList<String> musicUrls = PromUtil.getMusicNodeURL();
		for (String musicUrl: musicUrls) {
			try {
				updateTableEventual(musicUrl, keyspaceName, tableName, keyName, keyValue, values);
				return;
			} catch (ClientHandlerException che) {
				logger.warn(EELFLoggerDelegate.applicationLogger, "Timed out connection to MUSIC. Consider setting"
						+ " 'music-connection-timeout-ms' in the configuration");
			} catch (RuntimeException e) {
				logger.warn(EELFLoggerDelegate.applicationLogger, e.getMessage());
			}
			logger.warn(EELFLoggerDelegate.applicationLogger, "Could not reach music at '" + musicUrl +"'");
		}
		logger.error(EELFLoggerDelegate.errorLogger, "Unable to update the table. "
									+ "Could not successfully reach any music instance.");
	}

	
	private static void updateTableEventual(String musicUrl, String keyspaceName, String tableName,
									String keyName, String keyValue, Map<String,Object> values) {		
		Map<String,String> consistencyInfo= new HashMap<String, String>();
		consistencyInfo.put("type", "eventual");

		JsonInsert jIns = new JsonInsert();
		jIns.setValues(values);
		jIns.setConsistencyInfo(consistencyInfo);
		
		WebResource webResource = createMusicWebResource(musicUrl+"/keyspaces/"+keyspaceName
								+"/tables/"+tableName+"/rows?"+keyName+"="+keyValue);

		ClientResponse response = addMusicHeaders(webResource).put(ClientResponse.class, jIns);

		if (response.getStatus() < 200 || response.getStatus() > 299) {
			logger.error(EELFLoggerDelegate.errorLogger,
					"Failed to updateTableEventual : Status Code "+response.getStatus());
			throw new RuntimeException("Failed : HTTP error code : "+ response.getStatus());
		}

		Map<String,Object> output = response.getEntity(Map.class);
		if (!output.containsKey("status") || !output.get("status").equals("SUCCESS")) {
			logger.error(EELFLoggerDelegate.errorLogger, "Failed to createKeySpaceEventual : Status Code "+ output.toString());
			throw new RuntimeException("Failed: MUSIC Response " + output.toString());
		}
	}

	public static Map<String,Object> readSpecificRow(String keyspaceName, String tableName,
			String keyName, String keyValue) {
		ArrayList<String> musicUrls = PromUtil.getMusicNodeURL();
		Map<String, Object> result;
		for (String musicUrl: musicUrls) {
			try {
				result = readSpecificRow(musicUrl, keyspaceName, tableName, keyName, keyValue);
				return result;
			} catch (ClientHandlerException che) {
				logger.warn(EELFLoggerDelegate.applicationLogger, "Timed out connection to MUSIC. Consider setting"
						+ " 'music-connection-timeout-ms' in the configuration");
			} catch (RuntimeException e) {
				logger.warn(EELFLoggerDelegate.applicationLogger, e.getMessage());
			}
			logger.warn(EELFLoggerDelegate.applicationLogger, "Could not reach music at '" + musicUrl +"'");
		}
		logger.error(EELFLoggerDelegate.errorLogger, "Unable to read row. "
							+ "Could not successfully reach any music instance.");
		result = null;
		return result;
	}
	
	private static Map<String,Object> readSpecificRow(String musicUrl, String keyspaceName, String tableName,
												String keyName, String keyValue) {
		logger.info(EELFLoggerDelegate.applicationLogger,
				"readSpecificRow "+keyspaceName+" tableName "+tableName + " key" +keyName + " value" + keyValue);

		WebResource webResource = createMusicWebResource(musicUrl+"/keyspaces/"+keyspaceName
											+"/tables/"+tableName+"/rows?"+keyName+"="+keyValue);

		ClientResponse response = addMusicHeaders(webResource).get(ClientResponse.class);

		if (response.getStatus() < 200 || response.getStatus() > 299) {
			logger.error(EELFLoggerDelegate.errorLogger,
					"Failed to insertIntoTableEventual : Status Code "+response.getStatus());
			throw new RuntimeException("Failed : HTTP error code : "+ response.getStatus());
		}

		Map<String,Object> output = response.getEntity(Map.class);

		Map<String, Object> rowMap = (Map<String, Object>) output.getOrDefault("result", null);

		return rowMap;	
	}

	public static Map<String,Object> readAllRows(String keyspaceName, String tableName) {
		ArrayList<String> musicUrls = PromUtil.getMusicNodeURL();
		Map<String, Object> result;
		for (String musicUrl: musicUrls) {
			try {
				result = readAllRows(musicUrl, keyspaceName, tableName);
				return result;
			} catch (ClientHandlerException che) {
				logger.warn(EELFLoggerDelegate.applicationLogger, "Timed out connection to MUSIC. Consider setting"
						+ " 'music-connection-timeout-ms' in the configuration");
			} catch (RuntimeException e) {
				logger.warn(EELFLoggerDelegate.applicationLogger, e.getMessage());
			}
			logger.warn(EELFLoggerDelegate.applicationLogger, "Could not reach music at '" + musicUrl +"'");
		}
		logger.error(EELFLoggerDelegate.errorLogger, "Unable to read all rows. "
								+ "Could not successfully reach any music instance.");
		result = null;
		return result;
	}
	
	private static Map<String,Object> readAllRows(String musicUrl, String keyspaceName, String tableName) {
		logger.info(EELFLoggerDelegate.applicationLogger, "readAllRows "+keyspaceName+" tableName "+tableName);

		WebResource webResource = createMusicWebResource(musicUrl+"/keyspaces/"+keyspaceName+"/tables/"+tableName+"/rows");

		ClientResponse response = addMusicHeaders(webResource).get(ClientResponse.class);

		if (response.getStatus() < 200 || response.getStatus() > 299) {
			logger.error(EELFLoggerDelegate.errorLogger, "Failed to readAllRows : Status Code "+response.getStatus());
			throw new RuntimeException("Failed : HTTP error code : "+ response.getStatus());
		}

		Map<String,Object> output = response.getEntity(Map.class);
		return output;	
	}

	public static void dropTable(String keyspaceName, String tableName) {
		logger.info(EELFLoggerDelegate.applicationLogger, "dropTable "+keyspaceName+" tableName "+tableName);
		
		ArrayList<String> musicUrls = PromUtil.getMusicNodeURL();
		for (String musicUrl: musicUrls) {
			try {
				dropTable(musicUrl, keyspaceName, tableName);
				return;
			}  catch (ClientHandlerException che) {
				logger.warn(EELFLoggerDelegate.applicationLogger, "Timed out connection to MUSIC. Consider setting"
						+ " 'music-connection-timeout-ms' in the configuration");
			} catch (RuntimeException e) {
				logger.warn(EELFLoggerDelegate.applicationLogger, e.getMessage());
			}
			logger.warn(EELFLoggerDelegate.applicationLogger, "Could not reach music at '" + musicUrl +"'");
		}
		logger.error(EELFLoggerDelegate.errorLogger, "Unable to drop table."
							+ " Could not successfully reach any music instance.");
		return;
	}
	
	private static void dropTable(String musicUrl, String keyspaceName, String tableName) {
		Map<String,String> consistencyInfo= new HashMap<String, String>();
		consistencyInfo.put("type", "eventual");

		JsonTable jsonTb = new JsonTable();
		jsonTb.setConsistencyInfo(consistencyInfo);

		WebResource webResource = createMusicWebResource(musicUrl+"/keyspaces/"+keyspaceName+"/tables/"+tableName);
	
		ClientResponse response = addMusicHeaders(webResource).delete(ClientResponse.class, jsonTb);

		if (response.getStatus() < 200 || response.getStatus() > 299) {
			logger.error(EELFLoggerDelegate.errorLogger, "Failed to dropTable : Status Code "+response.getStatus());
			throw new RuntimeException("Failed : HTTP error code : "+ response.getStatus());
		}
	}

	public static void dropKeySpace(String keyspaceName) {
		logger.info(EELFLoggerDelegate.applicationLogger, "dropKeySpace "+keyspaceName);
		
		ArrayList<String> musicUrls = PromUtil.getMusicNodeURL();
		for (String musicUrl: musicUrls) {
			try {
				dropKeySpace(musicUrl, keyspaceName);
				return;
			} catch (ClientHandlerException che) {
				logger.warn(EELFLoggerDelegate.applicationLogger, "Timed out connection to MUSIC. Consider setting"
						+ " 'music-connection-timeout-ms' in the configuration");
			} catch (RuntimeException e) {
				logger.warn(EELFLoggerDelegate.applicationLogger, e.getMessage());
			}
			logger.warn(EELFLoggerDelegate.applicationLogger, "Could not reach music at '" + musicUrl +"'");
		}
		logger.error(EELFLoggerDelegate.errorLogger, "Unable to drop keyspace."
							+ " Could not successfully reach any music instance.");
		return;
	}
	
	private static void dropKeySpace(String musicUrl, String keyspaceName) {		
		Map<String,String> consistencyInfo= new HashMap<String, String>();
		consistencyInfo.put("type", "eventual");

		JsonKeySpace jsonKp = new JsonKeySpace();
		jsonKp.setConsistencyInfo(consistencyInfo);

		WebResource webResource = createMusicWebResource(musicUrl+"/keyspaces/"+keyspaceName);

		ClientResponse response = addMusicHeaders(webResource).delete(ClientResponse.class, jsonKp);

		if (response.getStatus() < 200 || response.getStatus() > 299) {
			logger.error(EELFLoggerDelegate.errorLogger, "Failed to dropTable : Status Code "+response.getStatus());
			throw new RuntimeException("Failed : HTTP error code : "+ response.getStatus());
		}
	}

	public static String createLockRef(String lockName) {
		logger.info(EELFLoggerDelegate.applicationLogger, "createLockRef "+lockName);
		
		ArrayList<String> musicUrls = PromUtil.getMusicNodeURL();
		String result;
		for (String musicUrl: musicUrls) {
			try {
				result = createLockRef(musicUrl, lockName);
				return result;
			} catch (ClientHandlerException che) {
				logger.warn(EELFLoggerDelegate.applicationLogger, "Timed out connection to MUSIC. Consider setting"
						+ " 'music-connection-timeout-ms' in the configuration");
			} catch (RuntimeException e) {
				logger.warn(EELFLoggerDelegate.applicationLogger, e.getMessage());
			}
			logger.warn(EELFLoggerDelegate.applicationLogger, "Could not reach music at '" + musicUrl +"'");
		}
		logger.error(EELFLoggerDelegate.errorLogger, "Unable to create lock reference. "
											+ "Could not successfully reach any music instance.");
		result = "";
		return result;
	}
	
	private static String createLockRef(String musicUrl, String lockName) {
		WebResource webResource = createMusicWebResource(musicUrl+"/locks/create/"+lockName);
		
		ClientResponse response = addMusicHeaders(webResource).post(ClientResponse.class);

		if (response.getStatus() != 200 ) {
			logger.error(EELFLoggerDelegate.errorLogger,
					"Failed to createLockRef : Status Code "+response.getStatus());
			throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
		}

		Map<String,Object> responseMap = response.getEntity(Map.class);
		if (!responseMap.containsKey("status") || !responseMap.get("status").equals("SUCCESS") ||
				!responseMap.containsKey("lock")) {
			logger.error(EELFLoggerDelegate.errorLogger, 
					"Failed to createLockRef : Status Code "+ responseMap.toString());
			return "";
		}
		String lockRef = ((Map<String, String>) responseMap.get("lock")).get("lock");
		logger.info(EELFLoggerDelegate.applicationLogger, "This site's lockReference is "+lockRef);
		return lockRef;
	}

	/**
	 * Try to acquire the lock lockid.
	 * If cannot reach any music instance, return status:FAILURE
	 * @param lockId
	 * @return
	 */
	public static Map<String,Object> acquireLock(String lockId) {
		logger.info(EELFLoggerDelegate.applicationLogger, "acquireLock "+lockId);
		
		ArrayList<String> musicUrls = PromUtil.getMusicNodeURL();
		Map<String, Object> result;

		for (String musicUrl: musicUrls) {
			try {
				result = acquireLock(musicUrl, lockId);
				return result;
			} catch (ClientHandlerException che) {
				logger.warn(EELFLoggerDelegate.applicationLogger, "Timed out connection to MUSIC. Consider setting"
						+ " 'music-connection-timeout-ms' in the configuration");
			} catch (RuntimeException e) {
				logger.warn(EELFLoggerDelegate.applicationLogger, e.getMessage());
			}
			logger.warn(EELFLoggerDelegate.applicationLogger, "Could not reach music at '" + musicUrl +"'");
		}
		logger.error(EELFLoggerDelegate.errorLogger, "Unable to acquireLock. Could not successfully reach any music instance.");
		result = new HashMap<String, Object>();
		result.put("status", "FAILURE");
		return result;
	}
	
	private static Map<String,Object> acquireLock(String musicUrl, String lockId){
		//should be fixed in MUSIC, but putting patch here too
		if (lockId==null) {
			Map<String,Object> fail = new HashMap<String, Object>();
			fail.put("status", "FAILURE");
			return fail;
		}

		WebResource webResource = createMusicWebResource(musicUrl+"/locks/acquire/"+lockId);

		ClientResponse response = addMusicHeaders(webResource).get(ClientResponse.class);

		if (response.getStatus() != 200 && response.getStatus() != 400) {
			logger.error(EELFLoggerDelegate.errorLogger, "Failed to acquireLock : Status Code "+response.getStatus());
			throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
		}

		Map<String,Object> output = response.getEntity(Map.class);

		return output;
	}

	public static String whoIsLockHolder(String lockName) {
		logger.info(EELFLoggerDelegate.applicationLogger, "whoIsLockHolder "+lockName);
		
		ArrayList<String> musicUrls = PromUtil.getMusicNodeURL();
		String result;
		for (String musicUrl: musicUrls) {
			try {
				result = whoIsLockHolder(musicUrl, lockName);
				return result;
			} catch (ClientHandlerException che) {
				logger.warn(EELFLoggerDelegate.applicationLogger, "Timed out connection to MUSIC. Consider setting"
						+ " 'music-connection-timeout-ms' in the configuration");
			} catch (RuntimeException e) {
				logger.warn(EELFLoggerDelegate.applicationLogger, e.getMessage());
			}
			logger.warn(EELFLoggerDelegate.applicationLogger, "Could not reach music at '" + musicUrl +"'");
		}
		logger.error(EELFLoggerDelegate.errorLogger, "Unable to check who the lock holder is. "
											+ "Could not successfully reach any music instance.");
		result = null;
		return result;
	}
	
	private static String whoIsLockHolder(String musicUrl, String lockName) {	
		WebResource webResource = createMusicWebResource(musicUrl+"/locks/enquire/"+lockName);

		ClientResponse response = addMusicHeaders(webResource).get(ClientResponse.class);

		if (response.getStatus() != 200) {
			logger.error(EELFLoggerDelegate.errorLogger,
					"Failed to determine whoIsLockHolder : Status Code "+response.getStatus());
			throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
		}

		Map<String,String> lockoutput = (Map<String, String>) response.getEntity(Map.class).get("lock");
		if (lockoutput.get("lock-holder").equals("No lock holder!")) {
			logger.info(EELFLoggerDelegate.applicationLogger, "No lock holder");
			return null;
		}
		return (String) lockoutput.get("lock-holder");
	}

	public static void unlock(String lockId) {
		ArrayList<String> musicUrls = PromUtil.getMusicNodeURL();
		for (String musicUrl: musicUrls) {
			try {
				unlock(musicUrl, lockId);
				return;
			} catch (ClientHandlerException che) {
				logger.warn(EELFLoggerDelegate.applicationLogger, "Timed out connection to MUSIC. Consider setting"
						+ " 'music-connection-timeout-ms' in the configuration");
			} catch (RuntimeException e) {
				logger.warn(EELFLoggerDelegate.applicationLogger, e.getMessage());
			}
			logger.warn(EELFLoggerDelegate.applicationLogger, "Could not reach music at '" + musicUrl +"'");
		}
		logger.error(EELFLoggerDelegate.errorLogger, "Unable to unlock the lock. "
								+ "Could not successfully reach any music instance.");
		return;
	}
	
	private static void unlock(String musicUrl, String lockId) {
		logger.info(EELFLoggerDelegate.applicationLogger, "unlock "+lockId);

		WebResource webResource = createMusicWebResource(musicUrl+"/locks/release/"+lockId);

		ClientResponse response = addMusicHeaders(webResource).delete(ClientResponse.class);

		Map<String,Object> responseMap = response.getEntity(Map.class);
		
		if (response.getStatus() < 200 || response.getStatus() > 299) {
			logger.error(EELFLoggerDelegate.errorLogger, "Failed to unlock : Status Code "+response.getStatus());
			if (responseMap.containsKey("error")) {
				logger.error(EELFLoggerDelegate.errorLogger, "Failed to unlock : "+responseMap.get("error"));
			}
			throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
		}
	}


	
	/**
	 * Gets a connection timeout to music. This function will return the 
	 * configured parameter given in the prom json config, if available.
	 * Otherwise, it will calculate a timeout such that it the connection will be able
	 * to cycle through the different music locations prior to other nodes assuming this
	 * replica is dead.
	 * @return
	 */
	private static int getMaxConnectionTimeout() {
		int timeout = PromUtil.getTimeoutToMusicMillis();
		if (timeout<=0) { // user hasn't defined a valid timeout
			ArrayList<String> musicUrls = PromUtil.getMusicNodeURL();
			int promTimeout = PromUtil.getPromTimeout();
			timeout = promTimeout/musicUrls.size();
		}
		return timeout;
	}
	
	
	public static void main(String[] args){
		Map<String,Object> results = MusicHandle.readAllRows("votingappbharath", "replicas");
		for (Map.Entry<String, Object> entry : results.entrySet()){
			Map<String, Object> valueMap = (Map<String, Object>)entry.getValue();
			for (Map.Entry<String, Object> rowentry : valueMap.entrySet()){
				if(rowentry.getKey().equals("timeoflastupdate")){
					System.out.println(rowentry.getValue());
				}
				break;
			}
			break;
		}
	}

}