Fix sonar issues in models: sdc to vfc
[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 import com.google.gson.JsonSyntaxException;
26
27 import java.util.HashMap;
28 import java.util.Map;
29
30 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
31 import org.onap.policy.common.endpoints.utils.NetLoggerUtil;
32 import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;
33 import org.onap.policy.rest.RestManager;
34 import org.onap.policy.rest.RestManager.Pair;
35 import org.onap.policy.sdnc.util.Serialization;
36
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 public final class SdncManager implements Runnable {
41
42     private String sdncUrlBase;
43     private String username;
44     private String password;
45     private SdncRequest sdncRequest;
46     private SdncCallback callback;
47     private static final Logger logger = LoggerFactory.getLogger(SdncManager.class);
48
49     // The REST manager used for processing REST calls for this Sdnc manager
50     private RestManager restManager;
51
52     @FunctionalInterface
53     public interface SdncCallback {
54         public void onCallback(SdncResponse response);
55     }
56
57     /**
58      * Constructor.
59      *
60      * @param cb Callback method
61      * @param request request
62      */
63     public SdncManager(SdncCallback cb, SdncRequest request, String url,
64             String user, String password) {
65         if (cb == null || request == null) {
66             throw new IllegalArgumentException(
67                   "the parameters \"callback\" and \"request\" on the SdncManager constructor may not be null"
68             );
69         }
70         this.callback = cb;
71         this.sdncRequest = request;
72         if (url == null) {
73             throw new IllegalArgumentException(
74                     "the \"url\" parameter on the SdncManager constructor may not be null"
75               );
76         }
77         this.sdncUrlBase = url;
78         this.username = user;
79         this.password = password;
80
81         restManager = new RestManager();
82     }
83
84     /**
85      * Set the parameters.
86      *
87      * @param baseUrl base URL
88      * @param name username
89      * @param pwd password
90      */
91     public void setSdncParams(String baseUrl, String name, String pwd) {
92         sdncUrlBase = baseUrl;
93         username = name;
94         password = pwd;
95     }
96
97     @Override
98     public void run() {
99         Map<String, String> headers = new HashMap<>();
100         Pair<Integer, String> httpDetails;
101
102         SdncResponse responseError = new SdncResponse();
103         SdncResponseOutput responseOutput = new SdncResponseOutput();
104         responseOutput.setResponseCode("404");
105         responseError.setResponseOutput(responseOutput);
106
107         headers.put("Accept", "application/json");
108         String sdncUrl = sdncUrlBase + sdncRequest.getUrl();
109
110         try {
111             String sdncRequestJson = Serialization.gsonPretty.toJson(sdncRequest);
112             NetLoggerUtil.log(EventType.OUT, CommInfrastructure.REST, sdncUrl, sdncRequestJson);
113             logger.info("[OUT|{}|{}|]{}{}", CommInfrastructure.REST, sdncUrl, NetLoggerUtil.SYSTEM_LS, sdncRequestJson);
114
115             httpDetails = restManager.post(sdncUrl, username, password, headers, "application/json",
116                                            sdncRequestJson);
117         } catch (Exception e) {
118             logger.info(e.getMessage(), e);
119             this.callback.onCallback(responseError);
120             return;
121         }
122
123         if (httpDetails == null) {
124             this.callback.onCallback(responseError);
125             return;
126         }
127
128         try {
129             SdncResponse response = Serialization.gsonPretty.fromJson(httpDetails.second, SdncResponse.class);
130             NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST, sdncUrl, httpDetails.second);
131             logger.info("[IN|{}|{}|]{}{}", "Sdnc", sdncUrl, NetLoggerUtil.SYSTEM_LS, httpDetails.second);
132             String body = Serialization.gsonPretty.toJson(response);
133             logger.info("Response to Sdnc Heal post:");
134             logger.info(body);
135             response.setRequestId(sdncRequest.getRequestId().toString());
136
137             if (!"200".equals(response.getResponseOutput().getResponseCode())) {
138                 logger.info(
139                     "Sdnc Heal Restcall failed with http error code {} {}", httpDetails.first, httpDetails.second
140                 );
141             }
142
143             this.callback.onCallback(response);
144         } catch (JsonSyntaxException e) {
145             logger.info("Failed to deserialize into SdncResponse {}", e.getLocalizedMessage(), e);
146         } catch (Exception e) {
147             logger.info("Unknown error deserializing into SdncResponse {}", e.getLocalizedMessage(), e);
148         }
149     }
150
151     /**
152      * Protected setter for rest manager to allow mocked rest manager to be used for testing.
153      * @param restManager the test REST manager
154      */
155     protected void setRestManager(final RestManager restManager) {
156         this.restManager = restManager;
157     }
158 }