Fix path issues
[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     protected CompletableFuture<OperationOutcome> startOperationAsync(int attempt, OperationOutcome outcome) {
94
95         Map<String, Object> headers = makeHeaders();
96
97         headers.put("Accept", MediaType.APPLICATION_JSON);
98
99         StringBuilder str = new StringBuilder(getClient().getBaseUrl());
100
101         String path = getPath();
102         WebTarget web = getClient().getWebTarget().path(path);
103         str.append(path);
104
105         web = addQuery(web, str, "?", "search-node-type", "vserver");
106         web = addQuery(web, str, "&", "filter", "vserver-name:EQUALS:" + params.getTargetEntity());
107
108         Builder webldr = web.request();
109         for (Entry<String, Object> header : headers.entrySet()) {
110             webldr.header(header.getKey(), header.getValue());
111         }
112
113         String url = str.toString();
114
115         logMessage(EventType.OUT, CommInfrastructure.REST, url, null);
116
117         return handleResponse(outcome, url, callback -> webldr.async().get(callback));
118     }
119
120     private WebTarget addQuery(WebTarget web, StringBuilder str, String separator, String name, String value) {
121         str.append(separator);
122         str.append(name);
123         str.append('=');
124         str.append(value);
125
126         return web.queryParam(name, value);
127     }
128
129     @Override
130     protected Map<String, Object> makeHeaders() {
131         return AaiUtil.makeHeaders(params);
132     }
133
134     @Override
135     public String makePath() {
136         return (getPath() + params.getTargetEntity());
137     }
138
139     /**
140      * Injects the response into the context.
141      */
142     @Override
143     protected CompletableFuture<OperationOutcome> postProcessResponse(OperationOutcome outcome, String url,
144                     Response rawResponse, StandardCoderObject response) {
145         String entity = params.getTargetEntity();
146
147         logger.info("{}: caching response of {} for {}", getFullName(), entity, params.getRequestId());
148
149         params.getContext().setProperty(propertyPrefix + entity, response);
150
151         return super.postProcessResponse(outcome, url, rawResponse, response);
152     }
153
154     /**
155      * Provides a default retry value, if none specified.
156      */
157     @Override
158     protected int getRetry(Integer retry) {
159         return (retry == null ? DEFAULT_RETRY : retry);
160     }
161 }