2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 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 java.security.KeyManagementException;
24 import java.util.ArrayList;
25 import java.util.List;
26 import java.util.UUID;
28 import org.onap.aai.exceptions.AAIException;
29 import org.onap.aai.logging.LoggingContext;
31 import com.att.eelf.configuration.EELFLogger;
32 import com.att.eelf.configuration.EELFManager;
33 import com.fasterxml.jackson.databind.ObjectMapper;
34 import com.fasterxml.jackson.databind.type.TypeFactory;
35 import com.sun.jersey.api.client.Client;
36 import com.sun.jersey.api.client.ClientHandlerException;
37 import com.sun.jersey.api.client.ClientResponse;
39 public class RestController {
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 //To do - Come up with helper function that will automatically
49 //generate the REST API path based on path parameter(s) and query parameter(s)!
50 public static final String REST_APIPATH_COMPLEXES = "cloud-infrastructure/complexes";
51 public static final String REST_APIPATH_COMPLEX = "cloud-infrastructure/complexes/complex/";
52 public static final String REST_APIPATH_PSERVERS = "cloud-infrastructure/pservers";
53 public static final String REST_APIPATH_PSERVER = "cloud-infrastructure/pservers/pserver/";
54 public static final String REST_APIPATH_PHYSICALLINKS = "network/physical-links/";
55 public static final String REST_APIPATH_PHYSICALLINK = "network/physical-links/physical-link/";
56 public static final String REST_APIPATH_PINTERFACES = "network/p-interfaces/";
57 public static final String REST_APIPATH_PINTERFACE = "network/p-interfaces/p-interface/";
58 public static final String REST_APIPATH_VPLSPES = "network/vpls-pes/";
59 public static final String REST_APIPATH_VPLSPE = "network/vpls-pes/vpls-pe/";
60 public static final String REST_APIPATH_UPDATE = "actions/update/";
61 public static final String REST_APIPATH_SEARCH = "search/nodes-query?search-node-type=";
63 public static final String REST_APIPATH_CLOUDREGION = "cloud-infrastructure/cloud-regions/cloud-region/";
64 public static final String REST_APIPATH_TENANT = "cloud-infrastructure/tenants/tenant/";
65 public static final String REST_APIPATH_VIRTUAL_DATA_CENTER = "cloud-infrastructure/virtual-data-centers/virtual-data-center/";
66 public static final String REST_APIPATH_VIRTUAL_DATA_CENTERS = "cloud-infrastructure/virtual-data-centers/";
67 //network/generic-vnfs/generic-vnf/{vnf-id}
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";
75 public static final String REST_APIPATH_VCE = "network/vces/vce/";
77 public static final String REST_APIPATH_SERVICE = "service-design-and-creation/services/service/";
78 public static final String REST_APIPATH_LOGICALLINKS = "network/logical-links/";
79 public static final String REST_APIPATH_LOGICALLINK = "network/logical-links/logical-link/";
82 * Inits the rest client.
84 * @throws AAIException the AAI exception
86 private static void initRestClient() throws AAIException
90 client = HttpsAuthClient.getClient();
92 catch (KeyManagementException e){
93 throw new AAIException("AAI_7117", "KeyManagementException in REST call to DB: " + e.toString());
94 } catch (Exception e) {
95 throw new AAIException("AAI_7117", " Exception in REST call to DB: " + e.toString());
101 * Sets the rest srvr base URL.
103 * @param baseURL the base URL
104 * @throws AAIException the AAI exception
106 public void SetRestSrvrBaseURL(String baseURL) throws AAIException
109 throw new AAIException("AAI_7117", "REST Server base URL cannot be null.");
110 restSrvrBaseURL = baseURL;
114 * Gets the rest srvr base URL.
116 * @return the rest srvr base URL
118 public String getRestSrvrBaseURL()
120 return restSrvrBaseURL;
124 public static <T> void Get(T t, String sourceID, String transId, String path, RestObject<T> restObject, boolean oldserver) throws AAIException {
125 RestController.<T>Get(t, sourceID, transId, path, restObject, oldserver, AAIConstants.AAI_RESOURCES_PORT);
128 * To do - optimization and automation. Also make it as generic as possible.
130 * @param <T> the generic type
132 * @param sourceID the source ID
133 * @param transId the trans id
134 * @param path the path
135 * @param restObject the rest object
136 * @param oldserver the oldserver
137 * @throws AAIException the AAI exception
139 @SuppressWarnings("unchecked")
140 public static <T> void Get(T t, String sourceID, String transId, String path, RestObject<T> restObject, boolean oldserver, int port) throws AAIException {
141 String methodName = "Get";
143 transId += ":" + UUID.randomUUID().toString();
145 LoggingContext.save();
146 LoggingContext.partnerName(sourceID);
147 LoggingContext.targetEntity(TARGET_NAME);
148 LoggingContext.requestId(transId);
149 LoggingContext.serviceName(methodName);
150 LoggingContext.targetServiceName(methodName);
152 LOGGER.debug(methodName + " start");
157 url = AAIConfig.get(AAIConstants.AAI_OLDSERVER_URL) + path;
159 url = String.format(AAIConstants.AAI_LOCAL_REST, port) + path;
161 LOGGER.debug(url + " for the get REST API");
162 ClientResponse cres = client.resource(url)
163 .accept("application/json")
164 .header("X-TransactionId", transId)
165 .header("X-FromAppId", sourceID)
166 .header("Real-Time", "true")
167 .type("application/json")
168 .get(ClientResponse.class);
170 // System.out.println("cres.EntityInputSream()="+cres.getEntityInputStream().toString());
171 // System.out.println("cres.tostring()="+cres.toString());
173 if (cres.getStatus() == 200) {
174 // System.out.println(methodName + ": url=" + url);
175 t = (T) cres.getEntity(t.getClass());
177 LOGGER.debug(methodName + "REST api GET was successfull!");
179 LoggingContext.restore();
180 // System.out.println(methodName + ": url=" + url + " failed with status=" + cres.getStatus());
181 throw new AAIException("AAI_7116", methodName +" with status="+cres.getStatus()+", url="+url);
184 LoggingContext.restore();
188 * Map json to object list.
190 * @param <T> the generic type
191 * @param typeDef the type def
192 * @param json the json
193 * @param clazz the clazz
195 * @throws Exception the exception
197 private static <T> List<T> mapJsonToObjectList(T typeDef,String json, Class clazz) throws Exception
200 ObjectMapper mapper = new ObjectMapper();
201 System.out.println(json);
202 TypeFactory t = TypeFactory.defaultInstance();
203 list = mapper.readValue(json, t.constructCollectionType(ArrayList.class,clazz));
211 * @param <T> the generic type
213 * @param sourceID the source ID
214 * @param transId the trans id
215 * @param path the path
216 * @throws AAIException the AAI exception
218 public static <T> void Put(T t, String sourceID, String transId, String path) throws AAIException {
219 Put( t, sourceID, transId, path, false, AAIConstants.AAI_RESOURCES_PORT);
225 * @param <T> the generic type
227 * @param sourceID the source ID
228 * @param transId the trans id
229 * @param path the path
230 * @throws AAIException the AAI exception
232 public static <T> void Put(T t, String sourceID, String transId, String path, boolean oldserver) throws AAIException {
233 Put( t, sourceID, transId, path, oldserver, AAIConstants.AAI_RESOURCES_PORT);
239 * @param <T> the generic type
241 * @param sourceID the source ID
242 * @param transId the trans id
243 * @param path the path
244 * @param oldserver the oldserver
245 * @throws AAIException the AAI exception
247 public static <T> void Put(T t, String sourceID, String transId, String path, boolean oldserver, int port) throws AAIException {
248 String methodName = "Put";
250 transId += ":" + UUID.randomUUID().toString();
252 LoggingContext.save();
253 LoggingContext.partnerName(sourceID);
254 LoggingContext.targetEntity(TARGET_NAME);
255 LoggingContext.requestId(transId);
256 LoggingContext.serviceName(methodName);
257 LoggingContext.targetServiceName(methodName);
259 LOGGER.debug(methodName + " start");
264 url = AAIConfig.get(AAIConstants.AAI_OLDSERVER_URL) + path;
266 url = String.format(AAIConstants.AAI_LOCAL_REST, port) + path;
268 ClientResponse cres = client.resource(url)
269 .accept("application/json")
270 .header("X-TransactionId", transId)
271 .header("X-FromAppId", sourceID)
272 .header("Real-Time", "true")
273 .type("application/json")
275 .put(ClientResponse.class);
277 // System.out.println("cres.tostring()="+cres.toString());
279 int statuscode = cres.getStatus();
280 if ( statuscode >= 200 && statuscode <= 299 ) {
281 LOGGER.debug(methodName+": url=" + url + ", request=" + path);
282 LoggingContext.restore();
284 LoggingContext.restore();
285 throw new AAIException("AAI_7116", methodName +" with status="+statuscode+", url="+url + ", msg=" + cres.getEntity(String.class));
289 public static void Delete(String sourceID, String transId, String path) throws AAIException {
290 RestController.Delete(sourceID, transId, path, AAIConstants.AAI_RESOURCES_PORT);
295 * @param sourceID the source ID
296 * @param transId the trans id
297 * @param path the path
298 * @throws AAIException the AAI exception
300 public static void Delete(String sourceID, String transId, String path, int port) throws AAIException {
301 String methodName = "Delete";
303 transId += ":" + UUID.randomUUID().toString();
305 LoggingContext.save();
306 LoggingContext.partnerName(sourceID);
307 LoggingContext.targetEntity(TARGET_NAME);
308 LoggingContext.requestId(transId);
309 LoggingContext.serviceName(methodName);
310 LoggingContext.targetServiceName(methodName);
312 LOGGER.debug(methodName + " start");
315 String request = "{}";
316 url = String.format(AAIConstants.AAI_LOCAL_REST, port) + path;
317 ClientResponse cres = client.resource(url)
318 .accept("application/json")
319 .header("X-TransactionId", transId)
320 .header("X-FromAppId", sourceID)
321 .header("Real-Time", "true")
322 .type("application/json")
324 .delete(ClientResponse.class);
326 if (cres.getStatus() == 404) { // resource not found
327 LOGGER.info("Resource does not exist...: " + cres.getStatus()
328 + ":" + cres.getEntity(String.class));
329 LoggingContext.restore();
330 } else if (cres.getStatus() == 200 || cres.getStatus() == 204){
331 LOGGER.info("Resource " + url + " deleted");
332 LoggingContext.restore();
334 LOGGER.error("Deleting Resource failed: " + cres.getStatus()
335 + ":" + cres.getEntity(String.class));
336 LoggingContext.restore();
337 throw new AAIException("AAI_7116", "Error during DELETE");
344 * @param <T> the generic type
346 * @param sourceID the source ID
347 * @param transId the trans id
348 * @param path the path
350 * @throws Exception the exception
352 public static <T> String Post(T t, String sourceID, String transId, String path) throws Exception {
353 String methodName = "Post";
355 transId += ":" + UUID.randomUUID().toString();
357 LoggingContext.save();
358 LoggingContext.partnerName(sourceID);
359 LoggingContext.targetEntity(TARGET_NAME);
360 LoggingContext.requestId(transId);
361 LoggingContext.serviceName(methodName);
362 LoggingContext.targetServiceName(methodName);
364 LOGGER.debug(methodName + " start");
370 url = AAIConfig.get(AAIConstants.AAI_SERVER_URL) + path;
372 ClientResponse cres = client.resource(url)
373 .accept("application/json")
374 .header("X-TransactionId", transId)
375 .header("X-FromAppId", sourceID)
376 .header("Real-Time", "true")
377 .type("application/json")
379 .post(ClientResponse.class);
381 int statuscode = cres.getStatus();
382 if ( statuscode >= 200 && statuscode <= 299 ) {
383 LOGGER.debug(methodName + "REST api POST was successful!");
384 return cres.getEntity(String.class);
386 throw new AAIException("AAI_7116", methodName +" with status="+statuscode+", url="+url + ", msg=" + cres.getEntity(String.class));
389 } catch (AAIException e) {
390 throw new AAIException("AAI_7116", methodName + " with url="+url+ ", Exception: " + e.toString());
391 } catch (Exception e)
393 throw new AAIException("AAI_7116", methodName + " with url="+url+ ", Exception: " + e.toString());
397 LoggingContext.restore();
403 * Gets the single instance of RestController.
405 * @param <T> the generic type
406 * @param clazz the clazz
407 * @return single instance of RestController
408 * @throws IllegalAccessException the illegal access exception
409 * @throws InstantiationException the instantiation exception
411 public static <T> T getInstance(Class<T> clazz) throws IllegalAccessException, InstantiationException
413 return clazz.newInstance();
417 * Does resource exist.
419 * @param <T> the generic type
420 * @param resourcePath the resource path
421 * @param resourceClassName the resource class name
422 * @param fromAppId the from app id
423 * @param transId the trans id
429 * To check whether a resource exist or get a copy of the existing version of the resource
431 * Resourcepath: should contain the qualified resource path (including encoded unique key identifier value),
432 * resourceClassName: is the canonical name of the resource class name,
436 * Will return null (if the resource doesn’t exist) (or)
437 * Will return the specified resource from the Graph.
440 * LogicalLink llink = new LogicalLink();
441 * String resourceClassName = llink.getClass().getCanonicalName();
442 * llink = RestController.DoesResourceExist("network/logical-links/logical-link/" + <encoded-link-name>, resourceClassName, fromAppId, transId);
444 public static <T> T DoesResourceExist(String resourcePath, String resourceClassName, String fromAppId, String transId) {
448 RestObject<T> restObj = new RestObject<T>();
449 @SuppressWarnings("unchecked")
450 T resourceObj = (T)getInstance(Class.forName(resourceClassName));
451 restObj.set(resourceObj);
452 RestController.<T>Get(resourceObj, fromAppId, transId, resourcePath, restObj, false, AAIConstants.AAI_RESOURCES_PORT);
454 resourceObj = restObj.get();
455 if (resourceObj != null)
458 } catch (AAIException e) {
460 } catch (ClientHandlerException che) {
462 }catch (Exception e) {