Java 17 Upgrade
[policy/models.git] / models-interactions / model-actors / actor.so / src / main / java / org / onap / policy / controlloop / actor / so / VfModuleDelete.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2020 Wipro Limited.
7  * Modifications Copyright (C) 2023 Nordix Foundation.
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.controlloop.actor.so;
24
25 import jakarta.ws.rs.client.InvocationCallback;
26 import jakarta.ws.rs.core.MediaType;
27 import jakarta.ws.rs.core.Response;
28 import java.net.URI;
29 import java.net.http.HttpRequest;
30 import java.net.http.HttpRequest.BodyPublishers;
31 import java.net.http.HttpRequest.Builder;
32 import java.net.http.HttpResponse;
33 import java.net.http.HttpResponse.BodyHandlers;
34 import java.nio.charset.StandardCharsets;
35 import java.util.Base64;
36 import java.util.List;
37 import java.util.Map;
38 import java.util.Map.Entry;
39 import java.util.concurrent.CompletableFuture;
40 import org.apache.commons.lang3.StringUtils;
41 import org.apache.commons.lang3.tuple.Pair;
42 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
43 import org.onap.policy.common.endpoints.http.client.HttpClient;
44 import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;
45 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
46 import org.onap.policy.controlloop.actorserviceprovider.OperationProperties;
47 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
48 import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpPollingConfig;
49 import org.onap.policy.controlloop.actorserviceprovider.pipeline.PipelineControllerFuture;
50 import org.onap.policy.so.SoOperationType;
51 import org.onap.policy.so.SoRequest;
52 import org.onap.policy.so.SoRequestDetails;
53 import org.onap.policy.so.SoResponse;
54
55 /**
56  * Operation to delete a VF Module. When this completes successfully, it decrements its VF
57  * Count property.
58  */
59 public class VfModuleDelete extends SoOperation {
60     public static final String NAME = "VF Module Delete";
61
62     private static final String PATH_PREFIX = "/";
63
64     // @formatter:off
65     private static final List<String> PROPERTY_NAMES = List.of(
66                             OperationProperties.AAI_SERVICE,
67                             OperationProperties.AAI_VNF,
68                             OperationProperties.AAI_DEFAULT_CLOUD_REGION,
69                             OperationProperties.AAI_DEFAULT_TENANT,
70                             OperationProperties.DATA_VF_COUNT);
71     // @formatter:on
72
73     /**
74      * Constructs the object.
75      *
76      * @param params operation parameters
77      * @param config configuration for this operation
78      */
79     public VfModuleDelete(ControlLoopOperationParams params, HttpPollingConfig config) {
80         super(params, config, PROPERTY_NAMES, params.getTargetEntityIds());
81
82         setUsePolling();
83
84         // ensure we have the necessary parameters
85         validateTarget();
86     }
87
88     @Override
89     protected CompletableFuture<OperationOutcome> startOperationAsync(int attempt, OperationOutcome outcome) {
90
91         // starting a whole new attempt - reset the count
92         resetPollCount();
93
94         Pair<String, SoRequest> pair = makeRequest();
95         SoRequest request = pair.getRight();
96         String url = getPath() + pair.getLeft();
97
98         String strRequest = prettyPrint(request);
99         logMessage(EventType.OUT, CommInfrastructure.REST, url, strRequest);
100
101         Map<String, Object> headers = createSimpleHeaders();
102
103         // @formatter:off
104         return handleResponse(outcome, url,
105             callback -> delete(url, headers, MediaType.APPLICATION_JSON, strRequest, callback));
106         // @formatter:on
107     }
108
109     /**
110      * Issues an HTTP "DELETE" request, containing a request body, using the java built-in
111      * HttpClient, as the JerseyClient does not support it. This will add the content-type
112      * and authorization headers, so they should not be included within "headers".
113      *
114      * @param uri URI suffix, to be appended to the URI prefix
115      * @param headers headers to be included
116      * @param contentType content type of the request
117      * @param request request to be posted
118      * @param callback response callbacks
119      * @return a future to await the response. Note: it's untested whether canceling this
120      *         future will actually cancel the underlying HTTP request
121      */
122     protected CompletableFuture<Response> delete(String uri, Map<String, Object> headers, String contentType,
123                     String request, InvocationCallback<Response> callback) {
124         // TODO move to HttpOperation
125
126         final String url = getClient().getBaseUrl() + uri;
127
128         var builder = HttpRequest.newBuilder(URI.create(url));
129         builder = builder.header("Content-type", contentType);
130         builder = addAuthHeader(builder);
131
132         for (Entry<String, Object> header : headers.entrySet()) {
133             builder = builder.header(header.getKey(), header.getValue().toString());
134         }
135
136         PipelineControllerFuture<Response> controller = new PipelineControllerFuture<>();
137
138         HttpRequest req = builder.method("DELETE", BodyPublishers.ofString(request)).build();
139
140         CompletableFuture<HttpResponse<String>> future = makeHttpClient().sendAsync(req, BodyHandlers.ofString());
141
142         // propagate "cancel" to the future
143         controller.add(future);
144
145         future.thenApply(response -> new RestManagerResponse(response.statusCode(), response.body(), getCoder()))
146                         .whenComplete((resp, thrown) -> {
147                             if (thrown != null) {
148                                 callback.failed(thrown);
149                                 controller.completeExceptionally(thrown);
150                             } else {
151                                 callback.completed(resp);
152                                 controller.complete(resp);
153                             }
154                         });
155
156         return controller;
157     }
158
159     /**
160      * Adds the authorization header to the HTTP request, if configured.
161      *
162      * @param builder request builder to which the header should be added
163      * @return the builder
164      */
165     protected Builder addAuthHeader(Builder builder) {
166         // TODO move to HttpOperation
167         final HttpClient client = getClient();
168         String username = client.getUserName();
169         if (StringUtils.isBlank(username)) {
170             return builder;
171         }
172
173         String password = client.getPassword();
174         if (password == null) {
175             password = "";
176         }
177
178         String encoded = username + ":" + password;
179         encoded = Base64.getEncoder().encodeToString(encoded.getBytes(StandardCharsets.UTF_8));
180         return builder.header("Authorization", "Basic " + encoded);
181     }
182
183
184     /**
185      * Decrements the VF count that's stored in the context, if the request was
186      * successful.
187      */
188     @Override
189     protected Status detmStatus(Response rawResponse, SoResponse response) {
190         var status = super.detmStatus(rawResponse, response);
191
192         if (status == Status.SUCCESS) {
193             setVfCount(getVfCount() - 1);
194         }
195
196         return status;
197     }
198
199     /**
200      * Makes a request.
201      *
202      * @return a pair containing the request URL and the new request
203      */
204     protected Pair<String, SoRequest> makeRequest() {
205         final var soModelInfo = prepareSoModelInfo();
206         final var vnfItem = getVnfItem();
207         final var vnfServiceItem = getServiceInstance();
208         final var tenantItem = getDefaultTenant();
209         final var cloudRegionItem = getDefaultCloudRegion();
210
211         var request = new SoRequest();
212         request.setOperationType(SoOperationType.DELETE_VF_MODULE);
213
214         //
215         //
216         // Do NOT send SO the requestId, they do not support this field
217         //
218         var details = new SoRequestDetails();
219         request.setRequestDetails(details);
220         details.setRelatedInstanceList(null);
221         details.setConfigurationParameters(null);
222
223         // cloudConfiguration
224         details.setCloudConfiguration(constructCloudConfiguration(tenantItem, cloudRegionItem));
225
226         // modelInfo
227         details.setModelInfo(soModelInfo);
228
229         // requestInfo
230         details.setRequestInfo(constructRequestInfo());
231
232         /*
233          * TODO the legacy SO code always passes null for the last argument, though it
234          * should be passing the vfModuleInstanceId
235          */
236
237         // compute the path
238         String svcId = getRequiredText("service instance ID", vnfServiceItem.getServiceInstanceId());
239         String path = PATH_PREFIX + svcId + "/vnfs/" + vnfItem.getVnfId() + "/vfModules/null";
240
241         return Pair.of(path, request);
242     }
243
244     // these may be overridden by junit tests
245
246     protected java.net.http.HttpClient makeHttpClient() {
247         return java.net.http.HttpClient.newHttpClient();
248     }
249 }