d2f90159c8af181dcb7f05d995cea3e0fd06111e
[ccsdk/sli/adaptors.git] / aai-service / provider / src / main / java / org / onap / ccsdk / sli / adaptors / aai / AAIService.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * openECOMP : SDN-C
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights
6  *             reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.ccsdk.sli.adaptors.aai;
23
24
25 import java.io.BufferedReader;
26 import java.io.ByteArrayInputStream;
27 import java.io.File;
28 import java.io.FileInputStream;
29 import java.io.InputStream;
30 import java.io.InputStreamReader;
31 import java.io.OutputStreamWriter;
32 import java.io.UnsupportedEncodingException;
33 import java.lang.reflect.Field;
34 import java.lang.reflect.InvocationTargetException;
35 import java.lang.reflect.Method;
36 import java.lang.reflect.Modifier;
37 import java.net.HttpURLConnection;
38 import java.net.MalformedURLException;
39 import java.net.URI;
40 import java.net.URISyntaxException;
41 import java.net.URL;
42 import java.net.URLEncoder;
43 import java.nio.charset.StandardCharsets;
44 import java.security.KeyManagementException;
45 import java.security.KeyStore;
46 import java.security.NoSuchAlgorithmException;
47 import java.text.SimpleDateFormat;
48 import java.util.ArrayList;
49 import java.util.Calendar;
50 import java.util.Enumeration;
51 import java.util.HashMap;
52 import java.util.LinkedList;
53 import java.util.List;
54 import java.util.Map;
55 import java.util.Map.Entry;
56 import java.util.Properties;
57 import java.util.Set;
58 import java.util.TimeZone;
59 import java.util.UUID;
60 import java.util.regex.Matcher;
61 import java.util.regex.Pattern;
62
63 import javax.net.ssl.HostnameVerifier;
64 import javax.net.ssl.HttpsURLConnection;
65 import javax.net.ssl.KeyManagerFactory;
66 import javax.net.ssl.SSLContext;
67 import javax.net.ssl.SSLSession;
68 import javax.net.ssl.SSLSocketFactory;
69 import javax.ws.rs.HttpMethod;
70 import javax.xml.bind.annotation.XmlElement;
71
72 import org.apache.commons.codec.binary.Base64;
73 import org.apache.commons.lang3.StringUtils;
74 import org.onap.ccsdk.sli.core.sli.ConfigurationException;
75 import org.onap.ccsdk.sli.core.sli.MetricLogger;
76 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
77 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
78 import org.onap.ccsdk.sli.core.sli.SvcLogicResource;
79 import org.openecomp.aai.inventory.v11.AvailabilityZone;
80 import org.openecomp.aai.inventory.v11.Complex;
81 import org.openecomp.aai.inventory.v11.CtagPool;
82 import org.openecomp.aai.inventory.v11.DvsSwitch;
83 import org.openecomp.aai.inventory.v11.GenericVnf;
84 import org.openecomp.aai.inventory.v11.L3Network;
85 import org.openecomp.aai.inventory.v11.OamNetwork;
86 import org.openecomp.aai.inventory.v11.PInterface;
87 import org.openecomp.aai.inventory.v11.PhysicalLink;
88 import org.openecomp.aai.inventory.v11.Pserver;
89 import org.openecomp.aai.inventory.v11.ResultData;
90 import org.openecomp.aai.inventory.v11.SearchResults;
91 import org.openecomp.aai.inventory.v11.Service;
92 import org.openecomp.aai.inventory.v11.ServiceInstance;
93 import org.openecomp.aai.inventory.v11.SitePairSet;
94 import org.openecomp.aai.inventory.v11.Tenant;
95 import org.openecomp.aai.inventory.v11.Vce;
96 import org.openecomp.aai.inventory.v11.VnfImage;
97 import org.openecomp.aai.inventory.v11.VnfImages;
98 import org.openecomp.aai.inventory.v11.VplsPe;
99 import org.openecomp.aai.inventory.v11.VpnBinding;
100 import org.openecomp.aai.inventory.v11.Vserver;
101 import org.onap.ccsdk.sli.adaptors.aai.data.AAIDatum;
102 import org.onap.ccsdk.sli.adaptors.aai.data.ErrorResponse;
103 import org.onap.ccsdk.sli.adaptors.aai.data.RequestError;
104 import org.onap.ccsdk.sli.adaptors.aai.data.ResourceVersion;
105 import org.onap.ccsdk.sli.adaptors.aai.data.ServiceException;
106 import org.onap.ccsdk.sli.adaptors.aai.data.notify.NotifyEvent;
107 import org.slf4j.Logger;
108 import org.slf4j.LoggerFactory;
109 import org.slf4j.MDC;
110
111 import com.fasterxml.jackson.annotation.JsonInclude.Include;
112 import com.fasterxml.jackson.databind.AnnotationIntrospector;
113 import com.fasterxml.jackson.databind.DeserializationFeature;
114 import com.fasterxml.jackson.databind.ObjectMapper;
115 import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector;
116 import com.fasterxml.jackson.databind.type.TypeFactory;
117 import com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector;
118 import com.sun.jersey.api.client.config.DefaultClientConfig;
119 import com.sun.jersey.client.urlconnection.HTTPSProperties;
120
121
122 public class AAIService extends AAIDeclarations implements AAIClient, SvcLogicResource {
123
124     public static final String AAICLIENT_PROPERTIES = "/aaiclient.properties";
125     public static final String PATH_PROPERTIES = "/aai-path.properties";
126
127     private static final Logger LOG = LoggerFactory.getLogger(AAIService.class);
128
129     private final String truststorePath;
130     private final String truststorePassword;
131     private final String keystorePath;
132     private final String keystorePassword;
133     private final Boolean ignoreCertificateHostError;
134
135     private final String target_uri;
136     private final String queryPath;
137
138     private final String networkVserverPath;
139
140     private final String svcInstancePath;
141     private final String svc_inst_qry_path;
142
143     private final String vnf_image_query_path;
144
145     private final String param_service_type;            //= "service-type";
146
147     private final String ubb_notify_path;
148     private final String selflink_avpn;
149     private final String selflink_fqdn;
150
151     private final String p_interface_path;
152
153     private final String service_path;
154     private final String site_pair_set_path;
155
156     private final int connection_timeout;
157     private final int read_timeout;
158
159     // 1602
160     private final String query_nodes_path;
161     private final String update_path;
162
163     private final String application_id;
164
165     // authentication credentials
166     private String user_name;
167     private String user_password;
168
169     // runtime
170     private final boolean runtimeOSGI;
171
172     private SSLContext CTX;
173
174     private final MetricLogger ml = new MetricLogger();
175
176     private final AAIRequestExecutor executor;
177
178     public AAIService(URL propURL) {
179         LOG.info("Entered AAIService.ctor");
180
181         String runtime = System.getProperty("aaiclient.runtime");
182         if("OSGI".equals(runtime)) {
183             runtimeOSGI = true;
184         } else {
185             runtimeOSGI = false;
186         }
187
188         Properties props = null;
189         try {
190             props = initialize(propURL);
191             AAIRequest.setProperties(props, this);
192
193         } catch(Exception exc){
194             LOG.error("AicAAIResource.static", exc);
195         }
196
197         executor = new AAIRequestExecutor();
198
199         user_name            = props.getProperty(CLIENT_NAME);
200         user_password        = props.getProperty(CLIENT_PWWD);
201
202         if(user_name == null || user_name.isEmpty()){
203             LOG.debug("Basic user name is not set");
204         }
205         if(user_password == null || user_password.isEmpty()) {
206             LOG.debug("Basic password is not set");
207         }
208
209         truststorePath     = props.getProperty(TRUSTSTORE_PATH);
210         truststorePassword = props.getProperty(TRUSTSTORE_PSSWD);
211         keystorePath         = props.getProperty(KEYSTORE_PATH);
212         keystorePassword     = props.getProperty(KEYSTORE_PSSWD);
213
214         target_uri             = props.getProperty(TARGET_URI);
215         queryPath             = props.getProperty(QUERY_PATH);
216         update_path         = props.getProperty(UPDATE_PATH);
217
218         String applicationId =props.getProperty(APPLICATION_ID);
219         if(applicationId == null || applicationId.isEmpty()) {
220             applicationId = "SDNC";
221         }
222         application_id = applicationId;
223
224         // connection timeout
225         int tmpConnectionTimeout = 30000;
226         int tmpReadTimeout = 30000;
227
228         try {
229             String tmpValue = null;
230             tmpValue = props.getProperty(CONNECTION_TIMEOUT, "30000");
231             tmpConnectionTimeout = Integer.parseInt(tmpValue);
232             tmpValue = props.getProperty(READ_TIMEOUT, "30000");
233             tmpReadTimeout = Integer.parseInt(tmpValue);
234         } catch(Exception exc) {
235             LOG.error("Failed setting connection timeout", exc);
236             tmpConnectionTimeout = 30000;
237             tmpReadTimeout = 30000;
238         }
239         connection_timeout = tmpConnectionTimeout;
240         read_timeout = tmpReadTimeout;
241
242         networkVserverPath =props.getProperty(NETWORK_VSERVER_PATH);
243
244         svcInstancePath    = props.getProperty(SVC_INSTANCE_PATH);
245         svc_inst_qry_path    = props.getProperty(SVC_INST_QRY_PATH);
246         param_service_type     = props.getProperty(PARAM_SERVICE_TYPE, "service-type");
247
248         // P-Interfaces
249         p_interface_path   = props.getProperty(P_INTERFACE_PATH);
250
251         vnf_image_query_path    = props.getProperty(VNF_IMAGE_QUERY_PATH);
252
253         ubb_notify_path = props.getProperty(UBB_NOTIFY_PATH);
254         selflink_avpn = props.getProperty(SELFLINK_AVPN);
255         selflink_fqdn = props.getProperty(SELFLINK_FQDN);
256
257         service_path  = props.getProperty(SERVICE_PATH);
258
259         site_pair_set_path  = props.getProperty(SITE_PAIR_SET_PATH);
260
261         query_nodes_path = props.getProperty(QUERY_NODES_PATH);
262
263         String iche = props.getProperty(CERTIFICATE_HOST_ERROR);
264         boolean host_error = false;
265         if(iche != null && !iche.isEmpty()) {
266             host_error = Boolean.valueOf(iche);
267         }
268
269         ignoreCertificateHostError = host_error;
270
271         HttpsURLConnection.setDefaultHostnameVerifier( new HostnameVerifier(){
272             public boolean verify(String string,SSLSession ssls) {
273                 return ignoreCertificateHostError;
274             }
275         });
276
277         if(truststorePath != null && truststorePassword != null && (new File(truststorePath)).exists()) {
278             System.setProperty("javax.net.ssl.trustStore", truststorePath);
279             System.setProperty("javax.net.ssl.trustStorePassword", truststorePassword);
280         }
281
282         if(keystorePath != null && keystorePassword != null && (new File(keystorePath)).exists()) {
283         DefaultClientConfig config = new DefaultClientConfig();
284         //both jersey and HttpURLConnection can use this
285         SSLContext ctx = null;
286         try {
287             ctx = SSLContext.getInstance("TLS");
288
289             KeyManagerFactory kmf = null;
290             try (FileInputStream fin = new FileInputStream(keystorePath)){
291                 String def = "SunX509";
292                 String storeType = "PKCS12";
293                 def = KeyStore.getDefaultType();
294                 kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
295
296                 String extension = keystorePath.substring(keystorePath.lastIndexOf(".") + 1);
297                 if("JKS".equalsIgnoreCase(extension)) {
298                     storeType = "JKS";
299                 }
300                 KeyStore ks = KeyStore.getInstance(storeType);
301
302                 char[] pwd = keystorePassword.toCharArray();
303                 ks.load(fin, pwd);
304                 kmf.init(ks, pwd);
305             } catch (Exception ex) {
306                 LOG.error("AAIResource", ex);
307             }
308
309             ctx.init(kmf.getKeyManagers(), null, null);
310             config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties( new HostnameVerifier() {
311                     @Override
312                     public boolean verify( String s, SSLSession sslSession ) {
313                         return ignoreCertificateHostError;
314                     }
315             }, ctx));
316
317             CTX = ctx;
318                 LOG.debug("SSLContext created");
319
320         } catch (KeyManagementException | NoSuchAlgorithmException exc) {
321             LOG.error("AAIResource", exc);
322         }
323         }
324
325         LOG.info("AAIResource.ctor initialized.");
326
327         try {
328             Field methodsField = HttpURLConnection.class.getDeclaredField("methods");
329             methodsField.setAccessible(true);
330             // get the methods field modifiers
331             Field modifiersField = Field.class.getDeclaredField("modifiers");
332             // bypass the "private" modifier
333             modifiersField.setAccessible(true);
334
335             // remove the "final" modifier
336             modifiersField.setInt(methodsField, methodsField.getModifiers() & ~Modifier.FINAL);
337
338             /* valid HTTP methods */
339             String[] methods = {
340                        "GET", "POST", "HEAD", "OPTIONS", "PUT", "DELETE", "TRACE", "PATCH"
341             };
342             // set the new methods - including patch
343             methodsField.set(null, methods);
344
345         } catch (SecurityException | IllegalArgumentException | IllegalAccessException | NoSuchFieldException e) {
346          e.printStackTrace();
347         }
348
349     }
350
351     public void cleanUp() {
352
353     }
354
355     /**
356      *
357      * @param http_req_url
358      * @param method
359      * @return
360      * @throws Exception
361      */
362     protected HttpURLConnection getConfiguredConnection(URL http_req_url, String method) throws Exception {
363         HttpURLConnection con = (HttpURLConnection) http_req_url.openConnection();
364
365         // Set up the connection properties
366         con.setRequestProperty( "Connection", "close" );
367         con.setDoInput(true);
368         con.setDoOutput(true);
369         con.setUseCaches(false);
370         con.setConnectTimeout( connection_timeout );
371         con.setReadTimeout( read_timeout );
372         con.setRequestMethod( method );
373         con.setRequestProperty( "Accept", "application/json" );
374         con.setRequestProperty( "Content-Type",  "PATCH".equalsIgnoreCase(method) ? "application/merge-patch+json" : "application/json" );
375         con.setRequestProperty("X-FromAppId", application_id);
376         con.setRequestProperty("X-TransactionId",TransactionIdTracker.getNextTransactionId());
377         String mlId = ml.getRequestID();
378         if(mlId != null && !mlId.isEmpty()) {
379             LOG.debug(String.format("MetricLogger requestId = %s", mlId));
380             con.setRequestProperty(MetricLogger.REQUEST_ID, mlId);
381         } else {
382             LOG.debug("MetricLogger requestId is null");
383         }
384         con.setRequestProperty("Transfer-Encoding","chunked");
385
386         if(user_name != null && !user_name.isEmpty() && user_password != null && !user_password.isEmpty()) {
387             String basicAuth = "Basic " + new String(Base64.encodeBase64((user_name + ":" + user_password).getBytes()));
388             con.setRequestProperty ("Authorization", basicAuth);
389         }
390
391         if(con instanceof HttpsURLConnection && CTX != null) {
392             SSLSocketFactory sockFact = CTX.getSocketFactory();
393             HttpsURLConnection.class.cast(con).setSSLSocketFactory( sockFact );
394         }
395         return con;
396     }
397
398
399     @Override
400     public GenericVnf requestGenericVnfData(String vnf_id) throws AAIServiceException {
401         GenericVnf response = null;
402
403         try {
404             AAIRequest request = AAIRequest.getRequestFromResource("generic-vnf");
405             request.addRequestProperty("generic-vnf.vnf-id", vnf_id);
406             String rv = executor.get(request);
407             if(rv != null) {
408                 ObjectMapper mapper = getObjectMapper();
409                 response = mapper.readValue(rv, GenericVnf.class);
410             }
411         } catch(AAIServiceException aaiexc) {
412             throw aaiexc;
413         } catch (Exception exc) {
414             LOG.warn(Object.class.getClass().getEnclosingMethod().getName(), exc);
415             throw new AAIServiceException(exc);
416         }
417
418         return response;
419
420     }
421
422     @Override
423     public boolean postGenericVnfData(String vnf_id, GenericVnf data) throws AAIServiceException {
424         try {
425             AAIRequest request = AAIRequest.getRequestFromResource("generic-vnf");
426             request.addRequestProperty("generic-vnf.vnf-id", vnf_id);
427             request.setRequestObject(data);
428             Object response = executor.post(request);
429             return true;
430         } catch(AAIServiceException aaiexc) {
431             throw aaiexc;
432         } catch (Exception exc) {
433             LOG.warn("requestGenericVnfData", exc);
434             throw new AAIServiceException(exc);
435         }
436     }
437
438     @Override
439     public boolean deleteGenericVnfData(String vnf_id, String resourceVersion) throws AAIServiceException {
440         boolean response = false;
441
442         try {
443             AAIRequest request = AAIRequest.getRequestFromResource("generic-vnf");
444             request.addRequestProperty("generic-vnf.vnf-id", vnf_id);
445             response = executor.delete(request, resourceVersion);
446         } catch(AAIServiceException aaiexc) {
447             throw aaiexc;
448         } catch (Exception exc) {
449             LOG.warn("deleteGenericVnfData", exc);
450             throw new AAIServiceException(exc);
451         }
452         return response;
453     }
454
455     /* (non-Javadoc)
456      * @see org.onap.ccsdk.sli.adaptors.resource.aic.AnAIClient#requestSdnZoneQuery(java.lang.String, java.lang.String, java.lang.String)
457      */
458     @Override
459     public Vce requestNetworkVceData(String vnf_id) throws AAIServiceException {
460         Vce response = null;
461         try {
462             AAIRequest request = AAIRequest.getRequestFromResource("vce");
463             request.addRequestProperty("vce.vnf-id", vnf_id);
464             String rv = executor.get(request);
465             if(rv != null) {
466                 ObjectMapper mapper = getObjectMapper();
467                 response = mapper.readValue(rv, Vce.class);
468             }
469         } catch(AAIServiceException aaiexc) {
470             throw aaiexc;
471         } catch (Exception exc) {
472             LOG.warn(Object.class.getClass().getEnclosingMethod().getName(), exc);
473             throw new AAIServiceException(exc);
474         }
475
476         return response;
477     }
478
479
480     /* (non-Javadoc)
481      * @see org.onap.ccsdk.sli.adaptors.resource.aic.AnAIClient#requestSdnZoneQuery(java.lang.String, java.lang.String, java.lang.String)
482      */
483     @Override
484     public boolean deleteNetworkVceData(String vnf_id, String resourceVersion) throws AAIServiceException {
485         boolean response = false;
486
487         try {
488             AAIRequest request = AAIRequest.getRequestFromResource("vce");
489             request.addRequestProperty("vce.vnf-id", vnf_id);
490             response = executor.delete(request, resourceVersion);
491         } catch(AAIServiceException aaiexc) {
492             throw aaiexc;
493         } catch (Exception exc) {
494             LOG.warn("deleteNetworkVceData", exc);
495             throw new AAIServiceException(exc);
496         }
497         return response;
498     }
499
500     /* (non-Javadoc)
501      * @see org.onap.ccsdk.sli.adaptors.resource.aic.AnAIClient#postNetworkVceData(java.lang.String, org.onap.ccsdk.sli.adaptors.resource.aic.aai.VCERequest)
502      */
503     @Override
504     public boolean postNetworkVceData(String vnf_id, Vce data) throws AAIServiceException {
505         try {
506             AAIRequest request = AAIRequest.getRequestFromResource("vce");
507             request.addRequestProperty("vce.vnf-id", vnf_id);
508             request.setRequestObject(data);
509             Object response = executor.post(request);
510             return true;
511         } catch(AAIServiceException aaiexc) {
512             throw aaiexc;
513         } catch (Exception exc) {
514             LOG.warn("requestGenericVnfData", exc);
515             throw new AAIServiceException(exc);
516         }
517     }
518
519
520     @Override
521     public SearchResults requestServiceInstanceURL(String svc_instance_id) throws AAIServiceException {
522         SearchResults response = null;
523         InputStream inputStream = null;
524
525         try {
526             String path = svc_inst_qry_path;
527             path = path.replace("{svc-instance-id}", encodeQuery(svc_instance_id));
528
529             String request_url = target_uri+path;
530             URL http_req_url =    new URL(request_url);
531
532             HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.GET);
533
534             LOGwriteFirstTrace(HttpMethod.GET, http_req_url.toString());
535             LOGwriteDateTrace("svc_instance_id", svc_instance_id);
536
537             // Check for errors
538             int responseCode = con.getResponseCode();
539             if (responseCode == HttpURLConnection.HTTP_OK) {
540                 inputStream = con.getInputStream();
541             } else {
542                 inputStream = con.getErrorStream();
543             }
544
545             // Process the response
546             LOG.debug("HttpURLConnection result:" + responseCode);
547             if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
548             BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
549
550             ObjectMapper mapper = getObjectMapper();
551
552     if (responseCode == HttpURLConnection.HTTP_OK) {
553                 response = mapper.readValue(reader, SearchResults.class);
554                 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, "SUCCESS", mapper.writeValueAsString(response));
555             } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
556                 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
557                 return response;
558             } else {
559                 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
560                 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
561                 throw new AAIServiceException(responseCode, errorresponse);
562             }
563
564         } catch(AAIServiceException aaiexc) {
565             throw aaiexc;
566         } catch (Exception exc) {
567             LOG.warn("requestServiceInstanceURL", exc);
568             throw new AAIServiceException(exc);
569         } finally {
570             if(inputStream != null){
571                 try {
572                     inputStream.close();
573                 } catch(Exception exc) {
574                 }
575             }
576         }
577         return response;
578     }
579
580     @Override
581     public ServiceInstance requestServiceInterfaceData(String customer_id, String service_type, String svc_instance_id) throws AAIServiceException {
582         ServiceInstance response = null;
583
584         try {
585             AAIRequest request = AAIRequest.getRequestFromResource("service-instance");
586             request.addRequestProperty("customer.global-customer-id", customer_id);
587             request.addRequestProperty("service-subscription.service-type", service_type);
588             request.addRequestProperty("service-instance.service-instance-id", svc_instance_id);
589
590             String rv = executor.get(request);
591             if(rv != null) {
592                 ObjectMapper mapper = getObjectMapper();
593                 response = mapper.readValue(rv, ServiceInstance.class);
594             }
595         } catch(AAIServiceException aaiexc) {
596             throw aaiexc;
597         } catch (Exception exc) {
598             LOG.warn("requestServiceInterfaceData", exc);
599             throw new AAIServiceException(exc);
600         }
601         return response;
602     }
603
604     @Override
605     public boolean postServiceInterfaceData(String customer_id, String service_type, String svc_instance_id, ServiceInstance data) throws AAIServiceException {
606         try {
607             AAIRequest request = AAIRequest.getRequestFromResource("service-instance");
608             request.addRequestProperty("customer.global-customer-id", customer_id);
609             request.addRequestProperty("service-subscription.service-type", service_type);
610             request.addRequestProperty("service-instance.service-instance-id", svc_instance_id);
611             request.setRequestObject(data);
612             Object response = executor.post(request);
613             return true;
614         } catch(AAIServiceException aaiexc) {
615             throw aaiexc;
616         } catch (Exception exc) {
617             LOG.warn("requestGenericVnfData", exc);
618             throw new AAIServiceException(exc);
619         }
620     }
621
622
623     private static Properties initialize(URL url ) throws ConfigurationException {
624
625         if(url ==  null) {
626             throw new NullPointerException();
627         }
628
629         InputStream is = null;
630         Properties props = new Properties();
631
632         try {
633             if(LOG.isDebugEnabled())
634                 LOG.info("Property file is: " + url.toString());
635
636             is = url.openStream();
637
638             props.load(is);
639             if(LOG.isDebugEnabled()) {
640                 LOG.info("Properties loaded: " + props.size());
641                 Enumeration<Object> en = props.keys();
642
643                 while(en.hasMoreElements()) {
644                     String key = (String)en.nextElement();
645                     String property = props.getProperty(key);
646                     LOG.debug(key + " : " + property);
647                 }
648             }
649         } catch (Exception e) {
650             throw new ConfigurationException("Could not load properties file.", e);
651         }
652         return props;
653     }
654
655     static class TransactionIdTracker {
656 //        protected static AtomicLong tracker = new AtomicLong();
657
658         public static String getNextTransactionId() {
659             // Check if RequestId exists as MDC. If not, create new.
660             String transactionId = MDC.get("RequestId");
661             if ("".equals(transactionId) || transactionId == null) {
662                 transactionId = UUID.randomUUID().toString();
663                 LOG.info("Missing requestID. Assigned " + transactionId);
664                 MDC.put("RequestId", transactionId);
665             }
666             return transactionId;
667         }
668
669     }
670
671     protected void LOGwriteFirstTrace(String method, String url) {
672         String time = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").format(System.currentTimeMillis());
673         LOG.info("A&AI transaction :");
674         LOG.info("Request Time : " + time + ", Method : " + method);
675         LOG.info("Request URL : "+ url);
676     }
677
678     protected void LOGwriteDateTrace(String name, String data) {
679         LOG.info("Input - " + name  + " : " + data);
680     }
681
682     protected void LOGwriteEndingTrace(int response_code, String comment, String data) {
683         LOG.info("Response code : " + response_code +", " + comment);
684         LOG.info(String.format("Response data : %s", data));
685     }
686
687     protected String encodeQuery(String param) throws UnsupportedEncodingException {
688         return URLEncoder.encode(param, "UTF-8").replace("+", "%20");
689     }
690
691     private String encodeCustomerURL(final String selection)
692     {
693         String encrypted_url = selection;
694         String apnpattern =
695                 "/aai/v11/business/customers/customer/(.+)/service-subscriptions/service-subscription/(.+)/service-instances/service-instance/(.+)/";
696         Pattern pattern = Pattern.compile(apnpattern);
697
698         try {
699             URL url =    new URL(selection);
700             String path = url.getPath();
701
702             LOG.info("Trying to match apn to <" + path + ">");
703
704             Matcher matcher = pattern.matcher(path);
705
706             while(matcher.find()) {
707                 String customer = matcher.group(1);
708                 String subscription = matcher.group(2);
709                 String service = matcher.group(3);
710
711                 encrypted_url = selection.replace(customer, encodeQuery(customer));
712                 encrypted_url = encrypted_url.replace(subscription, encodeQuery(subscription));
713                 encrypted_url = encrypted_url.replace(service, encodeQuery(service));
714             }
715         } catch (Exception e) {
716             LOG.warn("", e);
717         }
718
719         return encrypted_url;
720     }
721
722     @Override
723         public VplsPe requestNetworkVplsPeData(String equipment_name)throws AAIServiceException {
724             VplsPe response = null;
725
726             try {
727                 AAIRequest request = AAIRequest.getRequestFromResource("vpls-pe");
728                 request.addRequestProperty("vpls-pe.equipment-name", equipment_name);
729
730                 String rv = executor.get(request);
731                 if(rv != null) {
732                     ObjectMapper mapper = getObjectMapper();
733                     response = mapper.readValue(rv, VplsPe.class);
734                 }
735             } catch(AAIServiceException aaiexc) {
736                 throw aaiexc;
737             } catch (Exception exc) {
738                 LOG.warn(Object.class.getClass().getEnclosingMethod().getName(),
739                         exc);
740                 throw new AAIServiceException(exc);
741             }
742             return response;
743         }
744
745     @Override
746     public boolean postNetworkVplsPeData(String equipment_name, VplsPe data) throws AAIServiceException {
747         try {
748             AAIRequest request = AAIRequest.getRequestFromResource("vpls-pe");
749             request.addRequestProperty("vpls-pe.equipment-name", equipment_name);
750             request.setRequestObject(data);
751             Object response = executor.post(request);
752             return true;
753         } catch(AAIServiceException aaiexc) {
754             throw aaiexc;
755         } catch (Exception exc) {
756             LOG.warn("requestGenericVnfData", exc);
757             throw new AAIServiceException(exc);
758         }
759     }
760
761     @Override
762     public boolean deleteNetworkVplsPeData(String vnf_id, String resourceVersion)    throws AAIServiceException {
763         boolean response = false;
764
765         try {
766             AAIRequest request = AAIRequest.getRequestFromResource("vpls-pe");
767             request.addRequestProperty("vpls-pe.equipment-name", vnf_id);
768             response = executor.delete(request, resourceVersion);
769         } catch(AAIServiceException aaiexc) {
770             throw aaiexc;
771         } catch (Exception exc) {
772             LOG.warn("deleteNetworkVplsPeData", exc);
773             throw new AAIServiceException(exc);
774         }
775         return response;
776     }
777
778     @Override
779     public Complex  requestNetworkComplexData(String pLocId) throws AAIServiceException {
780         Complex response = null;
781
782         try {
783             AAIRequest request = AAIRequest.getRequestFromResource("complex");
784             request.addRequestProperty("complex.physical-location-id", pLocId);
785
786             String rv = executor.get(request);
787             if(rv != null) {
788                 ObjectMapper mapper = getObjectMapper();
789                 response = mapper.readValue(rv, Complex.class);
790             }
791         } catch(AAIServiceException aaiexc) {
792             throw aaiexc;
793         } catch (Exception exc) {
794             LOG.warn("requestNetworkComplexData", exc);
795             throw new AAIServiceException(exc);
796         }
797         return response;
798     }
799
800     @Override
801     public boolean postNetworkComplexData(String vnf_id, Complex data) throws AAIServiceException {
802         try {
803             AAIRequest request = AAIRequest.getRequestFromResource("complex");
804             request.addRequestProperty("complex.physical-location-id", vnf_id);
805             request.setRequestObject(data);
806             Object response = executor.post(request);
807             return true;
808         } catch(AAIServiceException aaiexc) {
809             throw aaiexc;
810         } catch (Exception exc) {
811             LOG.warn("postNetworkComplexData", exc);
812             throw new AAIServiceException(exc);
813         }
814     }
815
816     @Override
817     public boolean deleteNetworkComplexData(String pLocId, String resourceVersion) throws AAIServiceException {
818         boolean response = false;
819
820         try {
821             AAIRequest request = AAIRequest.getRequestFromResource("complex");
822             request.addRequestProperty("complex.physical-location-id", pLocId);
823
824             response = executor.delete(request, resourceVersion);
825
826         } catch(AAIServiceException aaiexc) {
827             throw aaiexc;
828         } catch (Exception exc) {
829             LOG.warn("deleteNetworkComplexData", exc);
830             throw new AAIServiceException(exc);
831         }
832         return response;
833     }
834
835     /*
836      * (non-Javadoc)
837      * @see org.openecomp.sdnct.sli.aai.AAIClient#requestVServersData(java.lang.String, java.lang.String)
838      */
839     @Override
840     public Vserver requestVServerData(String tenantId, String vserverId, String cloudOwner, String cloudRegionId)    throws AAIServiceException {
841         Vserver response = null;
842
843         try {
844             AAIRequest request = AAIRequest.getRequestFromResource("vserver");
845             request.addRequestProperty("cloud-region.cloud-owner", cloudOwner);
846             request.addRequestProperty("cloud-region.cloud-region-id", cloudRegionId);
847             request.addRequestProperty("tenant.tenant-id", tenantId);
848             request.addRequestProperty("vserver.vserver-id", vserverId);
849
850             String rv = executor.get(request);
851             if(rv != null) {
852                 ObjectMapper mapper = getObjectMapper();
853                 response = mapper.readValue(rv, Vserver.class);
854             }
855         } catch(AAIServiceException aaiexc) {
856             throw aaiexc;
857         } catch (Exception exc) {
858             LOG.warn(Object.class.getClass().getEnclosingMethod().getName(), exc);
859             throw new AAIServiceException(exc);
860         }
861         return response;
862     }
863
864
865     @Override
866     public boolean postVServerData(String tenantId, String vserverId, String cloudOwner, String cloudRegionId, Vserver data) throws AAIServiceException {
867         try {
868             AAIRequest request = AAIRequest.getRequestFromResource("vserver");
869             request.addRequestProperty("cloud-region.cloud-owner", cloudOwner);
870             request.addRequestProperty("cloud-region.cloud-region-id", cloudRegionId);
871             request.addRequestProperty("tenant.tenant-id", tenantId);
872             request.addRequestProperty("vserver.vserver-id", vserverId);
873             request.setRequestObject(data);
874             Object response = executor.post(request);
875             return true;
876         } catch(AAIServiceException aaiexc) {
877             throw aaiexc;
878         } catch (Exception exc) {
879             LOG.warn("postNetworkComplexData", exc);
880             throw new AAIServiceException(exc);
881         }
882     }
883
884     @Override
885     public boolean deleteVServerData(String tenant_id, String vserver_id, String cloudOwner, String cloudRegionId, String resourceVersion) throws AAIServiceException {
886         boolean response = false;
887
888         try {
889             AAIRequest request = AAIRequest.getRequestFromResource("vserver");
890
891             request.addRequestProperty("vserver.vserver-id", vserver_id);
892             request.addRequestProperty("tenant.tenant-id", tenant_id);
893             request.addRequestProperty("cloud-region.cloud-owner", cloudOwner);
894             request.addRequestProperty("cloud-region.cloud-region-id",cloudRegionId);
895
896             response = executor.delete(request, resourceVersion);
897
898         } catch(AAIServiceException aaiexc) {
899             throw aaiexc;
900         } catch (Exception exc) {
901             LOG.warn("deleteVServerData", exc);
902             throw new AAIServiceException(exc);
903         }
904         return response;
905     }
906
907
908     /*
909      * (non-Javadoc)
910      * @see org.onap.ccsdk.sli.adaptors.aai.AAIClient#requestCtagPoolData(String)
911      */
912     @Override
913     public CtagPool requestCtagPoolData(String physical_location_id, String target_pe, String availability_zone_name)    throws AAIServiceException {
914         CtagPool response = null;
915
916         try {
917             AAIRequest request = AAIRequest.getRequestFromResource("ctag-pool");
918
919             request.addRequestProperty("ctag-pool.target-pe", target_pe);
920             request.addRequestProperty("ctag-pool.availability-zone-name", availability_zone_name);
921             request.addRequestProperty("complex.physical-location-id", physical_location_id);
922
923             String rv = executor.get(request);
924             if(rv != null) {
925                 ObjectMapper mapper = getObjectMapper();
926                 response = mapper.readValue(rv, CtagPool.class);
927             }
928         } catch(AAIServiceException aaiexc) {
929             throw aaiexc;
930         } catch (Exception exc) {
931             LOG.warn("requestNetworkVceData", exc);
932             throw new AAIServiceException(exc);
933         }
934         return response;
935     }
936
937     //==================== DvsSwitch ======================
938     @Override
939     public DvsSwitch  requestDvsSwitchData(String vnf_id) throws AAIServiceException {
940         DvsSwitch response = null;
941
942         try {
943             AAIRequest request = AAIRequest.getRequestFromResource("dvs-switch");
944             request.addRequestProperty("dvs-switch.switch-name", vnf_id);
945
946             String rv = executor.get(request);
947             if(rv != null) {
948                 ObjectMapper mapper = getObjectMapper();
949                 response = mapper.readValue(rv, DvsSwitch.class);
950             }
951         } catch(AAIServiceException aaiexc) {
952             throw aaiexc;
953         } catch (Exception exc) {
954             LOG.warn("requestDvsSwitchData", exc);
955             throw new AAIServiceException(exc);
956         }
957         return response;
958     }
959
960     @Override
961     public boolean postDvsSwitchData(String switch_name, DvsSwitch data) throws AAIServiceException {
962         try {
963             AAIRequest request = AAIRequest.getRequestFromResource("dvs-switch");
964             request.addRequestProperty("dvs-switch.switch-name", switch_name);
965             request.setRequestObject(data);
966             Object response = executor.post(request);
967             return true;
968         } catch(AAIServiceException aaiexc) {
969             throw aaiexc;
970         } catch (Exception exc) {
971             LOG.warn(Object.class.getClass().getEnclosingMethod().getName(), exc);
972             throw new AAIServiceException(exc);
973         }
974     }
975
976     @Override
977     public boolean deleteDvsSwitchData(String vnf_id, String resourceVersion) throws AAIServiceException {
978         boolean response = false;
979
980         try {
981             AAIRequest request = AAIRequest.getRequestFromResource("dvs-switch");
982             request.addRequestProperty("dvs-switch.switch-name", vnf_id);
983             response = executor.delete(request, resourceVersion);
984         } catch(AAIServiceException aaiexc) {
985             throw aaiexc;
986         } catch (Exception exc) {
987             LOG.warn("deleteDvsSwitchData", exc);
988             throw new AAIServiceException(exc);
989         }
990         return response;
991     }
992     //================== End of DvsSwitch =================
993     //==================== PhysicalLink ======================
994     @Override
995     public PhysicalLink  requestPhysicalLinkData(String linkName) throws AAIServiceException {
996         PhysicalLink response = null;
997
998         try {
999             AAIRequest request = AAIRequest.getRequestFromResource("physical-link");
1000             request.addRequestProperty("physical-link.link-name", linkName);
1001
1002             String rv = executor.get(request);
1003             if(rv != null) {
1004                 ObjectMapper mapper = getObjectMapper();
1005                 response = mapper.readValue(rv, PhysicalLink.class);
1006             }
1007         } catch(AAIServiceException aaiexc) {
1008             throw aaiexc;
1009         } catch (Exception exc) {
1010             LOG.warn("requestPhysicalLinkData", exc);
1011             throw new AAIServiceException(exc);
1012         }
1013         return response;
1014     }
1015
1016     @Override
1017     public boolean postPhysicalLinkData(String linkName, PhysicalLink data) throws AAIServiceException {
1018         try {
1019             AAIRequest request = AAIRequest.getRequestFromResource("physical-link");
1020             request.addRequestProperty("physical-link.link-name", linkName);
1021             request.setRequestObject(data);
1022             Object response = executor.post(request);
1023             return true;
1024         } catch(AAIServiceException aaiexc) {
1025             throw aaiexc;
1026         } catch (Exception exc) {
1027             LOG.warn(Object.class.getClass().getEnclosingMethod().getName(), exc);
1028             throw new AAIServiceException(exc);
1029         }
1030     }
1031
1032     @Override
1033     public boolean deletePhysicalLinkData(String linkName, String resourceVersion) throws AAIServiceException {
1034         boolean response = false;
1035
1036         try {
1037             AAIRequest request = AAIRequest.getRequestFromResource("physical-link");
1038             request.addRequestProperty("physical-link.link-name", linkName);
1039             response = executor.delete(request, resourceVersion);
1040         } catch(AAIServiceException aaiexc) {
1041             throw aaiexc;
1042         } catch (Exception exc) {
1043             LOG.warn("deletePhysicalLinkData", exc);
1044             throw new AAIServiceException(exc);
1045         }
1046         return response;
1047     }
1048     //================== End of PhysicalLink =================
1049     //==================== PInterface ======================
1050     @Override
1051     public PInterface  requestPInterfaceData(String hostname, String interfaceName) throws AAIServiceException {
1052         PInterface response = null;
1053
1054         try {
1055             AAIRequest request =  AAIRequest.getRequestFromResource("p-interface");
1056             request.addRequestProperty("p-interface.interface-name", interfaceName);
1057             request.addRequestProperty("pserver.hostname", hostname);
1058             String rv = executor.get(request);
1059             if(rv != null) {
1060                 ObjectMapper mapper = getObjectMapper();
1061                 response = mapper.readValue(rv, PInterface.class);
1062             }
1063         } catch(AAIServiceException aaiexc) {
1064             throw aaiexc;
1065         } catch (Exception exc) {
1066             LOG.warn(Object.class.getClass().getEnclosingMethod().getName(), exc);
1067             throw new AAIServiceException(exc);
1068         }
1069         return response;
1070     }
1071
1072     @Override
1073     public boolean postPInterfaceData(String hostname, String interfaceName, PInterface request) throws AAIServiceException {
1074         InputStream inputStream = null;
1075
1076         try {
1077
1078             ObjectMapper mapper = getObjectMapper();
1079             String json_text = mapper.writeValueAsString(request);
1080
1081             SSLSocketFactory sockFact = CTX.getSocketFactory();
1082
1083             String request_url = target_uri+p_interface_path;
1084             String encoded_vnf = encodeQuery(hostname);
1085             request_url = request_url.replace("{hostname}", encoded_vnf) ;
1086             encoded_vnf = encodeQuery(interfaceName);
1087             request_url = request_url.replace("{interface-name}", encoded_vnf) ;
1088             URL http_req_url =    new URL(request_url);
1089
1090             HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.PUT);
1091
1092             if (json_text != null) {
1093                 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
1094                 osw.write(json_text);
1095                 osw.flush();
1096                 osw.close();
1097             }
1098
1099             LOGwriteFirstTrace("PUT", request_url);
1100             LOGwriteDateTrace("hostname", hostname);
1101             LOGwriteDateTrace("interface-name", interfaceName);
1102             LOGwriteDateTrace("PInterface", json_text);
1103
1104             // Check for errors
1105             int responseCode = con.getResponseCode();
1106             if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1107                 inputStream = con.getInputStream();
1108             } else {
1109                 inputStream = con.getErrorStream();
1110             }
1111
1112             // Process the response
1113             BufferedReader reader;
1114             String line = null;
1115             reader = new BufferedReader( new InputStreamReader( inputStream ) );
1116
1117             if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1118                 StringBuilder stringBuilder = new StringBuilder();
1119
1120                 while( ( line = reader.readLine() ) != null ) {
1121                     stringBuilder.append( line );
1122                 }
1123                 LOGwriteEndingTrace(responseCode, "SUCCESS", (stringBuilder.length() > 0) ? stringBuilder.toString() : "{no-data}");
1124                 return true;
1125             } else {
1126                 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
1127                 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
1128
1129                 throw new AAIServiceException(responseCode, errorresponse);
1130             }
1131         } catch(AAIServiceException aaiexc) {
1132             throw aaiexc;
1133         } catch (Exception exc) {
1134             LOG.warn("postPInterfaceData", exc);
1135             throw new AAIServiceException(exc);
1136         } finally {
1137             try {
1138                 if(inputStream != null)
1139                 inputStream.close();
1140             } catch (Exception exc) {
1141
1142             }
1143         }
1144     }
1145
1146     @Override
1147     public boolean deletePInterfaceData(String hostname, String interfaceName, String resourceVersion) throws AAIServiceException {
1148         boolean response = false;
1149
1150         try {
1151             AAIRequest request = AAIRequest.getRequestFromResource("p-interface");
1152             request.addRequestProperty("p-interface.interface-name", interfaceName);
1153             request.addRequestProperty("pserver.hostname", hostname);
1154             response = executor.delete(request, resourceVersion);
1155         } catch(AAIServiceException aaiexc) {
1156             throw aaiexc;
1157         } catch (Exception exc) {
1158             LOG.warn("deletePInterfaceData", exc);
1159             throw new AAIServiceException(exc);
1160         }
1161         return response;
1162     }
1163     //================== End of PInterface =================
1164     //==================== SitePairSet ======================
1165     @Override
1166     public SitePairSet requestSitePairSetData(String sitePairSetId) throws AAIServiceException {
1167         SitePairSet response = null;
1168
1169         try {
1170             AAIRequest request = AAIRequest.getRequestFromResource("site-pair-set");
1171             request.addRequestProperty("site-pair-set.site-pair-set-id", sitePairSetId);
1172             String rv = executor.get(request);
1173             if(rv != null) {
1174                 ObjectMapper mapper = getObjectMapper();
1175                 response = mapper.readValue(rv, SitePairSet.class);
1176             }
1177         } catch(AAIServiceException aaiexc) {
1178             throw aaiexc;
1179         } catch (Exception exc) {
1180             LOG.warn(Object.class.getClass().getEnclosingMethod().getName(), exc);
1181             throw new AAIServiceException(exc);
1182         }
1183         return response;
1184     }
1185
1186     @Override
1187     public boolean postSitePairSetData(String linkName, SitePairSet request) throws AAIServiceException {
1188         InputStream inputStream = null;
1189
1190         try {
1191
1192             ObjectMapper mapper = getObjectMapper();
1193             String json_text = mapper.writeValueAsString(request);
1194
1195             SSLSocketFactory sockFact = CTX.getSocketFactory();
1196
1197             String request_url = target_uri+site_pair_set_path;
1198             String encoded_vnf = encodeQuery(linkName);
1199             request_url = request_url.replace("{site-pair-set-id}", encoded_vnf) ;
1200             URL http_req_url =    new URL(request_url);
1201
1202             HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.PUT);
1203
1204             if (json_text != null) {
1205                 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
1206                 osw.write(json_text);
1207                 osw.flush();
1208                 osw.close();
1209             }
1210
1211             LOGwriteFirstTrace("PUT", request_url);
1212             LOGwriteDateTrace("link-name", linkName);
1213             LOGwriteDateTrace("SitePairSet", json_text);
1214
1215             // Check for errors
1216             int responseCode = con.getResponseCode();
1217             if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1218                 inputStream = con.getInputStream();
1219             } else {
1220                 inputStream = con.getErrorStream();
1221             }
1222
1223             // Process the response
1224             BufferedReader reader;
1225             String line = null;
1226             reader = new BufferedReader( new InputStreamReader( inputStream ) );
1227
1228             if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1229                 StringBuilder stringBuilder = new StringBuilder();
1230
1231                 while( ( line = reader.readLine() ) != null ) {
1232                     stringBuilder.append( line );
1233                 }
1234                 LOGwriteEndingTrace(responseCode, "SUCCESS", (stringBuilder.length() > 0) ? stringBuilder.toString() : "{no-data}");
1235                 return true;
1236             } else {
1237                 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
1238                 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
1239
1240                 throw new AAIServiceException(responseCode, errorresponse);
1241             }
1242         } catch(AAIServiceException aaiexc) {
1243             throw aaiexc;
1244         } catch (Exception exc) {
1245             LOG.warn("postSitePairSetData", exc);
1246             throw new AAIServiceException(exc);
1247         } finally {
1248             try {
1249                 if(inputStream != null)
1250                 inputStream.close();
1251             } catch (Exception exc) {
1252
1253             }
1254         }
1255     }
1256
1257     @Override
1258     public boolean deleteSitePairSetData(String linkName, String resourceVersion) throws AAIServiceException {
1259         boolean response = false;
1260
1261         try {
1262             AAIRequest request = AAIRequest.getRequestFromResource("site-pair-set");
1263             request.addRequestProperty("site-pair-set.site-pair-set-id", linkName);
1264             response = executor.delete(request, resourceVersion);
1265         } catch(AAIServiceException aaiexc) {
1266             throw aaiexc;
1267         } catch (Exception exc) {
1268             LOG.warn("deleteSitePairSetData", exc);
1269             throw new AAIServiceException(exc);
1270         }
1271
1272         return response;
1273     }
1274     //================== End of SitePairSet =================
1275     //==================== Service ======================
1276     @Override
1277     public Service requestServiceData(String serviceId) throws AAIServiceException {
1278         Service response = null;
1279
1280         try {
1281             AAIRequest request = AAIRequest.getRequestFromResource("service");
1282             request.addRequestProperty("service.service-id", serviceId);
1283
1284
1285             String rv = executor.get(request);
1286             if(rv != null) {
1287                 ObjectMapper mapper = getObjectMapper();
1288                 response = mapper.readValue(rv, Service.class);
1289             }
1290         } catch(AAIServiceException aaiexc) {
1291             throw aaiexc;
1292         } catch (Exception exc) {
1293             LOG.warn("requestServiceData", exc);
1294             throw new AAIServiceException(exc);
1295         }
1296         return response;
1297     }
1298
1299     @Override
1300     public boolean postServiceData(String linkName, Service request) throws AAIServiceException {
1301         InputStream inputStream = null;
1302
1303         try {
1304
1305             ObjectMapper mapper = getObjectMapper();
1306             String json_text = mapper.writeValueAsString(request);
1307
1308             SSLSocketFactory sockFact = CTX.getSocketFactory();
1309
1310             String request_url = target_uri+service_path;
1311             String encoded_vnf = encodeQuery(linkName);
1312             request_url = request_url.replace("{service-id}", encoded_vnf) ;
1313             URL http_req_url =    new URL(request_url);
1314
1315             HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.PUT);
1316
1317             if (json_text != null) {
1318                 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
1319                 osw.write(json_text);
1320                 osw.flush();
1321                 osw.close();
1322             }
1323
1324             LOGwriteFirstTrace("PUT", request_url);
1325             LOGwriteDateTrace("service-id", linkName);
1326             LOGwriteDateTrace("Service", json_text);
1327
1328             // Check for errors
1329             int responseCode = con.getResponseCode();
1330             if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1331                 inputStream = con.getInputStream();
1332             } else {
1333                 inputStream = con.getErrorStream();
1334             }
1335
1336             // Process the response
1337             BufferedReader reader;
1338             String line = null;
1339             reader = new BufferedReader( new InputStreamReader( inputStream ) );
1340
1341             if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1342                 StringBuilder stringBuilder = new StringBuilder();
1343
1344                 while( ( line = reader.readLine() ) != null ) {
1345                     stringBuilder.append( line );
1346                 }
1347                 LOGwriteEndingTrace(responseCode, "SUCCESS", (stringBuilder.length() > 0) ? stringBuilder.toString() : "{no-data}");
1348                 return true;
1349             } else {
1350                 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
1351                 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
1352
1353                 throw new AAIServiceException(responseCode, errorresponse);
1354             }
1355         } catch(AAIServiceException aaiexc) {
1356             throw aaiexc;
1357         } catch (Exception exc) {
1358             LOG.warn("postServiceData", exc);
1359             throw new AAIServiceException(exc);
1360         } finally {
1361             try {
1362                 if(inputStream != null)
1363                 inputStream.close();
1364             } catch (Exception exc) {
1365
1366             }
1367         }
1368     }
1369
1370     @Override
1371     public boolean deleteServiceData(String service_id, String resourceVersion) throws AAIServiceException {
1372         boolean response = false;
1373
1374         try {
1375             AAIRequest request = AAIRequest.getRequestFromResource("service");
1376             request.addRequestProperty("service.service-id", service_id);
1377             response = executor.delete(request, resourceVersion);
1378         } catch(AAIServiceException aaiexc) {
1379             throw aaiexc;
1380         } catch (Exception exc) {
1381             LOG.warn("deleteServiceData", exc);
1382             throw new AAIServiceException(exc);
1383         }
1384
1385         return response;
1386     }
1387     //================== End of Service =================
1388
1389
1390     @Override
1391     public Vserver dataChangeRequestVServerData(URL url) throws AAIServiceException {
1392
1393         if(url ==  null) {
1394             throw new NullPointerException();
1395         }
1396
1397         return this.getResource(url.toString(), Vserver.class);
1398     }
1399
1400     @Override
1401     public Pserver dataChangeRequestPServerData(URL url) throws AAIServiceException {
1402
1403         if(url ==  null) {
1404             throw new NullPointerException();
1405         }
1406
1407         return this.getResource(url.toString(), Pserver.class);
1408     }
1409
1410     @Override
1411     public CtagPool dataChangeRequestCtagPoolData(URL url) throws AAIServiceException {
1412
1413         if(url ==  null) {
1414             throw new NullPointerException();
1415         }
1416
1417         return this.getResource(url.toString(), CtagPool.class);
1418     }
1419
1420     @Override
1421     public VplsPe dataChangeRequestVplsPeData(URL url) throws AAIServiceException {
1422
1423         if(url ==  null) {
1424             throw new NullPointerException();
1425         }
1426
1427         return this.getResource(url.toString(), VplsPe.class);
1428     }
1429
1430     @Override
1431     public DvsSwitch dataChangeRequestDvsSwitchData(URL url) throws AAIServiceException {
1432
1433         if(url ==  null) {
1434             throw new NullPointerException();
1435         }
1436
1437         return this.getResource(url.toString(), DvsSwitch.class);
1438     }
1439
1440     @Override
1441     public OamNetwork dataChangeRequestOAMNetworkData(URL url) throws AAIServiceException {
1442
1443         if(url ==  null) {
1444             throw new NullPointerException();
1445         }
1446
1447         return this.getResource(url.toString(), OamNetwork.class);
1448     }
1449
1450     @Override
1451     public AvailabilityZone dataChangeRequestAvailabilityZoneData(URL url) throws AAIServiceException {
1452
1453         if(url ==  null) {
1454             throw new NullPointerException();
1455         }
1456
1457         return this.getResource(url.toString(), AvailabilityZone.class);
1458     }
1459
1460     @Override
1461     public Complex dataChangeRequestComplexData(URL url) throws AAIServiceException {
1462
1463         if(url ==  null) {
1464             throw new NullPointerException();
1465         }
1466
1467         return this.getResource(url.toString(), Complex.class);
1468     }
1469
1470     /* DELETE */
1471     @Override
1472     public boolean dataChangeDeleteVServerData(URL url) throws AAIServiceException {
1473
1474         if(url ==  null) {
1475             throw new NullPointerException();
1476         }
1477
1478         return deleteAAIEntity(url, Object.class.getClass().getEnclosingMethod()
1479                 .getName());
1480     }
1481
1482     @Override
1483     public boolean dataChangeDeleteCtagPoolData(URL url) throws AAIServiceException {
1484
1485         if(url ==  null) {
1486             throw new NullPointerException();
1487         }
1488
1489         return deleteAAIEntity(url, Object.class.getClass().getEnclosingMethod()
1490                 .getName());
1491     }
1492
1493     @Override
1494     public boolean dataChangeDeleteVplsPeData(URL url) throws AAIServiceException {
1495
1496         if(url ==  null) {
1497             throw new NullPointerException();
1498         }
1499
1500         return deleteAAIEntity(url, Object.class.getClass().getEnclosingMethod()
1501                 .getName());
1502     }
1503
1504     @Override
1505     public boolean dataChangeDeleteVpeData(URL url) throws AAIServiceException {
1506
1507         if(url ==  null) {
1508             throw new NullPointerException();
1509         }
1510
1511         return deleteAAIEntity(url, Object.class.getClass().getEnclosingMethod()
1512                 .getName());
1513     }
1514
1515     @Override
1516     public boolean dataChangeDeleteDvsSwitchData(URL url) throws AAIServiceException {
1517
1518         if(url ==  null) {
1519             throw new NullPointerException();
1520         }
1521
1522         return deleteAAIEntity(url, Object.class.getClass().getEnclosingMethod()
1523                 .getName());
1524     }
1525     //OAM-Network:
1526     @Override
1527     public boolean dataChangeDeleteOAMNetworkData(URL url) throws AAIServiceException {
1528
1529         if(url ==  null) {
1530             throw new NullPointerException();
1531         }
1532
1533         return deleteAAIEntity(url, Object.class.getClass().getEnclosingMethod()
1534                 .getName());
1535     }
1536     //Availability-Zone:
1537     @Override
1538     public boolean dataChangeDeleteAvailabilityZoneData(URL url) throws AAIServiceException {
1539
1540         if(url ==  null) {
1541             throw new NullPointerException();
1542         }
1543
1544         return deleteAAIEntity(url, Object.class.getClass().getEnclosingMethod()
1545                 .getName());
1546     }
1547     //Complex:
1548     @Override
1549     public boolean dataChangeDeleteComplexData(URL url) throws AAIServiceException {
1550
1551         if(url ==  null) {
1552             throw new NullPointerException();
1553         }
1554
1555         return deleteAAIEntity(url, Object.class.getClass().getEnclosingMethod()
1556                 .getName());
1557     }
1558
1559     private boolean deleteAAIEntity(URL url, String caller) throws AAIServiceException {
1560
1561         if(url ==  null) {
1562             throw new NullPointerException();
1563         }
1564
1565         boolean response = false;
1566         InputStream inputStream = null;
1567
1568         try {
1569             URL http_req_url =    url;
1570
1571             HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.DELETE);
1572
1573             LOGwriteFirstTrace("DELETE", http_req_url.toString());
1574
1575
1576             // Check for errors
1577             int responseCode = con.getResponseCode();
1578             if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1579                 inputStream = con.getInputStream();
1580             } else {
1581                 inputStream = con.getErrorStream();
1582             }
1583
1584             // Process the response
1585             LOG.debug("HttpURLConnection result:" + responseCode);
1586             if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
1587             BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
1588             String line = null;
1589
1590             ObjectMapper mapper = getObjectMapper();
1591
1592             if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1593                 StringBuilder stringBuilder = new StringBuilder();
1594
1595                 while( ( line = reader.readLine() ) != null ) {
1596                     stringBuilder.append( line );
1597                 }
1598                 LOGwriteEndingTrace(responseCode, "SUCCESS", stringBuilder.toString());
1599                 response = true;
1600             } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
1601                 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
1602                 response = false;
1603             } else {
1604                 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
1605                 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
1606                 throw new AAIServiceException(responseCode, errorresponse);
1607             }
1608
1609         } catch(AAIServiceException aaiexc) {
1610             throw aaiexc;
1611         } catch (Exception exc) {
1612             LOG.warn(caller, exc);
1613             throw new AAIServiceException(exc);
1614         } finally {
1615             if(inputStream != null){
1616                 try {
1617                     inputStream.close();
1618                 } catch(Exception exc) {
1619
1620                 }
1621             }
1622         }
1623         return response;
1624     }
1625
1626     /**
1627      * Generic method to GET json data from an A&AI callback URL.
1628      * Then convert that json to an Object.
1629      * If successful the Object is attempted to be cast to the type parameter.
1630      *
1631      * @param key
1632      *            callback url for A&AI
1633      * @param type
1634      *            the class of object that A&AI will return
1635      * @return the object created from json or null if the response code is not 200
1636      *
1637      * @throws AAIServiceException
1638      *             if empty or null key and or type or there's an error with processing
1639      */
1640     public <T> T dataChangeRequestAaiData(String key, Class<T> type) throws AAIServiceException {
1641         if (StringUtils.isEmpty(key) || type == null) {
1642             throw new AAIServiceException("Key is empty or null and or type is null");
1643         }
1644
1645         T response = null;
1646
1647         SvcLogicContext ctx = new SvcLogicContext();
1648         if(!key.contains(" = ") && isValidURL(key)) {
1649             key = String.format("selflink = '%s'", key);
1650         } else
1651         if(!key.contains(" = ") && isValidURI(key)) {
1652             key = String.format("resource-path = '%s'", key);
1653         }
1654
1655         HashMap<String, String> nameValues = AAIServiceUtils.keyToHashMap(key, ctx);
1656
1657         SelfLinkRequest request = new SelfLinkRequest(type);
1658         request.processRequestPathValues(nameValues);
1659         Object obj = this.getExecutor().query(request, type);
1660         response = type.cast(obj);
1661
1662         return response != null ? type.cast(response) : response;
1663     }
1664
1665     @Override
1666     public Pserver requestPServerData(String hostname) throws AAIServiceException {
1667         Pserver response = null;
1668
1669         try {
1670             AAIRequest request = AAIRequest.getRequestFromResource("pserver");
1671             request.addRequestProperty("pserver.hostname", hostname);
1672
1673
1674             String rv = executor.get(request);
1675             if(rv != null) {
1676                 ObjectMapper mapper = getObjectMapper();
1677                 response = mapper.readValue(rv, Pserver.class);
1678             }
1679         } catch(AAIServiceException aaiexc) {
1680             throw aaiexc;
1681         } catch (Exception exc) {
1682             LOG.warn("requestPServerData", exc);
1683             throw new AAIServiceException(exc);
1684         }
1685         return response;
1686     }
1687
1688     @Override
1689     public boolean postPServerData(String hostname, Pserver data) throws AAIServiceException {
1690         try {
1691             AAIRequest request = AAIRequest.getRequestFromResource("pserver");
1692             request.addRequestProperty("pserver.hostname", hostname);
1693             request.setRequestObject(data);
1694             Object response = executor.post(request);
1695             return true;
1696         } catch(AAIServiceException aaiexc) {
1697             throw aaiexc;
1698         } catch (Exception exc) {
1699             LOG.warn(Object.class.getClass().getEnclosingMethod().getName(), exc);
1700             throw new AAIServiceException(exc);
1701         }
1702     }
1703
1704     @Override
1705     public boolean deletePServerData(String hostname, String resourceVersion) throws AAIServiceException {
1706         boolean response = false;
1707
1708         try {
1709             AAIRequest request = AAIRequest.getRequestFromResource("pserver");
1710             request.addRequestProperty("pserver.hostname", hostname);
1711             response = executor.delete(request, resourceVersion);
1712         } catch(AAIServiceException aaiexc) {
1713             throw aaiexc;
1714         } catch (Exception exc) {
1715             LOG.warn("deletePServerData", exc);
1716             throw new AAIServiceException(exc);
1717         }
1718
1719         return response;
1720     }
1721
1722
1723     @Override
1724     public L3Network requestL3NetworkData(String networkId) throws AAIServiceException {
1725         L3Network response = null;
1726
1727         try {
1728             AAIRequest request = AAIRequest.getRequestFromResource("l3-network");
1729             request.addRequestProperty("l3-network.network-id", networkId);
1730
1731             String rv = executor.get(request);
1732             if(rv != null) {
1733                 ObjectMapper mapper = getObjectMapper();
1734                 response = mapper.readValue(rv, L3Network.class);
1735             }
1736         } catch(AAIServiceException aaiexc) {
1737             throw aaiexc;
1738         } catch (Exception exc) {
1739             LOG.warn("requestL3NetworkData", exc);
1740             throw new AAIServiceException(exc);
1741         }
1742         return response;
1743     }
1744
1745     @Override
1746     public L3Network requestL3NetworkQueryByName(String networkName) throws AAIServiceException {
1747         L3Network response = null;
1748
1749         try {
1750             AAIRequest request = AAIRequest.getRequestFromResource("l3-network");
1751             request.addRequestProperty("l3-network.network-name", networkName);
1752
1753             String rv = executor.get(request);
1754             if(rv != null) {
1755                 ObjectMapper mapper = getObjectMapper();
1756                 response = mapper.readValue(rv, L3Network.class);
1757             }
1758
1759         } catch(AAIServiceException aaiexc) {
1760             throw aaiexc;
1761         } catch (Exception exc) {
1762             LOG.warn("requestL3NetworkQueryByName", exc);
1763             throw new AAIServiceException(exc);
1764         }
1765         return response;
1766     }
1767
1768     @Override
1769     public boolean postL3NetworkData(String networkId, L3Network data) throws AAIServiceException {
1770         try {
1771             AAIRequest request = AAIRequest.getRequestFromResource("l3-network");
1772             request.addRequestProperty("l3-network.network-id", networkId);
1773             request.setRequestObject(data);
1774             Object response = executor.post(request);
1775             return true;
1776         } catch(AAIServiceException aaiexc) {
1777             throw aaiexc;
1778         } catch (Exception exc) {
1779             LOG.warn(Object.class.getClass().getEnclosingMethod().getName(), exc);
1780             throw new AAIServiceException(exc);
1781         }
1782     }
1783
1784     @Override
1785     public boolean deleteL3NetworkData(String networkId, String resourceVersion) throws AAIServiceException {
1786         boolean response = false;
1787
1788         try {
1789             AAIRequest request = AAIRequest.getRequestFromResource("l3-network");
1790             request.addRequestProperty("l3-network.network-id", networkId);
1791             response = executor.delete(request, resourceVersion);
1792         } catch(AAIServiceException aaiexc) {
1793             throw aaiexc;
1794         } catch (Exception exc) {
1795             LOG.warn("deleteL3NetworkData", exc);
1796             throw new AAIServiceException(exc);
1797         }
1798
1799         return response;
1800     }
1801
1802
1803     @Override
1804     public VpnBinding requestVpnBindingData(String vpnId) throws AAIServiceException {
1805         VpnBinding response = null;
1806
1807         try {
1808             AAIRequest request = AAIRequest.getRequestFromResource("vpn-binding");
1809             request.addRequestProperty("vpn-binding.vpn-id", vpnId);
1810
1811             String rv = executor.get(request);
1812             if(rv != null) {
1813                 ObjectMapper mapper = getObjectMapper();
1814                 response = mapper.readValue(rv, VpnBinding.class);
1815             }
1816         } catch(AAIServiceException aaiexc) {
1817             throw aaiexc;
1818         } catch (Exception exc) {
1819             LOG.warn("requestVpnBindingData", exc);
1820             throw new AAIServiceException(exc);
1821         }
1822         return response;
1823     }
1824
1825     @Override
1826     public boolean deleteVpnBindingData(String vpnId, String resourceVersion) throws AAIServiceException {
1827         boolean response = false;
1828
1829         try {
1830             AAIRequest request = AAIRequest.getRequestFromResource("vpn-binding");
1831             request.addRequestProperty("vpn-binding.vpn-id", vpnId);
1832             response = executor.delete(request, resourceVersion);
1833         } catch(AAIServiceException aaiexc) {
1834             throw aaiexc;
1835         } catch (Exception exc) {
1836             LOG.warn("deleteVpnBindingData", exc);
1837             throw new AAIServiceException(exc);
1838         }
1839         return response;
1840     }
1841
1842
1843     @Override
1844     public VnfImage requestVnfImageData(String vnf_image_uuid) throws AAIServiceException {
1845         VnfImage response = null;
1846
1847         try {
1848             AAIRequest request = AAIRequest.getRequestFromResource("vnf-image");
1849             request.addRequestProperty("vnf-image.vnf-image-uuid", vnf_image_uuid);
1850
1851             String rv = executor.get(request);
1852             if(rv != null) {
1853                 ObjectMapper mapper = getObjectMapper();
1854                 response = mapper.readValue(rv, VnfImage.class);
1855             }
1856         } catch(AAIServiceException aaiexc) {
1857             throw aaiexc;
1858         } catch (Exception exc) {
1859             LOG.warn("requestVnfImageData", exc);
1860             throw new AAIServiceException(exc);
1861         }
1862         return response;
1863     }
1864
1865     @Override
1866     public VnfImage requestVnfImageDataByVendorModel(String vendor, String model) throws AAIServiceException {
1867         return requestVnfImageDataByVendorModelVersion(vendor, model, null);
1868     }
1869
1870     @Override
1871     public VnfImage requestVnfImageDataByVendorModelVersion(String vendor, String model, String version) throws AAIServiceException
1872     {
1873         List<VnfImage> responseList = new ArrayList<VnfImage>();
1874         VnfImage response = null;
1875         InputStream inputStream = null;
1876
1877         try {
1878             String request_url = target_uri+vnf_image_query_path + (version==null? "": "&application-version={application_version}");
1879             request_url = request_url.replace("{application_vendor}", encodeQuery(vendor)) ;
1880             request_url = request_url.replace("{application_model}", encodeQuery(model)) ;
1881             if(version != null) {
1882                 request_url = request_url.replace("{application_version}", encodeQuery(version)) ;
1883             }
1884             URL http_req_url =    new URL(request_url);
1885
1886             HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.GET);
1887
1888             LOGwriteFirstTrace(HttpMethod.GET, http_req_url.toString());
1889             LOGwriteDateTrace("application_vendor", vendor);
1890             LOGwriteDateTrace("application_model", model);
1891             if(version != null) {
1892                 LOGwriteDateTrace("application_version", version);
1893             }
1894
1895             // Check for errors
1896             int responseCode = con.getResponseCode();
1897             if (responseCode == HttpURLConnection.HTTP_OK) {
1898                 inputStream = con.getInputStream();
1899             } else {
1900                 inputStream = con.getErrorStream();
1901             }
1902
1903             // Process the response
1904             LOG.debug("HttpURLConnection result:" + responseCode);
1905             if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
1906             BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
1907
1908             ObjectMapper mapper = getObjectMapper();
1909
1910             if (responseCode == HttpURLConnection.HTTP_OK) {
1911                 response = mapper.readValue(reader, VnfImage.class);
1912                 String original_buffer = mapper.writeValueAsString(response);
1913                 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, "SUCCESS", original_buffer);
1914                 if(response.getApplicationVendor() == null  /*&& response.getAdditionalProperties() != null && !response.getAdditionalProperties().isEmpty()*/){
1915                     LOG.warn("A List of multiple VNF-IMAGE entries has been returned");
1916                     VnfImages listOfObjects = mapper.readValue(original_buffer, VnfImages.class);
1917                     if(!listOfObjects.getVnfImage().isEmpty()) {
1918                         response = listOfObjects.getVnfImage().get(0);
1919                     }
1920                 }
1921             } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
1922                 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
1923                 return response;
1924             } else {
1925                 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
1926                 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
1927                 throw new AAIServiceException(responseCode, errorresponse);
1928             }
1929
1930         } catch(AAIServiceException aaiexc) {
1931             throw aaiexc;
1932         } catch (Exception exc) {
1933             LOG.warn("requestVnfImageData", exc);
1934             throw new AAIServiceException(exc);
1935         } finally {
1936             if(inputStream != null){
1937                 try {
1938                     inputStream.close();
1939                 } catch(Exception exc) {
1940
1941                 }
1942             }
1943         }
1944         return response;
1945     }
1946
1947
1948     public boolean sendNotify(NotifyEvent event, String serviceInstanceId, String pathCode) throws AAIServiceException {
1949         InputStream inputStream = null;
1950
1951         try {
1952
1953             String selfLink = selflink_fqdn;
1954             if(SELFLINK_AVPN != null && SELFLINK_AVPN.equals(pathCode)) {
1955                 selfLink = selflink_avpn;
1956             }
1957             selfLink = selfLink.replace("{service-instance-id}", encodeQuery(serviceInstanceId));
1958             event.setSelflink(selfLink);
1959
1960             ObjectMapper mapper = getObjectMapper();
1961             String json_text = mapper.writeValueAsString(event);
1962
1963             SSLSocketFactory sockFact = CTX.getSocketFactory();
1964
1965             String request_url = target_uri+ubb_notify_path;
1966             URL http_req_url =    new URL(request_url);
1967
1968             HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.PUT);
1969
1970             if (json_text != null) {
1971                 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
1972                 osw.write(json_text);
1973                 osw.flush();
1974                 osw.close();
1975             }
1976
1977             LOGwriteFirstTrace("PUT", request_url);
1978             LOGwriteDateTrace("NotifyEvent", json_text);
1979
1980             // Check for errors
1981             int responseCode = con.getResponseCode();
1982             if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1983                 inputStream = con.getInputStream();
1984             } else {
1985                 inputStream = con.getErrorStream();
1986             }
1987
1988             // Process the response
1989             BufferedReader reader;
1990             String line = null;
1991             reader = new BufferedReader( new InputStreamReader( inputStream ) );
1992
1993             if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1994                 StringBuilder stringBuilder = new StringBuilder();
1995
1996                 while( ( line = reader.readLine() ) != null ) {
1997                     stringBuilder.append( line );
1998                 }
1999                 LOGwriteEndingTrace(responseCode, "SUCCESS", (stringBuilder.length() > 0) ? stringBuilder.toString() :
2000                                                                                             "{no-data}");
2001                 return true;
2002             } else {
2003                 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2004                 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
2005
2006                 throw new AAIServiceException(responseCode, errorresponse);
2007             }
2008         } catch(AAIServiceException aaiexc) {
2009             throw aaiexc;
2010         } catch (Exception exc) {
2011             LOG.warn("sendNotify", exc);
2012             throw new AAIServiceException(exc);
2013         } finally {
2014             try {
2015                 if(inputStream != null)
2016                 inputStream.close();
2017             } catch (Exception exc) {
2018
2019             }
2020         }
2021     }
2022
2023     @Override
2024     public SearchResults requestNodeQuery(String node_type, String entityIdentifier, String entityName) throws AAIServiceException {
2025         SearchResults response = null;
2026         InputStream inputStream = null;
2027
2028         try {
2029             String request_url = target_uri+query_nodes_path;
2030             request_url = request_url.replace("{node-type}", encodeQuery(node_type)) ;
2031             request_url = request_url.replace("{entity-identifier}", entityIdentifier) ;
2032             request_url = request_url.replace("{entity-name}", encodeQuery(entityName)) ;
2033             URL http_req_url =    new URL(request_url);
2034
2035             HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.GET);
2036
2037             LOGwriteFirstTrace(HttpMethod.GET, http_req_url.toString());
2038             LOGwriteDateTrace("node_type", node_type);
2039             LOGwriteDateTrace("vnf_name", entityName);
2040
2041             // Check for errors
2042             int responseCode = con.getResponseCode();
2043             if (responseCode == HttpURLConnection.HTTP_OK) {
2044                 inputStream = con.getInputStream();
2045             } else {
2046                 inputStream = con.getErrorStream();
2047             }
2048
2049             // Process the response
2050             LOG.debug("HttpURLConnection result:" + responseCode);
2051             if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
2052             BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2053
2054             ObjectMapper mapper = getObjectMapper();
2055
2056             if (responseCode == HttpURLConnection.HTTP_OK) {
2057                 response = mapper.readValue(reader, SearchResults.class);
2058                 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, "SUCCESS", mapper.writeValueAsString(response));
2059             } else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
2060                 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
2061                 return response;
2062             } else {
2063                 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2064                 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
2065                 throw new AAIServiceException(responseCode, errorresponse);
2066             }
2067
2068         } catch(AAIServiceException aaiexc) {
2069             throw aaiexc;
2070         } catch (Exception exc) {
2071             LOG.warn("requestNodeQuery", exc);
2072             throw new AAIServiceException(exc);
2073         } finally {
2074             if(inputStream != null){
2075                 try {
2076                     inputStream.close();
2077                 } catch(Exception exc) {
2078
2079                 }
2080             }
2081         }
2082         return response;
2083
2084     }
2085
2086
2087     @Override
2088     public String requestDataByURL(URL url) throws AAIServiceException {
2089
2090         if(url ==  null) {
2091             throw new NullPointerException();
2092         }
2093
2094         String response = null;
2095         InputStream inputStream = null;
2096
2097         try {
2098             URL http_req_url = url;
2099
2100             HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.GET);
2101
2102             LOGwriteFirstTrace(HttpMethod.GET, http_req_url.toString());
2103
2104             // Check for errors
2105             int responseCode = con.getResponseCode();
2106             if (responseCode == HttpURLConnection.HTTP_OK) {
2107                 inputStream = con.getInputStream();
2108             } else {
2109                 inputStream = con.getErrorStream();
2110             }
2111
2112             // Process the response
2113             LOG.debug("HttpURLConnection result:" + responseCode);
2114             if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
2115             BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2116
2117             ObjectMapper mapper = getObjectMapper();
2118
2119             if (responseCode == HttpURLConnection.HTTP_OK) {
2120                 StringBuilder stringBuilder = new StringBuilder("\n");
2121                 String line = null;
2122                 while( ( line = reader.readLine() ) != null ) {
2123                     stringBuilder.append( line );
2124                 }
2125                 LOG.info(stringBuilder.toString());
2126 //                response = mapper.readValue(reader, String.class);
2127                 response = stringBuilder.toString();
2128                 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, "SUCCESS", mapper.writeValueAsString(response));
2129             } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
2130                 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
2131                 response = null;
2132             } else {
2133                 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2134                 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
2135                 throw new AAIServiceException(responseCode, errorresponse);
2136             }
2137
2138         } catch(AAIServiceException aaiexc) {
2139             throw aaiexc;
2140         } catch (Exception exc) {
2141             LOG.warn("requestNetworkVceData", exc);
2142             throw new AAIServiceException(exc);
2143         } finally {
2144             if(inputStream != null){
2145                 try {
2146                     inputStream.close();
2147                 } catch(Exception exc) {
2148
2149                 }
2150             }
2151         }
2152         return response;
2153     }
2154
2155
2156     @Override
2157     public GenericVnf requestGenericVnfeNodeQuery(String vnf_name) throws AAIServiceException {
2158
2159         if(vnf_name == null) {
2160             throw new NullPointerException();
2161         }
2162
2163         GenericVnf entity = null;
2164         SearchResults resp = this.requestNodeQuery("generic-vnf", "vnf-name", vnf_name);
2165
2166         List<ResultData> resultDataList = resp.getResultData();
2167
2168         try {
2169             for (ResultData datum : resultDataList) {
2170                 String data_type = datum.getResourceType();
2171                 URL url = new URL(datum.getResourceLink());
2172                 entity = this.getResource(url.toString(), GenericVnf.class);
2173             }
2174         }
2175         catch (Exception e)
2176         {
2177             LOG.error("Caught exception", e);
2178         }
2179         return entity;
2180     }
2181
2182     @Override
2183     public Vserver requestVServerDataByURL(URL url) throws AAIServiceException {
2184
2185         if(url == null) {
2186             throw new NullPointerException();
2187         }
2188
2189         Vserver entity = null;
2190
2191         try {
2192                 entity = this.getResource(url.toString(), Vserver.class);
2193         } catch (AAIServiceException exc) {
2194             throw exc;
2195         } catch (Exception e) {
2196             throw new AAIServiceException(e);
2197         }
2198         return entity;
2199     }
2200
2201     @Override
2202     public URL requestVserverURLNodeQuery(String vserver_name) throws AAIServiceException {
2203
2204         if(vserver_name == null) {
2205             throw new NullPointerException();
2206         }
2207
2208         URL entity = null;
2209         SearchResults resp = this.requestNodeQuery("vserver", "vserver-name", vserver_name);
2210
2211         List<ResultData> resultDataList = resp.getResultData();
2212
2213         try {
2214             for (ResultData datum : resultDataList) {
2215                 String data_type = datum.getResourceType();
2216                 String resourceLink = datum.getResourceLink();
2217                 if(!resourceLink.isEmpty() && !resourceLink.toLowerCase().startsWith("http")) {
2218                     resourceLink = (new EchoRequest()).targetUri + resourceLink;
2219                 }
2220                 entity = new URL(resourceLink);
2221             }
2222         } catch (Exception e) {
2223             throw new AAIServiceException(e);
2224         }
2225         return entity;
2226     }
2227
2228     class AAIRequestExecutor implements AAIExecutorInterface {
2229
2230         @Override
2231         public String get(AAIRequest request) throws AAIServiceException {
2232             String response = null;
2233             InputStream inputStream = null;
2234             HttpURLConnection con = null;
2235             URL requestUrl = null;
2236
2237             String requestId = UUID.randomUUID().toString();
2238             StringBuilder errorStringBuilder = new StringBuilder();
2239
2240             try {
2241
2242                 if(request.getRequestObject() != null) {
2243                     requestUrl = request.getRequestUrl(HttpMethod.POST, null);
2244                     requestUrl = appendDepth(requestUrl, request);
2245                     con = getConfiguredConnection(requestUrl, HttpMethod.POST);
2246                     String json_text = request.toJSONString();
2247                     LOGwriteDateTrace("data", json_text);
2248                     logMetricRequest(requestId, "POST "+requestUrl.getPath(), json_text, requestUrl.getPath());
2249                     OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
2250                     osw.write(json_text);
2251                     osw.flush();
2252                 } else {
2253                     requestUrl = request.getRequestUrl(HttpMethod.GET, null);
2254                     requestUrl = appendDepth(requestUrl, request);
2255                     con = getConfiguredConnection(requestUrl, HttpMethod.GET);
2256                     logMetricRequest(requestId, "GET "+requestUrl.getPath(), "", requestUrl.getPath());
2257                 }
2258
2259                 // Check for errors
2260                 String responseMessage = con.getResponseMessage();
2261                 int responseCode = con.getResponseCode();
2262                 if (responseCode == HttpURLConnection.HTTP_OK) {
2263                     inputStream = con.getInputStream();
2264                 } else {
2265                     inputStream = con.getErrorStream();
2266                 }
2267
2268                 // Process the response
2269                 LOG.debug("HttpURLConnection result:" + responseCode + " : " + responseMessage);
2270                 logMetricResponse(requestId, responseCode, responseMessage);
2271
2272                 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
2273                 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2274
2275                 ObjectMapper mapper = getObjectMapper();
2276
2277                 if (responseCode == HttpURLConnection.HTTP_OK) {
2278                     StringBuilder stringBuilder = new StringBuilder();
2279                     String line = null;
2280                     while( ( line = reader.readLine() ) != null ) {
2281                         stringBuilder.append( line );
2282                     }
2283                     response = stringBuilder.toString();
2284                     try {
2285                         Object object = mapper.readValue(response, Object.class);
2286                         LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, responseMessage, mapper.writeValueAsString(object));
2287                     } catch(Exception exc) {
2288                         LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, responseMessage, mapper.writeValueAsString(response));
2289                     }
2290                 } else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
2291                     LOGwriteEndingTrace(responseCode, responseMessage, "Entry does not exist.");
2292                     ErrorResponse errorresponse = null;
2293                     try {
2294                         errorresponse = mapper.readValue(reader, ErrorResponse.class);
2295                     } catch(Exception exc) {
2296                         errorresponse = new ErrorResponse();
2297                         RequestError requestError = new RequestError();
2298                         ServiceException serviceException = new ServiceException();
2299                         serviceException.setText("Entry does not exist.");
2300                         requestError.setServiceException(serviceException);
2301                         errorresponse.setRequestError(requestError );
2302                     }
2303                     throw new AAIServiceException(responseCode, errorresponse);
2304                 } else if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
2305                     StringBuilder stringBuilder = new StringBuilder();
2306                     String line = null;
2307                     while( ( line = reader.readLine() ) != null ) {
2308                         stringBuilder.append( line );
2309                     }
2310                     LOGwriteEndingTrace(responseCode, responseMessage, stringBuilder.toString());
2311                     ServiceException serviceException = new ServiceException();
2312                     serviceException.setMessageId("HTTP_UNAUTHORIZED");
2313                     serviceException.setText(stringBuilder.toString());
2314                     RequestError requestError = new RequestError();
2315                     requestError.setServiceException(serviceException);
2316                     ErrorResponse errorresponse = new ErrorResponse();
2317                     errorresponse.setRequestError(requestError);
2318                     throw new AAIServiceException(responseCode, errorresponse);
2319                 } else {
2320 //                    StringBuilder errorStringBuilder = new StringBuilder();
2321                     String line = null;
2322                     while( ( line = reader.readLine() ) != null ) {
2323                         errorStringBuilder.append("\n").append( line );
2324                     }
2325
2326                     ErrorResponse errorresponse = mapper.readValue(errorStringBuilder.toString(), ErrorResponse.class);
2327 //                    ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2328                     LOGwriteEndingTrace(responseCode, responseMessage, mapper.writeValueAsString(errorresponse));
2329                     throw new AAIServiceException(responseCode, errorresponse);
2330                 }
2331
2332             } catch(AAIServiceException aaiexc) {
2333                 throw aaiexc;
2334             } catch (Exception exc) {
2335                 LOG.warn(errorStringBuilder.toString(), exc);
2336                 throw new AAIServiceException(exc);
2337             } finally {
2338                 if (con != null) {
2339                     con.disconnect();
2340                 }
2341                 if(inputStream != null){
2342                     try {
2343                         inputStream.close();
2344                     } catch(Exception exc) {
2345
2346                     }
2347                 }
2348             }
2349             return response;
2350         }
2351
2352         private URL appendDepth(URL requestUrl, AAIRequest request) throws MalformedURLException {
2353
2354             String depth = request.requestProperties.getProperty("depth", "1");
2355             String path = requestUrl.toString();
2356             if(path.contains("?depth=") || path.contains("&depth=")) {
2357                 return requestUrl;
2358             } else {
2359                 if(path.contains("?")) {
2360                     path = String.format("%s&depth=%s", path, depth);
2361                 } else {
2362                     path = String.format("%s?depth=%s", path, depth);
2363                 }
2364                 return new URL(path);
2365             }
2366         }
2367
2368         @Override
2369         public String post(AAIRequest request) throws AAIServiceException {
2370             InputStream inputStream = null;
2371             String requestId = UUID.randomUUID().toString();
2372             HttpURLConnection con = null;
2373
2374             try {
2375                 String resourceVersion = null;
2376                 AAIDatum instance = request.getRequestObject();
2377
2378                 Method getResourceVersionMethod = instance.getClass().getMethod("getResourceVersion");
2379                 if(getResourceVersionMethod != null){
2380                     try {
2381                         getResourceVersionMethod.setAccessible(true);
2382                         Object object = getResourceVersionMethod.invoke(instance);
2383                         if(object != null)
2384                             resourceVersion = object.toString();
2385                     } catch (InvocationTargetException x) {
2386                         Throwable cause = x.getCause();
2387                     }
2388                 }
2389
2390                 URL requestUrl = null;
2391                 con = getConfiguredConnection(requestUrl = request.getRequestUrl(HttpMethod.PUT, resourceVersion), HttpMethod.PUT);
2392                 ObjectMapper mapper = getObjectMapper();
2393                 String json_text = request.toJSONString();
2394
2395                 LOGwriteDateTrace("data", json_text);
2396                 logMetricRequest(requestId, "PUT "+requestUrl.getPath(), json_text, requestUrl.getPath());
2397
2398                 if (json_text != null) {
2399                     OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
2400                     osw.write(json_text);
2401                     osw.flush();
2402                 }
2403                 // Check for errors
2404                 String responseMessage = con.getResponseMessage();
2405                 int responseCode = con.getResponseCode();
2406                 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2407                     inputStream = con.getInputStream();
2408                 } else {
2409                     inputStream = con.getErrorStream();
2410                 }
2411
2412                 LOG.debug("HttpURLConnection result:" + responseCode + " : " + responseMessage);
2413                 logMetricResponse(requestId,responseCode, responseMessage);
2414
2415                 // Process the response
2416                 BufferedReader reader;
2417                 String line = null;
2418                 reader = new BufferedReader( new InputStreamReader( inputStream ) );
2419                 mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
2420
2421                 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2422                     StringBuilder stringBuilder = new StringBuilder();
2423
2424                     while( ( line = reader.readLine() ) != null ) {
2425                         stringBuilder.append( line );
2426                     }
2427                     LOGwriteEndingTrace(responseCode, responseMessage, (stringBuilder != null) ? stringBuilder.toString() : "{no-data}");
2428                     return stringBuilder.toString();
2429                 } else {
2430                     ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2431                     LOGwriteEndingTrace(responseCode, responseMessage, mapper.writeValueAsString(errorresponse));
2432
2433                     throw new AAIServiceException(responseCode, errorresponse);
2434                 }
2435             } catch(AAIServiceException aaiexc) {
2436                 throw aaiexc;
2437             } catch (Exception exc) {
2438                 LOG.warn("AAIRequestExecutor.post", exc);
2439                 throw new AAIServiceException(exc);
2440             } finally {
2441                 if (con != null) {
2442                     con.disconnect();
2443                 }
2444                 try {
2445                     if(inputStream != null)
2446                     inputStream.close();
2447                 } catch (Exception exc) {
2448
2449                 }
2450             }
2451         }
2452
2453         @Override
2454         public Boolean delete(AAIRequest request, String resourceVersion) throws AAIServiceException {
2455             Boolean response = null;
2456             InputStream inputStream = null;
2457             String requestId = UUID.randomUUID().toString();
2458
2459             if(resourceVersion == null) {
2460                 throw new AAIServiceException("resource-version is required for DELETE request");
2461             }
2462
2463             try {
2464                 URL requestUrl = null;
2465                 HttpURLConnection conn = getConfiguredConnection(requestUrl = request.getRequestUrl(HttpMethod.DELETE, resourceVersion), HttpMethod.DELETE);
2466                 logMetricRequest(requestId, "DELETE "+requestUrl.getPath(), "", requestUrl.getPath());
2467                 conn.setDoOutput(true);
2468
2469                 // Check for errors
2470                 String responseMessage = conn.getResponseMessage();
2471                 int responseCode = conn.getResponseCode();
2472                 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2473                     inputStream = conn.getInputStream();
2474                 } else {
2475                     inputStream = conn.getErrorStream();
2476                 }
2477
2478                 // Process the response
2479                 LOG.debug("HttpURLConnection result:" + responseCode + " : " + responseMessage);
2480                 logMetricResponse(requestId,responseCode, responseMessage);
2481
2482                 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
2483                 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2484                 String line = null;
2485
2486                 ObjectMapper mapper = getObjectMapper();
2487
2488                 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2489                     StringBuilder stringBuilder = new StringBuilder();
2490
2491                     while( ( line = reader.readLine() ) != null ) {
2492                         stringBuilder.append( line );
2493                     }
2494                     LOGwriteEndingTrace(responseCode, responseMessage, stringBuilder.toString());
2495                     response = true;
2496                 } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
2497                     LOGwriteEndingTrace(responseCode, responseMessage, "Entry does not exist.");
2498                     response = false;
2499                 } else {
2500                     ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2501                     LOGwriteEndingTrace(responseCode, responseMessage, mapper.writeValueAsString(errorresponse));
2502                     throw new AAIServiceException(responseCode, errorresponse);
2503                 }
2504             } catch(AAIServiceException aaiexc) {
2505                 throw aaiexc;
2506             } catch (Exception exc) {
2507                 LOG.warn("delete", exc);
2508                 throw new AAIServiceException(exc);
2509             } finally {
2510                 if(inputStream != null){
2511                     try {
2512                         inputStream.close();
2513                     } catch(Exception exc) {
2514
2515                     }
2516                 }
2517             }
2518             return response;
2519         }
2520
2521         @Override
2522         public Object query(AAIRequest request, Class clas) throws AAIServiceException {
2523             Object response = null;
2524             InputStream inputStream = null;
2525             HttpURLConnection con = null;
2526             URL requestUrl = null;
2527             String requestId = UUID.randomUUID().toString();
2528
2529             try {
2530                 requestUrl = request.getRequestQueryUrl(HttpMethod.GET);
2531                 con = getConfiguredConnection(requestUrl , HttpMethod.GET);
2532                 logMetricRequest(requestId, "GET "+requestUrl.getPath(), "", requestUrl.getPath());
2533
2534                 // Check for errors
2535                 String responseMessage = con.getResponseMessage();
2536                 int responseCode = con.getResponseCode();
2537                 if (responseCode == HttpURLConnection.HTTP_OK) {
2538                     inputStream = con.getInputStream();
2539                 } else {
2540                     inputStream = con.getErrorStream();
2541                 }
2542
2543                 logMetricResponse(requestId,responseCode, responseMessage);
2544                 ObjectMapper mapper = getObjectMapper();
2545
2546                 if (responseCode == HttpURLConnection.HTTP_OK) {
2547                     // Process the response
2548                     BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2549                     response = mapper.readValue(reader, clas);
2550                     LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, "SUCCESS", mapper.writeValueAsString(response));
2551                 } else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
2552                     LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
2553                     return response;
2554                 } else {
2555                     BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2556                     ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2557                     LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
2558                     throw new AAIServiceException(responseCode, errorresponse);
2559                 }
2560
2561             } catch(AAIServiceException aaiexc) {
2562                 throw aaiexc;
2563             } catch (Exception exc) {
2564                 LOG.warn("GET", exc);
2565                 throw new AAIServiceException(exc);
2566             } finally {
2567                 if(inputStream != null){
2568                     try {
2569                         inputStream.close();
2570                     } catch(Exception exc) {
2571
2572                     }
2573                 }
2574                 if (con != null) {
2575                     con.disconnect();
2576                 }
2577             }
2578             return response;
2579         }
2580
2581         @Override
2582         public Boolean patch(AAIRequest request, String resourceVersion) throws AAIServiceException {
2583             InputStream inputStream = null;
2584             String requestId = UUID.randomUUID().toString();
2585
2586             try {
2587                 AAIDatum instance = request.getRequestObject();
2588                 if(instance instanceof ResourceVersion) {
2589                     resourceVersion = ((ResourceVersion)instance).getResourceVersion();
2590                 }
2591
2592                 URL requestUrl = null;
2593                 HttpURLConnection con = getConfiguredConnection(requestUrl = request.getRequestUrl("PATCH", resourceVersion), "PATCH");
2594                 ObjectMapper mapper = getObjectMapper();
2595                 String json_text = request.toJSONString();
2596
2597                 LOGwriteDateTrace("data", json_text);
2598                 logMetricRequest(requestId, "PATCH "+requestUrl.getPath(), json_text, requestUrl.getPath());
2599
2600                 if (json_text != null) {
2601                     OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
2602                     osw.write(json_text);
2603                     osw.flush();
2604                     osw.close();
2605                 }
2606
2607                 // Check for errors
2608                 String responseMessage = con.getResponseMessage();
2609                 int responseCode = con.getResponseCode();
2610                 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2611                     inputStream = con.getInputStream();
2612                 } else {
2613                     inputStream = con.getErrorStream();
2614                 }
2615
2616                 LOG.info("HttpURLConnection result: " + responseCode + " : " + responseMessage);
2617                 logMetricResponse(requestId,responseCode, responseMessage);
2618
2619                 // Process the response
2620                 BufferedReader reader;
2621                 String line = null;
2622                 reader = new BufferedReader( new InputStreamReader( inputStream ) );
2623                 mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
2624
2625                 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2626                     StringBuilder stringBuilder = new StringBuilder();
2627
2628                     while( ( line = reader.readLine() ) != null ) {
2629                         stringBuilder.append( line );
2630                     }
2631                     LOGwriteEndingTrace(responseCode, responseMessage,
2632                                                (stringBuilder.length() > 0) ? stringBuilder.toString() : "{no-data}");
2633                     return true;
2634                 } else {
2635                     StringBuilder stringBuilder = new StringBuilder();
2636
2637                     while( ( line = reader.readLine() ) != null ) {
2638                         stringBuilder.append("\n").append( line );
2639                     }
2640                     LOG.info(stringBuilder.toString());
2641
2642
2643                     ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2644                     LOGwriteEndingTrace(responseCode, responseMessage, mapper.writeValueAsString(errorresponse));
2645
2646                     throw new AAIServiceException(responseCode, errorresponse);
2647                 }
2648             } catch(AAIServiceException aaiexc) {
2649                 throw aaiexc;
2650             } catch (Exception exc) {
2651                 LOG.warn("AAIRequestExecutor.patch", exc);
2652                 throw new AAIServiceException(exc);
2653             } finally {
2654                 try {
2655                     if(inputStream != null)
2656                     inputStream.close();
2657                 } catch (Exception exc) {
2658
2659                 }
2660             }
2661         }
2662     }
2663
2664     @Override
2665     public Tenant requestTenantData(String tenant_id, String cloudOwner, String cloudRegionId) throws AAIServiceException {
2666         Tenant response = null;
2667
2668         try {
2669             AAIRequest request = AAIRequest.getRequestFromResource("tenant");
2670             request.addRequestProperty("tenant.tenant-id", tenant_id);
2671             request.addRequestProperty("cloud-region.cloud-owner", cloudOwner);
2672             request.addRequestProperty("cloud-region.cloud-region-id", cloudRegionId);
2673
2674             String rv = executor.get(request);
2675             if(rv != null) {
2676                 ObjectMapper mapper = getObjectMapper();
2677                 response = mapper.readValue(rv, Tenant.class);
2678             }
2679         } catch(AAIServiceException aaiexc) {
2680             throw aaiexc;
2681         } catch (Exception exc) {
2682             LOG.warn("requestTenantData", exc);
2683             throw new AAIServiceException(exc);
2684         }
2685
2686         return response;
2687     }
2688
2689     @Override
2690     public Tenant requestTenantDataByName(String tenant_name, String cloudOwner, String cloudRegionId) throws AAIServiceException {
2691         Tenant response = null;
2692
2693         try {
2694             AAIRequest request = AAIRequest.getRequestFromResource("tenant");
2695             request.addRequestProperty("tenant.tenant-name", tenant_name);
2696             request.addRequestProperty("cloud-region.cloud-owner", cloudOwner);
2697             request.addRequestProperty("cloud-region.cloud-region-id", cloudRegionId);
2698             Object rv = executor.query(request, Tenant.class);
2699             if(rv == null)
2700                 return (Tenant)null;
2701             else
2702                 response = (Tenant)rv;
2703         } catch(AAIServiceException aaiexc) {
2704             throw aaiexc;
2705         } catch (Exception exc) {
2706             LOG.warn("requestTenantDataByName", exc);
2707             throw new AAIServiceException(exc);
2708         }
2709
2710         return response;
2711     }
2712
2713
2714     @Override
2715     public boolean postTenantData(String tenant_id, String cloudOwner, String cloudRegionId, Tenant tenannt) throws AAIServiceException {
2716         try {
2717             AAIRequest request = AAIRequest.getRequestFromResource("tenant");
2718             request.addRequestProperty("tenant.tenant-id", tenant_id);
2719             request.addRequestProperty("cloud-region.cloud-owner", cloudOwner);
2720             request.addRequestProperty("cloud-region.cloud-region-id", cloudRegionId);
2721             request.setRequestObject(tenannt);
2722             Object response = executor.post(request);
2723             return true;
2724         } catch(AAIServiceException aaiexc) {
2725             throw aaiexc;
2726         } catch (Exception exc) {
2727             LOG.warn("postTenantData", exc);
2728             throw new AAIServiceException(exc);
2729         }
2730     }
2731
2732
2733     @Override
2734     public String getTenantIdFromVserverUrl(URL url) {
2735
2736         String path = url.getPath();
2737
2738         String[] split = path.split("/tenants/tenant/");
2739         if(split.length > 1) {
2740             split = split[1].split("/");
2741             return split[0];
2742         } else {
2743             return null;
2744         }
2745     }
2746
2747     @Override
2748     public String getCloudOwnerFromVserverUrl(URL url) {
2749
2750         String path = url.getPath();
2751
2752         String[] split = path.split("/cloud-regions/cloud-region/");
2753         if(split.length > 1) {
2754             split = split[1].split("/");
2755             return split[0];
2756         } else {
2757             return null;
2758         }
2759     }
2760
2761     @Override
2762     public String getCloudRegionFromVserverUrl(URL url) {
2763
2764         String path = url.getPath();
2765
2766         String[] split = path.split("/cloud-regions/cloud-region/");
2767         if(split.length > 1) {
2768             split = split[1].split("/");
2769             return split[1];
2770         } else {
2771             return null;
2772         }
2773     }
2774
2775     @Override
2776     public String getVServerIdFromVserverUrl(URL url, String tenantId) {
2777         String pattern =  networkVserverPath;
2778         pattern = pattern.replace("{tenant-id}", tenantId);
2779
2780         int end = pattern.indexOf("{vserver-id}");
2781         String prefix = pattern.substring(0, end);
2782
2783         String path = url.getPath();
2784
2785         if(path.startsWith(prefix)) {
2786             path = path.substring(prefix.length());
2787         }
2788
2789         return path;
2790     }
2791
2792     protected  Logger getLogger(){
2793         return LOG;
2794     }
2795
2796
2797     @Override
2798     public AAIRequestExecutor getExecutor() {
2799         return executor;
2800     }
2801
2802     /**
2803      * Creates a current time stamp in UTC i.e. 2016-03-08T22:15:13.343Z.
2804      * If there are any parameters the values are appended to the time stamp.
2805      *
2806      * @param parameters
2807      *            values to be appended to current time stamp
2808      * @param ctx
2809      *            used to set an attribute for a DG
2810      * @throws SvcLogicException
2811      */
2812     public void setStatusMethod(Map<String, String> parameters, SvcLogicContext ctx) throws SvcLogicException {
2813         if (ctx == null) {
2814             throw new SvcLogicException("SvcLogicContext is null.");
2815         }
2816
2817         StringBuilder sb = new StringBuilder();
2818         sb.append(String.format("%tFT%<tTZ", Calendar.getInstance(TimeZone.getTimeZone("Z")))).append(" - ");
2819
2820         for (Entry<String, String> entry : parameters.entrySet()) {
2821             sb.append(entry.getValue()).append("  ");
2822         }
2823
2824         if (sb.length() > 0) {
2825             sb.setLength(sb.length() - 2);
2826         }
2827
2828         ctx.setAttribute("aai-summary-status-message", sb.toString());
2829         LOG.info("aai-summary-status-message: " + sb.toString());
2830     }
2831
2832     /**
2833      * Generic method to GET json data from an A&AI using key structure.
2834      * Then convert that json to an Object.
2835      * If successful the Object is attempted to be cast to the type parameter.
2836      *
2837      * @param key
2838      *            key identifying the resource to be retrieved from AAI
2839      * @param type
2840      *            the class of object that A&AI will return
2841      * @return the object created from json or null if the response code is not 200
2842      *
2843      * @throws AAIServiceException
2844      *             if empty or null key and or type or there's an error with processing
2845      */
2846
2847     public <T> T getResource(String key, Class<T> type) throws AAIServiceException {
2848             if (StringUtils.isEmpty(key) || type == null) {
2849                 throw new AAIServiceException("Key is empty or null and or type is null");
2850             }
2851
2852             T response = null;
2853
2854             SvcLogicContext ctx = new SvcLogicContext();
2855             if(!key.contains(" = ")) {
2856                 if(isValidURL(key)) {
2857                     key = String.format("selflink = '%s'", key);
2858                 } else if(isValidURI(key)) {
2859                     key = String.format("resource-path = '%s'", key);
2860                 } else {
2861                     return response;
2862                 }
2863             }
2864
2865             HashMap<String, String> nameValues = AAIServiceUtils.keyToHashMap(key, ctx);
2866
2867             AAIRequest request = new SelfLinkRequest(type);
2868             if(nameValues.containsKey(PathRequest.RESOURCE_PATH.replaceAll("-", "_"))) {
2869                 request = new PathRequest(type);
2870             }
2871
2872             request.processRequestPathValues(nameValues);
2873             Object obj = this.getExecutor().query(request, type);
2874             response = type.cast(obj);
2875
2876             return response != null ? type.cast(response) : response;
2877      }
2878
2879      public boolean isValidURL(String url) {
2880
2881             URL u = null;
2882
2883             try {
2884                 u = new URL(url);
2885             } catch (MalformedURLException e) {
2886                 return false;
2887             }
2888
2889             try {
2890                 u.toURI();
2891             } catch (URISyntaxException e) {
2892                 return false;
2893             }
2894
2895             return true;
2896         }
2897
2898
2899     public boolean isValidURI(String url) {
2900
2901         URI u = null;
2902
2903         try {
2904             u = new URI(url);
2905         } catch (URISyntaxException e) {
2906             return false;
2907         }
2908
2909         return true;
2910     }
2911
2912
2913     protected boolean deleteList(URL httpReqUrl, String json_text) throws AAIServiceException {
2914         if(httpReqUrl ==  null) {
2915             throw new NullPointerException();
2916         }
2917
2918         boolean response = false;
2919         InputStream inputStream = null;
2920
2921         try {
2922             HttpURLConnection con = getConfiguredConnection(httpReqUrl, HttpMethod.DELETE);
2923
2924 //            SSLSocketFactory sockFact = CTX.getSocketFactory();
2925 //            con.setSSLSocketFactory( sockFact );
2926             if (json_text != null) {
2927                 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
2928                 osw.write(json_text);
2929                 osw.flush();
2930                 osw.close();
2931             }
2932
2933             LOGwriteFirstTrace("DELETE", httpReqUrl.toString());
2934             LOGwriteDateTrace("data", json_text);
2935
2936             // Check for errors
2937             int responseCode = con.getResponseCode();
2938             if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2939                 inputStream = con.getInputStream();
2940             } else {
2941                 inputStream = con.getErrorStream();
2942             }
2943
2944             // Process the response
2945             LOG.debug("HttpURLConnection result:" + responseCode);
2946             if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
2947             BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2948             String line = null;
2949
2950             ObjectMapper mapper = getObjectMapper();
2951
2952             if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2953                 StringBuilder stringBuilder = new StringBuilder();
2954
2955                 while( ( line = reader.readLine() ) != null ) {
2956                     stringBuilder.append( line );
2957                 }
2958                 LOGwriteEndingTrace(responseCode, "SUCCESS", stringBuilder.toString());
2959                 response = true;
2960             } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
2961                 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
2962                 response = false;
2963             } else {
2964                 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2965                 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
2966                 throw new AAIServiceException(responseCode, errorresponse);
2967             }
2968
2969         } catch(AAIServiceException aaiexc) {
2970             throw aaiexc;
2971         } catch (Exception exc) {
2972             LOG.warn("deleteList", exc);
2973             throw new AAIServiceException(exc);
2974         } finally {
2975             if(inputStream != null){
2976                 try {
2977                     inputStream.close();
2978                 } catch(Exception exc) {
2979
2980                 }
2981             }
2982         }
2983         return response;
2984     }
2985
2986     public static ObjectMapper getObjectMapper() {
2987         ObjectMapper mapper = new ObjectMapper();
2988         AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance());
2989         AnnotationIntrospector secondary = new JacksonAnnotationIntrospector();
2990         mapper.setAnnotationIntrospector(AnnotationIntrospector.pair(introspector, secondary));
2991         mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
2992         mapper.setSerializationInclusion(Include.NON_NULL);
2993         return mapper;
2994     }
2995
2996     public void logMetricRequest(String requestId, String targetServiceName, String msg, String path){
2997         String svcInstanceId = "";
2998         String svcName = null;
2999         String partnerName = null;
3000         String targetEntity = "A&AI";
3001         String targetVirtualEntity = null;
3002
3003         targetServiceName = "";
3004
3005         ml.logRequest(svcInstanceId, svcName, partnerName, targetEntity, targetServiceName, targetVirtualEntity, msg);
3006     }
3007
3008     public void logMetricResponse(String requestId, int responseCode, String responseDescription){
3009         ml.logResponse(responseCode < 400 ? "SUCCESS" : "FAILURE", Integer.toString(responseCode), responseDescription);
3010     }
3011
3012     public void logKeyError(String keys){
3013         LOG.error("Atleast one of the keys [" + keys + "] should have been populated. This will cause a NPE.");
3014     }
3015
3016
3017     /**
3018      * Retrofit code
3019      */
3020     @Override
3021     public QueryStatus save(String resource, boolean force, boolean localOnly, String key, Map<String, String> params, String prefix, SvcLogicContext ctx)
3022             throws SvcLogicException {
3023         String normResource = resource.split(":")[0];
3024
3025         switch(normResource){
3026         case "custom-query":
3027         case "formatted-query":
3028         case "generic-query":
3029         case "named-query":
3030         case "nodes-query":
3031         case "linterface":
3032         case "l2-bridge-sbg":
3033         case "l2-bridge-bgf":
3034         case "echo":
3035         case "test":
3036             break;
3037
3038         default:
3039             if(key.contains("selflink =")) {
3040                 break;
3041             }
3042             if(!key.contains(String.format("%s.", normResource))) {
3043                 key = rewriteKey(resource, key, ctx);
3044             }
3045         }
3046         return super.save(resource, force, localOnly, key, params, prefix, ctx);
3047     }
3048
3049     @Override
3050     public QueryStatus query(String resource, boolean localOnly, String select, String key, String prefix, String orderBy, SvcLogicContext ctx)
3051         throws SvcLogicException {
3052         String normResource = resource.split(":")[0];
3053
3054         switch(normResource){
3055         case "formatted-query":
3056         case "generic-query":
3057         case "named-query":
3058         case "nodes-query":
3059         case "linterface":
3060         case "l2-bridge-sbg":
3061         case "l2-bridge-bgf":
3062         case "echo":
3063         case "test":
3064             break;
3065
3066         default:
3067             if(key.contains("selflink =")) {
3068                 break;
3069             }
3070             if(!key.contains(String.format("%s.", normResource))) {
3071                 key = rewriteKey(resource, key, ctx);
3072             }
3073         }
3074
3075         return super.query(resource, localOnly, select, key, prefix, orderBy, ctx);
3076     }
3077
3078     @Override
3079     public QueryStatus delete(String resource, String key, SvcLogicContext ctx) throws SvcLogicException {
3080         String normResource = resource.split(":")[0];
3081
3082         switch(normResource){
3083         case "formatted-query":
3084         case "generic-query":
3085         case "named-query":
3086         case "nodes-query":
3087         case "linterface":
3088         case "l2-bridge-sbg":
3089         case "l2-bridge-bgf":
3090         case "echo":
3091         case "test":
3092             break;
3093
3094         default:
3095             if(key.contains("selflink =")) {
3096                 break;
3097             }
3098             if(!key.contains(String.format("%s.", normResource))) {
3099                 key = rewriteKey(resource, key, ctx);
3100             }
3101         }
3102
3103         return super.delete(resource, key, ctx);
3104     }
3105
3106     @Override
3107     public QueryStatus update(String resource, String key, Map<String, String> params, String prefix, SvcLogicContext ctx) throws SvcLogicException {
3108         String normResource = resource.split(":")[0];
3109
3110         switch(normResource){
3111         case "formatted-query":
3112         case "generic-query":
3113         case "named-query":
3114         case "nodes-query":
3115         case "linterface":
3116         case "l2-bridge-sbg":
3117         case "l2-bridge-bgf":
3118         case "echo":
3119         case "test":
3120             break;
3121
3122         default:
3123             if(key.contains("selflink =")) {
3124                 break;
3125             }
3126             if(!key.contains(String.format("%s.", normResource))) {
3127                 key = rewriteKey(resource, key, ctx);
3128             }
3129         }
3130
3131         return super.update(resource, key, params, prefix, ctx);
3132     }
3133
3134     private String rewriteKey(String resource, String key, SvcLogicContext ctx) {
3135         LOG.info("AAI Deprecation - the format of request key is no longer supported. Please rewrite this key : " + key);
3136
3137         String normResource = resource.split(":")[0];
3138         Class<? extends AAIDatum> clazz = null;
3139         try {
3140             clazz = AAIRequest.getClassFromResource(normResource) ;
3141         } catch (ClassNotFoundException e) {
3142             LOG.warn("AAIRequest does not support class: " + e.getMessage());
3143             return key;
3144         }
3145         if(clazz == null)
3146             return key;
3147
3148         List<String> fieldAnnotatedNames = new LinkedList<>();
3149
3150         Field[] fields = clazz.getDeclaredFields();
3151         for(Field field : fields) {
3152             String fieldName = field.getName();
3153             XmlElement annotation = field.getAnnotation(XmlElement.class);
3154             if(annotation == null)
3155                 continue;
3156             String primaryId = annotation.name();
3157             if("##default".equals(primaryId)) {
3158                 primaryId = fieldName;
3159             }
3160             fieldAnnotatedNames.add(primaryId);
3161         }
3162
3163         HashMap<String, String> nameValues = AAIServiceUtils.keyToHashMap(key, ctx);
3164         Set<String> keyset = nameValues.keySet();
3165         for(String keyName : keyset) {
3166             if(keyName.contains("."))
3167                 continue;
3168             else {
3169                 String tmpKeyName = keyName.replaceAll("_", "-");
3170                 String valueToSubstitute = String.format("%s =", tmpKeyName);
3171                 if(fieldAnnotatedNames.contains(tmpKeyName) && key.contains(valueToSubstitute)) {
3172                     key = key.replace(valueToSubstitute, String.format("%s.%s =", normResource, tmpKeyName));
3173                 }
3174             }
3175         }
3176
3177
3178         return key;
3179     }
3180
3181     @Override
3182     public String getPathTemplateForResource(String resoourceName, String keys, SvcLogicContext ctx) throws MalformedURLException {
3183         return AAIServiceUtils.getPathForResource(resoourceName, StringUtils.join(keys, " AND "), ctx);
3184     }
3185
3186     @Override
3187     public boolean isDeprecatedFormat(String resource, HashMap<String, String> nameValues) {
3188         return !AAIServiceUtils.isValidFormat(resource, nameValues);
3189     }
3190
3191     public AAIRequest getRequestFromResource(String resoourceName) {
3192         return AAIRequest.getRequestFromResource(resoourceName);
3193     }
3194
3195     /* (non-Javadoc)
3196      * @see org.openecomp.sdnc.sli.aai.haha#query(org.openecomp.sdnc.sli.aai.AAIRequest)
3197      */
3198     @Override
3199     public String query(AAIRequest request) throws AAIServiceException {
3200         return executor.get(request);
3201     }
3202
3203     /* (non-Javadoc)
3204      * @see org.openecomp.sdnc.sli.aai.haha#save(org.openecomp.sdnc.sli.aai.AAIRequest)
3205      */
3206     @Override
3207     public String save(AAIRequest request) throws AAIServiceException {
3208         return executor.post(request);
3209     }
3210
3211     public boolean update(AAIRequest request, String resourceVersion) throws AAIServiceException {
3212         return executor.patch(request, resourceVersion);
3213     }
3214
3215     /* (non-Javadoc)
3216      * @see org.openecomp.sdnc.sli.aai.haha#delete(org.openecomp.sdnc.sli.aai.AAIRequest, java.lang.String)
3217      */
3218     @Override
3219     public boolean delete(AAIRequest request, String resourceVersion) throws AAIServiceException {
3220         return executor.patch(request, resourceVersion);
3221     }
3222
3223 }