More actor clean-up
[policy/models.git] / models-interactions / model-actors / actor.appc / src / main / java / org / onap / policy / controlloop / actor / appc / AppcOperation.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.controlloop.actor.appc;
22
23 import java.util.List;
24 import java.util.Map;
25 import java.util.Map.Entry;
26 import java.util.UUID;
27 import org.onap.policy.appc.CommonHeader;
28 import org.onap.policy.appc.Request;
29 import org.onap.policy.appc.Response;
30 import org.onap.policy.appc.ResponseCode;
31 import org.onap.policy.common.utils.coder.CoderException;
32 import org.onap.policy.common.utils.coder.StandardCoder;
33 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
34 import org.onap.policy.controlloop.actorserviceprovider.impl.BidirectionalTopicOperation;
35 import org.onap.policy.controlloop.actorserviceprovider.parameters.BidirectionalTopicConfig;
36 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
37 import org.onap.policy.controlloop.actorserviceprovider.topic.SelectorKey;
38 import org.onap.policy.controlloop.policy.PolicyResult;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 /**
43  * Superclass for APPC Operations.
44  */
45 public abstract class AppcOperation extends BidirectionalTopicOperation<Request, Response> {
46     private static final Logger logger = LoggerFactory.getLogger(AppcOperation.class);
47     private static final StandardCoder coder = new StandardCoder();
48     public static final String VNF_ID_KEY = "generic-vnf.vnf-id";
49
50     /**
51      * Keys used to match the response with the request listener. The sub request ID is a
52      * UUID, so it can be used to uniquely identify the response.
53      * <p/>
54      * Note: if these change, then {@link #getExpectedKeyValues(int, Request)} must be
55      * updated accordingly.
56      */
57     public static final List<SelectorKey> SELECTOR_KEYS = List.of(new SelectorKey("CommonHeader", "SubRequestID"));
58
59     /**
60      * Constructs the object.
61      *
62      * @param params operation parameters
63      * @param config configuration for this operation
64      */
65     public AppcOperation(ControlLoopOperationParams params, BidirectionalTopicConfig config) {
66         super(params, config, Response.class);
67     }
68
69     /**
70      * Makes a request, given the target VNF. This is a support function for
71      * {@link #makeRequest(int)}.
72      *
73      * @param attempt attempt number
74      * @param targetVnf target VNF
75      * @return a new request
76      */
77     protected Request makeRequest(int attempt, String targetVnf) {
78         Request request = new Request();
79         request.setCommonHeader(new CommonHeader());
80         request.getCommonHeader().setRequestId(params.getRequestId());
81
82         // TODO ok to use UUID, or does it have to be the "attempt"?
83         request.getCommonHeader().setSubRequestId(UUID.randomUUID().toString());
84
85         request.setAction(getName());
86
87         // convert payload strings to objects
88         if (params.getPayload() == null) {
89             logger.info("{}: no payload specified for {}", getFullName(), params.getRequestId());
90         } else {
91             convertPayload(params.getPayload(), request.getPayload());
92         }
93
94         // add/replace specific values
95         request.getPayload().put(VNF_ID_KEY, targetVnf);
96
97         return request;
98     }
99
100     /**
101      * Converts a payload. The original value is assumed to be a JSON string, which is
102      * decoded into an object.
103      *
104      * @param source source from which to get the values
105      * @param target where to place the decoded values
106      */
107     private static void convertPayload(Map<String, String> source, Map<String, Object> target) {
108         for (Entry<String, String> ent : source.entrySet()) {
109             try {
110                 target.put(ent.getKey(), coder.decode(ent.getValue(), Object.class));
111
112             } catch (CoderException e) {
113                 logger.warn("cannot decode JSON value {}: {}", ent.getKey(), ent.getValue(), e);
114             }
115         }
116     }
117
118     /**
119      * Note: these values must match {@link #SELECTOR_KEYS}.
120      */
121     @Override
122     protected List<String> getExpectedKeyValues(int attempt, Request request) {
123         return List.of(request.getCommonHeader().getSubRequestId());
124     }
125
126     @Override
127     protected Status detmStatus(String rawResponse, Response response) {
128         if (response.getStatus() == null) {
129             throw new IllegalArgumentException("APP-C response is missing the response status");
130         }
131
132         ResponseCode code = ResponseCode.toResponseCode(response.getStatus().getCode());
133         if (code == null) {
134             throw new IllegalArgumentException(
135                             "unknown APPC-C response status code: " + response.getStatus().getCode());
136         }
137
138         switch (code) {
139             case SUCCESS:
140                 return Status.SUCCESS;
141             case FAILURE:
142                 return Status.FAILURE;
143             case ERROR:
144             case REJECT:
145                 throw new IllegalArgumentException("APP-C request was not accepted, code=" + code);
146             case ACCEPT:
147             default:
148                 // awaiting a "final" response
149                 return Status.STILL_WAITING;
150         }
151     }
152
153     /**
154      * Sets the message to the status description, if available.
155      */
156     @Override
157     public OperationOutcome setOutcome(OperationOutcome outcome, PolicyResult result, Response response) {
158         if (response.getStatus() == null || response.getStatus().getDescription() == null) {
159             return setOutcome(outcome, result);
160         }
161
162         outcome.setResult(result);
163         outcome.setMessage(response.getStatus().getDescription());
164         return outcome;
165     }
166 }