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