2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright © 2017-2018 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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.aai.util;
23 import com.att.eelf.configuration.EELFLogger;
24 import com.att.eelf.configuration.EELFManager;
25 import com.fasterxml.jackson.databind.ObjectMapper;
26 import com.fasterxml.jackson.databind.type.TypeFactory;
27 import com.sun.jersey.api.client.Client;
28 import com.sun.jersey.api.client.ClientHandlerException;
29 import com.sun.jersey.api.client.ClientResponse;
31 import java.security.KeyManagementException;
32 import java.util.ArrayList;
33 import java.util.List;
34 import java.util.UUID;
36 import org.onap.aai.exceptions.AAIException;
37 import org.onap.aai.logging.LoggingContext;
39 public class RestController implements RestControllerInterface {
41 private static final String TARGET_NAME = "AAI";
42 private static EELFLogger LOGGER = EELFManager.getInstance().getLogger(RestController.class);
44 private static Client client = null;
46 private String restSrvrBaseURL;
48 private String overrideLocalHost = null;
50 // To do - Come up with helper function that will automatically
51 // generate the REST API path based on path parameter(s) and query parameter(s)!
52 public static final String REST_APIPATH_COMPLEXES = "cloud-infrastructure/complexes";
53 public static final String REST_APIPATH_COMPLEX = "cloud-infrastructure/complexes/complex/";
54 public static final String REST_APIPATH_PSERVERS = "cloud-infrastructure/pservers";
55 public static final String REST_APIPATH_PSERVER = "cloud-infrastructure/pservers/pserver/";
56 public static final String REST_APIPATH_PHYSICALLINKS = "network/physical-links/";
57 public static final String REST_APIPATH_PHYSICALLINK = "network/physical-links/physical-link/";
58 public static final String REST_APIPATH_PINTERFACES = "network/p-interfaces/";
59 public static final String REST_APIPATH_PINTERFACE = "network/p-interfaces/p-interface/";
60 public static final String REST_APIPATH_VPLSPES = "network/vpls-pes/";
61 public static final String REST_APIPATH_VPLSPE = "network/vpls-pes/vpls-pe/";
62 public static final String REST_APIPATH_UPDATE = "actions/update/";
63 public static final String REST_APIPATH_SEARCH = "search/nodes-query?search-node-type=";
65 public static final String REST_APIPATH_CLOUDREGION = "cloud-infrastructure/cloud-regions/cloud-region/";
66 public static final String REST_APIPATH_TENANT = "cloud-infrastructure/tenants/tenant/";
67 public static final String REST_APIPATH_VIRTUAL_DATA_CENTER =
68 "cloud-infrastructure/virtual-data-centers/virtual-data-center/";
69 public static final String REST_APIPATH_VIRTUAL_DATA_CENTERS = "cloud-infrastructure/virtual-data-centers/";
70 public static final String REST_APIPATH_GENERIC_VNF = "network/generic-vnfs/generic-vnf/";
71 public static final String REST_APIPATH_GENERIC_VNFS = "network/generic-vnfs";
72 public static final String REST_APIPATH_L3_NETWORK = "network/l3-networks/l3-network/";
73 public static final String REST_APIPATH_L3_NETWORKS = "network/l3-networks";
74 public static final String REST_APIPATH_INSTANCE_GROUP = "network/instance-groups/instance-group";
75 public static final String REST_APIPATH_INSTANCE_GROUPS = "network/instance-groups";
76 public static final String REST_APIPATH_VFMODULE = "nodes/vf-modules/vf-module/";
78 public static final String REST_APIPATH_VCE = "network/vces/vce/";
80 public static final String REST_APIPATH_SERVICE = "service-design-and-creation/services/service/";
81 public static final String REST_APIPATH_LOGICALLINKS = "network/logical-links/";
82 public static final String REST_APIPATH_LOGICALLINK = "network/logical-links/logical-link/";
84 public RestController() throws AAIException {
85 this.initRestClient();
89 * Inits the rest client.
91 * @throws AAIException the AAI exception
93 public void initRestClient() throws AAIException {
96 client = getHttpsAuthClient();
97 } catch (KeyManagementException e) {
98 throw new AAIException("AAI_7117", "KeyManagementException in REST call to DB: " + e.toString());
99 } catch (Exception e) {
100 throw new AAIException("AAI_7117", " Exception in REST call to DB: " + e.toString());
105 public Client getHttpsAuthClient() throws KeyManagementException {
106 return HttpsAuthClient.getClient();
110 * Sets the rest srvr base URL.
112 * @param baseURL the base URL
113 * @throws AAIException the AAI exception
115 public void SetRestSrvrBaseURL(String baseURL) throws AAIException {
117 throw new AAIException("AAI_7117", "REST Server base URL cannot be null.");
118 restSrvrBaseURL = baseURL;
122 * Gets the rest srvr base URL.
124 * @return the rest srvr base URL
126 public String getRestSrvrBaseURL() {
127 return restSrvrBaseURL;
130 public <T> void Get(T t, String sourceID, String transId, String path, RestObject<T> restObject, boolean oldserver)
131 throws AAIException {
132 Get(t, sourceID, transId, path, restObject, oldserver, AAIConstants.AAI_RESOURCES_PORT);
136 * To do - optimization and automation. Also make it as generic as possible.
138 * @param <T> the generic type
140 * @param sourceID the source ID
141 * @param transId the trans id
142 * @param path the path
143 * @param restObject the rest object
144 * @param oldserver the oldserver
145 * @throws AAIException the AAI exception
147 @SuppressWarnings("unchecked")
148 public <T> void Get(T t, String sourceID, String transId, String path, RestObject<T> restObject, boolean oldserver,
149 int port) throws AAIException {
150 String methodName = "Get";
152 transId += ":" + UUID.randomUUID().toString();
154 LoggingContext.save();
155 LoggingContext.partnerName(sourceID);
156 LoggingContext.targetEntity(TARGET_NAME);
157 LoggingContext.requestId(transId);
158 LoggingContext.serviceName(methodName);
159 LoggingContext.targetServiceName(methodName);
161 LOGGER.debug(methodName + " start");
166 url = AAIConfig.get(AAIConstants.AAI_OLDSERVER_URL) + path;
168 if (overrideLocalHost == null) {
170 AAIConfig.get(AAIConstants.AAI_LOCAL_OVERRIDE, AAIConstants.AAI_LOCAL_OVERRIDE_DEFAULT);
172 if (AAIConstants.AAI_LOCAL_OVERRIDE_DEFAULT.equals(overrideLocalHost)) {
173 url = String.format(AAIConstants.AAI_LOCAL_REST, port,
174 AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP)) + path;
176 url = String.format(AAIConstants.AAI_LOCAL_REST_OVERRIDE, overrideLocalHost,
177 AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP)) + path;
181 LOGGER.debug(url + " for the get REST API");
182 ClientResponse cres = client.resource(url).accept("application/json").header("X-TransactionId", transId)
183 .header("X-FromAppId", sourceID).header("Real-Time", "true").type("application/json")
184 .get(ClientResponse.class);
186 // System.out.println("cres.EntityInputSream()="+cres.getEntityInputStream().toString());
187 // System.out.println("cres.tostring()="+cres.toString());
189 if (cres.getStatus() == 200) {
190 // System.out.println(methodName + ": url=" + url);
191 t = (T) cres.getEntity(t.getClass());
193 LOGGER.debug(methodName + "REST api GET was successfull!");
195 LoggingContext.restore();
196 // System.out.println(methodName + ": url=" + url + " failed with status=" + cres.getStatus());
197 throw new AAIException("AAI_7116", methodName + " with status=" + cres.getStatus() + ", url=" + url);
200 LoggingContext.restore();
204 * To do - optimization and automation. Also make it as generic as possible.
206 * @param <T> the generic type
208 * @param sourceID the source ID
209 * @param transId the trans id
210 * @param path the path
211 * @param restObject the rest object
212 * @param oldserver the oldserver
213 * @throws AAIException the AAI exception
215 @SuppressWarnings("unchecked")
216 public <T> void Get(T t, String sourceID, String transId, String path, RestObject<T> restObject, String apiVersion)
217 throws AAIException {
218 String methodName = "Get";
220 transId += ":" + UUID.randomUUID().toString();
222 LoggingContext.save();
223 LoggingContext.partnerName(sourceID);
224 LoggingContext.targetEntity(TARGET_NAME);
225 LoggingContext.requestId(transId);
226 LoggingContext.serviceName(methodName);
227 LoggingContext.targetServiceName(methodName);
229 LOGGER.debug(methodName + " start");
233 url = AAIConfig.get(AAIConstants.AAI_SERVER_URL_BASE) + apiVersion + "/" + path;
236 LOGGER.debug(url + " for the get REST API");
237 ClientResponse cres = client.resource(url).accept("application/json").header("X-TransactionId", transId)
238 .header("X-FromAppId", sourceID).header("Real-Time", "true").type("application/json")
239 .get(ClientResponse.class);
241 // System.out.println("cres.EntityInputSream()="+cres.getEntityInputStream().toString());
242 // System.out.println("cres.tostring()="+cres.toString());
244 if (cres.getStatus() == 200) {
245 // System.out.println(methodName + ": url=" + url);
246 t = (T) cres.getEntity(t.getClass());
248 LOGGER.debug(methodName + "REST api GET was successfull!");
250 LoggingContext.restore();
251 // System.out.println(methodName + ": url=" + url + " failed with status=" + cres.getStatus());
252 throw new AAIException("AAI_7116", methodName + " with status=" + cres.getStatus() + ", url=" + url);
255 LoggingContext.restore();
259 * Map json to object list.
261 * @param <T> the generic type
262 * @param typeDef the type def
263 * @param json the json
264 * @param clazz the clazz
266 * @throws Exception the exception
268 private <T> List<T> mapJsonToObjectList(T typeDef, String json, Class clazz) throws Exception {
270 ObjectMapper mapper = new ObjectMapper();
271 System.out.println(json);
272 TypeFactory t = TypeFactory.defaultInstance();
273 list = mapper.readValue(json, t.constructCollectionType(ArrayList.class, clazz));
281 * @param <T> the generic type
283 * @param sourceID the source ID
284 * @param transId the trans id
285 * @param path the path
286 * @throws AAIException the AAI exception
288 public <T> void Put(T t, String sourceID, String transId, String path) throws AAIException {
289 Put(t, sourceID, transId, path, false, AAIConstants.AAI_RESOURCES_PORT);
295 * @param <T> the generic type
297 * @param sourceID the source ID
298 * @param transId the trans id
299 * @param path the path
300 * @throws AAIException the AAI exception
302 public <T> void Put(T t, String sourceID, String transId, String path, boolean oldserver) throws AAIException {
303 Put(t, sourceID, transId, path, oldserver, AAIConstants.AAI_RESOURCES_PORT);
309 * @param <T> the generic type
311 * @param sourceID the source ID
312 * @param transId the trans id
313 * @param path the path
314 * @param oldserver the oldserver
315 * @throws AAIException the AAI exception
317 public <T> void Put(T t, String sourceID, String transId, String path, boolean oldserver, int port)
318 throws AAIException {
319 String methodName = "Put";
321 transId += ":" + UUID.randomUUID().toString();
323 LoggingContext.save();
324 LoggingContext.partnerName(sourceID);
325 LoggingContext.targetEntity(TARGET_NAME);
326 LoggingContext.requestId(transId);
327 LoggingContext.serviceName(methodName);
328 LoggingContext.targetServiceName(methodName);
330 LOGGER.debug(methodName + " start");
335 url = AAIConfig.get(AAIConstants.AAI_OLDSERVER_URL) + path;
337 if (overrideLocalHost == null) {
339 AAIConfig.get(AAIConstants.AAI_LOCAL_OVERRIDE, AAIConstants.AAI_LOCAL_OVERRIDE_DEFAULT);
341 if (AAIConstants.AAI_LOCAL_OVERRIDE_DEFAULT.equals(overrideLocalHost)) {
342 url = String.format(AAIConstants.AAI_LOCAL_REST, port,
343 AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP)) + path;
345 url = String.format(AAIConstants.AAI_LOCAL_REST_OVERRIDE, overrideLocalHost,
346 AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP)) + path;
350 ClientResponse cres = client.resource(url).accept("application/json").header("X-TransactionId", transId)
351 .header("X-FromAppId", sourceID).header("Real-Time", "true").type("application/json").entity(t)
352 .put(ClientResponse.class);
354 // System.out.println("cres.tostring()="+cres.toString());
356 int statuscode = cres.getStatus();
357 if (statuscode >= 200 && statuscode <= 299) {
358 LOGGER.debug(methodName + ": url=" + url + ", request=" + path);
359 LoggingContext.restore();
361 LoggingContext.restore();
362 throw new AAIException("AAI_7116", methodName + " with status=" + statuscode + ", url=" + url + ", msg="
363 + cres.getEntity(String.class));
367 public void Delete(String sourceID, String transId, String path) throws AAIException {
368 Delete(sourceID, transId, path, AAIConstants.AAI_RESOURCES_PORT);
374 * @param sourceID the source ID
375 * @param transId the trans id
376 * @param path the path
377 * @throws AAIException the AAI exception
379 public void Delete(String sourceID, String transId, String path, int port) throws AAIException {
380 String methodName = "Delete";
382 transId += ":" + UUID.randomUUID().toString();
384 LoggingContext.save();
385 LoggingContext.partnerName(sourceID);
386 LoggingContext.targetEntity(TARGET_NAME);
387 LoggingContext.requestId(transId);
388 LoggingContext.serviceName(methodName);
389 LoggingContext.targetServiceName(methodName);
391 LOGGER.debug(methodName + " start");
394 String request = "{}";
395 if (overrideLocalHost == null) {
396 overrideLocalHost = AAIConfig.get(AAIConstants.AAI_LOCAL_OVERRIDE, AAIConstants.AAI_LOCAL_OVERRIDE_DEFAULT);
398 if (AAIConstants.AAI_LOCAL_OVERRIDE_DEFAULT.equals(overrideLocalHost)) {
399 url = String.format(AAIConstants.AAI_LOCAL_REST, port,
400 AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP)) + path;
402 url = String.format(AAIConstants.AAI_LOCAL_REST_OVERRIDE, overrideLocalHost,
403 AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP)) + path;
405 ClientResponse cres = client.resource(url).accept("application/json").header("X-TransactionId", transId)
406 .header("X-FromAppId", sourceID).header("Real-Time", "true").type("application/json").entity(request)
407 .delete(ClientResponse.class);
409 if (cres.getStatus() == 404) { // resource not found
410 LOGGER.info("Resource does not exist...: " + cres.getStatus() + ":" + cres.getEntity(String.class));
411 LoggingContext.restore();
412 } else if (cres.getStatus() == 200 || cres.getStatus() == 204) {
413 LOGGER.info("Resource " + url + " deleted");
414 LoggingContext.restore();
416 LOGGER.error("Deleting Resource failed: " + cres.getStatus() + ":" + cres.getEntity(String.class));
417 LoggingContext.restore();
418 throw new AAIException("AAI_7116", "Error during DELETE");
422 public <T> String Post(T t, String sourceID, String transId, String path) throws Exception {
423 return Post(t, sourceID, transId, path, AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP));
429 * @param <T> the generic type
431 * @param sourceID the source ID
432 * @param transId the trans id
433 * @param path the path
434 * @param apiVersion the apiVersion
436 * @throws Exception the exception
438 public <T> String Post(T t, String sourceID, String transId, String path, String apiVersion) throws Exception {
439 String methodName = "Post";
441 transId += ":" + UUID.randomUUID().toString();
443 LoggingContext.save();
444 LoggingContext.partnerName(sourceID);
445 LoggingContext.targetEntity(TARGET_NAME);
446 LoggingContext.requestId(transId);
447 LoggingContext.serviceName(methodName);
448 LoggingContext.targetServiceName(methodName);
450 LOGGER.debug(methodName + " start");
455 url = AAIConfig.get(AAIConstants.AAI_SERVER_URL_BASE) + apiVersion + "/" + path;
457 ClientResponse cres = client.resource(url).accept("application/json").header("X-TransactionId", transId)
458 .header("X-FromAppId", sourceID).header("Real-Time", "true").type("application/json").entity(t)
459 .post(ClientResponse.class);
461 int statuscode = cres.getStatus();
462 if (statuscode >= 200 && statuscode <= 299) {
463 LOGGER.debug(methodName + "REST api POST was successful!");
464 return cres.getEntity(String.class);
466 throw new AAIException("AAI_7116", methodName + " with status=" + statuscode + ", url=" + url + ", msg="
467 + cres.getEntity(String.class));
470 } catch (AAIException e) {
471 throw new AAIException("AAI_7116", methodName + " with url=" + url + ", Exception: " + e.toString());
472 } catch (Exception e) {
473 throw new AAIException("AAI_7116", methodName + " with url=" + url + ", Exception: " + e.toString());
476 LoggingContext.restore();
481 * Gets the single instance of RestController.
483 * @param <T> the generic type
484 * @param clazz the clazz
485 * @return single instance of RestController
486 * @throws IllegalAccessException the illegal access exception
487 * @throws InstantiationException the instantiation exception
489 public <T> T getInstance(Class<T> clazz) throws IllegalAccessException, InstantiationException {
490 return clazz.newInstance();
494 * Does resource exist.
496 * @param <T> the generic type
497 * @param resourcePath the resource path
498 * @param resourceClassName the resource class name
499 * @param fromAppId the from app id
500 * @param transId the trans id
506 * To check whether a resource exist or get a copy of the existing version of the resource
508 * Resourcepath: should contain the qualified resource path (including encoded unique key identifier value),
509 * resourceClassName: is the canonical name of the resource class name,
513 * Will return null (if the resource doesn’t exist) (or)
514 * Will return the specified resource from the Graph.
517 * LogicalLink llink = new LogicalLink();
518 * String resourceClassName = llink.getClass().getCanonicalName();
519 * llink = RestController.DoesResourceExist("network/logical-links/logical-link/" + <encoded-link-name>,
520 * resourceClassName, fromAppId, transId);
522 public <T> T DoesResourceExist(String resourcePath, String resourceClassName, String fromAppId, String transId) {
526 RestObject<T> restObj = new RestObject<T>();
527 @SuppressWarnings("unchecked")
528 T resourceObj = (T) getInstance(Class.forName(resourceClassName));
529 restObj.set(resourceObj);
530 Get(resourceObj, fromAppId, transId, resourcePath, restObj, false, AAIConstants.AAI_RESOURCES_PORT);
532 resourceObj = restObj.get();
533 if (resourceObj != null)
536 } catch (AAIException e) {
538 } catch (ClientHandlerException che) {
540 } catch (Exception e) {
550 * @param <T> the generic type
551 * @param sourceID the source ID
552 * @param transId the trans id
553 * @param path the path
554 * @throws AAIException the AAI exception
556 public <T> void Patch(T t, String sourceID, String transId, String path) throws AAIException {
557 String methodName = "Patch";
559 transId += ":" + UUID.randomUUID().toString();
561 LoggingContext.save();
562 LoggingContext.partnerName(sourceID);
563 LoggingContext.targetEntity(TARGET_NAME);
564 LoggingContext.requestId(transId);
565 LoggingContext.serviceName(methodName);
566 LoggingContext.targetServiceName(methodName);
569 ClientResponse cres = null;
573 if (overrideLocalHost == null) {
575 AAIConfig.get(AAIConstants.AAI_LOCAL_OVERRIDE, AAIConstants.AAI_LOCAL_OVERRIDE_DEFAULT);
577 if (AAIConstants.AAI_LOCAL_OVERRIDE_DEFAULT.equals(overrideLocalHost)) {
578 url = String.format(AAIConstants.AAI_LOCAL_REST, AAIConstants.AAI_RESOURCES_PORT,
579 AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP)) + path;
581 url = String.format(AAIConstants.AAI_LOCAL_REST_OVERRIDE, overrideLocalHost,
582 AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP)) + path;
588 cres = client.resource(url).accept("application/json").header("X-TransactionId", transId)
589 .header("X-FromAppId", sourceID).header("X-HTTP-Method-Override", "PATCH")
590 .type("application/merge-patch+json").entity(t).post(ClientResponse.class);
592 statusCode = cres.getStatus();
594 if (statusCode >= 200 && statusCode <= 299) {
595 LOGGER.debug(methodName + "REST api PATCH was successful!");
598 LOGGER.debug(methodName + "Unable to make the patch request to url " + url + " so retrying");
603 } while (numRetries >= 0);
605 LOGGER.debug(methodName + "Unable to make the patch request to url " + url + " even after trying = "
606 + numRetries + " times.");
607 throw new AAIException("AAI_7116", methodName + " with status=" + statusCode + ", url=" + url + ", msg="
608 + cres.getEntity(String.class));
610 } catch (AAIException e) {
611 throw new AAIException("AAI_7116", methodName + " with url=" + url + ", Exception: " + e.toString());
612 } catch (Exception e) {
613 throw new AAIException("AAI_7116", methodName + " with url=" + url + ", Exception: " + e.toString());
616 LoggingContext.restore();