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=========================================================
20 package org.onap.aai.util;
22 import java.security.KeyManagementException;
23 import java.util.ArrayList;
24 import java.util.List;
25 import java.util.UUID;
27 import org.onap.aai.exceptions.AAIException;
28 import org.onap.aai.logging.LoggingContext;
30 import com.att.eelf.configuration.EELFLogger;
31 import com.att.eelf.configuration.EELFManager;
32 import com.fasterxml.jackson.databind.ObjectMapper;
33 import com.fasterxml.jackson.databind.type.TypeFactory;
34 import com.sun.jersey.api.client.Client;
35 import com.sun.jersey.api.client.ClientHandlerException;
36 import com.sun.jersey.api.client.ClientResponse;
38 public class RestController implements RestControllerInterface {
40 private static final String TARGET_NAME = "AAI";
41 private static EELFLogger LOGGER = EELFManager.getInstance().getLogger(RestController.class);
43 private static Client client = null;
45 private String restSrvrBaseURL;
47 private String overrideLocalHost = null;
49 //To do - Come up with helper function that will automatically
50 //generate the REST API path based on path parameter(s) and query parameter(s)!
51 public static final String REST_APIPATH_COMPLEXES = "cloud-infrastructure/complexes";
52 public static final String REST_APIPATH_COMPLEX = "cloud-infrastructure/complexes/complex/";
53 public static final String REST_APIPATH_PSERVERS = "cloud-infrastructure/pservers";
54 public static final String REST_APIPATH_PSERVER = "cloud-infrastructure/pservers/pserver/";
55 public static final String REST_APIPATH_PHYSICALLINKS = "network/physical-links/";
56 public static final String REST_APIPATH_PHYSICALLINK = "network/physical-links/physical-link/";
57 public static final String REST_APIPATH_PINTERFACES = "network/p-interfaces/";
58 public static final String REST_APIPATH_PINTERFACE = "network/p-interfaces/p-interface/";
59 public static final String REST_APIPATH_VPLSPES = "network/vpls-pes/";
60 public static final String REST_APIPATH_VPLSPE = "network/vpls-pes/vpls-pe/";
61 public static final String REST_APIPATH_UPDATE = "actions/update/";
62 public static final String REST_APIPATH_SEARCH = "search/nodes-query?search-node-type=";
64 public static final String REST_APIPATH_CLOUDREGION = "cloud-infrastructure/cloud-regions/cloud-region/";
65 public static final String REST_APIPATH_TENANT = "cloud-infrastructure/tenants/tenant/";
66 public static final String REST_APIPATH_VIRTUAL_DATA_CENTER = "cloud-infrastructure/virtual-data-centers/virtual-data-center/";
67 public static final String REST_APIPATH_VIRTUAL_DATA_CENTERS = "cloud-infrastructure/virtual-data-centers/";
68 public static final String REST_APIPATH_GENERIC_VNF = "network/generic-vnfs/generic-vnf/";
69 public static final String REST_APIPATH_GENERIC_VNFS = "network/generic-vnfs";
70 public static final String REST_APIPATH_L3_NETWORK = "network/l3-networks/l3-network/";
71 public static final String REST_APIPATH_L3_NETWORKS = "network/l3-networks";
72 public static final String REST_APIPATH_INSTANCE_GROUP = "network/instance-groups/instance-group";
73 public static final String REST_APIPATH_INSTANCE_GROUPS = "network/instance-groups";
74 public static final String REST_APIPATH_VFMODULE = "nodes/vf-modules/vf-module/";
76 public static final String REST_APIPATH_VCE = "network/vces/vce/";
78 public static final String REST_APIPATH_SERVICE = "service-design-and-creation/services/service/";
79 public static final String REST_APIPATH_LOGICALLINKS = "network/logical-links/";
80 public static final String REST_APIPATH_LOGICALLINK = "network/logical-links/logical-link/";
82 public RestController() throws AAIException {
83 this.initRestClient();
86 * Inits the rest client.
88 * @throws AAIException the AAI exception
90 public void initRestClient() throws AAIException
94 client = getHttpsAuthClient();
96 catch (KeyManagementException e){
97 throw new AAIException("AAI_7117", "KeyManagementException in REST call to DB: " + e.toString());
98 } catch (Exception e) {
99 throw new AAIException("AAI_7117", " Exception in REST call to DB: " + e.toString());
104 public Client getHttpsAuthClient() throws KeyManagementException {
105 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
118 throw new AAIException("AAI_7117", "REST Server base URL cannot be null.");
119 restSrvrBaseURL = baseURL;
123 * Gets the rest srvr base URL.
125 * @return the rest srvr base URL
127 public String getRestSrvrBaseURL()
129 return restSrvrBaseURL;
133 public <T> void Get(T t, String sourceID, String transId, String path, RestObject<T> restObject, boolean oldserver) throws AAIException {
134 Get(t, sourceID, transId, path, restObject, oldserver, AAIConstants.AAI_RESOURCES_PORT);
137 * To do - optimization and automation. Also make it as generic as possible.
139 * @param <T> the generic type
141 * @param sourceID the source ID
142 * @param transId the trans id
143 * @param path the path
144 * @param restObject the rest object
145 * @param oldserver the oldserver
146 * @throws AAIException the AAI exception
148 @SuppressWarnings("unchecked")
149 public <T> void Get(T t, String sourceID, String transId, String path, RestObject<T> restObject, boolean oldserver, 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 ) {
169 overrideLocalHost = AAIConfig.get(AAIConstants.AAI_LOCAL_OVERRIDE, AAIConstants.AAI_LOCAL_OVERRIDE_DEFAULT);
171 if ( AAIConstants.AAI_LOCAL_OVERRIDE_DEFAULT.equals(overrideLocalHost )) {
172 url = String.format(AAIConstants.AAI_LOCAL_REST, port, AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP)) + path;
174 url = String.format(AAIConstants.AAI_LOCAL_REST_OVERRIDE, overrideLocalHost, AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP)) + path;
178 LOGGER.debug(url + " for the get REST API");
179 ClientResponse cres = client.resource(url)
180 .accept("application/json")
181 .header("X-TransactionId", transId)
182 .header("X-FromAppId", sourceID)
183 .header("Real-Time", "true")
184 .type("application/json")
185 .get(ClientResponse.class);
187 // System.out.println("cres.EntityInputSream()="+cres.getEntityInputStream().toString());
188 // System.out.println("cres.tostring()="+cres.toString());
190 if (cres.getStatus() == 200) {
191 // System.out.println(methodName + ": url=" + url);
192 t = (T) cres.getEntity(t.getClass());
194 LOGGER.debug(methodName + "REST api GET was successfull!");
196 LoggingContext.restore();
197 // System.out.println(methodName + ": url=" + url + " failed with status=" + cres.getStatus());
198 throw new AAIException("AAI_7116", methodName +" with status="+cres.getStatus()+", url="+url);
201 LoggingContext.restore();
205 * To do - optimization and automation. Also make it as generic as possible.
207 * @param <T> the generic type
209 * @param sourceID the source ID
210 * @param transId the trans id
211 * @param path the path
212 * @param restObject the rest object
213 * @param oldserver the oldserver
214 * @throws AAIException the AAI exception
216 @SuppressWarnings("unchecked")
217 public <T> void Get(T t, String sourceID, String transId, String path, RestObject<T> restObject, String apiVersion) 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)
238 .accept("application/json")
239 .header("X-TransactionId", transId)
240 .header("X-FromAppId", sourceID)
241 .header("Real-Time", "true")
242 .type("application/json")
243 .get(ClientResponse.class);
245 // System.out.println("cres.EntityInputSream()="+cres.getEntityInputStream().toString());
246 // System.out.println("cres.tostring()="+cres.toString());
248 if (cres.getStatus() == 200) {
249 // System.out.println(methodName + ": url=" + url);
250 t = (T) cres.getEntity(t.getClass());
252 LOGGER.debug(methodName + "REST api GET was successfull!");
254 LoggingContext.restore();
255 // System.out.println(methodName + ": url=" + url + " failed with status=" + cres.getStatus());
256 throw new AAIException("AAI_7116", methodName +" with status="+cres.getStatus()+", url="+url);
259 LoggingContext.restore();
263 * Map json to object list.
265 * @param <T> the generic type
266 * @param typeDef the type def
267 * @param json the json
268 * @param clazz the clazz
270 * @throws Exception the exception
272 private <T> List<T> mapJsonToObjectList(T typeDef,String json, Class clazz) throws Exception
275 ObjectMapper mapper = new ObjectMapper();
276 System.out.println(json);
277 TypeFactory t = TypeFactory.defaultInstance();
278 list = mapper.readValue(json, t.constructCollectionType(ArrayList.class,clazz));
286 * @param <T> the generic type
288 * @param sourceID the source ID
289 * @param transId the trans id
290 * @param path the path
291 * @throws AAIException the AAI exception
293 public <T> void Put(T t, String sourceID, String transId, String path) throws AAIException {
294 Put( t, sourceID, transId, path, false, AAIConstants.AAI_RESOURCES_PORT);
300 * @param <T> the generic type
302 * @param sourceID the source ID
303 * @param transId the trans id
304 * @param path the path
305 * @throws AAIException the AAI exception
307 public <T> void Put(T t, String sourceID, String transId, String path, boolean oldserver) throws AAIException {
308 Put( t, sourceID, transId, path, oldserver, AAIConstants.AAI_RESOURCES_PORT);
314 * @param <T> the generic type
316 * @param sourceID the source ID
317 * @param transId the trans id
318 * @param path the path
319 * @param oldserver the oldserver
320 * @throws AAIException the AAI exception
322 public <T> void Put(T t, String sourceID, String transId, String path, boolean oldserver, int port) throws AAIException {
323 String methodName = "Put";
325 transId += ":" + UUID.randomUUID().toString();
327 LoggingContext.save();
328 LoggingContext.partnerName(sourceID);
329 LoggingContext.targetEntity(TARGET_NAME);
330 LoggingContext.requestId(transId);
331 LoggingContext.serviceName(methodName);
332 LoggingContext.targetServiceName(methodName);
334 LOGGER.debug(methodName + " start");
339 url = AAIConfig.get(AAIConstants.AAI_OLDSERVER_URL) + path;
341 if ( overrideLocalHost == null ) {
342 overrideLocalHost = AAIConfig.get(AAIConstants.AAI_LOCAL_OVERRIDE, AAIConstants.AAI_LOCAL_OVERRIDE_DEFAULT);
344 if ( AAIConstants.AAI_LOCAL_OVERRIDE_DEFAULT.equals(overrideLocalHost )) {
345 url = String.format(AAIConstants.AAI_LOCAL_REST, port, AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP)) + path;
347 url = String.format(AAIConstants.AAI_LOCAL_REST_OVERRIDE, overrideLocalHost, AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP)) + path;
351 ClientResponse cres = client.resource(url)
352 .accept("application/json")
353 .header("X-TransactionId", transId)
354 .header("X-FromAppId", sourceID)
355 .header("Real-Time", "true")
356 .type("application/json")
358 .put(ClientResponse.class);
360 // System.out.println("cres.tostring()="+cres.toString());
362 int statuscode = cres.getStatus();
363 if ( statuscode >= 200 && statuscode <= 299 ) {
364 LOGGER.debug(methodName+": url=" + url + ", request=" + path);
365 LoggingContext.restore();
367 LoggingContext.restore();
368 throw new AAIException("AAI_7116", methodName +" with status="+statuscode+", url="+url + ", msg=" + cres.getEntity(String.class));
372 public void Delete(String sourceID, String transId, String path) throws AAIException {
373 Delete(sourceID, transId, path, AAIConstants.AAI_RESOURCES_PORT);
378 * @param sourceID the source ID
379 * @param transId the trans id
380 * @param path the path
381 * @throws AAIException the AAI exception
383 public void Delete(String sourceID, String transId, String path, int port) throws AAIException {
384 String methodName = "Delete";
386 transId += ":" + UUID.randomUUID().toString();
388 LoggingContext.save();
389 LoggingContext.partnerName(sourceID);
390 LoggingContext.targetEntity(TARGET_NAME);
391 LoggingContext.requestId(transId);
392 LoggingContext.serviceName(methodName);
393 LoggingContext.targetServiceName(methodName);
395 LOGGER.debug(methodName + " start");
398 String request = "{}";
399 if ( overrideLocalHost == null ) {
400 overrideLocalHost = AAIConfig.get(AAIConstants.AAI_LOCAL_OVERRIDE, AAIConstants.AAI_LOCAL_OVERRIDE_DEFAULT);
402 if ( AAIConstants.AAI_LOCAL_OVERRIDE_DEFAULT.equals(overrideLocalHost )) {
403 url = String.format(AAIConstants.AAI_LOCAL_REST, port, AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP)) + path;
405 url = String.format(AAIConstants.AAI_LOCAL_REST_OVERRIDE, overrideLocalHost, AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP)) + path;
407 ClientResponse cres = client.resource(url)
408 .accept("application/json")
409 .header("X-TransactionId", transId)
410 .header("X-FromAppId", sourceID)
411 .header("Real-Time", "true")
412 .type("application/json")
414 .delete(ClientResponse.class);
416 if (cres.getStatus() == 404) { // resource not found
417 LOGGER.info("Resource does not exist...: " + cres.getStatus()
418 + ":" + cres.getEntity(String.class));
419 LoggingContext.restore();
420 } else if (cres.getStatus() == 200 || cres.getStatus() == 204){
421 LOGGER.info("Resource " + url + " deleted");
422 LoggingContext.restore();
424 LOGGER.error("Deleting Resource failed: " + cres.getStatus()
425 + ":" + cres.getEntity(String.class));
426 LoggingContext.restore();
427 throw new AAIException("AAI_7116", "Error during DELETE");
431 public <T> String Post(T t, String sourceID, String transId, String path) throws Exception {
432 return Post(t, sourceID, transId, path, AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP));
437 * @param <T> the generic type
439 * @param sourceID the source ID
440 * @param transId the trans id
441 * @param path the path
442 * @param apiVersion the apiVersion
444 * @throws Exception the exception
446 public <T> String Post(T t, String sourceID, String transId, String path, String apiVersion) throws Exception {
447 String methodName = "Post";
449 transId += ":" + UUID.randomUUID().toString();
451 LoggingContext.save();
452 LoggingContext.partnerName(sourceID);
453 LoggingContext.targetEntity(TARGET_NAME);
454 LoggingContext.requestId(transId);
455 LoggingContext.serviceName(methodName);
456 LoggingContext.targetServiceName(methodName);
458 LOGGER.debug(methodName + " start");
463 url = AAIConfig.get(AAIConstants.AAI_SERVER_URL_BASE) + apiVersion + "/" + path;
465 ClientResponse cres = client.resource(url)
466 .accept("application/json")
467 .header("X-TransactionId", transId)
468 .header("X-FromAppId", sourceID)
469 .header("Real-Time", "true")
470 .type("application/json")
472 .post(ClientResponse.class);
474 int statuscode = cres.getStatus();
475 if ( statuscode >= 200 && statuscode <= 299 ) {
476 LOGGER.debug(methodName + "REST api POST was successful!");
477 return cres.getEntity(String.class);
479 throw new AAIException("AAI_7116", methodName +" with status="+statuscode+", url="+url + ", msg=" + cres.getEntity(String.class));
482 } catch (AAIException e) {
483 throw new AAIException("AAI_7116", methodName + " with url="+url+ ", Exception: " + e.toString());
484 } catch (Exception e)
486 throw new AAIException("AAI_7116", methodName + " with url="+url+ ", Exception: " + e.toString());
490 LoggingContext.restore();
496 * Gets the single instance of RestController.
498 * @param <T> the generic type
499 * @param clazz the clazz
500 * @return single instance of RestController
501 * @throws IllegalAccessException the illegal access exception
502 * @throws InstantiationException the instantiation exception
504 public <T> T getInstance(Class<T> clazz) throws IllegalAccessException, InstantiationException
506 return clazz.newInstance();
510 * Does resource exist.
512 * @param <T> the generic type
513 * @param resourcePath the resource path
514 * @param resourceClassName the resource class name
515 * @param fromAppId the from app id
516 * @param transId the trans id
522 * To check whether a resource exist or get a copy of the existing version of the resource
524 * Resourcepath: should contain the qualified resource path (including encoded unique key identifier value),
525 * resourceClassName: is the canonical name of the resource class name,
529 * Will return null (if the resource doesn’t exist) (or)
530 * Will return the specified resource from the Graph.
533 * LogicalLink llink = new LogicalLink();
534 * String resourceClassName = llink.getClass().getCanonicalName();
535 * llink = RestController.DoesResourceExist("network/logical-links/logical-link/" + <encoded-link-name>, resourceClassName, fromAppId, transId);
537 public <T> T DoesResourceExist(String resourcePath, String resourceClassName, String fromAppId, String transId) {
541 RestObject<T> restObj = new RestObject<T>();
542 @SuppressWarnings("unchecked")
543 T resourceObj = (T)getInstance(Class.forName(resourceClassName));
544 restObj.set(resourceObj);
545 Get(resourceObj, fromAppId, transId, resourcePath, restObj, false, AAIConstants.AAI_RESOURCES_PORT);
547 resourceObj = restObj.get();
548 if (resourceObj != null)
551 } catch (AAIException e) {
553 } catch (ClientHandlerException che) {
555 }catch (Exception e) {
565 * @param <T> the generic type
566 * @param sourceID the source ID
567 * @param transId the trans id
568 * @param path the path
569 * @throws AAIException the AAI exception
571 public <T> void Patch(T t, String sourceID, String transId, String path) throws AAIException {
572 String methodName = "Patch";
574 transId += ":" + UUID.randomUUID().toString();
576 LoggingContext.save();
577 LoggingContext.partnerName(sourceID);
578 LoggingContext.targetEntity(TARGET_NAME);
579 LoggingContext.requestId(transId);
580 LoggingContext.serviceName(methodName);
581 LoggingContext.targetServiceName(methodName);
585 ClientResponse cres = null;
589 if ( overrideLocalHost == null ) {
590 overrideLocalHost = AAIConfig.get(AAIConstants.AAI_LOCAL_OVERRIDE, AAIConstants.AAI_LOCAL_OVERRIDE_DEFAULT);
592 if ( AAIConstants.AAI_LOCAL_OVERRIDE_DEFAULT.equals(overrideLocalHost )) {
593 url = String.format(AAIConstants.AAI_LOCAL_REST, AAIConstants.AAI_RESOURCES_PORT, AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP)) + path;
595 url = String.format(AAIConstants.AAI_LOCAL_REST_OVERRIDE, overrideLocalHost, AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP)) + path;
601 cres = client.resource(url)
602 .accept("application/json")
603 .header("X-TransactionId", transId)
604 .header("X-FromAppId", sourceID)
605 .header("X-HTTP-Method-Override", "PATCH")
606 .type("application/merge-patch+json")
608 .post(ClientResponse.class);
610 statusCode = cres.getStatus();
612 if ( statusCode >= 200 && statusCode <= 299 ) {
613 LOGGER.debug(methodName + "REST api PATCH was successful!");
616 LOGGER.debug(methodName + "Unable to make the patch request to url " + url + " so retrying");
621 } while(numRetries >= 0);
623 LOGGER.debug(methodName + "Unable to make the patch request to url " + url + " even after trying = " + numRetries + " times.");
624 throw new AAIException("AAI_7116", methodName +" with status="+statusCode+", url="+url + ", msg=" + cres.getEntity(String.class));
626 } catch (AAIException e) {
627 throw new AAIException("AAI_7116", methodName + " with url="+url+ ", Exception: " + e.toString());
628 } catch (Exception e)
630 throw new AAIException("AAI_7116", methodName + " with url="+url+ ", Exception: " + e.toString());
634 LoggingContext.restore();