Fix sonar issues in models: sdc to vfc
[policy/models.git] / models-interactions / model-impl / vfc / src / main / java / org / onap / policy / vfc / VfcManager.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * Copyright (C) 2017-2019 Intel Corp. All rights reserved.
4  * Modifications Copyright (C) 2019 Nordix Foundation.
5  * Modifications Copyright (C) 2018-2019 AT&T Corporation. 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.vfc;
23
24 import com.google.gson.JsonSyntaxException;
25
26 import java.util.HashMap;
27 import java.util.Map;
28
29 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
30 import org.onap.policy.common.endpoints.utils.NetLoggerUtil;
31 import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;
32 import org.onap.policy.rest.RestManager;
33 import org.onap.policy.rest.RestManager.Pair;
34 import org.onap.policy.vfc.util.Serialization;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37
38 public final class VfcManager implements Runnable {
39
40     private String vfcUrlBase;
41     private String username;
42     private String password;
43     private VfcRequest vfcRequest;
44     private VfcCallback callback;
45     private static final Logger logger = LoggerFactory.getLogger(VfcManager.class);
46
47     // The REST manager used for processing REST calls for this VFC manager
48     private RestManager restManager;
49
50     @FunctionalInterface
51     public interface VfcCallback {
52         void onResponse(VfcResponse responseError);
53     }
54
55     /**
56      * Constructor.
57      *
58      * @param cb Callback method to call when response
59      * @param request request
60      * @param url URL to VFC component
61      * @param user username
62      * @param pwd password
63      */
64     public VfcManager(VfcCallback cb, VfcRequest request, String url, String user, String pwd) {
65         if (cb == null || request == null) {
66             throw new IllegalArgumentException(
67                     "the parameters \"cb\" and \"request\" on the VfcManager constructor may not be null");
68         }
69         if (url == null) {
70             throw new IllegalArgumentException(
71                     "the \"url\" parameter on the VfcManager constructor may not be null");
72         }
73         callback = cb;
74         vfcRequest = request;
75         vfcUrlBase = url;
76         username = user;
77         password = pwd;
78
79         restManager = new RestManager();
80     }
81
82     /**
83      * Set the parameters.
84      *
85      * @param baseUrl base URL
86      * @param name username
87      * @param pwd password
88      */
89     public void setVfcParams(String baseUrl, String name, String pwd) {
90         vfcUrlBase = baseUrl + "/api/nslcm/v1";
91         username = name;
92         password = pwd;
93     }
94
95     @Override
96     public void run() {
97         Map<String, String> headers = new HashMap<>();
98         Pair<Integer, String> httpDetails;
99
100         VfcResponse responseError = new VfcResponse();
101         responseError.setResponseDescriptor(new VfcResponseDescriptor());
102         responseError.getResponseDescriptor().setStatus("error");
103
104         headers.put("Accept", "application/json");
105         String vfcUrl = vfcUrlBase + "/ns/" + vfcRequest.getNsInstanceId() + "/heal";
106         try {
107             String vfcRequestJson = Serialization.gsonPretty.toJson(vfcRequest);
108             NetLoggerUtil.log(EventType.OUT, CommInfrastructure.REST, vfcUrl, vfcRequestJson);
109
110             httpDetails = restManager.post(vfcUrl, username, password, headers, "application/json", vfcRequestJson);
111         } catch (Exception e) {
112             logger.error(e.getMessage(), e);
113             this.callback.onResponse(responseError);
114             return;
115         }
116
117         if (httpDetails == null) {
118             this.callback.onResponse(responseError);
119             return;
120         }
121
122         if (httpDetails.first != 202) {
123             logger.warn("VFC Heal Restcall failed");
124             return;
125         }
126
127         try {
128             VfcResponse response = Serialization.gsonPretty.fromJson(httpDetails.second, VfcResponse.class);
129             NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST, vfcUrl, httpDetails.second);
130             String body = Serialization.gsonPretty.toJson(response);
131             logger.debug("Response to VFC Heal post:");
132             logger.debug(body);
133
134             String jobId = response.getJobId();
135             int attemptsLeft = 20;
136
137             String urlGet = vfcUrlBase + "/jobs/" + jobId;
138             VfcResponse responseGet = null;
139
140             while (attemptsLeft-- > 0) {
141                 NetLoggerUtil.getNetworkLogger().info("[OUT|{}|{}|]", "VFC", urlGet);
142                 Pair<Integer, String> httpDetailsGet = restManager.get(urlGet, username, password, headers);
143                 responseGet = Serialization.gsonPretty.fromJson(httpDetailsGet.second, VfcResponse.class);
144                 NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST, vfcUrl, httpDetailsGet.second);
145                 responseGet.setRequestId(vfcRequest.getRequestId().toString());
146                 body = Serialization.gsonPretty.toJson(responseGet);
147                 logger.debug("Response to VFC Heal get:");
148                 logger.debug(body);
149
150                 String responseStatus = responseGet.getResponseDescriptor().getStatus();
151                 if (httpDetailsGet.first == 200
152                         && ("finished".equalsIgnoreCase(responseStatus) || "error".equalsIgnoreCase(responseStatus))) {
153                     logger.debug("VFC Heal Status {}", responseGet.getResponseDescriptor().getStatus());
154                     this.callback.onResponse(responseGet);
155                     break;
156                 }
157                 Thread.sleep(20000);
158             }
159             boolean isTimeout = (attemptsLeft <= 0) && (responseGet != null)
160                             && (responseGet.getResponseDescriptor() != null);
161             isTimeout = isTimeout && (responseGet.getResponseDescriptor().getStatus() != null)
162                             && (!responseGet.getResponseDescriptor().getStatus().isEmpty());
163             if (isTimeout) {
164                 logger.debug("VFC timeout. Status: ({})", responseGet.getResponseDescriptor().getStatus());
165                 this.callback.onResponse(responseGet);
166             }
167         } catch (JsonSyntaxException e) {
168             logger.error("Failed to deserialize into VfcResponse {}", e.getLocalizedMessage(), e);
169         } catch (InterruptedException e) {
170             logger.error("Interrupted exception: {}", e.getLocalizedMessage(), e);
171             Thread.currentThread().interrupt();
172         } catch (Exception e) {
173             logger.error("Unknown error deserializing into VfcResponse {}", e.getLocalizedMessage(), e);
174         }
175     }
176
177     /**
178      * Protected setter for rest manager to allow mocked rest manager to be used for testing.
179      *
180      * @param restManager the test REST manager
181      */
182     protected void setRestManager(final RestManager restManager) {
183         this.restManager = restManager;
184     }
185 }