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