- Client client = Client.create();
- ObjectMapper mapper = new ObjectMapper();
-
- @POST
- @Path("/callbackOps")
- @Produces(MediaType.APPLICATION_JSON)
- @Consumes(MediaType.APPLICATION_JSON)
- public Response callbackOps(final JSONObject inputJsonObj) {
- ResponseBuilder response = Response.noContent().header("X-latestVersion", MusicUtil.getVersion());
- Map<String, Object> resultMap = new HashMap<>();
- new Thread(new Runnable() {
- public void run() {
- makeAsyncCall(inputJsonObj);
- }
- }).start();
-
- return response.status(Status.OK).entity(resultMap).build();
- }
-
- private Response makeAsyncCall(JSONObject inputJsonObj) {
- ResponseBuilder response = Response.noContent().header("X-latestVersion", MusicUtil.getVersion());
- Map<String, Object> resultMap = new HashMap<>();
- try {
- logger.info(EELFLoggerDelegate.applicationLogger, "Got notification: " + inputJsonObj.getData());
- logger.info("Got notification: " + inputJsonObj.getData());
- String dataStr = inputJsonObj.getData();
- JSONCallbackResponse jsonResponse = mapper.readValue(dataStr, JSONCallbackResponse.class);
- String operation = jsonResponse.getOperation();
- Map<String, String> changeValueMap = jsonResponse.getChangeValue();
- String ksTableName = jsonResponse.getFull_table(); //conductor.plans
- if("admin.notification_master".equals(ksTableName)) {
- CachingUtil.updateCallbackNotifyList(new ArrayList<String>());
- return response.status(Status.OK).entity(resultMap).build();
- }
- List<String> inputUpdateList = jsonResponse.getUpdateList();
-
- String field_value = null;
- List<String> notifiyList = CachingUtil.getCallbackNotifyList();
- if(notifiyList == null || notifiyList.isEmpty()) {
- logger.info("Is cache empty? reconstructing Object from cache..");
- constructJsonCallbackFromCache();
- }
- notifiyList = CachingUtil.getCallbackNotifyList();
- JsonCallback baseRequestObj = null;
-
- if("update".equals(operation)) {
- for(String element: inputUpdateList) {
- baseRequestObj = CachingUtil.getCallBackCache(element);
- if(baseRequestObj != null) {
- logger.info("Found the element that was changed... "+element);
- break;
- }
- }
-
- List<String> updateList = jsonResponse.getUpdateList();
- for(String element : updateList) {
- if(notifiyList.contains(element)) {
- logger.info("Found the notifyOn property: "+element);
- field_value = element;
- break;
- }
- }
- if(baseRequestObj == null || field_value == null) {
- for(String element: inputUpdateList) {
- String[] elementArr = element.split(":");
- String newElement = null;
- if(elementArr.length >= 2) {
- newElement = elementArr[0]+":"+elementArr[1];
- }
- baseRequestObj = CachingUtil.getCallBackCache(newElement);
- if(baseRequestObj != null) {
- logger.info("Found the element that was changed... "+newElement);
- break;
- }
- }
- for(String element : updateList) {
- String[] elementArr = element.split(":");
- String newElement = null;
- if(elementArr.length >= 2) {
- newElement = elementArr[0]+":"+elementArr[1];
- }
- if(notifiyList.contains(newElement)) {
- logger.info("Found the notifyOn property: "+newElement);
- field_value = newElement;
- break;
- }
- }
- }
- } else {
- field_value = jsonResponse.getFull_table();
- baseRequestObj = CachingUtil.getCallBackCache(field_value);
- }
-
- if(baseRequestObj == null || field_value == null) {
- resultMap.put("Exception",
- "Oops. Something went wrong. Please make sure Callback properties are onboarded.");
- logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.INCORRECTDATA,
- ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
- return response.status(Status.BAD_REQUEST).entity(resultMap).build();
- }
- logger.info(EELFLoggerDelegate.applicationLogger, "Going through list: "+operation+ " && List: "+jsonResponse.getUpdateList());
-
- String key = "admin" + "." + "notification_master" + "." + baseRequestObj.getUuid();
- String lockId = MusicCore.createLockReference(key);
- ReturnType lockAcqResult = MusicCore.acquireLock(key, lockId);
- if(!"SUCCESS".equals(lockAcqResult.getResult().toString())) {
- logger.error(EELFLoggerDelegate.errorLogger, "Some other node is notifying the caller..: ");
- }
-
- logger.info(EELFLoggerDelegate.applicationLogger, operation+ ": Operation :: changeValue: "+changeValueMap);
- if("update".equals(operation)) {
- String notifyWhenChangeIn = baseRequestObj.getNotifyWhenChangeIn(); // conductor.plans.status
- if(null!=field_value && field_value.equals(notifyWhenChangeIn)) {
- notifyCallBackAppl(jsonResponse, baseRequestObj);
- }
- } else if("delete".equals(operation)) {
- String notifyWhenDeletesIn = baseRequestObj.getNotifyWhenDeletesIn(); // conductor.plans.status
- if(null!=field_value && field_value.equals(notifyWhenDeletesIn)) {
- notifyCallBackAppl(jsonResponse, baseRequestObj);
- }
- } else if("insert".equals(operation)) {
- String notifyWhenInsertsIn = baseRequestObj.getNotifyWhenInsertsIn(); // conductor.plans.status
- if(null!=field_value && field_value.equals(notifyWhenInsertsIn)) {
- notifyCallBackAppl(jsonResponse, baseRequestObj);
- }
- }
- MusicCore.releaseLock(lockId, true);
- } catch(Exception e) {
- e.printStackTrace();
- logger.error(EELFLoggerDelegate.errorLogger, "Exception while notifying...."+e.getMessage());
- }
- logger.info(EELFLoggerDelegate.applicationLogger, "callback is completed. Notification was sent from Music...");
- return response.status(Status.OK).entity(resultMap).build();
- }
-
- private void notifyCallBackAppl(JSONCallbackResponse jsonResponse, JsonCallback baseRequestObj) throws Exception {
- int notifytimeout = MusicUtil.getNotifyTimeout();
- int notifyinterval = MusicUtil.getNotifyInterval();
- String endpoint = baseRequestObj.getApplicationNotificationEndpoint();
- String username = baseRequestObj.getApplicationUsername();
- String password = baseRequestObj.getApplicationPassword();
- JsonNotification jsonNotification = constructJsonNotification(jsonResponse, baseRequestObj);
- jsonNotification.setPassword("************");
- jsonNotification.setOperation_type(jsonResponse.getOperation());
- logger.info(EELFLoggerDelegate.applicationLogger, "Notification Response sending is: "+jsonNotification);
- logger.info("Notification Response sending is: "+jsonNotification);
- jsonNotification.setPassword(baseRequestObj.getApplicationPassword());
- client.resource(endpoint);
- String authData = username+":"+password;
- byte[] plainCredsBytes = authData.getBytes();
- byte[] base64CredsBytes = Base64.encode(plainCredsBytes);
- String base64Creds = new String(base64CredsBytes);
- ClientConfig config = new DefaultClientConfig();
- config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
- ClientResponse response = null;
- WebResource service = null;
- boolean ok = false;
- try {
- Client client = Client.create(config);
- TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager(){
- public X509Certificate[] getAcceptedIssuers(){return null;}
- public void checkClientTrusted(X509Certificate[] certs, String authType){}
- public void checkServerTrusted(X509Certificate[] certs, String authType){}
- }};
-
- // Install the all-trusting trust manager
- try {
- SSLContext sc = SSLContext.getInstance("TLS");
- sc.init(null, trustAllCerts, new SecureRandom());
- HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
- } catch (Exception e) {
- logger.error(e.getMessage(), e);
- }
-
- try {
- SSLContext sslcontext = SSLContext.getInstance( "TLS" );
- sslcontext.init( null, null, null );
- Map<String, Object> properties = config.getProperties();
- HTTPSProperties httpsProperties = new HTTPSProperties(
- new HostnameVerifier() {
- @Override
- public boolean verify( String s, SSLSession sslSession ) {
- return true;
- }
- }, sslcontext
- );
- properties.put( HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, httpsProperties );
- HttpsURLConnection.setDefaultHostnameVerifier (new HostnameVerifier() {
- @Override
- public boolean verify(String hostname, SSLSession session) {
- return true;
- }
- });
- Client.create( config );
- }
- catch ( KeyManagementException | NoSuchAlgorithmException e ) {
- throw new RuntimeException( e );
- }
-
- service = client.resource(endpoint);
-
- response = service.header("Authorization", "Basic " + base64Creds).accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON)
- .post(ClientResponse.class, jsonNotification);
-
- } catch (Exception chf) {
- logger.info(EELFLoggerDelegate.applicationLogger, "Is Service down?");
- logger.info("An Exception occured while notifying. "+chf+ " : "+chf.getMessage() +" ...Retrying for: "+notifytimeout);
- }
- if(response != null && response.getStatus() == 200) ok = true;
- if(!ok) {
- long now= System.currentTimeMillis();
- long end = now+notifytimeout;
- while(! ok) {
- logger.info(EELFLoggerDelegate.applicationLogger, "retrying since error in notifying callback for "+notifytimeout+"ms");
- logger.info("retrying since error in notifying callback.. response status: "+ (response == null ? "404" : response.getStatus()));
- try {
- ok = true;
- response = service.header("Authorization", "Basic " + base64Creds).accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON)
- .post(ClientResponse.class, jsonNotification);
- if(response != null && response.getStatus() == 200) ok = true;
- else if(System.currentTimeMillis() < end) {
- try{ Thread.sleep(notifyinterval); } catch(Exception e1) {}
- ok = false;
- }
- }catch (Exception e) {
- logger.info(EELFLoggerDelegate.applicationLogger, "Retry until "+(end-System.currentTimeMillis()));
- if(response == null && System.currentTimeMillis() < end) ok = false;
- else ok = true;
- try{ Thread.sleep(notifyinterval); } catch(Exception e1) {}
- }
- }
- }
-
- if(response == null) {
- logger.error(EELFLoggerDelegate.errorLogger, "Can NOT notify the caller as caller failed to respond..");
- return;
- }
- try {
- JsonNotifyClientResponse responseStr = response.getEntity(JsonNotifyClientResponse.class);
- logger.info(EELFLoggerDelegate.applicationLogger, "Response from Notified client: "+responseStr);
- logger.info("Response from Notified client: "+responseStr);
- } catch(Exception e) {
- logger.info("Exception while reading response from Caller");
- logger.error("Exception while reading response from Caller");
- logger.error(EELFLoggerDelegate.errorLogger, "Can NOT notify the caller as caller failed to respond..");
- }
- }