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