Merge "Add PNF support to new CDS actor"
[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.Map;
24 import java.util.Map.Entry;
25 import java.util.concurrent.CompletableFuture;
26 import javax.ws.rs.client.Entity;
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 lombok.Getter;
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.impl.HttpOperation;
40 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
41 import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpConfig;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44
45 /**
46  * A&AI Custom Query. Stores the {@link AaiCqResponse} in the context. In addition, if the
47  * context does not contain the "tenant" data for the vserver, then it will request that,
48  * as well. Note: this ignores the "target entity" in the parameters as this query always
49  * applies to the vserver, thus the target entity may be set to an empty string.
50  */
51 public class AaiCustomQueryOperation extends HttpOperation<String> {
52     private static final Logger logger = LoggerFactory.getLogger(AaiCustomQueryOperation.class);
53
54     public static final String NAME = AaiCqResponse.OPERATION;
55
56     public static final String VSERVER_VSERVER_NAME = "vserver.vserver-name";
57     public static final String RESOURCE_LINK = "resource-link";
58     public static final String RESULT_DATA = "result-data";
59
60     // TODO make this configurable
61     private static final String PREFIX = "/aai/v16";
62
63     @Getter
64     private final String vserver;
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);
74
75         this.vserver = params.getContext().getEnrichment().get(VSERVER_VSERVER_NAME);
76         if (StringUtils.isBlank(this.vserver)) {
77             throw new IllegalArgumentException("missing " + VSERVER_VSERVER_NAME + " in enrichment data");
78         }
79     }
80
81     /**
82      * Queries the vserver, if necessary.
83      */
84     @Override
85     protected CompletableFuture<OperationOutcome> startPreprocessorAsync() {
86         ControlLoopOperationParams tenantParams =
87                         params.toBuilder().actor(AaiConstants.ACTOR_NAME).operation(AaiGetTenantOperation.NAME)
88                                         .targetEntity(vserver).payload(null).retry(null).timeoutSec(null).build();
89
90         return params.getContext().obtain(AaiGetTenantOperation.getKey(vserver), tenantParams);
91     }
92
93     @Override
94     public void generateSubRequestId(int attempt) {
95         setSubRequestId(String.valueOf(attempt));
96     }
97
98     @Override
99     protected CompletableFuture<OperationOutcome> startOperationAsync(int attempt, OperationOutcome outcome) {
100         outcome.setSubRequestId(String.valueOf(attempt));
101
102         final Map<String, String> request = makeRequest();
103         Map<String, Object> headers = makeHeaders();
104
105         StringBuilder str = new StringBuilder(getClient().getBaseUrl());
106
107         String path = getPath();
108         WebTarget web = getClient().getWebTarget().path(path);
109         str.append(path);
110
111         web = addQuery(web, str, "?", "format", "resource");
112
113         Builder webldr = web.request();
114         for (Entry<String, Object> header : headers.entrySet()) {
115             webldr.header(header.getKey(), header.getValue());
116         }
117
118         String url = str.toString();
119
120         logMessage(EventType.OUT, CommInfrastructure.REST, url, request);
121
122         Entity<Map<String, String>> entity = Entity.entity(request, MediaType.APPLICATION_JSON);
123
124         return handleResponse(outcome, url, callback -> webldr.async().put(entity, callback));
125     }
126
127     private WebTarget addQuery(WebTarget web, StringBuilder str, String separator, String name, String value) {
128         str.append(separator);
129         str.append(name);
130         str.append('=');
131         str.append(value);
132
133         return web.queryParam(name, value);
134     }
135
136     /**
137      * Constructs the custom query using the previously retrieved tenant data.
138      */
139     private Map<String, String> makeRequest() {
140         StandardCoderObject tenant = params.getContext().getProperty(AaiGetTenantOperation.getKey(vserver));
141
142         String resourceLink = tenant.getString(RESULT_DATA, 0, RESOURCE_LINK);
143         if (resourceLink == null) {
144             throw new IllegalArgumentException("cannot perform custom query - no resource-link");
145         }
146
147         resourceLink = resourceLink.replace(PREFIX, "");
148
149         return Map.of("start", resourceLink, "query", "query/closed-loop");
150     }
151
152     @Override
153     protected Map<String, Object> makeHeaders() {
154         return AaiUtil.makeHeaders(params);
155     }
156
157     /**
158      * Injects the response into the context.
159      */
160     @Override
161     protected CompletableFuture<OperationOutcome> postProcessResponse(OperationOutcome outcome, String url,
162                     Response rawResponse, String response) {
163
164         logger.info("{}: caching response for {}", getFullName(), params.getRequestId());
165         params.getContext().setProperty(AaiCqResponse.CONTEXT_KEY, new AaiCqResponse(response));
166
167         return super.postProcessResponse(outcome, url, rawResponse, response);
168     }
169 }