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