421946ef5dcfc1f9108a24a90e3f691b18653854
[aai/aai-common.git] / aai-core / src / main / java / org / onap / aai / util / RestController.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
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
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 package org.onap.aai.util;
22
23 import java.security.KeyManagementException;
24 import java.util.ArrayList;
25 import java.util.List;
26 import java.util.UUID;
27
28 import org.onap.aai.exceptions.AAIException;
29 import org.onap.aai.logging.LoggingContext;
30
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;
38
39 public class RestController {
40
41         private static final String TARGET_NAME = "AAI";
42         private static EELFLogger LOGGER = EELFManager.getInstance().getLogger(RestController.class);
43         
44         private static Client client = null;
45         
46         private String restSrvrBaseURL;
47         
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=";
62         
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";
74         
75         public static final  String REST_APIPATH_VCE = "network/vces/vce/";
76         
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/";
80         
81         /**
82          * Inits the rest client.
83          *
84          * @throws AAIException the AAI exception
85          */
86         private static void initRestClient() throws AAIException
87         {
88                 if (client == null) {
89                         try {
90                                 client = HttpsAuthClient.getClient();
91                         }
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());
96                         }
97                 }
98         }
99         
100         /**
101          * Sets the rest srvr base URL.
102          *
103          * @param baseURL the base URL
104          * @throws AAIException the AAI exception
105          */
106         public void SetRestSrvrBaseURL(String baseURL) throws AAIException
107         {
108                 if (baseURL == null)
109                         throw new AAIException("AAI_7117", "REST Server base URL cannot be null.");
110                 restSrvrBaseURL = baseURL;
111         }
112         
113         /**
114          * Gets the rest srvr base URL.
115          *
116          * @return the rest srvr base URL
117          */
118         public String getRestSrvrBaseURL() 
119         {
120                 return restSrvrBaseURL;
121         }
122         
123         
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);
126         }
127         /**
128          * To do - optimization and automation.  Also make it as generic as possible.
129          *
130          * @param <T> the generic type
131          * @param t the t
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
138          */
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";
142                 String url="";
143                 transId += ":" + UUID.randomUUID().toString();
144
145                 LoggingContext.save();
146                 LoggingContext.partnerName(sourceID);
147                 LoggingContext.targetEntity(TARGET_NAME);
148                 LoggingContext.requestId(transId);
149                 LoggingContext.serviceName(methodName);
150                 LoggingContext.targetServiceName(methodName);
151                 
152                 LOGGER.debug(methodName + " start");
153         
154                 restObject.set(t);
155                 
156                 if (oldserver)
157                         url = AAIConfig.get(AAIConstants.AAI_OLDSERVER_URL) + path;
158                 else
159                         url = String.format(AAIConstants.AAI_LOCAL_REST, port) + path;
160                 initRestClient();
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);
169
170 //                      System.out.println("cres.EntityInputSream()="+cres.getEntityInputStream().toString());
171 //                      System.out.println("cres.tostring()="+cres.toString());
172                         
173                  if (cres.getStatus() == 200) {
174 //                   System.out.println(methodName + ": url=" + url);
175                          t = (T) cres.getEntity(t.getClass());
176                          restObject.set(t);
177                          LOGGER.debug(methodName + "REST api GET was successfull!");                
178                  } else {
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);
182                  }
183
184                  LoggingContext.restore();
185         }
186         
187    /**
188     * Map json to object list.
189     *
190     * @param <T> the generic type
191     * @param typeDef the type def
192     * @param json the json
193     * @param clazz the clazz
194     * @return the list
195     * @throws Exception the exception
196     */
197    private static <T> List<T> mapJsonToObjectList(T typeDef,String json, Class clazz) throws Exception
198    {
199       List<T> list;
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));
204
205       return list;
206    }
207    
208    /**
209          * Put.
210          *
211          * @param <T> the generic type
212          * @param t the t
213          * @param sourceID the source ID
214          * @param transId the trans id
215          * @param path the path
216          * @throws AAIException the AAI exception
217          */
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);
220         }
221            
222         /**
223          * Put.
224          *
225          * @param <T> the generic type
226          * @param t the t
227          * @param sourceID the source ID
228          * @param transId the trans id
229          * @param path the path
230          * @throws AAIException the AAI exception
231          */
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);
234         }
235
236         /**
237          * Put.
238          *
239          * @param <T> the generic type
240          * @param t the t
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
246          */
247         public static <T> void Put(T t, String sourceID,  String transId,  String path, boolean oldserver, int port) throws AAIException {
248                 String methodName = "Put";
249                 String url="";
250                 transId += ":" + UUID.randomUUID().toString();
251                 
252                 LoggingContext.save();
253                 LoggingContext.partnerName(sourceID);
254                 LoggingContext.targetEntity(TARGET_NAME);
255                 LoggingContext.requestId(transId);
256                 LoggingContext.serviceName(methodName);
257                 LoggingContext.targetServiceName(methodName);
258                 
259                 LOGGER.debug(methodName + " start");            
260
261                 initRestClient();
262                 
263                 if (oldserver)
264                         url = AAIConfig.get(AAIConstants.AAI_OLDSERVER_URL) + path;
265                 else
266                         url = String.format(AAIConstants.AAI_LOCAL_REST, port) + path;
267                 
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")
274                  .entity(t)
275                  .put(ClientResponse.class);
276         
277 //                      System.out.println("cres.tostring()="+cres.toString());
278                 
279                 int statuscode = cres.getStatus();
280                 if ( statuscode >= 200 && statuscode <= 299 ) {
281                          LOGGER.debug(methodName+": url=" + url + ", request=" + path);
282                          LoggingContext.restore();
283                  } else {
284                          LoggingContext.restore();
285                          throw new AAIException("AAI_7116", methodName +" with status="+statuscode+", url="+url + ", msg=" + cres.getEntity(String.class));
286                  }                       
287         }
288         
289         public static void Delete(String sourceID,  String transId,  String path) throws AAIException {
290                 RestController.Delete(sourceID, transId, path, AAIConstants.AAI_RESOURCES_PORT);
291         }
292         /**
293          * Delete.
294          *
295          * @param sourceID the source ID
296          * @param transId the trans id
297          * @param path the path
298          * @throws AAIException the AAI exception
299          */
300         public static void Delete(String sourceID,  String transId,  String path, int port) throws AAIException {
301                 String methodName = "Delete";
302                 String url="";
303                 transId += ":" + UUID.randomUUID().toString();
304                 
305                 LoggingContext.save();
306                 LoggingContext.partnerName(sourceID);
307                 LoggingContext.targetEntity(TARGET_NAME);
308                 LoggingContext.requestId(transId);
309                 LoggingContext.serviceName(methodName);
310                 LoggingContext.targetServiceName(methodName);
311                 
312                 LOGGER.debug(methodName + " start");
313                 
314                 initRestClient();
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")
323                          .entity(request)
324                          .delete(ClientResponse.class);
325                         
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();
333                 } else {
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");
338                 }
339         }
340         
341     /**
342      * Post.
343      *
344      * @param <T> the generic type
345      * @param t the t
346      * @param sourceID the source ID
347      * @param transId the trans id
348      * @param path the path
349      * @return the string
350      * @throws Exception the exception
351      */
352     public static <T> String Post(T t, String sourceID,  String transId,  String path) throws Exception {
353         String methodName = "Post";
354         String url="";
355         transId += ":" + UUID.randomUUID().toString();
356         
357         LoggingContext.save();
358         LoggingContext.partnerName(sourceID);
359                 LoggingContext.targetEntity(TARGET_NAME);
360                 LoggingContext.requestId(transId);
361                 LoggingContext.serviceName(methodName);
362                 LoggingContext.targetServiceName(methodName);
363                 
364         LOGGER.debug(methodName + " start");        
365         
366         try {
367             
368             initRestClient();    
369     
370             url = AAIConfig.get(AAIConstants.AAI_SERVER_URL) + path;
371             
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")
378                  .entity(t)
379                  .post(ClientResponse.class);
380             
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);
385              } else {
386                  throw new AAIException("AAI_7116", methodName +" with status="+statuscode+", url="+url + ", msg=" + cres.getEntity(String.class));
387              }    
388         
389         } catch (AAIException e) {
390             throw new AAIException("AAI_7116", methodName + " with url="+url+ ", Exception: " + e.toString());
391         } catch (Exception e)
392         {
393             throw new AAIException("AAI_7116", methodName + " with url="+url+ ", Exception: " + e.toString());
394         
395         }
396         finally {
397                 LoggingContext.restore();
398         }
399     }
400
401         
402     /**
403      * Gets the single instance of RestController.
404      *
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
410      */
411     public static <T> T getInstance(Class<T> clazz) throws IllegalAccessException, InstantiationException
412         {
413                 return clazz.newInstance();
414         } 
415         
416     /**
417      * Does resource exist.
418      *
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
424      * @return the t
425      */
426     /*
427      *     DoesResourceExist
428      *     
429      *     To check whether a resource exist or get a copy of the existing version of the resource
430      *  
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, 
433      *       fromAppId:
434      *       transId:
435      *       
436      *     Will return null (if the resource doesn’t exist)  (or) 
437      *     Will return the specified resource from the Graph.
438      *     
439      *     Example:
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);
443    */
444         public static <T> T DoesResourceExist(String resourcePath, String resourceClassName, String fromAppId, String transId) {
445                                         
446                 try {
447                         
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);
453                         
454                         resourceObj = restObj.get();
455                         if (resourceObj != null)
456                           return resourceObj;
457
458                 } catch (AAIException e) {
459                         
460                 } catch (ClientHandlerException che) {
461                         
462                 }catch (Exception e) {
463                         
464                 }
465                 
466                 return null;
467         }
468         
469 }