Update SDNC changes
[policy/models.git] / models-interactions / model-impl / sdnc / src / main / java / org / onap / policy / sdnc / SdncManager.java
1 /*
2  * ============LICENSE_START=======================================================
3  * Copyright (C) 2018 Huawei. All rights reserved.
4  * ================================================================================
5  * Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved
6  * Modifications Copyright (C) 2019 Nordix Foundation.
7  * Modifications Copyright (C) 2019 Samsung Electronics Co., Ltd.
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
12  *
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  *
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.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.policy.sdnc;
24
25
26 import com.google.gson.JsonSyntaxException;
27
28 import java.util.HashMap;
29 import java.util.Map;
30
31 import org.drools.core.WorkingMemory;
32 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
33 import org.onap.policy.common.endpoints.utils.NetLoggerUtil;
34 import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;
35 import org.onap.policy.drools.system.PolicyEngine;
36 import org.onap.policy.rest.RestManager;
37 import org.onap.policy.rest.RestManager.Pair;
38 import org.onap.policy.sdnc.util.Serialization;
39
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 public final class SdncManager implements Runnable {
44
45     private String sdncUrlBase;
46     private String username;
47     private String password;
48     private SdncRequest sdncRequest;
49     private WorkingMemory workingMem;
50     private static final Logger logger = LoggerFactory.getLogger(SdncManager.class);
51
52     // The REST manager used for processing REST calls for this Sdnc manager
53     private RestManager restManager;
54
55     /**
56      * Constructor.
57      *
58      * @param wm Drools working memory
59      * @param request request
60      */
61     public SdncManager(WorkingMemory wm, SdncRequest request) {
62         if (wm == null || request == null) {
63             throw new IllegalArgumentException(
64                   "the parameters \"wm\" and \"request\" on the SdncManager constructor may not be null"
65             );
66         }
67         workingMem = wm;
68         sdncRequest = request;
69
70         restManager = new RestManager();
71
72         setSdncParams(getPeManagerEnvProperty("sdnc.url"), getPeManagerEnvProperty("sdnc.username"),
73             getPeManagerEnvProperty("sdnc.password"));
74     }
75
76     /**
77      * Set the parameters.
78      *
79      * @param baseUrl base URL
80      * @param name username
81      * @param pwd password
82      */
83     public void setSdncParams(String baseUrl, String name, String pwd) {
84         sdncUrlBase = baseUrl;
85         username = name;
86         password = pwd;
87     }
88
89     @Override
90     public void run() {
91         Map<String, String> headers = new HashMap<>();
92         Pair<Integer, String> httpDetails;
93
94         SdncResponse responseError = new SdncResponse();
95         SdncResponseOutput responseOutput = new SdncResponseOutput();
96         responseOutput.setResponseCode("404");
97         responseError.setResponseOutput(responseOutput);
98
99         headers.put("Accept", "application/json");
100         String sdncUrl = sdncUrlBase + sdncRequest.getUrl();
101
102         try {
103             String sdncRequestJson = Serialization.gsonPretty.toJson(sdncRequest);
104             NetLoggerUtil.log(EventType.OUT, CommInfrastructure.REST, sdncUrl, sdncRequestJson);
105             logger.info("[OUT|{}|{}|]{}{}", CommInfrastructure.REST, sdncUrl, NetLoggerUtil.SYSTEM_LS, sdncRequestJson);
106
107             httpDetails = restManager.post(sdncUrl, username, password, headers, "application/json",
108                                            sdncRequestJson);
109         } catch (Exception e) {
110             logger.info(e.getMessage(), e);
111             workingMem.insert(responseError);
112             return;
113         }
114
115         if (httpDetails == null) {
116             workingMem.insert(responseError);
117             return;
118         }
119
120         try {
121             SdncResponse response = Serialization.gsonPretty.fromJson(httpDetails.second, SdncResponse.class);
122             NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST, sdncUrl, httpDetails.second);
123             logger.info("[IN|{}|{}|]{}{}", "Sdnc", sdncUrl, NetLoggerUtil.SYSTEM_LS, httpDetails.second);
124             String body = Serialization.gsonPretty.toJson(response);
125             logger.info("Response to Sdnc Heal post:");
126             logger.info(body);
127             response.setRequestId(sdncRequest.getRequestId().toString());
128
129             if (!response.getResponseOutput().getResponseCode().equals("200")) {
130                 logger.info(
131                     "Sdnc Heal Restcall failed with http error code {} {}", httpDetails.first, httpDetails.second
132                 );
133             }
134
135             workingMem.insert(response);
136         } catch (JsonSyntaxException e) {
137             logger.info("Failed to deserialize into SdncResponse {}", e.getLocalizedMessage(), e);
138         } catch (Exception e) {
139             logger.info("Unknown error deserializing into SdncResponse {}", e.getLocalizedMessage(), e);
140         }
141     }
142
143     /**
144      * Protected setter for rest manager to allow mocked rest manager to be used for testing.
145      * @param restManager the test REST manager
146      */
147     protected void setRestManager(final RestManager restManager) {
148         this.restManager = restManager;
149     }
150
151     /**
152      * This method reads and validates environmental properties coming from the policy engine. Null properties cause
153      * an {@link IllegalArgumentException} runtime exception to be thrown
154      * @param  enginePropertyName name of the parameter to retrieve
155      * @return the property value
156      */
157
158     private String getPeManagerEnvProperty(String enginePropertyName) {
159         String enginePropertyValue = PolicyEngine.manager.getEnvironmentProperty(enginePropertyName);
160         if (enginePropertyValue == null) {
161             throw new IllegalArgumentException(
162                 "The value of policy engine manager environment property \""
163                    + enginePropertyName + "\" may not be null"
164             );
165         }
166         return enginePropertyValue;
167     }
168 }