Fix nexus and sonar vulnerabilities
[policy/models.git] / models-interactions / model-actors / actor.appclcm / src / main / java / org / onap / policy / controlloop / actor / appclcm / AppcLcmOperation.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2023 Nordix Foundation.
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.appclcm;
23
24 import java.util.List;
25 import java.util.Map;
26 import org.onap.policy.appclcm.AppcLcmBody;
27 import org.onap.policy.appclcm.AppcLcmCommonHeader;
28 import org.onap.policy.appclcm.AppcLcmDmaapWrapper;
29 import org.onap.policy.appclcm.AppcLcmInput;
30 import org.onap.policy.appclcm.AppcLcmOutput;
31 import org.onap.policy.appclcm.AppcLcmResponseCode;
32 import org.onap.policy.appclcm.AppcLcmResponseStatus;
33 import org.onap.policy.common.utils.coder.CoderException;
34 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
35 import org.onap.policy.controlloop.actorserviceprovider.OperationProperties;
36 import org.onap.policy.controlloop.actorserviceprovider.OperationResult;
37 import org.onap.policy.controlloop.actorserviceprovider.impl.BidirectionalTopicOperation;
38 import org.onap.policy.controlloop.actorserviceprovider.parameters.BidirectionalTopicConfig;
39 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
40 import org.onap.policy.controlloop.actorserviceprovider.topic.SelectorKey;
41
42 public class AppcLcmOperation extends BidirectionalTopicOperation<AppcLcmDmaapWrapper, AppcLcmDmaapWrapper> {
43
44     private static final String MISSING_STATUS = "APPC-LCM response is missing the response status";
45     public static final String VNF_ID_KEY = "vnf-id";
46
47     private static final List<String> PROPERTY_NAMES = List.of(OperationProperties.AAI_TARGET_ENTITY);
48
49     /**
50      * Keys used to match the response with the request listener. The sub request ID is a
51      * UUID, so it can be used to uniquely identify the response.
52      * <p/>
53      * Note: if these change, then {@link #getExpectedKeyValues(int, AppcLcmDmaapWrapper)}
54      * must be updated accordingly.
55      */
56     public static final List<SelectorKey> SELECTOR_KEYS =
57                     List.of(new SelectorKey("body", "output", "common-header", "sub-request-id"));
58
59     /**
60      * Constructs the object.
61      *
62      * @param params operation parameters
63      * @param config configuration for this operation
64      */
65     public AppcLcmOperation(ControlLoopOperationParams params, BidirectionalTopicConfig config) {
66         super(params, config, AppcLcmDmaapWrapper.class, PROPERTY_NAMES);
67     }
68
69     @Override
70     protected AppcLcmDmaapWrapper makeRequest(int attempt) {
71         String subRequestId = getSubRequestId();
72
73         var header = new AppcLcmCommonHeader();
74         header.setOriginatorId(params.getRequestId().toString());
75         header.setRequestId(params.getRequestId());
76         header.setSubRequestId(subRequestId);
77
78         var inputRequest = new AppcLcmInput();
79         inputRequest.setCommonHeader(header);
80
81         var recipeFormatter = new AppcLcmRecipeFormatter(getName());
82         inputRequest.setAction(recipeFormatter.getBodyRecipe());
83
84         /*
85          * Action Identifiers are required for APPC LCM requests. For R1, the recipes
86          * supported by Policy only require a vnf-id.
87          */
88         String target = getRequiredProperty(OperationProperties.AAI_TARGET_ENTITY, "target entity");
89         inputRequest.setActionIdentifiers(Map.of(VNF_ID_KEY, target));
90
91         /*
92          * For R1, the payloads will not be required for the Restart, Rebuild, or Migrate
93          * recipes. APPC will populate the payload based on A&AI look up of the vnd-id
94          * provided in the action identifiers. The payload is set when converPayload() is
95          * called.
96          */
97         if (operationSupportsPayload()) {
98             convertPayload(params.getPayload(), inputRequest);
99         } else {
100             inputRequest.setPayload(null);
101         }
102
103         var body = new AppcLcmBody();
104         body.setInput(inputRequest);
105
106         var dmaapRequest = new AppcLcmDmaapWrapper();
107         dmaapRequest.setBody(body);
108         dmaapRequest.setVersion("2.0");
109         dmaapRequest.setCorrelationId(params.getRequestId() + "-" + subRequestId);
110         dmaapRequest.setRpcName(recipeFormatter.getUrlRecipe());
111         dmaapRequest.setType("request");
112
113         body.setInput(inputRequest);
114         dmaapRequest.setBody(body);
115         return dmaapRequest;
116     }
117
118     /**
119      * Converts a payload. The original value is assumed to be a JSON string, which is
120      * decoded into an object.
121      *
122      * @param source source from which to get the values
123      * @param request where to place the decoded values
124      */
125     private void convertPayload(Map<String, Object> source, AppcLcmInput request) {
126         try {
127             var encodedPayloadString = getCoder().encode(source);
128             request.setPayload(encodedPayloadString);
129         } catch (CoderException e) {
130             throw new IllegalArgumentException("Cannot convert payload", e);
131         }
132     }
133
134     /**
135      * Note: these values must match {@link #SELECTOR_KEYS}.
136      */
137     @Override
138     protected List<String> getExpectedKeyValues(int attempt, AppcLcmDmaapWrapper request) {
139         return List.of(getSubRequestId());
140     }
141
142     @Override
143     protected Status detmStatus(String rawResponse, AppcLcmDmaapWrapper response) {
144         AppcLcmResponseStatus status = getStatus(response);
145         if (status == null) {
146             throw new IllegalArgumentException(MISSING_STATUS);
147         }
148
149         String code = AppcLcmResponseCode.toResponseValue(status.getCode());
150         if (code == null) {
151             throw new IllegalArgumentException("unknown APPC-LCM response status code: " + status.getCode());
152         }
153
154         return switch (code) {
155             case AppcLcmResponseCode.SUCCESS -> Status.SUCCESS;
156             case AppcLcmResponseCode.FAILURE -> Status.FAILURE;
157             case AppcLcmResponseCode.ERROR, AppcLcmResponseCode.REJECT ->
158                 throw new IllegalArgumentException("APPC-LCM request was not accepted, code=" + code);
159             default -> Status.STILL_WAITING;
160         };
161     }
162
163     /**
164      * Sets the message to the status description, if available.
165      */
166     @Override
167     public OperationOutcome setOutcome(OperationOutcome outcome, OperationResult result, AppcLcmDmaapWrapper response) {
168         outcome.setResponse(response);
169
170         AppcLcmResponseStatus status = getStatus(response);
171         if (status == null) {
172             return setOutcome(outcome, result);
173         }
174
175         String message = status.getMessage();
176         if (message == null) {
177             return setOutcome(outcome, result);
178         }
179
180         outcome.setResult(result);
181         outcome.setMessage(message);
182         return outcome;
183     }
184
185     /**
186      * Gets the status from the response.
187      *
188      * @param response the response from which to extract the status, or {@code null}
189      * @return the status, or {@code null} if it does not exist
190      */
191     protected AppcLcmResponseStatus getStatus(AppcLcmDmaapWrapper response) {
192         if (response == null) {
193             return null;
194         }
195
196         AppcLcmBody body = response.getBody();
197         if (body == null) {
198             return null;
199         }
200
201         AppcLcmOutput output = body.getOutput();
202         if (output == null) {
203             return null;
204         }
205
206         return output.getStatus();
207     }
208
209     /**
210      * Determines if the operation supports a payload.
211      *
212      * @return {@code true} if the operation supports a payload, {@code false} otherwise
213      */
214     protected boolean operationSupportsPayload() {
215         return params.getPayload() != null && !params.getPayload().isEmpty()
216                         && AppcLcmConstants.SUPPORTS_PAYLOAD.contains(params.getOperation().toLowerCase());
217     }
218 }