Set sub request ID before start callback
[policy/models.git] / models-interactions / model-actors / actor.aai / src / main / java / org / onap / policy / controlloop / actor / aai / AaiGetOperation.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.aai;
22
23 import java.util.Map;
24 import java.util.Map.Entry;
25 import java.util.Set;
26 import java.util.concurrent.CompletableFuture;
27 import javax.ws.rs.client.Invocation.Builder;
28 import javax.ws.rs.client.WebTarget;
29 import javax.ws.rs.core.MediaType;
30 import javax.ws.rs.core.Response;
31 import org.onap.policy.aai.AaiConstants;
32 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
33 import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;
34 import org.onap.policy.common.utils.coder.StandardCoderObject;
35 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
36 import org.onap.policy.controlloop.actorserviceprovider.impl.HttpOperation;
37 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
38 import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpConfig;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 /**
43  * Superclass of A&AI operators that use "get" to perform their request and store their
44  * response within the context as a {@link StandardCoderObject}. The property name under
45  * which they are stored is ${actor}.${operation}.${targetEntity}.
46  */
47 public class AaiGetOperation extends HttpOperation<StandardCoderObject> {
48     private static final Logger logger = LoggerFactory.getLogger(AaiGetOperation.class);
49
50     public static final int DEFAULT_RETRY = 3;
51
52     // operation names
53     public static final String TENANT = "Tenant";
54
55     // property prefixes
56     private static final String TENANT_KEY_PREFIX = AaiConstants.CONTEXT_PREFIX + TENANT + ".";
57
58     /**
59      * Operation names supported by this operator.
60      */
61     public static final Set<String> OPERATIONS = Set.of(TENANT);
62
63
64     /**
65      * Responses that are retrieved from A&AI are placed in the operation context under
66      * the name "${propertyPrefix}.${targetEntity}".
67      */
68     private final String propertyPrefix;
69
70     /**
71      * Constructs the object.
72      *
73      * @param params operation parameters
74      * @param config configuration for this operation
75      */
76     public AaiGetOperation(ControlLoopOperationParams params, HttpConfig config) {
77         super(params, config, StandardCoderObject.class);
78         this.propertyPrefix = getFullName() + ".";
79     }
80
81     /**
82      * Gets the "context key" for the tenant query response associated with the given
83      * target entity.
84      *
85      * @param targetEntity target entity
86      * @return the "context key" for the response associated with the given target
87      */
88     public static String getTenantKey(String targetEntity) {
89         return (TENANT_KEY_PREFIX + targetEntity);
90     }
91
92     @Override
93     public void generateSubRequestId(int attempt) {
94         setSubRequestId(String.valueOf(attempt));
95     }
96
97     @Override
98     protected CompletableFuture<OperationOutcome> startOperationAsync(int attempt, OperationOutcome outcome) {
99         Map<String, Object> headers = makeHeaders();
100
101         headers.put("Accept", MediaType.APPLICATION_JSON);
102
103         StringBuilder str = new StringBuilder(getClient().getBaseUrl());
104
105         String path = getPath();
106         WebTarget web = getClient().getWebTarget().path(path);
107         str.append(path);
108
109         web = addQuery(web, str, "?", "search-node-type", "vserver");
110         web = addQuery(web, str, "&", "filter", "vserver-name:EQUALS:" + params.getTargetEntity());
111
112         Builder webldr = web.request();
113         for (Entry<String, Object> header : headers.entrySet()) {
114             webldr.header(header.getKey(), header.getValue());
115         }
116
117         String url = str.toString();
118
119         logMessage(EventType.OUT, CommInfrastructure.REST, url, null);
120
121         return handleResponse(outcome, url, callback -> webldr.async().get(callback));
122     }
123
124     private WebTarget addQuery(WebTarget web, StringBuilder str, String separator, String name, String value) {
125         str.append(separator);
126         str.append(name);
127         str.append('=');
128         str.append(value);
129
130         return web.queryParam(name, value);
131     }
132
133     @Override
134     protected Map<String, Object> makeHeaders() {
135         return AaiUtil.makeHeaders(params);
136     }
137
138     /**
139      * Injects the response into the context.
140      */
141     @Override
142     protected CompletableFuture<OperationOutcome> postProcessResponse(OperationOutcome outcome, String url,
143                     Response rawResponse, StandardCoderObject response) {
144         String entity = params.getTargetEntity();
145
146         logger.info("{}: caching response of {} for {}", getFullName(), entity, params.getRequestId());
147
148         params.getContext().setProperty(propertyPrefix + entity, response);
149
150         return super.postProcessResponse(outcome, url, rawResponse, response);
151     }
152
153     /**
154      * Provides a default retry value, if none specified.
155      */
156     @Override
157     protected int getRetry(Integer retry) {
158         return (retry == null ? DEFAULT_RETRY : retry);
159     }
160 }