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 {
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 //To do - Come up with helper function that will automatically
48 //generate the REST API path based on path parameter(s) and query parameter(s)!
49 public static final String REST_APIPATH_COMPLEXES = "cloud-infrastructure/complexes";
50 public static final String REST_APIPATH_COMPLEX = "cloud-infrastructure/complexes/complex/";
51 public static final String REST_APIPATH_PSERVERS = "cloud-infrastructure/pservers";
52 public static final String REST_APIPATH_PSERVER = "cloud-infrastructure/pservers/pserver/";
53 public static final String REST_APIPATH_PHYSICALLINKS = "network/physical-links/";
54 public static final String REST_APIPATH_PHYSICALLINK = "network/physical-links/physical-link/";
55 public static final String REST_APIPATH_PINTERFACES = "network/p-interfaces/";
56 public static final String REST_APIPATH_PINTERFACE = "network/p-interfaces/p-interface/";
57 public static final String REST_APIPATH_VPLSPES = "network/vpls-pes/";
58 public static final String REST_APIPATH_VPLSPE = "network/vpls-pes/vpls-pe/";
59 public static final String REST_APIPATH_UPDATE = "actions/update/";
60 public static final String REST_APIPATH_SEARCH = "search/nodes-query?search-node-type=";
62 public static final String REST_APIPATH_CLOUDREGION = "cloud-infrastructure/cloud-regions/cloud-region/";
63 public static final String REST_APIPATH_TENANT = "cloud-infrastructure/tenants/tenant/";
64 public static final String REST_APIPATH_VIRTUAL_DATA_CENTER = "cloud-infrastructure/virtual-data-centers/virtual-data-center/";
65 public static final String REST_APIPATH_VIRTUAL_DATA_CENTERS = "cloud-infrastructure/virtual-data-centers/";
66 //network/generic-vnfs/generic-vnf/{vnf-id}
67 public static final String REST_APIPATH_GENERIC_VNF = "network/generic-vnfs/generic-vnf/";
68 public static final String REST_APIPATH_GENERIC_VNFS = "network/generic-vnfs";
69 public static final String REST_APIPATH_L3_NETWORK = "network/l3-networks/l3-network/";
70 public static final String REST_APIPATH_L3_NETWORKS = "network/l3-networks";
71 public static final String REST_APIPATH_INSTANCE_GROUP = "network/instance-groups/instance-group";
72 public static final String REST_APIPATH_INSTANCE_GROUPS = "network/instance-groups";
74 public static final String REST_APIPATH_VCE = "network/vces/vce/";
76 public static final String REST_APIPATH_SERVICE = "service-design-and-creation/services/service/";
77 public static final String REST_APIPATH_LOGICALLINKS = "network/logical-links/";
78 public static final String REST_APIPATH_LOGICALLINK = "network/logical-links/logical-link/";
81 * Inits the rest client.
83 * @throws AAIException the AAI exception
85 private static void initRestClient() throws AAIException
89 client = HttpsAuthClient.getClient();
91 catch (KeyManagementException e){
92 throw new AAIException("AAI_7117", "KeyManagementException in REST call to DB: " + e.toString());
93 } catch (Exception e) {
94 throw new AAIException("AAI_7117", " Exception in REST call to DB: " + e.toString());
100 * Sets the rest srvr base URL.
102 * @param baseURL the base URL
103 * @throws AAIException the AAI exception
105 public void SetRestSrvrBaseURL(String baseURL) throws AAIException
108 throw new AAIException("AAI_7117", "REST Server base URL cannot be null.");
109 restSrvrBaseURL = baseURL;
113 * Gets the rest srvr base URL.
115 * @return the rest srvr base URL
117 public String getRestSrvrBaseURL()
119 return restSrvrBaseURL;
123 public static <T> void Get(T t, String sourceID, String transId, String path, RestObject<T> restObject, boolean oldserver) throws AAIException {
124 RestController.<T>Get(t, sourceID, transId, path, restObject, oldserver, AAIConstants.AAI_RESOURCES_PORT);
127 * To do - optimization and automation. Also make it as generic as possible.
129 * @param <T> the generic type
131 * @param sourceID the source ID
132 * @param transId the trans id
133 * @param path the path
134 * @param restObject the rest object
135 * @param oldserver the oldserver
136 * @throws AAIException the AAI exception
138 @SuppressWarnings("unchecked")
139 public static <T> void Get(T t, String sourceID, String transId, String path, RestObject<T> restObject, boolean oldserver, int port) throws AAIException {
140 String methodName = "Get";
142 transId += ":" + UUID.randomUUID().toString();
144 LoggingContext.save();
145 LoggingContext.partnerName(sourceID);
146 LoggingContext.targetEntity(TARGET_NAME);
147 LoggingContext.requestId(transId);
148 LoggingContext.serviceName(methodName);
149 LoggingContext.targetServiceName(methodName);
151 LOGGER.debug(methodName + " start");
156 url = AAIConfig.get(AAIConstants.AAI_OLDSERVER_URL) + path;
158 url = String.format(AAIConstants.AAI_LOCAL_REST, port) + path;
160 LOGGER.debug(url + " for the get REST API");
161 ClientResponse cres = client.resource(url)
162 .accept("application/json")
163 .header("X-TransactionId", transId)
164 .header("X-FromAppId", sourceID)
165 .header("Real-Time", "true")
166 .type("application/json")
167 .get(ClientResponse.class);
169 // System.out.println("cres.EntityInputSream()="+cres.getEntityInputStream().toString());
170 // System.out.println("cres.tostring()="+cres.toString());
172 if (cres.getStatus() == 200) {
173 // System.out.println(methodName + ": url=" + url);
174 t = (T) cres.getEntity(t.getClass());
176 LOGGER.debug(methodName + "REST api GET was successfull!");
178 LoggingContext.restore();
179 // System.out.println(methodName + ": url=" + url + " failed with status=" + cres.getStatus());
180 throw new AAIException("AAI_7116", methodName +" with status="+cres.getStatus()+", url="+url);
183 LoggingContext.restore();
187 * Map json to object list.
189 * @param <T> the generic type
190 * @param typeDef the type def
191 * @param json the json
192 * @param clazz the clazz
194 * @throws Exception the exception
196 private static <T> List<T> mapJsonToObjectList(T typeDef,String json, Class clazz) throws Exception
199 ObjectMapper mapper = new ObjectMapper();
200 System.out.println(json);
201 TypeFactory t = TypeFactory.defaultInstance();
202 list = mapper.readValue(json, t.constructCollectionType(ArrayList.class,clazz));
210 * @param <T> the generic type
212 * @param sourceID the source ID
213 * @param transId the trans id
214 * @param path the path
215 * @throws AAIException the AAI exception
217 public static <T> void Put(T t, String sourceID, String transId, String path) throws AAIException {
218 Put( t, sourceID, transId, path, false, AAIConstants.AAI_RESOURCES_PORT);
224 * @param <T> the generic type
226 * @param sourceID the source ID
227 * @param transId the trans id
228 * @param path the path
229 * @throws AAIException the AAI exception
231 public static <T> void Put(T t, String sourceID, String transId, String path, boolean oldserver) throws AAIException {
232 Put( t, sourceID, transId, path, oldserver, AAIConstants.AAI_RESOURCES_PORT);
238 * @param <T> the generic type
240 * @param sourceID the source ID
241 * @param transId the trans id
242 * @param path the path
243 * @param oldserver the oldserver
244 * @throws AAIException the AAI exception
246 public static <T> void Put(T t, String sourceID, String transId, String path, boolean oldserver, int port) throws AAIException {
247 String methodName = "Put";
249 transId += ":" + UUID.randomUUID().toString();
251 LoggingContext.save();
252 LoggingContext.partnerName(sourceID);
253 LoggingContext.targetEntity(TARGET_NAME);
254 LoggingContext.requestId(transId);
255 LoggingContext.serviceName(methodName);
256 LoggingContext.targetServiceName(methodName);
258 LOGGER.debug(methodName + " start");
263 url = AAIConfig.get(AAIConstants.AAI_OLDSERVER_URL) + path;
265 url = String.format(AAIConstants.AAI_LOCAL_REST, port) + path;
267 ClientResponse cres = client.resource(url)
268 .accept("application/json")
269 .header("X-TransactionId", transId)
270 .header("X-FromAppId", sourceID)
271 .header("Real-Time", "true")
272 .type("application/json")
274 .put(ClientResponse.class);
276 // System.out.println("cres.tostring()="+cres.toString());
278 int statuscode = cres.getStatus();
279 if ( statuscode >= 200 && statuscode <= 299 ) {
280 LOGGER.debug(methodName+": url=" + url + ", request=" + path);
281 LoggingContext.restore();
283 LoggingContext.restore();
284 throw new AAIException("AAI_7116", methodName +" with status="+statuscode+", url="+url + ", msg=" + cres.getEntity(String.class));
288 public static void Delete(String sourceID, String transId, String path) throws AAIException {
289 RestController.Delete(sourceID, transId, path, AAIConstants.AAI_RESOURCES_PORT);
294 * @param sourceID the source ID
295 * @param transId the trans id
296 * @param path the path
297 * @throws AAIException the AAI exception
299 public static void Delete(String sourceID, String transId, String path, int port) throws AAIException {
300 String methodName = "Delete";
302 transId += ":" + UUID.randomUUID().toString();
304 LoggingContext.save();
305 LoggingContext.partnerName(sourceID);
306 LoggingContext.targetEntity(TARGET_NAME);
307 LoggingContext.requestId(transId);
308 LoggingContext.serviceName(methodName);
309 LoggingContext.targetServiceName(methodName);
311 LOGGER.debug(methodName + " start");
314 String request = "{}";
315 url = String.format(AAIConstants.AAI_LOCAL_REST, port) + path;
316 ClientResponse cres = client.resource(url)
317 .accept("application/json")
318 .header("X-TransactionId", transId)
319 .header("X-FromAppId", sourceID)
320 .header("Real-Time", "true")
321 .type("application/json")
323 .delete(ClientResponse.class);
325 if (cres.getStatus() == 404) { // resource not found
326 LOGGER.info("Resource does not exist...: " + cres.getStatus()
327 + ":" + cres.getEntity(String.class));
328 LoggingContext.restore();
329 } else if (cres.getStatus() == 200 || cres.getStatus() == 204){
330 LOGGER.info("Resource " + url + " deleted");
331 LoggingContext.restore();
333 LOGGER.error("Deleting Resource failed: " + cres.getStatus()
334 + ":" + cres.getEntity(String.class));
335 LoggingContext.restore();
336 throw new AAIException("AAI_7116", "Error during DELETE");
343 * @param <T> the generic type
345 * @param sourceID the source ID
346 * @param transId the trans id
347 * @param path the path
349 * @throws Exception the exception
351 public static <T> String Post(T t, String sourceID, String transId, String path) throws Exception {
352 String methodName = "Post";
354 transId += ":" + UUID.randomUUID().toString();
356 LoggingContext.save();
357 LoggingContext.partnerName(sourceID);
358 LoggingContext.targetEntity(TARGET_NAME);
359 LoggingContext.requestId(transId);
360 LoggingContext.serviceName(methodName);
361 LoggingContext.targetServiceName(methodName);
363 LOGGER.debug(methodName + " start");
369 url = AAIConfig.get(AAIConstants.AAI_SERVER_URL) + path;
371 ClientResponse cres = client.resource(url)
372 .accept("application/json")
373 .header("X-TransactionId", transId)
374 .header("X-FromAppId", sourceID)
375 .header("Real-Time", "true")
376 .type("application/json")
378 .post(ClientResponse.class);
380 int statuscode = cres.getStatus();
381 if ( statuscode >= 200 && statuscode <= 299 ) {
382 LOGGER.debug(methodName + "REST api POST was successful!");
383 return cres.getEntity(String.class);
385 throw new AAIException("AAI_7116", methodName +" with status="+statuscode+", url="+url + ", msg=" + cres.getEntity(String.class));
388 } catch (AAIException e) {
389 throw new AAIException("AAI_7116", methodName + " with url="+url+ ", Exception: " + e.toString());
390 } catch (Exception e)
392 throw new AAIException("AAI_7116", methodName + " with url="+url+ ", Exception: " + e.toString());
396 LoggingContext.restore();
402 * Gets the single instance of RestController.
404 * @param <T> the generic type
405 * @param clazz the clazz
406 * @return single instance of RestController
407 * @throws IllegalAccessException the illegal access exception
408 * @throws InstantiationException the instantiation exception
410 public static <T> T getInstance(Class<T> clazz) throws IllegalAccessException, InstantiationException
412 return clazz.newInstance();
416 * Does resource exist.
418 * @param <T> the generic type
419 * @param resourcePath the resource path
420 * @param resourceClassName the resource class name
421 * @param fromAppId the from app id
422 * @param transId the trans id
428 * To check whether a resource exist or get a copy of the existing version of the resource
430 * Resourcepath: should contain the qualified resource path (including encoded unique key identifier value),
431 * resourceClassName: is the canonical name of the resource class name,
435 * Will return null (if the resource doesn’t exist) (or)
436 * Will return the specified resource from the Graph.
439 * LogicalLink llink = new LogicalLink();
440 * String resourceClassName = llink.getClass().getCanonicalName();
441 * llink = RestController.DoesResourceExist("network/logical-links/logical-link/" + <encoded-link-name>, resourceClassName, fromAppId, transId);
443 public static <T> T DoesResourceExist(String resourcePath, String resourceClassName, String fromAppId, String transId) {
447 RestObject<T> restObj = new RestObject<T>();
448 @SuppressWarnings("unchecked")
449 T resourceObj = (T)getInstance(Class.forName(resourceClassName));
450 restObj.set(resourceObj);
451 RestController.<T>Get(resourceObj, fromAppId, transId, resourcePath, restObj, false, AAIConstants.AAI_RESOURCES_PORT);
453 resourceObj = restObj.get();
454 if (resourceObj != null)
457 } catch (AAIException e) {
459 } catch (ClientHandlerException che) {
461 }catch (Exception e) {