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