613b6689dc781a3ed67f7d5003c452733d12ca84
[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.concurrent.CompletableFuture;
25 import javax.ws.rs.client.Entity;
26 import javax.ws.rs.core.MediaType;
27 import javax.ws.rs.core.Response;
28 import lombok.Getter;
29 import org.apache.commons.lang3.StringUtils;
30 import org.onap.policy.aai.AaiConstants;
31 import org.onap.policy.aai.AaiCqResponse;
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  * A&AI Custom Query. Stores the {@link AaiCqResponse} in the context. In addition, if the
44  * context does not contain the "tenant" data for the vserver, then it will request that,
45  * as well. Note: this ignores the "target entity" in the parameters as this query always
46  * applies to the vserver, thus the target entity may be set to an empty string.
47  */
48 public class AaiCustomQueryOperation extends HttpOperation<String> {
49     private static final Logger logger = LoggerFactory.getLogger(AaiCustomQueryOperation.class);
50
51     public static final String NAME = AaiCqResponse.OPERATION;
52
53     public static final String VSERVER_VSERVER_NAME = "vserver.vserver-name";
54     public static final String RESOURCE_LINK = "resource-link";
55     public static final String RESULT_DATA = "result-data";
56
57     private static final String PREFIX = "/aai/v16";
58
59     @Getter
60     private final String vserver;
61
62     /**
63      * Constructs the object.
64      *
65      * @param params operation parameters
66      * @param config configuration for this operation
67      */
68     public AaiCustomQueryOperation(ControlLoopOperationParams params, HttpConfig config) {
69         super(params, config, String.class);
70
71         this.vserver = params.getContext().getEnrichment().get(VSERVER_VSERVER_NAME);
72         if (StringUtils.isBlank(this.vserver)) {
73             throw new IllegalArgumentException("missing " + VSERVER_VSERVER_NAME + " in enrichment data");
74         }
75     }
76
77     /**
78      * Queries the vserver, if necessary.
79      */
80     @Override
81     protected CompletableFuture<OperationOutcome> startPreprocessorAsync() {
82         ControlLoopOperationParams tenantParams =
83                         params.toBuilder().actor(AaiConstants.ACTOR_NAME).operation(AaiGetOperation.TENANT)
84                                         .targetEntity(vserver).payload(null).retry(null).timeoutSec(null).build();
85
86         return params.getContext().obtain(AaiGetOperation.getTenantKey(vserver), tenantParams);
87     }
88
89     @Override
90     protected CompletableFuture<OperationOutcome> startOperationAsync(int attempt, OperationOutcome outcome) {
91
92         Map<String, String> request = makeRequest();
93
94         Entity<Map<String, String>> entity = Entity.entity(request, MediaType.APPLICATION_JSON);
95
96         Map<String, Object> headers = makeHeaders();
97
98         headers.put("Accept", MediaType.APPLICATION_JSON);
99         String url = makeUrl();
100
101         logMessage(EventType.OUT, CommInfrastructure.REST, url, request);
102
103         // @formatter:off
104         return handleResponse(outcome, url,
105             callback -> getClient().put(callback, makePath(), entity, headers));
106         // @formatter:on
107     }
108
109     /**
110      * Constructs the custom query using the previously retrieved tenant data.
111      */
112     private Map<String, String> makeRequest() {
113         StandardCoderObject tenant = params.getContext().getProperty(AaiGetOperation.getTenantKey(vserver));
114
115         String resourceLink = tenant.getString(RESULT_DATA, 0, RESOURCE_LINK);
116         if (resourceLink == null) {
117             throw new IllegalArgumentException("cannot perform custom query - no resource-link");
118         }
119
120         resourceLink = resourceLink.replace(PREFIX, "");
121
122         return Map.of("start", resourceLink, "query", "query/closed-loop");
123     }
124
125     @Override
126     protected Map<String, Object> makeHeaders() {
127         return AaiUtil.makeHeaders(params);
128     }
129
130     /**
131      * Injects the response into the context.
132      */
133     @Override
134     protected CompletableFuture<OperationOutcome> postProcessResponse(OperationOutcome outcome, String url,
135                     Response rawResponse, String response) {
136
137         logger.info("{}: caching response for {}", getFullName(), params.getRequestId());
138         params.getContext().setProperty(AaiCqResponse.CONTEXT_KEY, new AaiCqResponse(response));
139
140         return super.postProcessResponse(outcome, url, rawResponse, response);
141     }
142 }