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