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