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