Translate APPC Instant to Long
[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 java.util.concurrent.CompletableFuture;
28 import org.onap.policy.appc.CommonHeader;
29 import org.onap.policy.appc.Request;
30 import org.onap.policy.appc.Response;
31 import org.onap.policy.appc.ResponseCode;
32 import org.onap.policy.common.utils.coder.Coder;
33 import org.onap.policy.common.utils.coder.CoderException;
34 import org.onap.policy.common.utils.coder.StandardCoder;
35 import org.onap.policy.common.utils.coder.StandardCoderInstantAsMillis;
36 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
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 import org.onap.policy.controlloop.policy.PolicyResult;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44
45 /**
46  * Superclass for APPC Operations.
47  */
48 public abstract class AppcOperation extends BidirectionalTopicOperation<Request, Response> {
49     private static final Logger logger = LoggerFactory.getLogger(AppcOperation.class);
50     private static final StandardCoder coder = new StandardCoderInstantAsMillis();
51     public static final String VNF_ID_KEY = "generic-vnf.vnf-id";
52
53     /**
54      * Keys used to match the response with the request listener. The sub request ID is a
55      * UUID, so it can be used to uniquely identify the response.
56      * <p/>
57      * Note: if these change, then {@link #getExpectedKeyValues(int, Request)} must be
58      * updated accordingly.
59      */
60     public static final List<SelectorKey> SELECTOR_KEYS = List.of(new SelectorKey("CommonHeader", "SubRequestID"));
61
62     /**
63      * Constructs the object.
64      *
65      * @param params operation parameters
66      * @param config configuration for this operation
67      */
68     public AppcOperation(ControlLoopOperationParams params, BidirectionalTopicConfig config) {
69         super(params, config, Response.class);
70     }
71
72     /**
73      * Starts the GUARD.
74      */
75     @Override
76     protected CompletableFuture<OperationOutcome> startPreprocessorAsync() {
77         return startGuardAsync();
78     }
79
80     /**
81      * Makes a request, given the target VNF. This is a support function for
82      * {@link #makeRequest(int)}.
83      *
84      * @param attempt attempt number
85      * @param targetVnf target VNF
86      * @return a new request
87      */
88     protected Request makeRequest(int attempt, String targetVnf) {
89         Request request = new Request();
90         request.setCommonHeader(new CommonHeader());
91         request.getCommonHeader().setRequestId(params.getRequestId());
92
93         // TODO ok to use UUID, or does it have to be the "attempt"?
94         request.getCommonHeader().setSubRequestId(UUID.randomUUID().toString());
95
96         request.setAction(getName());
97
98         // convert payload strings to objects
99         if (params.getPayload() == null) {
100             logger.info("{}: no payload specified for {}", getFullName(), params.getRequestId());
101         } else {
102             convertPayload(params.getPayload(), request.getPayload());
103         }
104
105         // add/replace specific values
106         request.getPayload().put(VNF_ID_KEY, targetVnf);
107
108         return request;
109     }
110
111     /**
112      * Converts a payload. The original value is assumed to be a JSON string, which is
113      * decoded into an object.
114      *
115      * @param source source from which to get the values
116      * @param target where to place the decoded values
117      */
118     private static void convertPayload(Map<String, Object> source, Map<String, Object> target) {
119         for (Entry<String, Object> ent : source.entrySet()) {
120             Object value = ent.getValue();
121             if (value == null) {
122                 target.put(ent.getKey(), null);
123                 continue;
124             }
125
126             try {
127                 target.put(ent.getKey(), coder.decode(value.toString(), Object.class));
128
129             } catch (CoderException e) {
130                 logger.warn("cannot decode JSON value {}: {}", ent.getKey(), ent.getValue(), e);
131             }
132         }
133     }
134
135     /**
136      * Note: these values must match {@link #SELECTOR_KEYS}.
137      */
138     @Override
139     protected List<String> getExpectedKeyValues(int attempt, Request request) {
140         return List.of(request.getCommonHeader().getSubRequestId());
141     }
142
143     @Override
144     protected Status detmStatus(String rawResponse, Response response) {
145         if (response.getStatus() == null) {
146             throw new IllegalArgumentException("APP-C response is missing the response status");
147         }
148
149         ResponseCode code = ResponseCode.toResponseCode(response.getStatus().getCode());
150         if (code == null) {
151             throw new IllegalArgumentException(
152                             "unknown APPC-C response status code: " + response.getStatus().getCode());
153         }
154
155         switch (code) {
156             case SUCCESS:
157                 return Status.SUCCESS;
158             case FAILURE:
159                 return Status.FAILURE;
160             case ERROR:
161             case REJECT:
162                 throw new IllegalArgumentException("APP-C request was not accepted, code=" + code);
163             case ACCEPT:
164             default:
165                 // awaiting a "final" response
166                 return Status.STILL_WAITING;
167         }
168     }
169
170     /**
171      * Sets the message to the status description, if available.
172      */
173     @Override
174     public OperationOutcome setOutcome(OperationOutcome outcome, PolicyResult result, Response response) {
175         if (response.getStatus() == null || response.getStatus().getDescription() == null) {
176             return setOutcome(outcome, result);
177         }
178
179         outcome.setResult(result);
180         outcome.setMessage(response.getStatus().getDescription());
181         return outcome;
182     }
183
184     @Override
185     protected Coder makeCoder() {
186         return coder;
187     }
188 }