Exception test Fix
[nonrtric.git] / policy-agent / src / main / java / org / oransc / policyagent / dmaap / DmaapMessageHandler.java
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  * %%
5  * Copyright (C) 2019 Nordix Foundation
6  * %%
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ========================LICENSE_END===================================
19  */
20
21 package org.oransc.policyagent.dmaap;
22
23 import com.fasterxml.jackson.core.JsonProcessingException;
24 import com.fasterxml.jackson.databind.ObjectMapper;
25 import java.io.IOException;
26 import java.util.Optional;
27 import java.util.Properties;
28 import org.json.JSONException;
29 import org.json.JSONObject;
30 import org.json.JSONTokener;
31 import org.oransc.policyagent.clients.AsyncRestClient;
32 import org.oransc.policyagent.configuration.ApplicationConfig;
33 import org.oransc.policyagent.controllers.PolicyController;
34 import org.oransc.policyagent.model.DmaapRequestMessage;
35 import org.oransc.policyagent.model.DmaapResponseMessage;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38 import org.springframework.beans.factory.annotation.Autowired;
39 import org.springframework.http.ResponseEntity;
40 import org.springframework.scheduling.annotation.Async;
41 import org.springframework.stereotype.Component;
42
43 @Component
44 public class DmaapMessageHandler {
45
46     private static final Logger logger = LoggerFactory.getLogger(DmaapMessageHandler.class);
47
48     private boolean initialize = false;
49     @Autowired
50     private ObjectMapper mapper;
51     @Autowired
52     private PolicyController policyController;
53     private AsyncRestClient restClient;
54     @Autowired
55     private ApplicationConfig applicationConfig;
56     private String topic = "";
57
58     // The publish properties is corrupted. It contains the subscribe property values.
59     @Async("threadPoolTaskExecutor")
60     public void handleDmaapMsg(String msg) {
61         if (!initialize) {
62             init();
63         }
64         DmaapRequestMessage dmaapRequestMessage = null;
65         Optional<String> dmaapResponse = null;
66         // Process the message
67         /**
68          * Sample Request Message from DMAAP { "type": "request", "correlationId":
69          * "c09ac7d1-de62-0016-2000-e63701125557-201", "target": "policy-agent", "timestamp": "2019-05-14T11:44:51.36Z",
70          * "apiVersion": "1.0", "originatorId": "849e6c6b420", "requestId": "23343221", "operation": "getPolicySchemas",
71          * "payload": "{\"ricName\":\"ric1\"}" }
72          *
73          * -------------------------------------------------------------------------------------------------------------
74          * Sample Response Message to DMAAP {type=response, correlationId=c09ac7d1-de62-0016-2000-e63701125557-201,
75          * timestamp=null, originatorId=849e6c6b420, requestId=23343221, status=200 OK, message=[]}
76          * -------------------------------------------------------------------------------------------------------------
77          */
78         try {
79             dmaapRequestMessage = mapper.readValue(msg, DmaapRequestMessage.class);
80             // Call the Controller
81             logger.debug("Invoke the Policy Agent Controller");
82             dmaapResponse = invokeController(dmaapRequestMessage);
83             // Post the Response message to the DMAAP bus
84             logger.debug("DMAAP Response Message to Client- {}", dmaapResponse);
85             if (dmaapResponse.isPresent()) {
86                 restClient.post("A1-POLICY-AGENT-WRITE", dmaapResponse.get()).block(); //
87             }
88         } catch (IOException e) {
89             logger.error("Exception occured during message processing", e);
90         }
91     }
92
93     private Optional<String> invokeController(DmaapRequestMessage dmaapRequestMessage) {
94         String formattedString = "";
95         String ricName;
96         String instance;
97         String jsonBody;
98         logger.debug("Payload from the Message - {}", dmaapRequestMessage.getPayload());
99         try {
100             formattedString = new JSONTokener(dmaapRequestMessage.getPayload()).nextValue().toString();
101             logger.debug("Removed the Escape charater in payload- {}", formattedString);
102         } catch (JSONException e) {
103             logger.error("Exception occurred during formating Payload- {}", dmaapRequestMessage.getPayload());
104         }
105         JSONObject jsonObject = new JSONObject(formattedString);
106         switch (dmaapRequestMessage.getOperation()) {
107             case "getPolicySchemas":
108                 ricName = (String) jsonObject.get("ricName");
109                 logger.debug("Received the request for getPolicySchemas with Ric Name- {}", ricName);
110                 return getDmaapResponseMessage(dmaapRequestMessage, policyController.getPolicySchemas(ricName));
111             case "getPolicySchema":
112                 String policyTypeId = (String) jsonObject.get("id");
113                 logger.debug("Received the request for getPolicySchema with Policy Type Id- {}", policyTypeId);
114                 return getDmaapResponseMessage(dmaapRequestMessage, policyController.getPolicySchema(policyTypeId));
115             case "getPolicyTypes":
116                 ricName = (String) jsonObject.get("ricName");
117                 logger.debug("Received the request for getPolicyTypes with Ric Name- {}", ricName);
118                 return getDmaapResponseMessage(dmaapRequestMessage, policyController.getPolicyTypes(ricName));
119             case "getPolicy":
120                 instance = (String) jsonObject.get("instance");
121                 logger.debug("Received the request for getPolicy with Instance- {}", instance);
122                 return getDmaapResponseMessage(dmaapRequestMessage, policyController.getPolicy(instance));
123             case "deletePolicy":
124                 instance = (String) jsonObject.get("instance");
125                 logger.debug("Received the request for deletePolicy with Instance- {}", instance);
126                 return getDmaapResponseMessage(dmaapRequestMessage, policyController.deletePolicy(instance).block());
127             case "putPolicy":
128                 String type = (String) jsonObject.get("type");
129                 String putPolicyInstance = (String) jsonObject.get("instance");
130                 String putPolicyRic = (String) jsonObject.get("ric");
131                 String service = (String) jsonObject.get("service");
132                 jsonBody = (String) jsonObject.get("jsonBody");
133                 return getDmaapResponseMessage(dmaapRequestMessage,
134                         policyController.putPolicy(type, putPolicyInstance, putPolicyRic, service, jsonBody).block());
135             case "getPolicies":
136                 String getPolicyType = (String) jsonObject.get("type");
137                 instance = (String) jsonObject.get("instance");
138                 String getPolicyRic = (String) jsonObject.get("ric");
139                 String getPolicyService = (String) jsonObject.get("service");
140                 jsonBody = (String) jsonObject.get("jsonBody");
141                 return getDmaapResponseMessage(dmaapRequestMessage, policyController
142                         .putPolicy(getPolicyType, instance, getPolicyRic, getPolicyService, jsonBody).block());
143             default:
144                 break;
145         }
146         return Optional.empty();
147     }
148
149     private Optional<String> getDmaapResponseMessage(DmaapRequestMessage dmaapRequestMessage,
150             ResponseEntity<?> policySchemas) {
151         DmaapResponseMessage dmaapResponseMessage = DmaapResponseMessage.builder()
152                 .status(policySchemas.getStatusCode().toString()).message(policySchemas.getBody().toString())
153                 .type("response").correlationId(dmaapRequestMessage.getCorrelationId())
154                 .originatorId(dmaapRequestMessage.getOriginatorId()).requestId(dmaapRequestMessage.getRequestId())
155                 .build();
156         try {
157             return Optional.of(mapper.writeValueAsString(dmaapResponseMessage));
158         } catch (JsonProcessingException e) {
159             logger.error("Exception occured during getDmaapResponseMessage", e);
160         }
161         return Optional.empty();
162     }
163
164     public void init() {
165         logger.debug("Reading DMAAP Publisher bus details from Application Config");
166         Properties dmaapPublisherConfig = applicationConfig.getDmaapPublisherConfig();
167         String host = (String) dmaapPublisherConfig.get("ServiceName");
168         topic = dmaapPublisherConfig.getProperty("topic");
169         logger.debug("Read the topic & Service Name - {} , {}", host, topic);
170         this.restClient = new AsyncRestClient("http://" + host + "/"); // get this value from application config
171         initialize = true;
172
173     }
174 }