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