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