388959ddf30e66a634328999fc9ab0e6ecf619bc
[policy/models.git] / models-interactions / model-actors / actor.aai / src / main / java / org / onap / policy / controlloop / actor / aai / AaiCustomQueryOperation.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.List;
24 import java.util.Map;
25 import java.util.Map.Entry;
26 import java.util.concurrent.CompletableFuture;
27 import javax.ws.rs.client.Entity;
28 import javax.ws.rs.client.Invocation.Builder;
29 import javax.ws.rs.client.WebTarget;
30 import javax.ws.rs.core.MediaType;
31 import javax.ws.rs.core.Response;
32 import org.apache.commons.lang3.StringUtils;
33 import org.onap.policy.aai.AaiConstants;
34 import org.onap.policy.aai.AaiCqResponse;
35 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
36 import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;
37 import org.onap.policy.common.utils.coder.StandardCoderObject;
38 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
39 import org.onap.policy.controlloop.actorserviceprovider.OperationProperties;
40 import org.onap.policy.controlloop.actorserviceprovider.impl.HttpOperation;
41 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
42 import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpConfig;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45
46 /**
47  * A&AI Custom Query. Stores the {@link AaiCqResponse} in the context. In addition, if the
48  * context does not contain the "tenant" data for the vserver, then it will request that,
49  * as well. Note: this ignores the "target entity" in the parameters as this query always
50  * applies to the vserver, thus the target entity may be set to an empty string.
51  */
52 public class AaiCustomQueryOperation extends HttpOperation<String> {
53     private static final Logger logger = LoggerFactory.getLogger(AaiCustomQueryOperation.class);
54
55     public static final String NAME = AaiCqResponse.OPERATION;
56
57     public static final String VSERVER_VSERVER_NAME = "vserver.vserver-name";
58     public static final String RESOURCE_LINK = "resource-link";
59     public static final String RESULT_DATA = "result-data";
60
61     private static final List<String> PROPERTY_NAMES = List.of(OperationProperties.AAI_VSERVER_LINK);
62
63     // TODO make this configurable
64     private static final String PREFIX = "/aai/v16";
65
66     /**
67      * Constructs the object.
68      *
69      * @param params operation parameters
70      * @param config configuration for this operation
71      */
72     public AaiCustomQueryOperation(ControlLoopOperationParams params, HttpConfig config) {
73         super(params, config, String.class, PROPERTY_NAMES);
74     }
75
76     /**
77      * Gets the vserver name from the enrichment data.
78      *
79      * @return the vserver name
80      */
81     protected String getVserver() {
82         String vserver = this.params.getContext().getEnrichment().get(VSERVER_VSERVER_NAME);
83         if (StringUtils.isBlank(vserver)) {
84             throw new IllegalArgumentException("missing " + VSERVER_VSERVER_NAME + " in enrichment data");
85         }
86
87         return vserver;
88     }
89
90     /**
91      * Queries the vserver, if necessary.
92      */
93     @Override
94     protected CompletableFuture<OperationOutcome> startPreprocessorAsync() {
95         if (params.isPreprocessed()) {
96             return null;
97         }
98
99         String vserver = getVserver();
100         ControlLoopOperationParams tenantParams =
101                         params.toBuilder().actor(AaiConstants.ACTOR_NAME).operation(AaiGetTenantOperation.NAME)
102                                         .targetEntity(vserver).payload(null).retry(null).timeoutSec(null).build();
103
104         return params.getContext().obtain(AaiGetTenantOperation.getKey(vserver), tenantParams);
105     }
106
107     @Override
108     public void generateSubRequestId(int attempt) {
109         setSubRequestId(String.valueOf(attempt));
110     }
111
112     @Override
113     protected CompletableFuture<OperationOutcome> startOperationAsync(int attempt, OperationOutcome outcome) {
114         outcome.setSubRequestId(String.valueOf(attempt));
115
116         final Map<String, String> request = makeRequest();
117         Map<String, Object> headers = makeHeaders();
118
119         StringBuilder str = new StringBuilder(getClient().getBaseUrl());
120
121         String path = getPath();
122         WebTarget web = getClient().getWebTarget().path(path);
123         str.append(path);
124
125         web = addQuery(web, str, "?", "format", "resource");
126
127         Builder webldr = web.request();
128         for (Entry<String, Object> header : headers.entrySet()) {
129             webldr.header(header.getKey(), header.getValue());
130         }
131
132         String url = str.toString();
133
134         String strRequest = prettyPrint(request);
135         logMessage(EventType.OUT, CommInfrastructure.REST, url, strRequest);
136
137         Entity<String> entity = Entity.entity(strRequest, MediaType.APPLICATION_JSON);
138
139         return handleResponse(outcome, url, callback -> webldr.async().put(entity, callback));
140     }
141
142     private WebTarget addQuery(WebTarget web, StringBuilder str, String separator, String name, String value) {
143         str.append(separator);
144         str.append(name);
145         str.append('=');
146         str.append(value);
147
148         return web.queryParam(name, value);
149     }
150
151     /**
152      * Constructs the custom query using the previously retrieved tenant data.
153      */
154     private Map<String, String> makeRequest() {
155         return Map.of("start", getVserverLink(), "query", "query/closed-loop");
156     }
157
158     /**
159      * Gets the vserver link, first checking the properties, and then the tenant data.
160      *
161      * @return the vserver link
162      */
163     protected String getVserverLink() {
164         String resourceLink = getProperty(OperationProperties.AAI_VSERVER_LINK);
165         if (resourceLink != null) {
166             return resourceLink;
167         }
168
169         String vserver = getVserver();
170         StandardCoderObject tenant = params.getContext().getProperty(AaiGetTenantOperation.getKey(vserver));
171         if (tenant == null) {
172             throw new IllegalStateException("cannot perform custom query - cannot determine resource-link");
173         }
174
175         resourceLink = tenant.getString(RESULT_DATA, 0, RESOURCE_LINK);
176         if (resourceLink == null) {
177             throw new IllegalArgumentException("cannot perform custom query - no resource-link");
178         }
179
180         resourceLink = resourceLink.replace(PREFIX, "");
181         return resourceLink;
182     }
183
184     @Override
185     protected Map<String, Object> makeHeaders() {
186         return AaiUtil.makeHeaders(params);
187     }
188
189     /**
190      * Injects the response into the context.
191      */
192     @Override
193     protected CompletableFuture<OperationOutcome> postProcessResponse(OperationOutcome outcome, String url,
194                     Response rawResponse, String response) {
195
196         if (params.getContext() != null) {
197             logger.info("{}: caching response for {}", getFullName(), params.getRequestId());
198             params.getContext().setProperty(AaiCqResponse.CONTEXT_KEY, new AaiCqResponse(response));
199         }
200
201         return super.postProcessResponse(outcome, url, rawResponse, response);
202     }
203 }