blob: 8a6907639a6939bd857a57e0f058bdd5fdf50706 [file] [log] [blame]
Aharoni, Pavel (pa0916)ca3cb012018-10-22 15:29:57 +03001/*-
2 * ============LICENSE_START=======================================================
3 * OSAM
4 * ================================================================================
5 * Copyright (C) 2018 AT&T
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
22package org.onap.osam.aai.util;
23
24
25import com.att.eelf.configuration.EELFLogger;
26import org.apache.commons.lang3.exception.ExceptionUtils;
27import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
28import org.onap.osam.aai.ExceptionWithRequestInfo;
29import org.onap.osam.aai.ResponseWithRequestInfo;
30import org.onap.osam.aai.exceptions.InvalidPropertyException;
31import org.onap.osam.utils.Logging;
32import org.springframework.beans.factory.annotation.Autowired;
33import org.springframework.http.HttpMethod;
34
35import javax.ws.rs.client.Client;
36import javax.ws.rs.client.Entity;
37import javax.ws.rs.client.Invocation;
38import javax.ws.rs.core.MediaType;
39import javax.ws.rs.core.Response;
40import java.io.UnsupportedEncodingException;
41import java.net.URLEncoder;
42import java.util.Optional;
43import java.util.UUID;
44
45import static org.apache.commons.lang3.ObjectUtils.defaultIfNull;
46import static org.onap.osam.utils.Logging.REQUEST_ID_HEADER_KEY;
47
48
49public class AAIRestInterface {
50
51 protected EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AAIRestInterface.class);
52
53 protected final EELFLogger outgoingRequestsLogger = Logging.getRequestsLogger("aai");
54
55
56 /** The client. */
57 private Client client = null;
58
59 /** The rest srvr base URL. */
60 private String restSrvrBaseURL;
61
62 @Autowired
63 protected HttpsAuthClient httpsAuthClientFactory;
64 private final ServletRequestHelper servletRequestHelper;
65 private final SystemPropertyHelper systemPropertyHelper;
66
67 protected static final String START_STRING = " start";
68 protected static final String TRANSACTION_ID_HEADER = "X-TransactionId";
69 protected static final String FROM_APP_ID_HEADER = "X-FromAppId";
70 protected static final String SUCCESSFUL_API_MESSAGE = " REST api call was successful!";
71 protected static final String URL_DECLARATION = ", url=";
72
73 public AAIRestInterface(HttpsAuthClient httpsAuthClientFactory, ServletRequestHelper servletRequestHelper, SystemPropertyHelper systemPropertyHelper) {
74 this.httpsAuthClientFactory = httpsAuthClientFactory;
75 this.servletRequestHelper = servletRequestHelper;
76 this.systemPropertyHelper = systemPropertyHelper;
77 initRestClient();
78 }
79
80 /**
81 * For testing purpose
82 */
83 AAIRestInterface(Optional<Client> client,
84 HttpsAuthClient httpsAuthClientFactory, ServletRequestHelper servletRequestHelper, SystemPropertyHelper systemPropertyHelper){
85 this.httpsAuthClientFactory = httpsAuthClientFactory;
86 this.servletRequestHelper = servletRequestHelper;
87 this.systemPropertyHelper = systemPropertyHelper;
88 if (client != null && client.isPresent()){
89 this.client = client.get();
90 }
91
92 }
93
94 /**
95 * Encode URL.
96 *
97 * @param nodeKey the node key
98 * @return the string
99 * @throws UnsupportedEncodingException the unsupported encoding exception
100 */
101 public String encodeURL (String nodeKey) throws UnsupportedEncodingException {
102 return URLEncoder.encode(nodeKey, "UTF-8").replaceAll("\\+", "%20");
103 }
104
105 private void initRestClient() {
106 initRestClient(false);
107 }
108
109
110 private void initRestClient(boolean propagateExceptions) {
111 if (client == null) {
112 try {
113 client = httpsAuthClientFactory.getClient(HttpClientMode.WITH_KEYSTORE);
114 } catch (Exception e) {
115 logger.info(EELFLoggerDelegate.errorLogger, "Exception in REST call to DB in initRestClient" + e.toString());
116 logger.debug(EELFLoggerDelegate.debugLogger, "Exception in REST call to DB : " + e.toString());
117 if (propagateExceptions) {
118 ExceptionUtils.rethrow(e);
119 }
120 }
121 }
122 }
123
124
125
126 /**
127 * Sets the rest srvr base URL.
128 *
129 * @param baseURL the base URL
130 */
131 public void SetRestSrvrBaseURL(String baseURL)
132 {
133 if (baseURL == null) {
134 logger.info(EELFLoggerDelegate.errorLogger, "REST Server base URL cannot be null.");
135 logger.debug(EELFLoggerDelegate.debugLogger, "REST Server base URL cannot be null.");
136 }
137
138 restSrvrBaseURL = baseURL;
139 }
140
141 /**
142 * Gets the rest srvr base URL.
143 *
144 * @return the rest srvr base URL
145 */
146 public String getRestSrvrBaseURL() {
147 return restSrvrBaseURL;
148 }
149
150
151 /**
152 * Rest get.
153 *
154 * @param fromAppId the from app id
155 * @param transId the trans id
156 * @param requestUri the request uri
157 * @param xml the xml
158 * @return the string
159 */
160 public ResponseWithRequestInfo RestGet(String fromAppId, String transId, String requestUri, boolean xml) {
161 return RestGet(fromAppId, transId, requestUri, xml, false);
162 }
163
164 public ResponseWithRequestInfo RestGet(String fromAppId, String transId, String requestUri, boolean xml, boolean propagateExceptions) {
165 String methodName = "RestGet";
166 String url = systemPropertyHelper.getFullServicePath(requestUri);
167 try {
168 initRestClient(propagateExceptions);
169
170 logger.debug(EELFLoggerDelegate.debugLogger, methodName + START_STRING);
171 logger.debug(EELFLoggerDelegate.debugLogger, url + " for the get REST API");
172
173 Logging.logRequest(outgoingRequestsLogger, HttpMethod.GET, url);
174
175 final Response response;
176 Invocation.Builder requestBuilder = client.target(url)
177 .request()
178 .accept(xml ? MediaType.APPLICATION_XML : MediaType.APPLICATION_JSON)
179 .header(TRANSACTION_ID_HEADER, transId)
180 .header(FROM_APP_ID_HEADER, fromAppId)
181 .header("Content-Type", MediaType.APPLICATION_JSON)
182 .header(REQUEST_ID_HEADER_KEY, extractOrGenerateRequestId());
183 response = systemPropertyHelper.isClientCertEnabled() ?
184 requestBuilder.get() : authenticateRequest(requestBuilder).get();
185 Logging.logResponse(outgoingRequestsLogger, HttpMethod.GET, url, response);
186
187 if (response.getStatusInfo().equals(Response.Status.OK)) {
188 logger.debug(EELFLoggerDelegate.debugLogger, methodName + SUCCESSFUL_API_MESSAGE);
189 logger.info(EELFLoggerDelegate.errorLogger, methodName + SUCCESSFUL_API_MESSAGE);
190 } else {
191 logger.debug(EELFLoggerDelegate.debugLogger, getInvalidResponseLogMessage(url, methodName, response));
192 }
193 return new ResponseWithRequestInfo(response, url, HttpMethod.GET);
194 } catch (Exception e) {
195 logger.debug(EELFLoggerDelegate.debugLogger, getFailedResponseLogMessage(url, methodName, e));
196 if (propagateExceptions) {
197 throw new ExceptionWithRequestInfo(HttpMethod.GET, defaultIfNull(url, requestUri), e);
198 } else {
199 return new ResponseWithRequestInfo(null, url, HttpMethod.GET);
200 }
201 }
202 }
203
204 protected String extractOrGenerateRequestId() {
205 return servletRequestHelper.extractOrGenerateRequestId();
206 }
207
208
209 /**
210 * Delete.
211 *
212 * @param sourceID the source ID
213 * @param transId the trans id
214 * @param path the path
215 * @return true, if successful
216 */
217 public boolean Delete(String sourceID, String transId, String path) {
218 String methodName = "Delete";
219 transId += ":" + UUID.randomUUID().toString();
220 logger.debug(methodName + START_STRING);
221 Boolean response = false;
222 String url = systemPropertyHelper.getFullServicePath(path);;
223 try {
224
225 initRestClient();
226 Logging.logRequest(outgoingRequestsLogger, HttpMethod.DELETE, url);
227 final Response cres = client.target(url)
228 .request()
229 .accept(MediaType.APPLICATION_JSON)
230 .header(TRANSACTION_ID_HEADER, transId)
231 .header(FROM_APP_ID_HEADER, sourceID)
232 .header(REQUEST_ID_HEADER_KEY, extractOrGenerateRequestId())
233 .delete();
234 Logging.logResponse(outgoingRequestsLogger, HttpMethod.DELETE, url, cres);
235 if (cres.getStatusInfo().equals(Response.Status.NOT_FOUND)) {
236 logger.debug(EELFLoggerDelegate.debugLogger, "Resource does not exist...: " + cres.getStatus()
237 + ":" + cres.readEntity(String.class));
238 response = false;
239 } else if (cres.getStatusInfo().equals(Response.Status.OK) || cres.getStatusInfo().equals(Response.Status.NO_CONTENT)) {
240 logger.debug(EELFLoggerDelegate.debugLogger, "Resource " + url + " deleted");
241 logger.info(EELFLoggerDelegate.errorLogger, "Resource " + url + " deleted");
242 response = true;
243 } else {
244 logger.debug(EELFLoggerDelegate.debugLogger, "Deleting Resource failed: " + cres.getStatus()
245 + ":" + cres.readEntity(String.class));
246 response = false;
247 }
248
249 } catch (Exception e) {
250 logger.debug(EELFLoggerDelegate.debugLogger, getFailedResponseLogMessage(url, methodName, e));
251 }
252 return response;
253 }
254
255
256 /**
257 * Rest put.
258 *
259 * @param fromAppId the from app id
260 * @param path the path
261 * @param payload the payload
262 * @param xml the xml
263 * @return the string
264 */
265 public Response RestPut(String fromAppId, String path, String payload, boolean xml) {
266 String methodName = "RestPut";
267 String url=systemPropertyHelper.getFullServicePath(path);
268 String transId = UUID.randomUUID().toString();
269 logger.debug(EELFLoggerDelegate.debugLogger, methodName + START_STRING);
270
271 Response response = null;
272 try {
273 initRestClient();
274 Logging.logRequest(outgoingRequestsLogger, HttpMethod.PUT, url, payload);
275 response = authenticateRequest(client.target(url)
276 .request()
277 .accept(xml ? MediaType.APPLICATION_XML : MediaType.APPLICATION_JSON)
278 .header(TRANSACTION_ID_HEADER, transId)
279 .header(FROM_APP_ID_HEADER, fromAppId))
280 .header(REQUEST_ID_HEADER_KEY, extractOrGenerateRequestId())
281 .put(Entity.entity(payload, MediaType.APPLICATION_JSON));
282 Logging.logResponse(outgoingRequestsLogger, HttpMethod.PUT, url, response);
283
284 if (response.getStatusInfo().getFamily().equals(Response.Status.Family.SUCCESSFUL)) {
285 logger.info(EELFLoggerDelegate.errorLogger, getValidResponseLogMessage(methodName));
286 logger.debug(EELFLoggerDelegate.debugLogger, getValidResponseLogMessage(methodName));
287 } else {
288 logger.debug(EELFLoggerDelegate.debugLogger, getInvalidResponseLogMessage(url, methodName, response));
289 }
290 } catch (Exception e) {
291 logger.debug(EELFLoggerDelegate.debugLogger, getFailedResponseLogMessage(url, methodName, e));
292 }
293 return response;
294 }
295
296
297
298 /**
299 * Rest post.
300 *
301 * @param fromAppId the from app id
302 * @param path the path
303 * @param payload the payload
304 * @param xml the xml
305 * @return the string
306 */
307 public Response RestPost(String fromAppId, String path, String payload, boolean xml) {
308 String methodName = "RestPost";
309 String url=systemPropertyHelper.getServiceBasePath(path);
310 String transId = UUID.randomUUID().toString();
311 logger.debug(EELFLoggerDelegate.debugLogger, methodName + START_STRING);
312
313 Response response = null;
314 try {
315 initRestClient();
316 Logging.logRequest(outgoingRequestsLogger, HttpMethod.POST, url, payload);
317 response = authenticateRequest(client.target(systemPropertyHelper.getServiceBasePath(path))
318 .request()
319 .accept(xml ? MediaType.APPLICATION_XML : MediaType.APPLICATION_JSON)
320 .header(TRANSACTION_ID_HEADER, transId)
321 .header(FROM_APP_ID_HEADER, fromAppId))
322 .header(REQUEST_ID_HEADER_KEY, extractOrGenerateRequestId())
323 .post(Entity.entity(payload, MediaType.APPLICATION_JSON));
324 Logging.logResponse(outgoingRequestsLogger, HttpMethod.POST, url, response);
325
326 if (response.getStatusInfo().getFamily().equals(Response.Status.Family.SUCCESSFUL)) {
327 logger.info(EELFLoggerDelegate.errorLogger, getValidResponseLogMessage(methodName));
328 logger.debug(EELFLoggerDelegate.debugLogger, getValidResponseLogMessage(methodName));
329 } else {
330 logger.debug(EELFLoggerDelegate.debugLogger, getInvalidResponseLogMessage(url, methodName, response));
331 }
332 } catch (Exception e) {
333 logger.debug(EELFLoggerDelegate.debugLogger, getFailedResponseLogMessage(url, methodName, e));
334 }
335 return response;
336 }
337
338 protected String getFailedResponseLogMessage(String path, String methodName, Exception e) {
339 return methodName + URL_DECLARATION + path + ", Exception: " + e.toString();
340 }
341
342 protected String getValidResponseLogMessage(String methodName) {
343 return methodName + URL_DECLARATION;
344 }
345
346 protected String getInvalidResponseLogMessage(String path, String methodName, Response cres) {
347 return methodName + " with status=" + cres.getStatus() + URL_DECLARATION + path;
348 }
349
350 private Invocation.Builder authenticateRequest(Invocation.Builder requestBuilder) throws InvalidPropertyException, UnsupportedEncodingException {
351 return requestBuilder
352 .header("Authorization", "Basic " + systemPropertyHelper.getEncodedCredentials());
353 }
354
355}