Changes for the async support in MDONS
[sdnc/northbound.git] / optical-service / provider / src / main / java / org / onap / sdnc / northbound / asyncrequests / AsyncNotificationHandling.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : SDN-C
4  * ================================================================================
5  * Copyright (C) 2019-2020 Fujitsu Limited Intellectual Property. All rights
6  *                             reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.sdnc.northbound.asyncrequests;
23
24 import javax.servlet.Servlet;
25 import javax.servlet.ServletException;
26 import javax.servlet.http.HttpServlet;
27 import javax.servlet.http.HttpServletRequest;
28 import javax.servlet.http.HttpServletResponse;
29 import java.util.Properties;
30
31 import java.io.Writer;
32 import java.io.StringWriter;
33 import java.io.BufferedReader;
34 import java.io.File;
35 import java.io.FileInputStream;
36 import java.io.FileNotFoundException;
37 import java.io.IOException;
38 import java.util.stream.Collectors;
39
40 import org.apache.velocity.VelocityContext;
41 import org.apache.velocity.app.VelocityEngine;
42 import org.apache.velocity.Template;
43
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46 import org.json.JSONArray;
47 import org.json.JSONObject;
48 import org.osgi.service.component.annotations.Component;
49
50 @Component(immediate = true, property = {"alias=/asyncNotification", "servlet-name=AsyncNotification"})
51 public class AsyncNotificationHandling extends HttpServlet implements Servlet {
52
53     private static final long serialVersionUID = 1L;
54
55     private final Logger LOG = LoggerFactory.getLogger(AsyncNotificationHandling.class);
56
57     private static final String PARAMETER_NAME = "parameter-name";
58     private static final String STRING_VALUE = "string-value";
59     private static final String REQUEST_ID = "request-id";
60     private static final String SVC_REQUEST_ID = "svc-request-id";
61     private static final String RESPONSE_CODE = "response-code";
62     private static final String ACK_FINAL_INDICATOR = "ack-final-indicator";
63     private static final String CONFIGURATION_RESPONSE = "configuration-response-common";
64     private static final String PROPERTIES_PATH = "/opt/onap/sdnc/data/properties/";
65     private static final String TEMPLATE_NAME = "rpc-message-sliapi-execute-async.vt";
66     private static final String UTF_8 = "UTF-8";
67
68     /**
69      * Handles async request for different domain controllers
70      */
71
72     @Override
73     public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
74
75         LOG.info("Reached async servlet");
76         BufferedReader requestInput = null;
77         try {
78             requestInput = request.getReader();
79         } catch (Exception e) {
80             LOG.error("Unable to read input from request", e);
81         }
82
83         if (requestInput == null) {
84             return;
85         }
86         String json = requestInput.lines().collect(Collectors.joining());
87         LOG.info("Async Request payload {}", json);
88         if (json == null) {
89             return;
90         }
91
92         JSONObject jsonObj = new JSONObject(json);
93         JSONObject input = jsonObj.getJSONObject("input");
94
95         if (input.has(CONFIGURATION_RESPONSE)) {
96             JSONObject payloadString = null;
97
98             try {
99                 payloadString = input.getJSONObject(CONFIGURATION_RESPONSE);
100                 String rpcMessageBody = buildAsyncNotifRPCMsgRoadm(payloadString);
101                 LOG.debug("rpc message body {}", rpcMessageBody);
102                 invokeRPC(rpcMessageBody);
103             } catch (Exception e) {
104                 LOG.error("Unable to build rpc message body::", e);
105             }
106         } else {
107             LOG.info("Async request received for wrong domain");
108         }
109
110     }
111
112     private void invokeRPC(String rpcMsgbody) {
113         try {
114             Properties baseProperties = new Properties(); 
115             baseProperties.load(new FileInputStream(new File("/opt/onap/sdnc/data/properties/optical-service-dg.properties")));
116             String odlUrlBase = baseProperties.getProperty("odlUrlBase");
117             String odlUser = baseProperties.getProperty("controller.user");
118             String odlPassword = baseProperties.getProperty("controller.pwd");
119             String sdncEndpoint = baseProperties.getProperty("sdncEndpoint");
120
121             if ((odlUrlBase != null) && (odlUrlBase.length() > 0)) {
122                 SdncOdlConnection conn =
123                         SdncOdlConnection.newInstance(odlUrlBase + "/" + sdncEndpoint, odlUser, odlPassword);
124
125                 conn.send("POST", "application/json", rpcMsgbody);
126             } else {
127                 LOG.info("POST message body would be:\n {}", rpcMsgbody);
128             }
129         } catch (Exception e) {
130             LOG.error("Unable to process message", e);
131         }
132
133     }
134
135     private String buildAsyncNotifRPCMsgRoadm(JSONObject payloadString) throws IOException {
136         VelocityEngine velocityEngine = new VelocityEngine();
137
138         Properties props = new Properties();
139         props.put("file.resource.loader.path", PROPERTIES_PATH);
140         velocityEngine.init(props);
141
142         String sliParameters = "sli_parameters";
143
144         JSONArray sliParametersArray = new JSONArray();
145
146         VelocityContext context = new VelocityContext();
147
148         context.put("rpc_name", "handle-async-notif");
149         String requestId = payloadString.getString(SVC_REQUEST_ID);
150         String responseCode = payloadString.getString(RESPONSE_CODE);
151         String ackIndicator = payloadString.getString(ACK_FINAL_INDICATOR);
152
153         sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, REQUEST_ID).put(STRING_VALUE, requestId));
154         sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, RESPONSE_CODE).put(STRING_VALUE, responseCode));
155         sliParametersArray
156                 .put(new JSONObject().put(PARAMETER_NAME, ACK_FINAL_INDICATOR).put(STRING_VALUE, ackIndicator));
157
158         context.put(sliParameters, sliParametersArray);
159
160         Writer writer = new StringWriter();
161         velocityEngine.mergeTemplate(TEMPLATE_NAME, UTF_8, context, writer);
162         writer.flush();
163
164         return writer.toString();
165
166     }
167
168 }