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