2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (c) 2017 AT&T Intellectual Property
6 * ===================================================================
7 * Modifications Copyright (C) 2018 IBM.
8 * ================================================================================
9 * Licensed under the Apache License, Version 2.0 (the "License");
10 * you may not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
21 * ============LICENSE_END=============================================
22 * ====================================================================
24 package org.onap.music.rest;
27 import java.nio.ByteBuffer;
28 import java.nio.charset.Charset;
29 import java.security.KeyManagementException;
30 import java.security.NoSuchAlgorithmException;
31 import java.security.SecureRandom;
32 import java.security.cert.X509Certificate;
33 import java.util.ArrayList;
34 import java.util.HashMap;
35 import java.util.HashSet;
36 import java.util.Iterator;
37 import java.util.List;
39 import java.util.Map.Entry;
41 import java.util.UUID;
43 import javax.net.ssl.HostnameVerifier;
44 import javax.net.ssl.HttpsURLConnection;
45 import javax.net.ssl.SSLContext;
46 import javax.net.ssl.SSLSession;
47 import javax.net.ssl.TrustManager;
48 import javax.net.ssl.X509TrustManager;
49 import javax.ws.rs.Consumes;
50 import javax.ws.rs.DELETE;
51 import javax.ws.rs.POST;
52 import javax.ws.rs.PUT;
53 import javax.ws.rs.Path;
54 import javax.ws.rs.Produces;
55 import javax.ws.rs.core.MediaType;
56 import javax.ws.rs.core.Response;
57 import javax.ws.rs.core.Response.ResponseBuilder;
58 import javax.ws.rs.core.Response.Status;
60 import org.codehaus.jackson.map.ObjectMapper;
61 import org.mindrot.jbcrypt.BCrypt;
62 import org.onap.music.datastore.PreparedQueryObject;
63 import org.onap.music.datastore.jsonobjects.JSONCallbackResponse;
64 import org.onap.music.datastore.jsonobjects.JSONObject;
65 import org.onap.music.datastore.jsonobjects.JsonCallback;
66 import org.onap.music.datastore.jsonobjects.JsonNotification;
67 import org.onap.music.datastore.jsonobjects.JsonNotifyClientResponse;
68 import org.onap.music.datastore.jsonobjects.JsonOnboard;
69 import org.onap.music.eelf.logging.EELFLoggerDelegate;
70 import org.onap.music.eelf.logging.format.AppMessages;
71 import org.onap.music.eelf.logging.format.ErrorSeverity;
72 import org.onap.music.eelf.logging.format.ErrorTypes;
73 //import org.onap.music.main.CacheAccess;
74 import org.onap.music.main.CachingUtil;
75 import org.onap.music.main.MusicCore;
76 import org.onap.music.main.MusicUtil;
77 import org.onap.music.main.ResultType;
78 import org.onap.music.main.ReturnType;
79 import org.onap.music.response.jsonobjects.JsonResponse;
81 import com.datastax.driver.core.ColumnDefinitions;
82 import com.datastax.driver.core.ColumnDefinitions.Definition;
83 import com.datastax.driver.core.DataType;
84 import com.datastax.driver.core.ResultSet;
85 import com.datastax.driver.core.Row;
86 import com.datastax.driver.core.TableMetadata;
87 import com.datastax.driver.core.exceptions.InvalidQueryException;
88 import com.sun.jersey.api.client.Client;
89 import com.sun.jersey.api.client.ClientResponse;
90 import com.sun.jersey.api.client.WebResource;
91 import com.sun.jersey.api.client.config.ClientConfig;
92 import com.sun.jersey.api.client.config.DefaultClientConfig;
93 import com.sun.jersey.api.json.JSONConfiguration;
94 import com.sun.jersey.client.urlconnection.HTTPSProperties;
95 import com.sun.jersey.core.util.Base64;
97 import io.swagger.annotations.Api;
98 import io.swagger.annotations.ApiOperation;
101 // @Path("/v{version: [0-9]+}/admin")
103 @Api(value = "Admin Api", hidden = true)
104 public class RestMusicAdminAPI {
105 private static EELFLoggerDelegate logger =
106 EELFLoggerDelegate.getLogger(RestMusicAdminAPI.class);
108 * API to onboard an application with MUSIC. This is the mandatory first step.
112 @Path("/onboardAppWithMusic")
113 @ApiOperation(value = "Onboard application", response = String.class)
114 @Consumes(MediaType.APPLICATION_JSON)
115 @Produces(MediaType.APPLICATION_JSON)
116 public Response onboardAppWithMusic(JsonOnboard jsonObj) throws Exception {
117 ResponseBuilder response =
118 Response.noContent().header("X-latestVersion", MusicUtil.getVersion());
119 Map<String, Object> resultMap = new HashMap<>();
120 String appName = jsonObj.getAppname();
121 String userId = jsonObj.getUserId();
122 String isAAF = jsonObj.getIsAAF();
123 String password = jsonObj.getPassword();
124 if (appName == null || userId == null || isAAF == null || password == null) {
125 logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGINFO,
126 ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR);
127 resultMap.put("Exception",
128 "Unauthorized: Please check the request parameters. Some of the required values appName(ns), userId, password, isAAF are missing.");
129 return Response.status(Status.UNAUTHORIZED).entity(resultMap).build();
132 PreparedQueryObject pQuery = new PreparedQueryObject();
133 pQuery.appendQueryString(
134 "select uuid from admin.keyspace_master where application_name = ? allow filtering");
135 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
136 ResultSet rs = MusicCore.get(pQuery);
137 if (!rs.all().isEmpty()) {
138 resultMap.put("Exception", "Application " + appName
139 + " has already been onboarded. Please contact admin.");
140 return Response.status(Status.BAD_REQUEST).entity(resultMap).build();
143 pQuery = new PreparedQueryObject();
144 String uuid = CachingUtil.generateUUID();
145 pQuery.appendQueryString(
146 "INSERT INTO admin.keyspace_master (uuid, keyspace_name, application_name, is_api, "
147 + "password, username, is_aaf) VALUES (?,?,?,?,?,?,?)");
148 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid));
149 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(),
150 MusicUtil.DEFAULTKEYSPACENAME));
151 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
152 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), "True"));
153 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), BCrypt.hashpw(password, BCrypt.gensalt())));
154 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId));
155 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF));
157 String returnStr = MusicCore.eventualPut(pQuery).toString();
158 if (returnStr.contains("Failure")) {
159 resultMap.put("Exception",
160 "Oops. Something wrong with onboarding process. Please retry later or contact admin.");
161 return Response.status(Status.BAD_REQUEST).entity(resultMap).build();
163 CachingUtil.updateisAAFCache(appName, isAAF);
164 resultMap.put("Success", "Your application " + appName + " has been onboarded with MUSIC.");
165 resultMap.put("Generated AID", uuid);
166 return Response.status(Status.OK).entity(resultMap).build();
172 @ApiOperation(value = "Search Onboard application", response = String.class)
173 @Consumes(MediaType.APPLICATION_JSON)
174 @Produces(MediaType.APPLICATION_JSON)
175 public Response getOnboardedInfoSearch(JsonOnboard jsonObj) throws Exception {
176 Map<String, Object> resultMap = new HashMap<>();
177 ResponseBuilder response =
178 Response.noContent().header("X-latestVersion", MusicUtil.getVersion());
179 String appName = jsonObj.getAppname();
180 String uuid = jsonObj.getAid();
181 String isAAF = jsonObj.getIsAAF();
183 if (appName == null && uuid == null && isAAF == null) {
184 logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGINFO,
185 ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR);
186 resultMap.put("Exception",
187 "Unauthorized: Please check the request parameters. Enter atleast one of the following parameters: appName(ns), aid, isAAF.");
188 return Response.status(Status.BAD_REQUEST).entity(resultMap).build();
191 PreparedQueryObject pQuery = new PreparedQueryObject();
192 String cql = "select uuid, keyspace_name from admin.keyspace_master where ";
194 cql = cql + "application_name = ? AND ";
196 cql = cql + "uuid = ? AND ";
198 cql = cql + "is_aaf = ?";
200 if (cql.endsWith("AND "))
201 cql = cql.trim().substring(0, cql.length() - 4);
202 logger.info("Query in callback is: " + cql);
203 cql = cql + " allow filtering";
204 pQuery.appendQueryString(cql);
206 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
208 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid));
210 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(),
211 Boolean.parseBoolean(isAAF)));
212 ResultSet rs = MusicCore.get(pQuery);
213 Iterator<Row> it = rs.iterator();
214 while (it.hasNext()) {
215 Row row = (Row) it.next();
216 resultMap.put(row.getUUID("uuid").toString(), row.getString("keyspace_name"));
218 if (resultMap.isEmpty()) {
220 resultMap.put("Exception",
221 "Please make sure Aid is correct and application is onboarded.");
222 return Response.status(Status.BAD_REQUEST).entity(resultMap).build();
224 resultMap.put("Exception",
225 "Application is not onboarded. Please make sure all the information is correct.");
226 return Response.status(Status.BAD_REQUEST).entity(resultMap).build();
229 return Response.status(Status.OK).entity(resultMap).build();
234 @Path("/onboardAppWithMusic")
235 @ApiOperation(value = "Delete Onboard application", response = String.class)
236 @Consumes(MediaType.APPLICATION_JSON)
237 @Produces(MediaType.APPLICATION_JSON)
238 public Response deleteOnboardApp(JsonOnboard jsonObj) throws Exception {
239 Map<String, Object> resultMap = new HashMap<>();
240 ResponseBuilder response =
241 Response.noContent().header("X-latestVersion", MusicUtil.getVersion());
242 String appName = jsonObj.getAppname();
243 String aid = jsonObj.getAid();
244 PreparedQueryObject pQuery = new PreparedQueryObject();
245 String consistency = MusicUtil.EVENTUAL;;
246 if (appName == null && aid == null) {
247 logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGINFO,
248 ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
249 resultMap.put("Exception", "Please make sure either appName(ns) or Aid is present");
250 return Response.status(Status.BAD_REQUEST).entity(resultMap).build();
253 pQuery.appendQueryString(
254 "SELECT keyspace_name FROM admin.keyspace_master WHERE uuid = ?");
255 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(),
256 UUID.fromString(aid)));
257 Row row = MusicCore.get(pQuery).one();
259 String ks = row.getString("keyspace_name");
260 if (!ks.equals(MusicUtil.DEFAULTKEYSPACENAME)) {
261 PreparedQueryObject queryObject = new PreparedQueryObject();
262 queryObject.appendQueryString("DROP KEYSPACE IF EXISTS " + ks + ";");
263 MusicCore.nonKeyRelatedPut(queryObject, consistency);
266 pQuery = new PreparedQueryObject();
267 pQuery.appendQueryString("delete from admin.keyspace_master where uuid = ? IF EXISTS");
268 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(),
269 UUID.fromString(aid)));
270 ResultType result = MusicCore.nonKeyRelatedPut(pQuery, consistency);
271 if (result == ResultType.SUCCESS) {
272 resultMap.put("Success", "Your application has been deleted successfully");
274 resultMap.put("Exception",
275 "Oops. Something went wrong. Please make sure Aid is correct or Application is onboarded");
276 logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.INCORRECTDATA,
277 ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
278 return Response.status(Status.BAD_REQUEST).entity(resultMap).build();
281 return Response.status(Status.OK).entity(resultMap).build();
284 pQuery.appendQueryString(
285 "select uuid from admin.keyspace_master where application_name = ? allow filtering");
286 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
287 ResultSet rs = MusicCore.get(pQuery);
288 List<Row> rows = rs.all();
290 if (rows.isEmpty()) {
291 resultMap.put("Exception",
292 "Application not found. Please make sure Application exists.");
293 logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.INCORRECTDATA,
294 ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
295 return Response.status(Status.BAD_REQUEST).entity(resultMap).build();
296 } else if (rows.size() == 1) {
297 uuid = rows.get(0).getUUID("uuid").toString();
298 pQuery = new PreparedQueryObject();
299 pQuery.appendQueryString(
300 "SELECT keyspace_name FROM admin.keyspace_master WHERE uuid = ?");
301 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(),
302 UUID.fromString(uuid)));
303 Row row = MusicCore.get(pQuery).one();
304 String ks = row.getString("keyspace_name");
305 if (!ks.equals(MusicUtil.DEFAULTKEYSPACENAME)) {
306 PreparedQueryObject queryObject = new PreparedQueryObject();
307 queryObject.appendQueryString("DROP KEYSPACE " + ks + ";");
308 MusicCore.nonKeyRelatedPut(queryObject, consistency);
311 pQuery = new PreparedQueryObject();
312 pQuery.appendQueryString("delete from admin.keyspace_master where uuid = ?");
313 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(),
314 UUID.fromString(uuid)));
315 MusicCore.eventualPut(pQuery);
316 resultMap.put("Success", "Your application " + appName + " has been deleted.");
317 return Response.status(Status.OK).entity(resultMap).build();
319 resultMap.put("Failure",
320 "More than one Aid exists for this application, so please provide Aid.");
321 logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MULTIPLERECORDS,
322 ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
323 return Response.status(Status.BAD_REQUEST).entity(resultMap).build();
329 @Path("/onboardAppWithMusic")
330 @ApiOperation(value = "Update Onboard application", response = String.class)
331 @Consumes(MediaType.APPLICATION_JSON)
332 @Produces(MediaType.APPLICATION_JSON)
333 public Response updateOnboardApp(JsonOnboard jsonObj) throws Exception {
334 Map<String, Object> resultMap = new HashMap<>();
335 ResponseBuilder response =
336 Response.noContent().header("X-latestVersion", MusicUtil.getVersion());
337 String aid = jsonObj.getAid();
338 String appName = jsonObj.getAppname();
339 String userId = jsonObj.getUserId();
340 String isAAF = jsonObj.getIsAAF();
341 String password = jsonObj.getPassword();
342 String consistency = "eventual";
343 PreparedQueryObject pQuery;
346 resultMap.put("Exception", "Please make sure Aid is present");
347 logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA,
348 ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
349 return Response.status(Status.BAD_REQUEST).entity(resultMap).build();
352 if (appName == null && userId == null && password == null && isAAF == null) {
353 resultMap.put("Exception",
354 "No parameters found to update. Please update atleast one parameter.");
355 logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA,
356 ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
357 return Response.status(Status.BAD_REQUEST).entity(resultMap).build();
360 if (appName != null) {
361 pQuery = new PreparedQueryObject();
362 pQuery.appendQueryString(
363 "select uuid from admin.keyspace_master where application_name = ? allow filtering");
364 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
365 ResultSet rs = MusicCore.get(pQuery);
366 if (!rs.all().isEmpty()) {
367 resultMap.put("Exception", "Application " + appName
368 + " has already been onboarded. Please contact admin.");
369 logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.ALREADYEXIST,
370 ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
371 return Response.status(Status.BAD_REQUEST).entity(resultMap).build();
375 pQuery = new PreparedQueryObject();
376 StringBuilder preCql = new StringBuilder("UPDATE admin.keyspace_master SET ");
378 preCql.append(" application_name = ?,");
380 preCql.append(" username = ?,");
381 if (password != null)
382 preCql.append(" password = ?,");
384 preCql.append(" is_aaf = ?,");
385 preCql.deleteCharAt(preCql.length() - 1);
386 preCql.append(" WHERE uuid = ? IF EXISTS");
387 pQuery.appendQueryString(preCql.toString());
389 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
391 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId));
392 if (password != null)
393 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), BCrypt.hashpw(password, BCrypt.gensalt())));
395 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF));
397 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), UUID.fromString(aid)));
398 ResultType result = MusicCore.nonKeyRelatedPut(pQuery, consistency);
400 if (result == ResultType.SUCCESS) {
401 resultMap.put("Success", "Your application has been updated successfully");
403 resultMap.put("Exception",
404 "Oops. Something went wrong. Please make sure Aid is correct and application is onboarded");
405 logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.INCORRECTDATA,
406 ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
407 return Response.status(Status.BAD_REQUEST).entity(resultMap).build();
410 return Response.status(Status.OK).entity(resultMap).build();
413 Client client = Client.create();
414 ObjectMapper mapper = new ObjectMapper();
417 @Path("/callbackOps")
418 @Produces(MediaType.APPLICATION_JSON)
419 @Consumes(MediaType.APPLICATION_JSON)
420 public Response callbackOps(final JSONObject inputJsonObj) {
421 Map<String, Object> resultMap = new HashMap<>();
422 new Thread(new Runnable() {
424 makeAsyncCall(inputJsonObj);
428 return Response.status(Status.OK).entity(resultMap).build();
431 private Response makeAsyncCall(JSONObject inputJsonObj) {
433 Map<String, Object> resultMap = new HashMap<>();
435 logger.info(EELFLoggerDelegate.applicationLogger, "Got notification: " + inputJsonObj.getData());
436 logger.info("Got notification: " + inputJsonObj.getData());
437 String dataStr = inputJsonObj.getData();
438 JSONCallbackResponse jsonResponse = mapper.readValue(dataStr, JSONCallbackResponse.class);
439 String operation = jsonResponse.getOperation();
440 Map<String, String> changeValueMap = jsonResponse.getChangeValue();
441 String primaryKey = jsonResponse.getPrimary_key();
442 String ksTableName = jsonResponse.getFull_table(); //conductor.plans
443 if(ksTableName.equals("admin.notification_master")) {
444 CachingUtil.updateCallbackNotifyList(new ArrayList<String>());
445 return Response.status(Status.OK).entity(resultMap).build();
447 List<String> inputUpdateList = jsonResponse.getUpdateList();
449 String field_value = null;
450 List<String> notifiyList = CachingUtil.getCallbackNotifyList();
451 if(notifiyList == null || notifiyList.isEmpty()) {
452 logger.info("Is cache empty? reconstructing Object from cache..");
453 constructJsonCallbackFromCache();
455 notifiyList = CachingUtil.getCallbackNotifyList();
456 JsonCallback baseRequestObj = null;
458 if("update".equals(operation)) {
459 for(String element: inputUpdateList) {
460 baseRequestObj = CachingUtil.getCallBackCache(element);
461 if(baseRequestObj != null) {
462 logger.info("Found the element that was changed... "+element);
467 List<String> updateList = jsonResponse.getUpdateList();
468 //logger.info("update list from trigger: "+updateList);
469 for(String element : updateList) {
470 if(notifiyList.contains(element)) {
471 logger.info("Found the notifyOn property: "+element);
472 field_value = element;
476 if(baseRequestObj == null || field_value == null) {
477 for(String element: inputUpdateList) {
478 String[] elementArr = element.split(":");
479 String newElement = null;
480 if(elementArr.length >= 2) {
481 newElement = elementArr[0]+":"+elementArr[1];
483 baseRequestObj = CachingUtil.getCallBackCache(newElement);
484 if(baseRequestObj != null) {
485 logger.info("Found the element that was changed... "+newElement);
489 for(String element : updateList) {
490 String[] elementArr = element.split(":");
491 String newElement = null;
492 if(elementArr.length >= 2) {
493 newElement = elementArr[0]+":"+elementArr[1];
495 if(notifiyList.contains(newElement)) {
496 logger.info("Found the notifyOn property: "+newElement);
497 field_value = newElement;
503 field_value = jsonResponse.getFull_table();
504 baseRequestObj = CachingUtil.getCallBackCache(field_value);
507 if(baseRequestObj == null || field_value == null) {
508 resultMap.put("Exception",
509 "Oops. Something went wrong. Please make sure Callback properties are onboarded.");
510 logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.INCORRECTDATA,
511 ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
512 return Response.status(Status.BAD_REQUEST).entity(resultMap).build();
514 logger.info(EELFLoggerDelegate.applicationLogger, "Going through list: "+operation+ " && List: "+jsonResponse.getUpdateList());
516 String key = "admin" + "." + "notification_master" + "." + baseRequestObj.getUuid();
517 String lockId = MusicCore.createLockReference(key);
518 ReturnType lockAcqResult = MusicCore.acquireLock(key, lockId);
519 if(! lockAcqResult.getResult().toString().equals("SUCCESS")) {
520 logger.error(EELFLoggerDelegate.errorLogger, "Some other node is notifying the caller..: ");
523 logger.info(EELFLoggerDelegate.applicationLogger, operation+ ": Operation :: changeValue: "+changeValueMap);
524 if(operation.equals("update")) {
525 String notifyWhenChangeIn = baseRequestObj.getNotifyWhenChangeIn(); // conductor.plans.status
526 if(null!=field_value) {
527 if(field_value.equals(notifyWhenChangeIn)) {
528 notifyCallBackAppl(jsonResponse, baseRequestObj);
531 } else if(operation.equals("delete")) {
532 String notifyWhenDeletesIn = baseRequestObj.getNotifyWhenDeletesIn(); // conductor.plans.status
533 if(null!=field_value) {
534 if(field_value.equals(notifyWhenDeletesIn)) {
535 notifyCallBackAppl(jsonResponse, baseRequestObj);
538 } else if(operation.equals("insert")) {
539 String notifyWhenInsertsIn = baseRequestObj.getNotifyWhenInsertsIn(); // conductor.plans.status
540 if(null!=field_value) {
541 if(field_value.equals(notifyWhenInsertsIn)) {
542 notifyCallBackAppl(jsonResponse, baseRequestObj);
546 MusicCore.releaseLock(lockId, true);
547 } catch(Exception e) {
549 logger.error(EELFLoggerDelegate.errorLogger, "Exception while notifying...."+e.getMessage());
551 logger.info(EELFLoggerDelegate.applicationLogger, "callback is completed. Notification was sent from Music...");
552 return Response.status(Status.OK).entity(resultMap).build();
555 private void notifyCallBackAppl(JSONCallbackResponse jsonResponse, JsonCallback baseRequestObj) throws Exception {
556 int notifytimeout = MusicUtil.getNotifyTimeout();
557 int notifyinterval = MusicUtil.getNotifyInterval();
558 String endpoint = baseRequestObj.getApplicationNotificationEndpoint();
559 String username = baseRequestObj.getApplicationUsername();
560 String password = baseRequestObj.getApplicationPassword();
561 JsonNotification jsonNotification = constructJsonNotification(jsonResponse, baseRequestObj);
562 jsonNotification.setPassword("************");
563 jsonNotification.setOperation_type(jsonResponse.getOperation());
564 logger.info(EELFLoggerDelegate.applicationLogger, "Notification Response sending is: "+jsonNotification);
565 logger.info("Notification Response sending is: "+jsonNotification);
566 jsonNotification.setPassword(baseRequestObj.getApplicationPassword());
567 WebResource webResource = client.resource(endpoint);
568 String authData = username+":"+password;
569 byte[] plainCredsBytes = authData.getBytes();
570 byte[] base64CredsBytes = Base64.encode(plainCredsBytes);
571 String base64Creds = new String(base64CredsBytes);
572 ClientConfig config = new DefaultClientConfig();
573 config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
574 ClientResponse response = null;
575 WebResource service = null;
578 Client client = Client.create(config);
579 TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager(){
580 public X509Certificate[] getAcceptedIssuers(){return null;}
581 public void checkClientTrusted(X509Certificate[] certs, String authType){}
582 public void checkServerTrusted(X509Certificate[] certs, String authType){}
585 // Install the all-trusting trust manager
587 SSLContext sc = SSLContext.getInstance("TLS");
588 sc.init(null, trustAllCerts, new SecureRandom());
589 HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
590 } catch (Exception e) {
595 SSLContext sslcontext = SSLContext.getInstance( "TLS" );
596 sslcontext.init( null, null, null );
597 Map<String, Object> properties = config.getProperties();
598 HTTPSProperties httpsProperties = new HTTPSProperties(
599 new HostnameVerifier() {
601 public boolean verify( String s, SSLSession sslSession ) {
606 properties.put( HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, httpsProperties );
607 HttpsURLConnection.setDefaultHostnameVerifier (new HostnameVerifier() {
609 public boolean verify(String hostname, SSLSession session) {
613 Client.create( config );
615 catch ( KeyManagementException | NoSuchAlgorithmException e ) {
616 throw new RuntimeException( e );
619 service = client.resource(endpoint);
621 response = service.header("Authorization", "Basic " + base64Creds).accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON)
622 .post(ClientResponse.class, jsonNotification);
624 } catch (Exception chf) {
625 logger.info(EELFLoggerDelegate.applicationLogger, "Is Service down?");
626 logger.info("An Exception occured while notifying. "+chf+ " : "+chf.getMessage() +" ...Retrying for: "+notifytimeout);
628 if(response != null && response.getStatus() == 200) ok = true;
630 long now= System.currentTimeMillis();
631 long end = now+notifytimeout;
633 logger.info(EELFLoggerDelegate.applicationLogger, "retrying since error in notifying callback for "+notifytimeout+"ms");
634 logger.info("retrying since error in notifying callback.. response status: "+ (response == null ? "404" : response.getStatus()));
637 response = service.header("Authorization", "Basic " + base64Creds).accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON)
638 .post(ClientResponse.class, jsonNotification);
639 if(response != null && response.getStatus() == 200) ok = true;
640 else if(System.currentTimeMillis() < end) {
641 try{ Thread.sleep(notifyinterval); } catch(Exception e1) {}
644 }catch (Exception e) {
645 logger.info(EELFLoggerDelegate.applicationLogger, "Retry until "+(end-System.currentTimeMillis()));
646 if(response == null && System.currentTimeMillis() < end) ok = false;
648 try{ Thread.sleep(notifyinterval); } catch(Exception e1) {}
653 if(response == null) {
654 logger.error(EELFLoggerDelegate.errorLogger, "Can NOT notify the caller as caller failed to respond..");
658 JsonNotifyClientResponse responseStr = response.getEntity(JsonNotifyClientResponse.class);
659 logger.info(EELFLoggerDelegate.applicationLogger, "Response from Notified client: "+responseStr);
660 logger.info("Response from Notified client: "+responseStr);
661 } catch(Exception e) {
662 logger.info("Exception while reading response from Caller");
663 logger.error("Exception while reading response from Caller");
664 logger.error(EELFLoggerDelegate.errorLogger, "Can NOT notify the caller as caller failed to respond..");
667 /*ClientResponse response = null;
669 response = webResource.header("Authorization", "Basic " + base64Creds).accept("application/json").type("application/json")
670 .post(ClientResponse.class, jsonNotification);
671 } catch (com.sun.jersey.api.client.ClientHandlerException chf) {
673 logger.info(EELFLoggerDelegate.applicationLogger, "Is Service down?");
674 long now= System.currentTimeMillis();
675 long end = now+notifytimeout;
677 logger.info(EELFLoggerDelegate.applicationLogger, "retrying since error in notifying callback..");
679 response = webResource.header("Authorization", "Basic " + base64Creds).accept("application/json").type("application/json")
680 .post(ClientResponse.class, jsonNotification);
681 if(response.getStatus() == 200) ok = true;
682 }catch (Exception e) {
683 logger.info(EELFLoggerDelegate.applicationLogger, "Retry until "+(end-System.currentTimeMillis()));
684 if(response == null && System.currentTimeMillis() < end) ok = false;
686 try{ Thread.sleep(notifyinterval); } catch(Exception e1) {}
690 if(response == null) {
691 logger.error(EELFLoggerDelegate.errorLogger, "Can NOT notify the caller as caller failed to respond..");
694 JsonNotifyClientResponse responseStr = response.getEntity(JsonNotifyClientResponse.class);
695 logger.info(EELFLoggerDelegate.applicationLogger, "Response from Notified client: "+responseStr);
697 if(response.getStatus() != 200){
698 long now= System.currentTimeMillis();
699 long end = now+30000;
700 while(response.getStatus() != 200 && System.currentTimeMillis() < end) {
701 logger.info(EELFLoggerDelegate.applicationLogger, "retrying since error in notifying callback..");
702 response = webResource.header("Authorization", "Basic " + base64Creds).accept("application/json").type("application/json")
703 .post(ClientResponse.class, jsonNotification);
705 logger.info(EELFLoggerDelegate.applicationLogger, "Exception while notifying.. "+response.getStatus());
709 private JsonNotification constructJsonNotification(JSONCallbackResponse jsonResponse, JsonCallback baseRequestObj) {
711 JsonNotification jsonNotification = new JsonNotification();
713 jsonNotification.setNotify_field(baseRequestObj.getNotifyOn());
714 jsonNotification.setEndpoint(baseRequestObj.getApplicationNotificationEndpoint());
715 jsonNotification.setUsername(baseRequestObj.getApplicationUsername());
716 jsonNotification.setPassword(baseRequestObj.getApplicationPassword());
717 String pkValue = jsonResponse.getPrimary_key();
719 String[] fullNotifyArr = baseRequestObj.getNotifyOn().split(":");
721 String[] tableArr = fullNotifyArr[0].split("\\.");
722 TableMetadata tableInfo = MusicCore.returnColumnMetadata(tableArr[0], tableArr[1]);
723 DataType primaryIdType = tableInfo.getPrimaryKey().get(0).getType();
724 String primaryId = tableInfo.getPrimaryKey().get(0).getName();
726 Map<String, String> responseBodyMap = baseRequestObj.getResponseBody();
727 for (Entry<String, String> entry : new HashSet<>(responseBodyMap.entrySet())) {
728 String trimmed = entry.getKey().trim();
729 if (!trimmed.equals(entry.getKey())) {
730 responseBodyMap.remove(entry.getKey());
731 responseBodyMap.put(trimmed, entry.getValue());
735 Set<String> keySet = responseBodyMap.keySet();
736 Map<String, String> newMap = new HashMap<>();
737 if(responseBodyMap.size() == 1 && responseBodyMap.containsKey("")) {
738 jsonNotification.setResponse_body(newMap);
739 return jsonNotification;
741 logger.info(EELFLoggerDelegate.applicationLogger, "responseBodyMap is not blank: "+responseBodyMap);
742 String cql = "select *";
743 /*for(String keys: keySet) {
744 cql = cql + keys + ",";
746 //cql = cql.substring(0, cql.length()-1);
747 cql = cql + " FROM "+fullNotifyArr[0]+" WHERE "+primaryId+" = ?";
748 logger.info(EELFLoggerDelegate.applicationLogger, "CQL in constructJsonNotification: "+cql);
749 PreparedQueryObject pQuery = new PreparedQueryObject();
750 pQuery.appendQueryString(cql);
751 pQuery.addValue(MusicUtil.convertToActualDataType(primaryIdType, pkValue));
752 Row row = MusicCore.get(pQuery).one();
754 ColumnDefinitions colInfo = row.getColumnDefinitions();
755 for (Definition definition : colInfo) {
756 String colName = definition.getName();
757 if(keySet.contains(colName)) {
758 DataType colType = definition.getType();
759 Object valueObj = MusicCore.getDSHandle().getColValue(row, colName, colType);
760 Object valueString = MusicUtil.convertToActualDataType(colType, valueObj);
761 logger.info(colName+" : "+valueString);
762 newMap.put(colName, valueString.toString());
763 keySet.remove(colName);
767 if(! keySet.isEmpty()) {
768 Iterator<String> iterator = keySet.iterator();
769 while (iterator.hasNext()) {
770 String element = iterator.next();
771 newMap.put(element,"COLUMN_NOT_FOUND");
775 if("delete".equals(jsonResponse.getOperation()) || newMap.isEmpty()) {
776 newMap.put(primaryId, pkValue);
778 jsonNotification.setResponse_body(newMap);
779 } catch(Exception e) {
782 return jsonNotification;
787 private void constructJsonCallbackFromCache() throws Exception{
788 PreparedQueryObject pQuery = new PreparedQueryObject();
789 JsonCallback jsonCallback = null;
790 List<String> notifyList = new java.util.ArrayList<>();
792 "select id, endpoint_userid, endpoint_password, notify_to_endpoint, notify_insert_on,"
793 + " notify_delete_on, notify_update_on, request, notifyon from admin.notification_master allow filtering";
794 pQuery.appendQueryString(cql);
795 //pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), fullTable));
797 ResultSet rs = MusicCore.get(pQuery);
798 Iterator<Row> it = rs.iterator();
799 while (it.hasNext()) {
800 Row row = (Row) it.next();
801 String endpoint = row.getString("notify_to_endpoint");
802 String username = row.getString("endpoint_userid");
803 ByteBuffer passwordBytes = row.getBytes("endpoint_password");
804 String insert = row.getString("notify_insert_on");
805 String delete = row.getString("notify_delete_on");
806 String update = row.getString("notify_update_on");
807 String request = row.getString("request");
808 String notifyon = row.getString("notifyon");
809 String uuid = row.getUUID("id").toString();
810 notifyList.add(notifyon);
811 jsonCallback = new JsonCallback();
812 jsonCallback.setApplicationNotificationEndpoint(endpoint);
814 Charset charset = Charset.forName("ISO-8859-1");
815 String decodedPwd = charset.decode(passwordBytes).toString();
816 jsonCallback.setApplicationPassword(decodedPwd);
817 jsonCallback.setApplicationUsername(username);
818 jsonCallback.setNotifyOn(notifyon);
819 jsonCallback.setNotifyWhenInsertsIn(insert);
820 jsonCallback.setNotifyWhenDeletesIn(delete);
821 jsonCallback.setNotifyWhenChangeIn(update);
822 jsonCallback.setUuid(uuid);
823 logger.info(EELFLoggerDelegate.applicationLogger, "From DB. Saved request_body: "+request);
824 request = request.substring(1, request.length()-1);
825 String[] keyValuePairs = request.split(",");
826 Map<String,String> responseBody = new HashMap<>();
828 for(String pair : keyValuePairs) {
829 String[] entry = pair.split("=");
831 if(entry.length == 2)
833 responseBody.put(entry[0], val);
835 logger.info(EELFLoggerDelegate.applicationLogger, "After parsing. Saved request_body: "+responseBody);
836 jsonCallback.setResponseBody(responseBody);
837 logger.info(EELFLoggerDelegate.applicationLogger, "Updating Cache with updateCallBackCache: "+notifyon+ " :::: "+jsonCallback);
838 CachingUtil.updateCallBackCache(notifyon, jsonCallback);
840 CachingUtil.updateCallbackNotifyList(notifyList);
844 @Path("/onboardCallback")
845 @Produces(MediaType.APPLICATION_JSON)
846 @Consumes(MediaType.APPLICATION_JSON)
847 public Response addCallback(JsonNotification jsonNotification) {
848 Map<String, Object> resultMap = new HashMap<>();
849 ResponseBuilder response =
850 Response.noContent().header("X-latestVersion", MusicUtil.getVersion());
851 String username = jsonNotification.getUsername();
852 String password = jsonNotification.getPassword();
853 String endpoint = jsonNotification.getEndpoint();
854 String notify_field = jsonNotification.getNotify_field();
855 Map<String, String> responseBody = jsonNotification.getResponse_body();
856 String triggerName = jsonNotification.getTriggerName();
857 if(triggerName == null || triggerName.length() == 0)
858 triggerName = "MusicTrigger";
860 /*JsonCallback callBackCache = CachingUtil.getCallBackCache(notify_field);
861 if(callBackCache != null) {
862 resultMap.put("Exception", "The notification property has already been onboarded.");
863 return Response.status(Status.BAD_REQUEST).entity(resultMap).build();
866 String[] allFields = notify_field.split(":");
867 String inserts = null;
868 String updates = null;
869 String deletes = null;
870 String tableName = null;
871 if(allFields.length >= 2) {
872 inserts = updates = notify_field;
873 } else if(allFields.length == 1) {
874 inserts = deletes = notify_field;;
876 tableName = allFields[0];
877 String cql = "CREATE TRIGGER IF NOT EXISTS musictrigger ON "+tableName+" Using '"+triggerName+"'";
878 PreparedQueryObject pQuery = new PreparedQueryObject();
880 String uuid = CachingUtil.generateUUID();
882 pQuery.appendQueryString(
883 "INSERT INTO admin.notification_master (id, endpoint_userid, endpoint_password, notify_to_endpoint, "
884 + "notifyon, notify_insert_on, notify_delete_on, notify_update_on, request, current_notifier) VALUES (?,?,?,?,?,?,?,?,?,?)");
885 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid));
886 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), username));
887 Charset charset = Charset.forName("ISO-8859-1");
888 ByteBuffer decodedPwd = charset.encode(password);
889 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.blob(), decodedPwd.array()));
890 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), endpoint));
891 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), notify_field));
892 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), inserts));
893 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), deletes));
894 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), updates));
895 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), responseBody));
896 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), MusicCore.getMyHostId()));
897 MusicCore.nonKeyRelatedPut(pQuery, MusicUtil.EVENTUAL);
898 JsonCallback jsonCallback = new JsonCallback();
899 jsonCallback.setUuid(uuid);
900 jsonCallback.setApplicationNotificationEndpoint(endpoint);
901 jsonCallback.setApplicationPassword(password);
902 jsonCallback.setApplicationUsername(username);
903 jsonCallback.setNotifyOn(notify_field);
904 jsonCallback.setNotifyWhenChangeIn(updates);
905 jsonCallback.setNotifyWhenDeletesIn(deletes);
906 jsonCallback.setNotifyWhenInsertsIn(inserts);
907 jsonCallback.setResponseBody(responseBody);
908 CachingUtil.updateCallBackCache(notify_field, jsonCallback);
909 pQuery = new PreparedQueryObject();
910 pQuery.appendQueryString(cql);
911 ResultType nonKeyRelatedPut = MusicCore.nonKeyRelatedPut(pQuery, MusicUtil.EVENTUAL);
912 logger.info(EELFLoggerDelegate.applicationLogger, "Created trigger");
913 //callBackCache.put(jsonCallback.getApplicationName(), jsonMap);
914 } catch (InvalidQueryException e) {
915 logger.error(EELFLoggerDelegate.errorLogger,"Exception callback_api table not configured."+e.getMessage());
916 resultMap.put("Exception", "Please make sure admin.notification_master table is configured.");
917 return Response.status(Status.BAD_REQUEST).entity(resultMap).build();
918 } catch(Exception e) {
920 resultMap.put("Exception", "Exception Occured.");
921 return Response.status(Status.BAD_REQUEST).entity(resultMap).build();
923 return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setMessage("Callback api successfully registered").toMap()).build();
927 @Path("/onboardCallback")
928 @Produces(MediaType.APPLICATION_JSON)
929 @Consumes(MediaType.APPLICATION_JSON)
930 public Response deleteCallbackProp(JsonNotification jsonNotification) {
931 Map<String, Object> resultMap = new HashMap<>();
932 ResponseBuilder response =
933 Response.noContent().header("X-latestVersion", MusicUtil.getVersion());
934 String notifyOn = jsonNotification.getNotify_field();
935 PreparedQueryObject pQuery = new PreparedQueryObject();
937 pQuery.appendQueryString("DELETE FROM admin.notification_master WHERE notifyon = ?");
938 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), notifyOn));
939 MusicCore.nonKeyRelatedPut(pQuery, MusicUtil.EVENTUAL);
940 } catch(Exception e) {
941 logger.error(EELFLoggerDelegate.errorLogger,e.getMessage());
942 return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setMessage("Callback api registration failed").toMap()).build();
944 return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setMessage("Callback api successfully deleted").toMap()).build();
947 /*public String encodePwd(String password) {
948 return Base64.getEncoder().encodeToString(password.getBytes());
951 public String decodePwd(String password) {
952 byte[] bytes = Base64.getDecoder().decode(password);
953 return new String(bytes);