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