2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
22 package org.onap.ccsdk.sli.adaptors.aai;
25 import java.io.BufferedReader;
26 import java.io.ByteArrayInputStream;
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;
40 import java.net.URISyntaxException;
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;
55 import java.util.Map.Entry;
56 import java.util.Properties;
58 import java.util.TimeZone;
59 import java.util.UUID;
60 import java.util.regex.Matcher;
61 import java.util.regex.Pattern;
63 import javax.net.ssl.HostnameVerifier;
64 import javax.net.ssl.HttpsURLConnection;
65 import javax.net.ssl.KeyManagerFactory;
66 import javax.net.ssl.SSLContext;
67 import javax.net.ssl.SSLSession;
68 import javax.net.ssl.SSLSocketFactory;
69 import javax.ws.rs.HttpMethod;
70 import javax.xml.bind.annotation.XmlElement;
72 import org.apache.commons.codec.binary.Base64;
73 import org.apache.commons.lang3.StringUtils;
74 import org.onap.ccsdk.sli.core.sli.ConfigurationException;
75 import org.onap.ccsdk.sli.core.sli.MetricLogger;
76 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
77 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
78 import org.onap.ccsdk.sli.core.sli.SvcLogicResource;
79 import org.openecomp.aai.inventory.v11.AvailabilityZone;
80 import org.openecomp.aai.inventory.v11.Complex;
81 import org.openecomp.aai.inventory.v11.CtagPool;
82 import org.openecomp.aai.inventory.v11.DvsSwitch;
83 import org.openecomp.aai.inventory.v11.GenericVnf;
84 import org.openecomp.aai.inventory.v11.L3Network;
85 import org.openecomp.aai.inventory.v11.OamNetwork;
86 import org.openecomp.aai.inventory.v11.PInterface;
87 import org.openecomp.aai.inventory.v11.PhysicalLink;
88 import org.openecomp.aai.inventory.v11.Pserver;
89 import org.openecomp.aai.inventory.v11.ResultData;
90 import org.openecomp.aai.inventory.v11.SearchResults;
91 import org.openecomp.aai.inventory.v11.Service;
92 import org.openecomp.aai.inventory.v11.ServiceInstance;
93 import org.openecomp.aai.inventory.v11.SitePairSet;
94 import org.openecomp.aai.inventory.v11.Tenant;
95 import org.openecomp.aai.inventory.v11.Vce;
96 import org.openecomp.aai.inventory.v11.VnfImage;
97 import org.openecomp.aai.inventory.v11.VnfImages;
98 import org.openecomp.aai.inventory.v11.VplsPe;
99 import org.openecomp.aai.inventory.v11.VpnBinding;
100 import org.openecomp.aai.inventory.v11.Vserver;
101 import org.onap.ccsdk.sli.adaptors.aai.data.AAIDatum;
102 import org.onap.ccsdk.sli.adaptors.aai.data.ErrorResponse;
103 import org.onap.ccsdk.sli.adaptors.aai.data.RequestError;
104 import org.onap.ccsdk.sli.adaptors.aai.data.ResourceVersion;
105 import org.onap.ccsdk.sli.adaptors.aai.data.ServiceException;
106 import org.onap.ccsdk.sli.adaptors.aai.data.notify.NotifyEvent;
107 import org.slf4j.Logger;
108 import org.slf4j.LoggerFactory;
109 import org.slf4j.MDC;
111 import com.fasterxml.jackson.annotation.JsonInclude.Include;
112 import com.fasterxml.jackson.databind.AnnotationIntrospector;
113 import com.fasterxml.jackson.databind.DeserializationFeature;
114 import com.fasterxml.jackson.databind.ObjectMapper;
115 import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector;
116 import com.fasterxml.jackson.databind.type.TypeFactory;
117 import com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector;
118 import com.sun.jersey.api.client.config.DefaultClientConfig;
119 import com.sun.jersey.client.urlconnection.HTTPSProperties;
122 public class AAIService extends AAIDeclarations implements AAIClient, SvcLogicResource {
124 public static final String AAICLIENT_PROPERTIES = "/aaiclient.properties";
125 public static final String PATH_PROPERTIES = "/aai-path.properties";
127 private static final Logger LOG = LoggerFactory.getLogger(AAIService.class);
129 private final String truststore_path;
130 private final String truststore_password;
131 private final String keystore_path;
132 private final String keystore_password;
133 private final Boolean ignore_certificate_host_error;
135 private final String target_uri;
136 private final String query_path;
138 private final String network_vserver_path;
140 private final String svc_instance_path;
141 private final String svc_inst_qry_path;
143 private final String vnf_image_query_path;
145 private final String param_service_type; //= "service-type";
147 private final String ubb_notify_path;
148 private final String selflink_avpn;
149 private final String selflink_fqdn;
151 private final String p_interface_path;
153 private final String service_path;
154 private final String site_pair_set_path;
156 private final int connection_timeout;
157 private final int read_timeout;
160 private final String query_nodes_path;
161 private final String update_path;
163 private final String application_id;
165 // authentication credentials
166 private String user_name;
167 private String user_password;
170 private final boolean runtimeOSGI;
172 private SSLContext CTX;
174 private final MetricLogger ml = new MetricLogger();
176 private final AAIRequestExecutor executor;
178 public AAIService(URL propURL) {
179 LOG.info("Entered AAIService.ctor");
181 String runtime = System.getProperty("aaiclient.runtime");
182 if("OSGI".equals(runtime)) {
188 Properties props = null;
190 props = initialize(propURL);
191 AAIRequest.setProperties(props, this);
193 } catch(Exception exc){
194 LOG.error("AicAAIResource.static", exc);
197 executor = new AAIRequestExecutor();
199 user_name = props.getProperty(CLIENT_NAME);
200 user_password = props.getProperty(CLIENT_PWWD);
202 if(user_name == null || user_name.isEmpty()){
203 LOG.debug("Basic user name is not set");
205 if(user_password == null || user_password.isEmpty()) {
206 LOG.debug("Basic password is not set");
209 truststore_path = props.getProperty(TRUSTSTORE_PATH);
210 truststore_password = props.getProperty(TRUSTSTORE_PSSWD);
211 keystore_path = props.getProperty(KEYSTORE_PATH);
212 keystore_password = props.getProperty(KEYSTORE_PSSWD);
214 target_uri = props.getProperty(TARGET_URI);
215 query_path = props.getProperty(QUERY_PATH);
216 update_path = props.getProperty(UPDATE_PATH);
218 String applicationId =props.getProperty(APPLICATION_ID);
219 if(applicationId == null || applicationId.isEmpty()) {
220 applicationId = "SDNC";
222 application_id = applicationId;
224 // connection timeout
225 int tmpConnectionTimeout = 30000;
226 int tmpReadTimeout = 30000;
229 String tmpValue = null;
230 tmpValue = props.getProperty(CONNECTION_TIMEOUT, "30000");
231 tmpConnectionTimeout = Integer.parseInt(tmpValue);
232 tmpValue = props.getProperty(READ_TIMEOUT, "30000");
233 tmpReadTimeout = Integer.parseInt(tmpValue);
234 } catch(Exception exc) {
235 LOG.error("Failed setting connection timeout", exc);
236 tmpConnectionTimeout = 30000;
237 tmpReadTimeout = 30000;
239 connection_timeout = tmpConnectionTimeout;
240 read_timeout = tmpReadTimeout;
242 network_vserver_path =props.getProperty(NETWORK_VSERVER_PATH);
244 svc_instance_path = props.getProperty(SVC_INSTANCE_PATH);
245 svc_inst_qry_path = props.getProperty(SVC_INST_QRY_PATH);
246 param_service_type = props.getProperty(PARAM_SERVICE_TYPE, "service-type");
249 p_interface_path = props.getProperty(P_INTERFACE_PATH);
251 vnf_image_query_path = props.getProperty(VNF_IMAGE_QUERY_PATH);
253 ubb_notify_path = props.getProperty(UBB_NOTIFY_PATH);
254 selflink_avpn = props.getProperty(SELFLINK_AVPN);
255 selflink_fqdn = props.getProperty(SELFLINK_FQDN);
257 service_path = props.getProperty(SERVICE_PATH);
259 site_pair_set_path = props.getProperty(SITE_PAIR_SET_PATH);
261 query_nodes_path = props.getProperty(QUERY_NODES_PATH);
263 String iche = props.getProperty(CERTIFICATE_HOST_ERROR);
264 boolean host_error = false;
265 if(iche != null && !iche.isEmpty()) {
266 host_error = Boolean.valueOf(iche);
269 ignore_certificate_host_error = host_error;
271 HttpsURLConnection.setDefaultHostnameVerifier( new HostnameVerifier(){
272 public boolean verify(String string,SSLSession ssls) {
273 return ignore_certificate_host_error;
277 if(truststore_path != null && truststore_password != null && (new File(truststore_path)).exists()) {
278 System.setProperty("javax.net.ssl.trustStore", truststore_path);
279 System.setProperty("javax.net.ssl.trustStorePassword", truststore_password);
282 if(keystore_path != null && keystore_password != null && (new File(keystore_path)).exists()) {
283 DefaultClientConfig config = new DefaultClientConfig();
284 //both jersey and HttpURLConnection can use this
285 SSLContext ctx = null;
287 ctx = SSLContext.getInstance("TLS");
289 KeyManagerFactory kmf = null;
290 try (FileInputStream fin = new FileInputStream(keystore_path)){
291 String def = "SunX509";
292 String storeType = "PKCS12";
293 def = KeyStore.getDefaultType();
294 kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
296 String extension = keystore_path.substring(keystore_path.lastIndexOf(".") + 1);
297 if("JKS".equalsIgnoreCase(extension)) {
300 KeyStore ks = KeyStore.getInstance(storeType);
302 char[] pwd = keystore_password.toCharArray();
305 } catch (Exception ex) {
306 LOG.error("AAIResource", ex);
309 ctx.init(kmf.getKeyManagers(), null, null);
310 config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties( new HostnameVerifier() {
312 public boolean verify( String s, SSLSession sslSession ) {
313 return ignore_certificate_host_error;
318 LOG.debug("SSLContext created");
320 } catch (KeyManagementException | NoSuchAlgorithmException exc) {
321 LOG.error("AAIResource", exc);
325 LOG.info("AAIResource.ctor initialized.");
328 Field methodsField = HttpURLConnection.class.getDeclaredField("methods");
329 methodsField.setAccessible(true);
330 // get the methods field modifiers
331 Field modifiersField = Field.class.getDeclaredField("modifiers");
332 // bypass the "private" modifier
333 modifiersField.setAccessible(true);
335 // remove the "final" modifier
336 modifiersField.setInt(methodsField, methodsField.getModifiers() & ~Modifier.FINAL);
338 /* valid HTTP methods */
340 "GET", "POST", "HEAD", "OPTIONS", "PUT", "DELETE", "TRACE", "PATCH"
342 // set the new methods - including patch
343 methodsField.set(null, methods);
345 } catch (SecurityException | IllegalArgumentException | IllegalAccessException | NoSuchFieldException e) {
351 public void cleanUp() {
357 * @param http_req_url
362 protected HttpURLConnection getConfiguredConnection(URL http_req_url, String method) throws Exception {
363 HttpURLConnection con = (HttpURLConnection) http_req_url.openConnection();
365 // Set up the connection properties
366 con.setRequestProperty( "Connection", "close" );
367 con.setDoInput(true);
368 con.setDoOutput(true);
369 con.setUseCaches(false);
370 con.setConnectTimeout( connection_timeout );
371 con.setReadTimeout( read_timeout );
372 con.setRequestMethod( method );
373 con.setRequestProperty( "Accept", "application/json" );
374 con.setRequestProperty( "Content-Type", "PATCH".equalsIgnoreCase(method) ? "application/merge-patch+json" : "application/json" );
375 con.setRequestProperty("X-FromAppId", application_id);
376 con.setRequestProperty("X-TransactionId",TransactionIdTracker.getNextTransactionId());
377 String mlId = ml.getRequestID();
378 if(mlId != null && !mlId.isEmpty()) {
379 LOG.debug(String.format("MetricLogger requestId = %s", mlId));
380 con.setRequestProperty(MetricLogger.REQUEST_ID, mlId);
382 LOG.debug("MetricLogger requestId is null");
385 if(user_name != null && !user_name.isEmpty() && user_password != null && !user_password.isEmpty()) {
386 String basicAuth = "Basic " + new String(Base64.encodeBase64((user_name + ":" + user_password).getBytes()));
387 con.setRequestProperty ("Authorization", basicAuth);
390 if(con instanceof HttpsURLConnection && CTX != null) {
391 SSLSocketFactory sockFact = CTX.getSocketFactory();
392 HttpsURLConnection.class.cast(con).setSSLSocketFactory( sockFact );
399 public GenericVnf requestGenericVnfData(String vnf_id) throws AAIServiceException {
400 GenericVnf response = null;
403 AAIRequest request = AAIRequest.getRequestFromResource("generic-vnf");
404 request.addRequestProperty("generic-vnf.vnf-id", vnf_id);
405 String rv = executor.get(request);
407 ObjectMapper mapper = getObjectMapper();
408 response = mapper.readValue(rv, GenericVnf.class);
410 } catch(AAIServiceException aaiexc) {
412 } catch (Exception exc) {
413 LOG.warn(Object.class.getClass().getEnclosingMethod().getName(), exc);
414 throw new AAIServiceException(exc);
422 public boolean postGenericVnfData(String vnf_id, GenericVnf data) throws AAIServiceException {
424 AAIRequest request = AAIRequest.getRequestFromResource("generic-vnf");
425 request.addRequestProperty("generic-vnf.vnf-id", vnf_id);
426 request.setRequestObject(data);
427 Object response = executor.post(request);
429 } catch(AAIServiceException aaiexc) {
431 } catch (Exception exc) {
432 LOG.warn("requestGenericVnfData", exc);
433 throw new AAIServiceException(exc);
438 public boolean deleteGenericVnfData(String vnf_id, String resourceVersion) throws AAIServiceException {
439 boolean response = false;
442 AAIRequest request = AAIRequest.getRequestFromResource("generic-vnf");
443 request.addRequestProperty("generic-vnf.vnf-id", vnf_id);
444 response = executor.delete(request, resourceVersion);
445 } catch(AAIServiceException aaiexc) {
447 } catch (Exception exc) {
448 LOG.warn("deleteGenericVnfData", exc);
449 throw new AAIServiceException(exc);
455 * @see org.onap.ccsdk.sli.adaptors.resource.aic.AnAIClient#requestSdnZoneQuery(java.lang.String, java.lang.String, java.lang.String)
458 public Vce requestNetworkVceData(String vnf_id) throws AAIServiceException {
461 AAIRequest request = AAIRequest.getRequestFromResource("vce");
462 request.addRequestProperty("vce.vnf-id", vnf_id);
463 String rv = executor.get(request);
465 ObjectMapper mapper = getObjectMapper();
466 response = mapper.readValue(rv, Vce.class);
468 } catch(AAIServiceException aaiexc) {
470 } catch (Exception exc) {
471 LOG.warn(Object.class.getClass().getEnclosingMethod().getName(), exc);
472 throw new AAIServiceException(exc);
480 * @see org.onap.ccsdk.sli.adaptors.resource.aic.AnAIClient#requestSdnZoneQuery(java.lang.String, java.lang.String, java.lang.String)
483 public boolean deleteNetworkVceData(String vnf_id, String resourceVersion) throws AAIServiceException {
484 boolean response = false;
487 AAIRequest request = AAIRequest.getRequestFromResource("vce");
488 request.addRequestProperty("vce.vnf-id", vnf_id);
489 response = executor.delete(request, resourceVersion);
490 } catch(AAIServiceException aaiexc) {
492 } catch (Exception exc) {
493 LOG.warn("deleteNetworkVceData", exc);
494 throw new AAIServiceException(exc);
500 * @see org.onap.ccsdk.sli.adaptors.resource.aic.AnAIClient#postNetworkVceData(java.lang.String, org.onap.ccsdk.sli.adaptors.resource.aic.aai.VCERequest)
503 public boolean postNetworkVceData(String vnf_id, Vce data) throws AAIServiceException {
505 AAIRequest request = AAIRequest.getRequestFromResource("vce");
506 request.addRequestProperty("vce.vnf-id", vnf_id);
507 request.setRequestObject(data);
508 Object response = executor.post(request);
510 } catch(AAIServiceException aaiexc) {
512 } catch (Exception exc) {
513 LOG.warn("requestGenericVnfData", exc);
514 throw new AAIServiceException(exc);
520 public SearchResults requestServiceInstanceURL(String svc_instance_id) throws AAIServiceException {
521 SearchResults response = null;
522 InputStream inputStream = null;
525 String path = svc_inst_qry_path;
526 path = path.replace("{svc-instance-id}", encodeQuery(svc_instance_id));
528 String request_url = target_uri+path;
529 URL http_req_url = new URL(request_url);
531 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.GET);
533 LOGwriteFirstTrace(HttpMethod.GET, http_req_url.toString());
534 LOGwriteDateTrace("svc_instance_id", svc_instance_id);
537 int responseCode = con.getResponseCode();
538 if (responseCode == HttpURLConnection.HTTP_OK) {
539 inputStream = con.getInputStream();
541 inputStream = con.getErrorStream();
544 // Process the response
545 LOG.debug("HttpURLConnection result:" + responseCode);
546 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
547 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
549 ObjectMapper mapper = getObjectMapper();
551 if (responseCode == HttpURLConnection.HTTP_OK) {
552 response = mapper.readValue(reader, SearchResults.class);
553 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, "SUCCESS", mapper.writeValueAsString(response));
554 } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
555 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
558 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
559 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
560 throw new AAIServiceException(responseCode, errorresponse);
563 } catch(AAIServiceException aaiexc) {
565 } catch (Exception exc) {
566 LOG.warn("requestServiceInstanceURL", exc);
567 throw new AAIServiceException(exc);
569 if(inputStream != null){
572 } catch(Exception exc) {
580 public ServiceInstance requestServiceInterfaceData(String customer_id, String service_type, String svc_instance_id) throws AAIServiceException {
581 ServiceInstance response = null;
584 AAIRequest request = AAIRequest.getRequestFromResource("service-instance");
585 request.addRequestProperty("customer.global-customer-id", customer_id);
586 request.addRequestProperty("service-subscription.service-type", service_type);
587 request.addRequestProperty("service-instance.service-instance-id", svc_instance_id);
589 String rv = executor.get(request);
591 ObjectMapper mapper = getObjectMapper();
592 response = mapper.readValue(rv, ServiceInstance.class);
594 } catch(AAIServiceException aaiexc) {
596 } catch (Exception exc) {
597 LOG.warn("requestServiceInterfaceData", exc);
598 throw new AAIServiceException(exc);
604 public boolean postServiceInterfaceData(String customer_id, String service_type, String svc_instance_id, ServiceInstance data) throws AAIServiceException {
606 AAIRequest request = AAIRequest.getRequestFromResource("service-instance");
607 request.addRequestProperty("customer.global-customer-id", customer_id);
608 request.addRequestProperty("service-subscription.service-type", service_type);
609 request.addRequestProperty("service-instance.service-instance-id", svc_instance_id);
610 request.setRequestObject(data);
611 Object response = executor.post(request);
613 } catch(AAIServiceException aaiexc) {
615 } catch (Exception exc) {
616 LOG.warn("requestGenericVnfData", exc);
617 throw new AAIServiceException(exc);
622 private static Properties initialize(URL url ) throws ConfigurationException {
625 throw new NullPointerException();
628 InputStream is = null;
629 Properties props = new Properties();
632 if(LOG.isDebugEnabled())
633 LOG.info("Property file is: " + url.toString());
635 is = url.openStream();
638 if(LOG.isDebugEnabled()) {
639 LOG.info("Properties loaded: " + props.size());
640 Enumeration<Object> en = props.keys();
642 while(en.hasMoreElements()) {
643 String key = (String)en.nextElement();
644 String property = props.getProperty(key);
645 LOG.debug(key + " : " + property);
648 } catch (Exception e) {
649 throw new ConfigurationException("Could not load properties file.", e);
654 static class TransactionIdTracker {
655 // protected static AtomicLong tracker = new AtomicLong();
657 public static String getNextTransactionId() {
658 // Check if RequestId exists as MDC. If not, create new.
659 String transactionId = MDC.get("RequestId");
660 if ("".equals(transactionId) || transactionId == null) {
661 transactionId = UUID.randomUUID().toString();
662 LOG.info("Missing requestID. Assigned " + transactionId);
663 MDC.put("RequestId", transactionId);
665 return transactionId;
670 protected void LOGwriteFirstTrace(String method, String url) {
671 String time = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").format(System.currentTimeMillis());
672 LOG.info("A&AI transaction :");
673 LOG.info("Request Time : " + time + ", Method : " + method);
674 LOG.info("Request URL : "+ url);
677 protected void LOGwriteDateTrace(String name, String data) {
678 LOG.info("Input - " + name + " : " + data);
681 protected void LOGwriteEndingTrace(int response_code, String comment, String data) {
682 LOG.info("Response code : " + response_code +", " + comment);
683 LOG.info(String.format("Response data : %s", data));
686 protected String encodeQuery(String param) throws UnsupportedEncodingException {
687 return URLEncoder.encode(param, "UTF-8").replace("+", "%20");
690 private String encodeCustomerURL(final String selection)
692 String encrypted_url = selection;
694 "/aai/v11/business/customers/customer/(.+)/service-subscriptions/service-subscription/(.+)/service-instances/service-instance/(.+)/";
695 Pattern pattern = Pattern.compile(apnpattern);
698 URL url = new URL(selection);
699 String path = url.getPath();
701 LOG.info("Trying to match apn to <" + path + ">");
703 Matcher matcher = pattern.matcher(path);
705 while(matcher.find()) {
706 String customer = matcher.group(1);
707 String subscription = matcher.group(2);
708 String service = matcher.group(3);
710 encrypted_url = selection.replace(customer, encodeQuery(customer));
711 encrypted_url = encrypted_url.replace(subscription, encodeQuery(subscription));
712 encrypted_url = encrypted_url.replace(service, encodeQuery(service));
714 } catch (Exception e) {
718 return encrypted_url;
722 public VplsPe requestNetworkVplsPeData(String equipment_name)throws AAIServiceException {
723 VplsPe response = null;
726 AAIRequest request = AAIRequest.getRequestFromResource("vpls-pe");
727 request.addRequestProperty("vpls-pe.equipment-name", equipment_name);
729 String rv = executor.get(request);
731 ObjectMapper mapper = getObjectMapper();
732 response = mapper.readValue(rv, VplsPe.class);
734 } catch(AAIServiceException aaiexc) {
736 } catch (Exception exc) {
737 LOG.warn(Object.class.getClass().getEnclosingMethod().getName(),
739 throw new AAIServiceException(exc);
745 public boolean postNetworkVplsPeData(String equipment_name, VplsPe data) throws AAIServiceException {
747 AAIRequest request = AAIRequest.getRequestFromResource("vpls-pe");
748 request.addRequestProperty("vpls-pe.equipment-name", equipment_name);
749 request.setRequestObject(data);
750 Object response = executor.post(request);
752 } catch(AAIServiceException aaiexc) {
754 } catch (Exception exc) {
755 LOG.warn("requestGenericVnfData", exc);
756 throw new AAIServiceException(exc);
761 public boolean deleteNetworkVplsPeData(String vnf_id, String resourceVersion) throws AAIServiceException {
762 boolean response = false;
765 AAIRequest request = AAIRequest.getRequestFromResource("vpls-pe");
766 request.addRequestProperty("vpls-pe.equipment-name", vnf_id);
767 response = executor.delete(request, resourceVersion);
768 } catch(AAIServiceException aaiexc) {
770 } catch (Exception exc) {
771 LOG.warn("deleteNetworkVplsPeData", exc);
772 throw new AAIServiceException(exc);
778 public Complex requestNetworkComplexData(String pLocId) throws AAIServiceException {
779 Complex response = null;
782 AAIRequest request = AAIRequest.getRequestFromResource("complex");
783 request.addRequestProperty("complex.physical-location-id", pLocId);
785 String rv = executor.get(request);
787 ObjectMapper mapper = getObjectMapper();
788 response = mapper.readValue(rv, Complex.class);
790 } catch(AAIServiceException aaiexc) {
792 } catch (Exception exc) {
793 LOG.warn("requestNetworkComplexData", exc);
794 throw new AAIServiceException(exc);
800 public boolean postNetworkComplexData(String vnf_id, Complex data) throws AAIServiceException {
802 AAIRequest request = AAIRequest.getRequestFromResource("complex");
803 request.addRequestProperty("complex.physical-location-id", vnf_id);
804 request.setRequestObject(data);
805 Object response = executor.post(request);
807 } catch(AAIServiceException aaiexc) {
809 } catch (Exception exc) {
810 LOG.warn("postNetworkComplexData", exc);
811 throw new AAIServiceException(exc);
816 public boolean deleteNetworkComplexData(String pLocId, String resourceVersion) throws AAIServiceException {
817 boolean response = false;
820 AAIRequest request = AAIRequest.getRequestFromResource("complex");
821 request.addRequestProperty("complex.physical-location-id", pLocId);
823 response = executor.delete(request, resourceVersion);
825 } catch(AAIServiceException aaiexc) {
827 } catch (Exception exc) {
828 LOG.warn("deleteNetworkComplexData", exc);
829 throw new AAIServiceException(exc);
836 * @see org.openecomp.sdnct.sli.aai.AAIClient#requestVServersData(java.lang.String, java.lang.String)
839 public Vserver requestVServerData(String tenantId, String vserverId, String cloudOwner, String cloudRegionId) throws AAIServiceException {
840 Vserver response = null;
843 AAIRequest request = AAIRequest.getRequestFromResource("vserver");
844 request.addRequestProperty("cloud-region.cloud-owner", cloudOwner);
845 request.addRequestProperty("cloud-region.cloud-region-id", cloudRegionId);
846 request.addRequestProperty("tenant.tenant-id", tenantId);
847 request.addRequestProperty("vserver.vserver-id", vserverId);
849 String rv = executor.get(request);
851 ObjectMapper mapper = getObjectMapper();
852 response = mapper.readValue(rv, Vserver.class);
854 } catch(AAIServiceException aaiexc) {
856 } catch (Exception exc) {
857 LOG.warn(Object.class.getClass().getEnclosingMethod().getName(), exc);
858 throw new AAIServiceException(exc);
865 public boolean postVServerData(String tenantId, String vserverId, String cloudOwner, String cloudRegionId, Vserver data) throws AAIServiceException {
867 AAIRequest request = AAIRequest.getRequestFromResource("vserver");
868 request.addRequestProperty("cloud-region.cloud-owner", cloudOwner);
869 request.addRequestProperty("cloud-region.cloud-region-id", cloudRegionId);
870 request.addRequestProperty("tenant.tenant-id", tenantId);
871 request.addRequestProperty("vserver.vserver-id", vserverId);
872 request.setRequestObject(data);
873 Object response = executor.post(request);
875 } catch(AAIServiceException aaiexc) {
877 } catch (Exception exc) {
878 LOG.warn("postNetworkComplexData", exc);
879 throw new AAIServiceException(exc);
884 public boolean deleteVServerData(String tenant_id, String vserver_id, String cloudOwner, String cloudRegionId, String resourceVersion) throws AAIServiceException {
885 boolean response = false;
886 InputStream inputStream = null;
889 String local_network_complexes_path = network_vserver_path.replace("{tenant-id}", encodeQuery(tenant_id));
890 local_network_complexes_path = local_network_complexes_path.replace("{vserver-id}", encodeQuery(vserver_id));
891 local_network_complexes_path = local_network_complexes_path.replace("{cloud-owner}", encodeQuery(cloudOwner));
892 local_network_complexes_path = local_network_complexes_path.replace("{cloud-region-id}", encodeQuery(cloudRegionId));
894 String request_url = target_uri+local_network_complexes_path;
895 if(resourceVersion!=null) {
896 request_url = request_url +"?resource-version="+resourceVersion;
898 URL http_req_url = new URL(request_url);
900 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.DELETE);
902 LOGwriteFirstTrace(HttpMethod.DELETE, http_req_url.toString());
903 LOGwriteDateTrace("tenant_id", tenant_id);
904 LOGwriteDateTrace("vserver_id", vserver_id);
905 LOGwriteDateTrace("cloud-owner", cloudOwner);
906 LOGwriteDateTrace("cloud-region-id", cloudRegionId);
909 int responseCode = con.getResponseCode();
910 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
911 inputStream = con.getInputStream();
913 inputStream = con.getErrorStream();
916 // Process the response
917 LOG.debug("HttpURLConnection result:" + responseCode);
918 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
919 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
922 ObjectMapper mapper = getObjectMapper();
924 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
925 StringBuilder stringBuilder = new StringBuilder();
927 while( ( line = reader.readLine() ) != null ) {
928 stringBuilder.append( line );
930 LOGwriteEndingTrace(responseCode, "SUCCESS", stringBuilder.toString());
932 } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
933 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
936 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
937 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
938 throw new AAIServiceException(responseCode, errorresponse);
941 } catch(AAIServiceException aaiexc) {
943 } catch (Exception exc) {
944 LOG.warn("deleteVServerData", exc);
945 throw new AAIServiceException(exc);
947 if(inputStream != null){
950 } catch(Exception exc) {
961 * @see org.onap.ccsdk.sli.adaptors.aai.AAIClient#requestCtagPoolData(String)
964 public CtagPool requestCtagPoolData(String physical_location_id, String target_pe, String availability_zone_name) throws AAIServiceException {
965 CtagPool response = null;
968 AAIRequest request = AAIRequest.getRequestFromResource("ctag-pool");
970 request.addRequestProperty("ctag-pool.target-pe", target_pe);
971 request.addRequestProperty("ctag-pool.availability-zone-name", availability_zone_name);
972 request.addRequestProperty("complex.physical-location-id", physical_location_id);
974 String rv = executor.get(request);
976 ObjectMapper mapper = getObjectMapper();
977 response = mapper.readValue(rv, CtagPool.class);
979 } catch(AAIServiceException aaiexc) {
981 } catch (Exception exc) {
982 LOG.warn("requestNetworkVceData", exc);
983 throw new AAIServiceException(exc);
988 //==================== DvsSwitch ======================
990 public DvsSwitch requestDvsSwitchData(String vnf_id) throws AAIServiceException {
991 DvsSwitch response = null;
994 AAIRequest request = AAIRequest.getRequestFromResource("dvs-switch");
995 request.addRequestProperty("dvs-switch.switch-name", vnf_id);
997 String rv = executor.get(request);
999 ObjectMapper mapper = getObjectMapper();
1000 response = mapper.readValue(rv, DvsSwitch.class);
1002 } catch(AAIServiceException aaiexc) {
1004 } catch (Exception exc) {
1005 LOG.warn("requestDvsSwitchData", exc);
1006 throw new AAIServiceException(exc);
1012 public boolean postDvsSwitchData(String switch_name, DvsSwitch data) throws AAIServiceException {
1014 AAIRequest request = AAIRequest.getRequestFromResource("dvs-switch");
1015 request.addRequestProperty("dvs-switch.switch-name", switch_name);
1016 request.setRequestObject(data);
1017 Object response = executor.post(request);
1019 } catch(AAIServiceException aaiexc) {
1021 } catch (Exception exc) {
1022 LOG.warn(Object.class.getClass().getEnclosingMethod().getName(), exc);
1023 throw new AAIServiceException(exc);
1028 public boolean deleteDvsSwitchData(String vnf_id, String resourceVersion) throws AAIServiceException {
1029 boolean response = false;
1032 AAIRequest request = AAIRequest.getRequestFromResource("dvs-switch");
1033 request.addRequestProperty("dvs-switch.switch-name", vnf_id);
1034 response = executor.delete(request, resourceVersion);
1035 } catch(AAIServiceException aaiexc) {
1037 } catch (Exception exc) {
1038 LOG.warn("deleteDvsSwitchData", exc);
1039 throw new AAIServiceException(exc);
1043 //================== End of DvsSwitch =================
1044 //==================== PhysicalLink ======================
1046 public PhysicalLink requestPhysicalLinkData(String linkName) throws AAIServiceException {
1047 PhysicalLink response = null;
1050 AAIRequest request = AAIRequest.getRequestFromResource("physical-link");
1051 request.addRequestProperty("physical-link.link-name", linkName);
1053 String rv = executor.get(request);
1055 ObjectMapper mapper = getObjectMapper();
1056 response = mapper.readValue(rv, PhysicalLink.class);
1058 } catch(AAIServiceException aaiexc) {
1060 } catch (Exception exc) {
1061 LOG.warn("requestPhysicalLinkData", exc);
1062 throw new AAIServiceException(exc);
1068 public boolean postPhysicalLinkData(String linkName, PhysicalLink data) throws AAIServiceException {
1070 AAIRequest request = AAIRequest.getRequestFromResource("physical-link");
1071 request.addRequestProperty("physical-link.link-name", linkName);
1072 request.setRequestObject(data);
1073 Object response = executor.post(request);
1075 } catch(AAIServiceException aaiexc) {
1077 } catch (Exception exc) {
1078 LOG.warn(Object.class.getClass().getEnclosingMethod().getName(), exc);
1079 throw new AAIServiceException(exc);
1084 public boolean deletePhysicalLinkData(String linkName, String resourceVersion) throws AAIServiceException {
1085 boolean response = false;
1088 AAIRequest request = AAIRequest.getRequestFromResource("physical-link");
1089 request.addRequestProperty("physical-link.link-name", linkName);
1090 response = executor.delete(request, resourceVersion);
1091 } catch(AAIServiceException aaiexc) {
1093 } catch (Exception exc) {
1094 LOG.warn("deletePhysicalLinkData", exc);
1095 throw new AAIServiceException(exc);
1099 //================== End of PhysicalLink =================
1100 //==================== PInterface ======================
1102 public PInterface requestPInterfaceData(String hostname, String interfaceName) throws AAIServiceException {
1103 PInterface response = null;
1106 AAIRequest request = AAIRequest.getRequestFromResource("p-interface");
1107 request.addRequestProperty("p-interface.interface-name", interfaceName);
1108 request.addRequestProperty("pserver.hostname", hostname);
1109 String rv = executor.get(request);
1111 ObjectMapper mapper = getObjectMapper();
1112 response = mapper.readValue(rv, PInterface.class);
1114 } catch(AAIServiceException aaiexc) {
1116 } catch (Exception exc) {
1117 LOG.warn(Object.class.getClass().getEnclosingMethod().getName(), exc);
1118 throw new AAIServiceException(exc);
1124 public boolean postPInterfaceData(String hostname, String interfaceName, PInterface request) throws AAIServiceException {
1125 InputStream inputStream = null;
1129 ObjectMapper mapper = getObjectMapper();
1130 String json_text = mapper.writeValueAsString(request);
1132 SSLSocketFactory sockFact = CTX.getSocketFactory();
1134 String request_url = target_uri+p_interface_path;
1135 String encoded_vnf = encodeQuery(hostname);
1136 request_url = request_url.replace("{hostname}", encoded_vnf) ;
1137 encoded_vnf = encodeQuery(interfaceName);
1138 request_url = request_url.replace("{interface-name}", encoded_vnf) ;
1139 URL http_req_url = new URL(request_url);
1141 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.PUT);
1143 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
1144 osw.write(json_text);
1149 LOGwriteFirstTrace("PUT", request_url);
1150 LOGwriteDateTrace("hostname", hostname);
1151 LOGwriteDateTrace("interface-name", interfaceName);
1152 LOGwriteDateTrace("PInterface", json_text);
1155 int responseCode = con.getResponseCode();
1156 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1157 inputStream = con.getInputStream();
1159 inputStream = con.getErrorStream();
1162 // Process the response
1163 BufferedReader reader;
1165 reader = new BufferedReader( new InputStreamReader( inputStream ) );
1167 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1168 StringBuilder stringBuilder = new StringBuilder();
1170 while( ( line = reader.readLine() ) != null ) {
1171 stringBuilder.append( line );
1173 LOGwriteEndingTrace(responseCode, "SUCCESS", (stringBuilder.length() > 0) ? stringBuilder.toString() : "{no-data}");
1176 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
1177 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
1179 throw new AAIServiceException(responseCode, errorresponse);
1181 } catch(AAIServiceException aaiexc) {
1183 } catch (Exception exc) {
1184 LOG.warn("postPInterfaceData", exc);
1185 throw new AAIServiceException(exc);
1188 if(inputStream != null)
1189 inputStream.close();
1190 } catch (Exception exc) {
1197 public boolean deletePInterfaceData(String hostname, String interfaceName, String resourceVersion) throws AAIServiceException {
1198 boolean response = false;
1201 AAIRequest request = AAIRequest.getRequestFromResource("p-interface");
1202 request.addRequestProperty("p-interface.interface-name", interfaceName);
1203 request.addRequestProperty("pserver.hostname", hostname);
1204 response = executor.delete(request, resourceVersion);
1205 } catch(AAIServiceException aaiexc) {
1207 } catch (Exception exc) {
1208 LOG.warn("deletePInterfaceData", exc);
1209 throw new AAIServiceException(exc);
1213 //================== End of PInterface =================
1214 //==================== SitePairSet ======================
1216 public SitePairSet requestSitePairSetData(String sitePairSetId) throws AAIServiceException {
1217 SitePairSet response = null;
1220 AAIRequest request = AAIRequest.getRequestFromResource("site-pair-set");
1221 request.addRequestProperty("site-pair-set.site-pair-set-id", sitePairSetId);
1222 String rv = executor.get(request);
1224 ObjectMapper mapper = getObjectMapper();
1225 response = mapper.readValue(rv, SitePairSet.class);
1227 } catch(AAIServiceException aaiexc) {
1229 } catch (Exception exc) {
1230 LOG.warn(Object.class.getClass().getEnclosingMethod().getName(), exc);
1231 throw new AAIServiceException(exc);
1237 public boolean postSitePairSetData(String linkName, SitePairSet request) throws AAIServiceException {
1238 InputStream inputStream = null;
1242 ObjectMapper mapper = getObjectMapper();
1243 String json_text = mapper.writeValueAsString(request);
1245 SSLSocketFactory sockFact = CTX.getSocketFactory();
1247 String request_url = target_uri+site_pair_set_path;
1248 String encoded_vnf = encodeQuery(linkName);
1249 request_url = request_url.replace("{site-pair-set-id}", encoded_vnf) ;
1250 URL http_req_url = new URL(request_url);
1252 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.PUT);
1254 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
1255 osw.write(json_text);
1260 LOGwriteFirstTrace("PUT", request_url);
1261 LOGwriteDateTrace("link-name", linkName);
1262 LOGwriteDateTrace("SitePairSet", json_text);
1265 int responseCode = con.getResponseCode();
1266 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1267 inputStream = con.getInputStream();
1269 inputStream = con.getErrorStream();
1272 // Process the response
1273 BufferedReader reader;
1275 reader = new BufferedReader( new InputStreamReader( inputStream ) );
1277 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1278 StringBuilder stringBuilder = new StringBuilder();
1280 while( ( line = reader.readLine() ) != null ) {
1281 stringBuilder.append( line );
1283 LOGwriteEndingTrace(responseCode, "SUCCESS", (stringBuilder.length() > 0) ? stringBuilder.toString() : "{no-data}");
1286 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
1287 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
1289 throw new AAIServiceException(responseCode, errorresponse);
1291 } catch(AAIServiceException aaiexc) {
1293 } catch (Exception exc) {
1294 LOG.warn("postSitePairSetData", exc);
1295 throw new AAIServiceException(exc);
1298 if(inputStream != null)
1299 inputStream.close();
1300 } catch (Exception exc) {
1307 public boolean deleteSitePairSetData(String linkName, String resourceVersion) throws AAIServiceException {
1308 boolean response = false;
1311 AAIRequest request = AAIRequest.getRequestFromResource("site-pair-set");
1312 request.addRequestProperty("site-pair-set.site-pair-set-id", linkName);
1313 response = executor.delete(request, resourceVersion);
1314 } catch(AAIServiceException aaiexc) {
1316 } catch (Exception exc) {
1317 LOG.warn("deleteSitePairSetData", exc);
1318 throw new AAIServiceException(exc);
1323 //================== End of SitePairSet =================
1324 //==================== Service ======================
1326 public Service requestServiceData(String serviceId) throws AAIServiceException {
1327 Service response = null;
1330 AAIRequest request = AAIRequest.getRequestFromResource("service");
1331 request.addRequestProperty("service.service-id", serviceId);
1334 String rv = executor.get(request);
1336 ObjectMapper mapper = getObjectMapper();
1337 response = mapper.readValue(rv, Service.class);
1339 } catch(AAIServiceException aaiexc) {
1341 } catch (Exception exc) {
1342 LOG.warn("requestServiceData", exc);
1343 throw new AAIServiceException(exc);
1349 public boolean postServiceData(String linkName, Service request) throws AAIServiceException {
1350 InputStream inputStream = null;
1354 ObjectMapper mapper = getObjectMapper();
1355 String json_text = mapper.writeValueAsString(request);
1357 SSLSocketFactory sockFact = CTX.getSocketFactory();
1359 String request_url = target_uri+service_path;
1360 String encoded_vnf = encodeQuery(linkName);
1361 request_url = request_url.replace("{service-id}", encoded_vnf) ;
1362 URL http_req_url = new URL(request_url);
1364 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.PUT);
1366 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
1367 osw.write(json_text);
1372 LOGwriteFirstTrace("PUT", request_url);
1373 LOGwriteDateTrace("service-id", linkName);
1374 LOGwriteDateTrace("Service", json_text);
1377 int responseCode = con.getResponseCode();
1378 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1379 inputStream = con.getInputStream();
1381 inputStream = con.getErrorStream();
1384 // Process the response
1385 BufferedReader reader;
1387 reader = new BufferedReader( new InputStreamReader( inputStream ) );
1389 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1390 StringBuilder stringBuilder = new StringBuilder();
1392 while( ( line = reader.readLine() ) != null ) {
1393 stringBuilder.append( line );
1395 LOGwriteEndingTrace(responseCode, "SUCCESS", (stringBuilder.length() > 0) ? stringBuilder.toString() : "{no-data}");
1398 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
1399 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
1401 throw new AAIServiceException(responseCode, errorresponse);
1403 } catch(AAIServiceException aaiexc) {
1405 } catch (Exception exc) {
1406 LOG.warn("postServiceData", exc);
1407 throw new AAIServiceException(exc);
1410 if(inputStream != null)
1411 inputStream.close();
1412 } catch (Exception exc) {
1419 public boolean deleteServiceData(String service_id, String resourceVersion) throws AAIServiceException {
1420 boolean response = false;
1423 AAIRequest request = AAIRequest.getRequestFromResource("service");
1424 request.addRequestProperty("service.service-id", service_id);
1425 response = executor.delete(request, resourceVersion);
1426 } catch(AAIServiceException aaiexc) {
1428 } catch (Exception exc) {
1429 LOG.warn("deleteServiceData", exc);
1430 throw new AAIServiceException(exc);
1435 //================== End of Service =================
1439 public Vserver dataChangeRequestVServerData(URL url) throws AAIServiceException {
1442 throw new NullPointerException();
1445 return this.getResource(url.toString(), Vserver.class);
1449 public Pserver dataChangeRequestPServerData(URL url) throws AAIServiceException {
1452 throw new NullPointerException();
1455 return this.getResource(url.toString(), Pserver.class);
1459 public CtagPool dataChangeRequestCtagPoolData(URL url) throws AAIServiceException {
1462 throw new NullPointerException();
1465 return this.getResource(url.toString(), CtagPool.class);
1469 public VplsPe dataChangeRequestVplsPeData(URL url) throws AAIServiceException {
1472 throw new NullPointerException();
1475 return this.getResource(url.toString(), VplsPe.class);
1479 public DvsSwitch dataChangeRequestDvsSwitchData(URL url) throws AAIServiceException {
1482 throw new NullPointerException();
1485 return this.getResource(url.toString(), DvsSwitch.class);
1489 public OamNetwork dataChangeRequestOAMNetworkData(URL url) throws AAIServiceException {
1492 throw new NullPointerException();
1495 return this.getResource(url.toString(), OamNetwork.class);
1499 public AvailabilityZone dataChangeRequestAvailabilityZoneData(URL url) throws AAIServiceException {
1502 throw new NullPointerException();
1505 return this.getResource(url.toString(), AvailabilityZone.class);
1509 public Complex dataChangeRequestComplexData(URL url) throws AAIServiceException {
1512 throw new NullPointerException();
1515 return this.getResource(url.toString(), Complex.class);
1520 public boolean dataChangeDeleteVServerData(URL url) throws AAIServiceException {
1523 throw new NullPointerException();
1526 return deleteAAIEntity(url, Object.class.getClass().getEnclosingMethod()
1531 public boolean dataChangeDeleteCtagPoolData(URL url) throws AAIServiceException {
1534 throw new NullPointerException();
1537 return deleteAAIEntity(url, Object.class.getClass().getEnclosingMethod()
1542 public boolean dataChangeDeleteVplsPeData(URL url) throws AAIServiceException {
1545 throw new NullPointerException();
1548 return deleteAAIEntity(url, Object.class.getClass().getEnclosingMethod()
1553 public boolean dataChangeDeleteVpeData(URL url) throws AAIServiceException {
1556 throw new NullPointerException();
1559 return deleteAAIEntity(url, Object.class.getClass().getEnclosingMethod()
1564 public boolean dataChangeDeleteDvsSwitchData(URL url) throws AAIServiceException {
1567 throw new NullPointerException();
1570 return deleteAAIEntity(url, Object.class.getClass().getEnclosingMethod()
1575 public boolean dataChangeDeleteOAMNetworkData(URL url) throws AAIServiceException {
1578 throw new NullPointerException();
1581 return deleteAAIEntity(url, Object.class.getClass().getEnclosingMethod()
1584 //Availability-Zone:
1586 public boolean dataChangeDeleteAvailabilityZoneData(URL url) throws AAIServiceException {
1589 throw new NullPointerException();
1592 return deleteAAIEntity(url, Object.class.getClass().getEnclosingMethod()
1597 public boolean dataChangeDeleteComplexData(URL url) throws AAIServiceException {
1600 throw new NullPointerException();
1603 return deleteAAIEntity(url, Object.class.getClass().getEnclosingMethod()
1607 private boolean deleteAAIEntity(URL url, String caller) throws AAIServiceException {
1610 throw new NullPointerException();
1613 boolean response = false;
1614 InputStream inputStream = null;
1617 URL http_req_url = url;
1619 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.DELETE);
1621 LOGwriteFirstTrace("DELETE", http_req_url.toString());
1625 int responseCode = con.getResponseCode();
1626 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1627 inputStream = con.getInputStream();
1629 inputStream = con.getErrorStream();
1632 // Process the response
1633 LOG.debug("HttpURLConnection result:" + responseCode);
1634 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
1635 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
1638 ObjectMapper mapper = getObjectMapper();
1640 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1641 StringBuilder stringBuilder = new StringBuilder();
1643 while( ( line = reader.readLine() ) != null ) {
1644 stringBuilder.append( line );
1646 LOGwriteEndingTrace(responseCode, "SUCCESS", stringBuilder.toString());
1648 } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
1649 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
1652 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
1653 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
1654 throw new AAIServiceException(responseCode, errorresponse);
1657 } catch(AAIServiceException aaiexc) {
1659 } catch (Exception exc) {
1660 LOG.warn(caller, exc);
1661 throw new AAIServiceException(exc);
1663 if(inputStream != null){
1665 inputStream.close();
1666 } catch(Exception exc) {
1675 * Generic method to GET json data from an A&AI callback URL.
1676 * Then convert that json to an Object.
1677 * If successful the Object is attempted to be cast to the type parameter.
1680 * callback url for A&AI
1682 * the class of object that A&AI will return
1683 * @return the object created from json or null if the response code is not 200
1685 * @throws AAIServiceException
1686 * if empty or null key and or type or there's an error with processing
1688 public <T> T dataChangeRequestAaiData(String key, Class<T> type) throws AAIServiceException {
1689 if (StringUtils.isEmpty(key) || type == null) {
1690 throw new AAIServiceException("Key is empty or null and or type is null");
1695 SvcLogicContext ctx = new SvcLogicContext();
1696 if(!key.contains(" = ") && isValidURL(key)) {
1697 key = String.format("selflink = '%s'", key);
1699 if(!key.contains(" = ") && isValidURI(key)) {
1700 key = String.format("resource-path = '%s'", key);
1703 HashMap<String, String> nameValues = AAIServiceUtils.keyToHashMap(key, ctx);
1705 SelfLinkRequest request = new SelfLinkRequest(type);
1706 request.processRequestPathValues(nameValues);
1707 Object obj = this.getExecutor().query(request, type);
1708 response = type.cast(obj);
1710 return response != null ? type.cast(response) : response;
1714 public Pserver requestPServerData(String hostname) throws AAIServiceException {
1715 Pserver response = null;
1718 AAIRequest request = AAIRequest.getRequestFromResource("pserver");
1719 request.addRequestProperty("pserver.hostname", hostname);
1722 String rv = executor.get(request);
1724 ObjectMapper mapper = getObjectMapper();
1725 response = mapper.readValue(rv, Pserver.class);
1727 } catch(AAIServiceException aaiexc) {
1729 } catch (Exception exc) {
1730 LOG.warn("requestPServerData", exc);
1731 throw new AAIServiceException(exc);
1737 public boolean postPServerData(String hostname, Pserver data) throws AAIServiceException {
1739 AAIRequest request = AAIRequest.getRequestFromResource("pserver");
1740 request.addRequestProperty("pserver.hostname", hostname);
1741 request.setRequestObject(data);
1742 Object response = executor.post(request);
1744 } catch(AAIServiceException aaiexc) {
1746 } catch (Exception exc) {
1747 LOG.warn(Object.class.getClass().getEnclosingMethod().getName(), exc);
1748 throw new AAIServiceException(exc);
1753 public boolean deletePServerData(String hostname, String resourceVersion) throws AAIServiceException {
1754 boolean response = false;
1757 AAIRequest request = AAIRequest.getRequestFromResource("pserver");
1758 request.addRequestProperty("pserver.hostname", hostname);
1759 response = executor.delete(request, resourceVersion);
1760 } catch(AAIServiceException aaiexc) {
1762 } catch (Exception exc) {
1763 LOG.warn("deletePServerData", exc);
1764 throw new AAIServiceException(exc);
1772 public L3Network requestL3NetworkData(String networkId) throws AAIServiceException {
1773 L3Network response = null;
1776 AAIRequest request = AAIRequest.getRequestFromResource("l3-network");
1777 request.addRequestProperty("l3-network.network-id", networkId);
1779 String rv = executor.get(request);
1781 ObjectMapper mapper = getObjectMapper();
1782 response = mapper.readValue(rv, L3Network.class);
1784 } catch(AAIServiceException aaiexc) {
1786 } catch (Exception exc) {
1787 LOG.warn("requestL3NetworkData", exc);
1788 throw new AAIServiceException(exc);
1794 public L3Network requestL3NetworkQueryByName(String networkName) throws AAIServiceException {
1795 L3Network response = null;
1798 AAIRequest request = AAIRequest.getRequestFromResource("l3-network");
1799 request.addRequestProperty("l3-network.network-name", networkName);
1801 String rv = executor.get(request);
1803 ObjectMapper mapper = getObjectMapper();
1804 response = mapper.readValue(rv, L3Network.class);
1807 } catch(AAIServiceException aaiexc) {
1809 } catch (Exception exc) {
1810 LOG.warn("requestL3NetworkQueryByName", exc);
1811 throw new AAIServiceException(exc);
1817 public boolean postL3NetworkData(String networkId, L3Network data) throws AAIServiceException {
1819 AAIRequest request = AAIRequest.getRequestFromResource("l3-network");
1820 request.addRequestProperty("l3-network.network-id", networkId);
1821 request.setRequestObject(data);
1822 Object response = executor.post(request);
1824 } catch(AAIServiceException aaiexc) {
1826 } catch (Exception exc) {
1827 LOG.warn(Object.class.getClass().getEnclosingMethod().getName(), exc);
1828 throw new AAIServiceException(exc);
1833 public boolean deleteL3NetworkData(String networkId, String resourceVersion) throws AAIServiceException {
1834 boolean response = false;
1837 AAIRequest request = AAIRequest.getRequestFromResource("l3-network");
1838 request.addRequestProperty("l3-network.network-id", networkId);
1839 response = executor.delete(request, resourceVersion);
1840 } catch(AAIServiceException aaiexc) {
1842 } catch (Exception exc) {
1843 LOG.warn("deleteL3NetworkData", exc);
1844 throw new AAIServiceException(exc);
1852 public VpnBinding requestVpnBindingData(String vpnId) throws AAIServiceException {
1853 VpnBinding response = null;
1856 AAIRequest request = AAIRequest.getRequestFromResource("vpn-binding");
1857 request.addRequestProperty("vpn-binding.vpn-id", vpnId);
1859 String rv = executor.get(request);
1861 ObjectMapper mapper = getObjectMapper();
1862 response = mapper.readValue(rv, VpnBinding.class);
1864 } catch(AAIServiceException aaiexc) {
1866 } catch (Exception exc) {
1867 LOG.warn("requestVpnBindingData", exc);
1868 throw new AAIServiceException(exc);
1874 public boolean deleteVpnBindingData(String vpnId, String resourceVersion) throws AAIServiceException {
1875 boolean response = false;
1878 AAIRequest request = AAIRequest.getRequestFromResource("vpn-binding");
1879 request.addRequestProperty("vpn-binding.vpn-id", vpnId);
1880 response = executor.delete(request, resourceVersion);
1881 } catch(AAIServiceException aaiexc) {
1883 } catch (Exception exc) {
1884 LOG.warn("deleteVpnBindingData", exc);
1885 throw new AAIServiceException(exc);
1892 public VnfImage requestVnfImageData(String vnf_image_uuid) throws AAIServiceException {
1893 VnfImage response = null;
1896 AAIRequest request = AAIRequest.getRequestFromResource("vnf-image");
1897 request.addRequestProperty("vnf-image.vnf-image-uuid", vnf_image_uuid);
1899 String rv = executor.get(request);
1901 ObjectMapper mapper = getObjectMapper();
1902 response = mapper.readValue(rv, VnfImage.class);
1904 } catch(AAIServiceException aaiexc) {
1906 } catch (Exception exc) {
1907 LOG.warn("requestVnfImageData", exc);
1908 throw new AAIServiceException(exc);
1914 public VnfImage requestVnfImageDataByVendorModel(String vendor, String model) throws AAIServiceException {
1915 return requestVnfImageDataByVendorModelVersion(vendor, model, null);
1919 public VnfImage requestVnfImageDataByVendorModelVersion(String vendor, String model, String version) throws AAIServiceException
1921 List<VnfImage> responseList = new ArrayList<VnfImage>();
1922 VnfImage response = null;
1923 InputStream inputStream = null;
1926 String request_url = target_uri+vnf_image_query_path + (version==null? "": "&application-version={application_version}");
1927 request_url = request_url.replace("{application_vendor}", encodeQuery(vendor)) ;
1928 request_url = request_url.replace("{application_model}", encodeQuery(model)) ;
1929 if(version != null) {
1930 request_url = request_url.replace("{application_version}", encodeQuery(version)) ;
1932 URL http_req_url = new URL(request_url);
1934 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.GET);
1936 LOGwriteFirstTrace(HttpMethod.GET, http_req_url.toString());
1937 LOGwriteDateTrace("application_vendor", vendor);
1938 LOGwriteDateTrace("application_model", model);
1939 if(version != null) {
1940 LOGwriteDateTrace("application_version", version);
1944 int responseCode = con.getResponseCode();
1945 if (responseCode == HttpURLConnection.HTTP_OK) {
1946 inputStream = con.getInputStream();
1948 inputStream = con.getErrorStream();
1951 // Process the response
1952 LOG.debug("HttpURLConnection result:" + responseCode);
1953 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
1954 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
1956 ObjectMapper mapper = getObjectMapper();
1958 if (responseCode == HttpURLConnection.HTTP_OK) {
1959 response = mapper.readValue(reader, VnfImage.class);
1960 String original_buffer = mapper.writeValueAsString(response);
1961 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, "SUCCESS", original_buffer);
1962 if(response.getApplicationVendor() == null /*&& response.getAdditionalProperties() != null && !response.getAdditionalProperties().isEmpty()*/){
1963 LOG.warn("A List of multiple VNF-IMAGE entries has been returned");
1964 VnfImages listOfObjects = mapper.readValue(original_buffer, VnfImages.class);
1965 if(!listOfObjects.getVnfImage().isEmpty()) {
1966 response = listOfObjects.getVnfImage().get(0);
1969 } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
1970 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
1973 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
1974 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
1975 throw new AAIServiceException(responseCode, errorresponse);
1978 } catch(AAIServiceException aaiexc) {
1980 } catch (Exception exc) {
1981 LOG.warn("requestVnfImageData", exc);
1982 throw new AAIServiceException(exc);
1984 if(inputStream != null){
1986 inputStream.close();
1987 } catch(Exception exc) {
1996 public boolean sendNotify(NotifyEvent event, String serviceInstanceId, String pathCode) throws AAIServiceException {
1997 InputStream inputStream = null;
2001 String selfLink = selflink_fqdn;
2002 if(SELFLINK_AVPN != null && SELFLINK_AVPN.equals(pathCode)) {
2003 selfLink = selflink_avpn;
2005 selfLink = selfLink.replace("{service-instance-id}", encodeQuery(serviceInstanceId));
2006 event.setSelflink(selfLink);
2008 ObjectMapper mapper = getObjectMapper();
2009 String json_text = mapper.writeValueAsString(event);
2011 SSLSocketFactory sockFact = CTX.getSocketFactory();
2013 String request_url = target_uri+ubb_notify_path;
2014 URL http_req_url = new URL(request_url);
2016 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.PUT);
2018 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
2019 osw.write(json_text);
2024 LOGwriteFirstTrace("PUT", request_url);
2025 LOGwriteDateTrace("NotifyEvent", json_text);
2028 int responseCode = con.getResponseCode();
2029 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2030 inputStream = con.getInputStream();
2032 inputStream = con.getErrorStream();
2035 // Process the response
2036 BufferedReader reader;
2038 reader = new BufferedReader( new InputStreamReader( inputStream ) );
2040 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2041 StringBuilder stringBuilder = new StringBuilder();
2043 while( ( line = reader.readLine() ) != null ) {
2044 stringBuilder.append( line );
2046 LOGwriteEndingTrace(responseCode, "SUCCESS", (stringBuilder.length() > 0) ? stringBuilder.toString() :
2050 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2051 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
2053 throw new AAIServiceException(responseCode, errorresponse);
2055 } catch(AAIServiceException aaiexc) {
2057 } catch (Exception exc) {
2058 LOG.warn("sendNotify", exc);
2059 throw new AAIServiceException(exc);
2062 if(inputStream != null)
2063 inputStream.close();
2064 } catch (Exception exc) {
2071 public SearchResults requestNodeQuery(String node_type, String entityIdentifier, String entityName) throws AAIServiceException {
2072 SearchResults response = null;
2073 InputStream inputStream = null;
2076 String request_url = target_uri+query_nodes_path;
2077 request_url = request_url.replace("{node-type}", encodeQuery(node_type)) ;
2078 request_url = request_url.replace("{entity-identifier}", entityIdentifier) ;
2079 request_url = request_url.replace("{entity-name}", encodeQuery(entityName)) ;
2080 URL http_req_url = new URL(request_url);
2082 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.GET);
2084 LOGwriteFirstTrace(HttpMethod.GET, http_req_url.toString());
2085 LOGwriteDateTrace("node_type", node_type);
2086 LOGwriteDateTrace("vnf_name", entityName);
2089 int responseCode = con.getResponseCode();
2090 if (responseCode == HttpURLConnection.HTTP_OK) {
2091 inputStream = con.getInputStream();
2093 inputStream = con.getErrorStream();
2096 // Process the response
2097 LOG.debug("HttpURLConnection result:" + responseCode);
2098 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
2099 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2101 ObjectMapper mapper = getObjectMapper();
2103 if (responseCode == HttpURLConnection.HTTP_OK) {
2104 response = mapper.readValue(reader, SearchResults.class);
2105 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, "SUCCESS", mapper.writeValueAsString(response));
2106 } else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
2107 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
2110 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2111 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
2112 throw new AAIServiceException(responseCode, errorresponse);
2115 } catch(AAIServiceException aaiexc) {
2117 } catch (Exception exc) {
2118 LOG.warn("requestNodeQuery", exc);
2119 throw new AAIServiceException(exc);
2121 if(inputStream != null){
2123 inputStream.close();
2124 } catch(Exception exc) {
2135 public String requestDataByURL(URL url) throws AAIServiceException {
2138 throw new NullPointerException();
2141 String response = null;
2142 InputStream inputStream = null;
2145 URL http_req_url = url;
2147 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.GET);
2149 LOGwriteFirstTrace(HttpMethod.GET, http_req_url.toString());
2152 int responseCode = con.getResponseCode();
2153 if (responseCode == HttpURLConnection.HTTP_OK) {
2154 inputStream = con.getInputStream();
2156 inputStream = con.getErrorStream();
2159 // Process the response
2160 LOG.debug("HttpURLConnection result:" + responseCode);
2161 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
2162 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2164 ObjectMapper mapper = getObjectMapper();
2166 if (responseCode == HttpURLConnection.HTTP_OK) {
2167 StringBuilder stringBuilder = new StringBuilder("\n");
2169 while( ( line = reader.readLine() ) != null ) {
2170 stringBuilder.append( line );
2172 LOG.info(stringBuilder.toString());
2173 // response = mapper.readValue(reader, String.class);
2174 response = stringBuilder.toString();
2175 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, "SUCCESS", mapper.writeValueAsString(response));
2176 } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
2177 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
2180 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2181 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
2182 throw new AAIServiceException(responseCode, errorresponse);
2185 } catch(AAIServiceException aaiexc) {
2187 } catch (Exception exc) {
2188 LOG.warn("requestNetworkVceData", exc);
2189 throw new AAIServiceException(exc);
2191 if(inputStream != null){
2193 inputStream.close();
2194 } catch(Exception exc) {
2204 public GenericVnf requestGenericVnfeNodeQuery(String vnf_name) throws AAIServiceException {
2206 if(vnf_name == null) {
2207 throw new NullPointerException();
2210 GenericVnf entity = null;
2211 SearchResults resp = this.requestNodeQuery("generic-vnf", "vnf-name", vnf_name);
2213 List<ResultData> resultDataList = resp.getResultData();
2216 for (ResultData datum : resultDataList) {
2217 String data_type = datum.getResourceType();
2218 URL url = new URL(datum.getResourceLink());
2219 entity = this.getResource(url.toString(), GenericVnf.class);
2224 LOG.error("Caught exception", e);
2230 public Vserver requestVServerDataByURL(URL url) throws AAIServiceException {
2233 throw new NullPointerException();
2236 Vserver entity = null;
2239 entity = this.getResource(url.toString(), Vserver.class);
2240 } catch (AAIServiceException exc) {
2242 } catch (Exception e) {
2243 throw new AAIServiceException(e);
2249 public URL requestVserverURLNodeQuery(String vserver_name) throws AAIServiceException {
2251 if(vserver_name == null) {
2252 throw new NullPointerException();
2256 SearchResults resp = this.requestNodeQuery("vserver", "vserver-name", vserver_name);
2258 List<ResultData> resultDataList = resp.getResultData();
2261 for (ResultData datum : resultDataList) {
2262 String data_type = datum.getResourceType();
2263 String resourceLink = datum.getResourceLink();
2264 if(!resourceLink.isEmpty() && !resourceLink.toLowerCase().startsWith("http")) {
2265 resourceLink = (new EchoRequest()).targetUri + resourceLink;
2267 entity = new URL(resourceLink);
2269 } catch (Exception e) {
2270 throw new AAIServiceException(e);
2275 class AAIRequestExecutor implements AAIExecutorInterface {
2278 public String get(AAIRequest request) throws AAIServiceException {
2279 String response = null;
2280 InputStream inputStream = null;
2281 HttpURLConnection con = null;
2282 URL requestUrl = null;
2284 String requestId = UUID.randomUUID().toString();
2285 StringBuilder errorStringBuilder = new StringBuilder();
2289 if(request.getRequestObject() != null) {
2290 requestUrl = request.getRequestUrl(HttpMethod.POST, null);
2291 requestUrl = appendDepth(requestUrl, request);
2292 con = getConfiguredConnection(requestUrl, HttpMethod.POST);
2293 String json_text = request.toJSONString();
2294 LOGwriteDateTrace("data", json_text);
2295 logMetricRequest(requestId, "POST "+requestUrl.getPath(), json_text, requestUrl.getPath());
2296 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
2297 osw.write(json_text);
2300 requestUrl = request.getRequestUrl(HttpMethod.GET, null);
2301 requestUrl = appendDepth(requestUrl, request);
2302 con = getConfiguredConnection(requestUrl, HttpMethod.GET);
2303 logMetricRequest(requestId, "GET "+requestUrl.getPath(), "", requestUrl.getPath());
2307 String responseMessage = con.getResponseMessage();
2308 int responseCode = con.getResponseCode();
2309 if (responseCode == HttpURLConnection.HTTP_OK) {
2310 inputStream = con.getInputStream();
2312 inputStream = con.getErrorStream();
2315 // Process the response
2316 LOG.debug("HttpURLConnection result:" + responseCode + " : " + responseMessage);
2317 logMetricResponse(requestId, responseCode, responseMessage);
2319 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
2320 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2322 ObjectMapper mapper = getObjectMapper();
2324 if (responseCode == HttpURLConnection.HTTP_OK) {
2325 StringBuilder stringBuilder = new StringBuilder();
2327 while( ( line = reader.readLine() ) != null ) {
2328 stringBuilder.append( line );
2330 response = stringBuilder.toString();
2332 Object object = mapper.readValue(response, Object.class);
2333 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, responseMessage, mapper.writeValueAsString(object));
2334 } catch(Exception exc) {
2335 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, responseMessage, mapper.writeValueAsString(response));
2337 } else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
2338 LOGwriteEndingTrace(responseCode, responseMessage, "Entry does not exist.");
2339 ErrorResponse errorresponse = null;
2341 errorresponse = mapper.readValue(reader, ErrorResponse.class);
2342 } catch(Exception exc) {
2343 errorresponse = new ErrorResponse();
2344 RequestError requestError = new RequestError();
2345 ServiceException serviceException = new ServiceException();
2346 serviceException.setText("Entry does not exist.");
2347 requestError.setServiceException(serviceException);
2348 errorresponse.setRequestError(requestError );
2350 throw new AAIServiceException(responseCode, errorresponse);
2351 } else if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
2352 StringBuilder stringBuilder = new StringBuilder();
2354 while( ( line = reader.readLine() ) != null ) {
2355 stringBuilder.append( line );
2357 LOGwriteEndingTrace(responseCode, responseMessage, stringBuilder.toString());
2358 ServiceException serviceException = new ServiceException();
2359 serviceException.setMessageId("HTTP_UNAUTHORIZED");
2360 serviceException.setText(stringBuilder.toString());
2361 RequestError requestError = new RequestError();
2362 requestError.setServiceException(serviceException);
2363 ErrorResponse errorresponse = new ErrorResponse();
2364 errorresponse.setRequestError(requestError);
2365 throw new AAIServiceException(responseCode, errorresponse);
2367 // StringBuilder errorStringBuilder = new StringBuilder();
2369 while( ( line = reader.readLine() ) != null ) {
2370 errorStringBuilder.append("\n").append( line );
2373 ErrorResponse errorresponse = mapper.readValue(errorStringBuilder.toString(), ErrorResponse.class);
2374 // ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2375 LOGwriteEndingTrace(responseCode, responseMessage, mapper.writeValueAsString(errorresponse));
2376 throw new AAIServiceException(responseCode, errorresponse);
2379 } catch(AAIServiceException aaiexc) {
2381 } catch (Exception exc) {
2382 LOG.warn(errorStringBuilder.toString(), exc);
2383 throw new AAIServiceException(exc);
2385 if(inputStream != null){
2387 inputStream.close();
2388 } catch(Exception exc) {
2396 private URL appendDepth(URL requestUrl, AAIRequest request) throws MalformedURLException {
2398 String depth = request.requestProperties.getProperty("depth", "1");
2399 String path = requestUrl.toString();
2400 if(path.contains("?depth=") || path.contains("&depth=")) {
2403 if(path.contains("?")) {
2404 path = String.format("%s&depth=%s", path, depth);
2406 path = String.format("%s?depth=%s", path, depth);
2408 return new URL(path);
2413 public String post(AAIRequest request) throws AAIServiceException {
2414 InputStream inputStream = null;
2415 String requestId = UUID.randomUUID().toString();
2418 String resourceVersion = null;
2419 AAIDatum instance = request.getRequestObject();
2421 Method getResourceVersionMethod = instance.getClass().getMethod("getResourceVersion");
2422 if(getResourceVersionMethod != null){
2424 getResourceVersionMethod.setAccessible(true);
2425 Object object = getResourceVersionMethod.invoke(instance);
2427 resourceVersion = object.toString();
2428 } catch (InvocationTargetException x) {
2429 Throwable cause = x.getCause();
2433 URL requestUrl = null;
2434 HttpURLConnection con = getConfiguredConnection(requestUrl = request.getRequestUrl(HttpMethod.PUT, resourceVersion), HttpMethod.PUT);
2435 ObjectMapper mapper = getObjectMapper();
2436 String json_text = request.toJSONString();
2438 LOGwriteDateTrace("data", json_text);
2439 logMetricRequest(requestId, "PUT "+requestUrl.getPath(), json_text, requestUrl.getPath());
2441 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
2442 osw.write(json_text);
2446 String responseMessage = con.getResponseMessage();
2447 int responseCode = con.getResponseCode();
2448 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2449 inputStream = con.getInputStream();
2451 inputStream = con.getErrorStream();
2454 LOG.debug("HttpURLConnection result:" + responseCode + " : " + responseMessage);
2455 logMetricResponse(requestId,responseCode, responseMessage);
2457 // Process the response
2458 BufferedReader reader;
2460 reader = new BufferedReader( new InputStreamReader( inputStream ) );
2461 mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
2463 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2464 StringBuilder stringBuilder = new StringBuilder();
2466 while( ( line = reader.readLine() ) != null ) {
2467 stringBuilder.append( line );
2469 LOGwriteEndingTrace(responseCode, responseMessage, (stringBuilder != null) ? stringBuilder.toString() : "{no-data}");
2470 return stringBuilder.toString();
2472 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2473 LOGwriteEndingTrace(responseCode, responseMessage, mapper.writeValueAsString(errorresponse));
2475 throw new AAIServiceException(responseCode, errorresponse);
2477 } catch(AAIServiceException aaiexc) {
2479 } catch (Exception exc) {
2480 LOG.warn("AAIRequestExecutor.post", exc);
2481 throw new AAIServiceException(exc);
2484 if(inputStream != null)
2485 inputStream.close();
2486 } catch (Exception exc) {
2493 public Boolean delete(AAIRequest request, String resourceVersion) throws AAIServiceException {
2494 Boolean response = null;
2495 InputStream inputStream = null;
2496 String requestId = UUID.randomUUID().toString();
2498 if(resourceVersion == null) {
2499 throw new AAIServiceException("resource-version is required for DELETE request");
2503 URL requestUrl = null;
2504 HttpURLConnection conn = getConfiguredConnection(requestUrl = request.getRequestUrl(HttpMethod.DELETE, resourceVersion), HttpMethod.DELETE);
2505 logMetricRequest(requestId, "DELETE "+requestUrl.getPath(), "", requestUrl.getPath());
2506 conn.setDoOutput(true);
2509 String responseMessage = conn.getResponseMessage();
2510 int responseCode = conn.getResponseCode();
2511 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2512 inputStream = conn.getInputStream();
2514 inputStream = conn.getErrorStream();
2517 // Process the response
2518 LOG.debug("HttpURLConnection result:" + responseCode + " : " + responseMessage);
2519 logMetricResponse(requestId,responseCode, responseMessage);
2521 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
2522 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2525 ObjectMapper mapper = getObjectMapper();
2527 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2528 StringBuilder stringBuilder = new StringBuilder();
2530 while( ( line = reader.readLine() ) != null ) {
2531 stringBuilder.append( line );
2533 LOGwriteEndingTrace(responseCode, responseMessage, stringBuilder.toString());
2535 } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
2536 LOGwriteEndingTrace(responseCode, responseMessage, "Entry does not exist.");
2539 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2540 LOGwriteEndingTrace(responseCode, responseMessage, mapper.writeValueAsString(errorresponse));
2541 throw new AAIServiceException(responseCode, errorresponse);
2543 } catch(AAIServiceException aaiexc) {
2545 } catch (Exception exc) {
2546 LOG.warn("delete", exc);
2547 throw new AAIServiceException(exc);
2549 if(inputStream != null){
2551 inputStream.close();
2552 } catch(Exception exc) {
2561 public Object query(AAIRequest request, Class clas) throws AAIServiceException {
2562 Object response = null;
2563 InputStream inputStream = null;
2564 HttpURLConnection con = null;
2565 URL requestUrl = null;
2566 String requestId = UUID.randomUUID().toString();
2569 requestUrl = request.getRequestQueryUrl(HttpMethod.GET);
2570 con = getConfiguredConnection(requestUrl , HttpMethod.GET);
2571 logMetricRequest(requestId, "GET "+requestUrl.getPath(), "", requestUrl.getPath());
2574 String responseMessage = con.getResponseMessage();
2575 int responseCode = con.getResponseCode();
2576 if (responseCode == HttpURLConnection.HTTP_OK) {
2577 inputStream = con.getInputStream();
2579 inputStream = con.getErrorStream();
2582 logMetricResponse(requestId,responseCode, responseMessage);
2583 ObjectMapper mapper = getObjectMapper();
2585 if (responseCode == HttpURLConnection.HTTP_OK) {
2586 // Process the response
2587 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2588 response = mapper.readValue(reader, clas);
2589 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, "SUCCESS", mapper.writeValueAsString(response));
2590 } else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
2591 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
2594 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2595 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2596 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
2597 throw new AAIServiceException(responseCode, errorresponse);
2600 } catch(AAIServiceException aaiexc) {
2602 } catch (Exception exc) {
2603 LOG.warn("GET", exc);
2604 throw new AAIServiceException(exc);
2606 if(inputStream != null){
2608 inputStream.close();
2609 } catch(Exception exc) {
2619 public Boolean patch(AAIRequest request, String resourceVersion) throws AAIServiceException {
2620 InputStream inputStream = null;
2621 String requestId = UUID.randomUUID().toString();
2624 AAIDatum instance = request.getRequestObject();
2625 if(instance instanceof ResourceVersion) {
2626 resourceVersion = ((ResourceVersion)instance).getResourceVersion();
2629 URL requestUrl = null;
2630 HttpURLConnection con = getConfiguredConnection(requestUrl = request.getRequestUrl("PATCH", resourceVersion), "PATCH");
2631 ObjectMapper mapper = getObjectMapper();
2632 String json_text = request.toJSONString();
2634 LOGwriteDateTrace("data", json_text);
2635 logMetricRequest(requestId, "PATCH "+requestUrl.getPath(), json_text, requestUrl.getPath());
2637 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
2638 osw.write(json_text);
2642 String responseMessage = con.getResponseMessage();
2643 int responseCode = con.getResponseCode();
2644 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2645 inputStream = con.getInputStream();
2647 inputStream = con.getErrorStream();
2650 LOG.info("HttpURLConnection result: " + responseCode + " : " + responseMessage);
2651 logMetricResponse(requestId,responseCode, responseMessage);
2653 // Process the response
2654 BufferedReader reader;
2656 reader = new BufferedReader( new InputStreamReader( inputStream ) );
2657 mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
2659 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2660 StringBuilder stringBuilder = new StringBuilder();
2662 while( ( line = reader.readLine() ) != null ) {
2663 stringBuilder.append( line );
2665 LOGwriteEndingTrace(responseCode, responseMessage,
2666 (stringBuilder.length() > 0) ? stringBuilder.toString() : "{no-data}");
2669 StringBuilder stringBuilder = new StringBuilder();
2671 while( ( line = reader.readLine() ) != null ) {
2672 stringBuilder.append("\n").append( line );
2674 LOG.info(stringBuilder.toString());
2677 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2678 LOGwriteEndingTrace(responseCode, responseMessage, mapper.writeValueAsString(errorresponse));
2680 throw new AAIServiceException(responseCode, errorresponse);
2682 } catch(AAIServiceException aaiexc) {
2684 } catch (Exception exc) {
2685 LOG.warn("AAIRequestExecutor.patch", exc);
2686 throw new AAIServiceException(exc);
2689 if(inputStream != null)
2690 inputStream.close();
2691 } catch (Exception exc) {
2699 public Tenant requestTenantData(String tenant_id, String cloudOwner, String cloudRegionId) throws AAIServiceException {
2700 Tenant response = null;
2703 AAIRequest request = AAIRequest.getRequestFromResource("tenant");
2704 request.addRequestProperty("tenant.tenant-id", tenant_id);
2705 request.addRequestProperty("cloud-region.cloud-owner", cloudOwner);
2706 request.addRequestProperty("cloud-region.cloud-region-id", cloudRegionId);
2708 String rv = executor.get(request);
2710 ObjectMapper mapper = getObjectMapper();
2711 response = mapper.readValue(rv, Tenant.class);
2713 } catch(AAIServiceException aaiexc) {
2715 } catch (Exception exc) {
2716 LOG.warn("requestTenantData", exc);
2717 throw new AAIServiceException(exc);
2724 public Tenant requestTenantDataByName(String tenant_name, String cloudOwner, String cloudRegionId) throws AAIServiceException {
2725 Tenant response = null;
2728 AAIRequest request = AAIRequest.getRequestFromResource("tenant");
2729 request.addRequestProperty("tenant.tenant-name", tenant_name);
2730 request.addRequestProperty("cloud-region.cloud-owner", cloudOwner);
2731 request.addRequestProperty("cloud-region.cloud-region-id", cloudRegionId);
2732 Object rv = executor.query(request, Tenant.class);
2734 return (Tenant)null;
2736 response = (Tenant)rv;
2737 } catch(AAIServiceException aaiexc) {
2739 } catch (Exception exc) {
2740 LOG.warn("requestTenantDataByName", exc);
2741 throw new AAIServiceException(exc);
2749 public boolean postTenantData(String tenant_id, String cloudOwner, String cloudRegionId, Tenant tenannt) throws AAIServiceException {
2751 AAIRequest request = AAIRequest.getRequestFromResource("tenant");
2752 request.addRequestProperty("tenant.tenant-id", tenant_id);
2753 request.addRequestProperty("cloud-region.cloud-owner", cloudOwner);
2754 request.addRequestProperty("cloud-region.cloud-region-id", cloudRegionId);
2755 request.setRequestObject(tenannt);
2756 Object response = executor.post(request);
2758 } catch(AAIServiceException aaiexc) {
2760 } catch (Exception exc) {
2761 LOG.warn("postTenantData", exc);
2762 throw new AAIServiceException(exc);
2768 public String getTenantIdFromVserverUrl(URL url) {
2770 String path = url.getPath();
2772 String[] split = path.split("/tenants/tenant/");
2773 if(split.length > 1) {
2774 split = split[1].split("/");
2782 public String getCloudOwnerFromVserverUrl(URL url) {
2784 String path = url.getPath();
2786 String[] split = path.split("/cloud-regions/cloud-region/");
2787 if(split.length > 1) {
2788 split = split[1].split("/");
2796 public String getCloudRegionFromVserverUrl(URL url) {
2798 String path = url.getPath();
2800 String[] split = path.split("/cloud-regions/cloud-region/");
2801 if(split.length > 1) {
2802 split = split[1].split("/");
2810 public String getVServerIdFromVserverUrl(URL url, String tenantId) {
2811 String pattern = network_vserver_path;
2812 pattern = pattern.replace("{tenant-id}", tenantId);
2814 int end = pattern.indexOf("{vserver-id}");
2815 String prefix = pattern.substring(0, end);
2817 String path = url.getPath();
2819 if(path.startsWith(prefix)) {
2820 path = path.substring(prefix.length());
2826 protected Logger getLogger(){
2832 public AAIRequestExecutor getExecutor() {
2837 * Creates a current time stamp in UTC i.e. 2016-03-08T22:15:13.343Z.
2838 * If there are any parameters the values are appended to the time stamp.
2841 * values to be appended to current time stamp
2843 * used to set an attribute for a DG
2844 * @throws SvcLogicException
2846 public void setStatusMethod(Map<String, String> parameters, SvcLogicContext ctx) throws SvcLogicException {
2848 throw new SvcLogicException("SvcLogicContext is null.");
2851 StringBuilder sb = new StringBuilder();
2852 sb.append(String.format("%tFT%<tTZ", Calendar.getInstance(TimeZone.getTimeZone("Z")))).append(" - ");
2854 for (Entry<String, String> entry : parameters.entrySet()) {
2855 sb.append(entry.getValue()).append(" ");
2858 if (sb.length() > 0) {
2859 sb.setLength(sb.length() - 2);
2862 ctx.setAttribute("aai-summary-status-message", sb.toString());
2863 LOG.info("aai-summary-status-message: " + sb.toString());
2867 * Generic method to GET json data from an A&AI using key structure.
2868 * Then convert that json to an Object.
2869 * If successful the Object is attempted to be cast to the type parameter.
2872 * key identifying the resource to be retrieved from AAI
2874 * the class of object that A&AI will return
2875 * @return the object created from json or null if the response code is not 200
2877 * @throws AAIServiceException
2878 * if empty or null key and or type or there's an error with processing
2881 public <T> T getResource(String key, Class<T> type) throws AAIServiceException {
2882 if (StringUtils.isEmpty(key) || type == null) {
2883 throw new AAIServiceException("Key is empty or null and or type is null");
2888 SvcLogicContext ctx = new SvcLogicContext();
2889 if(!key.contains(" = ")) {
2890 if(isValidURL(key)) {
2891 key = String.format("selflink = '%s'", key);
2892 } else if(isValidURI(key)) {
2893 key = String.format("resource-path = '%s'", key);
2899 HashMap<String, String> nameValues = AAIServiceUtils.keyToHashMap(key, ctx);
2901 AAIRequest request = new SelfLinkRequest(type);
2902 if(nameValues.containsKey(PathRequest.RESOURCE_PATH.replaceAll("-", "_"))) {
2903 request = new PathRequest(type);
2906 request.processRequestPathValues(nameValues);
2907 Object obj = this.getExecutor().query(request, type);
2908 response = type.cast(obj);
2910 return response != null ? type.cast(response) : response;
2913 public boolean isValidURL(String url) {
2919 } catch (MalformedURLException e) {
2925 } catch (URISyntaxException e) {
2933 public boolean isValidURI(String url) {
2939 } catch (URISyntaxException e) {
2947 protected boolean deleteRelationshipList(URL httpReqUrl, String json_text) throws AAIServiceException {
2948 if(httpReqUrl == null) {
2949 throw new NullPointerException();
2952 boolean response = false;
2953 InputStream inputStream = null;
2956 HttpURLConnection con = getConfiguredConnection(httpReqUrl, HttpMethod.DELETE);
2958 // SSLSocketFactory sockFact = CTX.getSocketFactory();
2959 // con.setSSLSocketFactory( sockFact );
2960 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
2961 osw.write(json_text);
2966 LOGwriteFirstTrace("DELETE", httpReqUrl.toString());
2967 LOGwriteDateTrace("data", json_text);
2970 int responseCode = con.getResponseCode();
2971 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2972 inputStream = con.getInputStream();
2974 inputStream = con.getErrorStream();
2977 // Process the response
2978 LOG.debug("HttpURLConnection result:" + responseCode);
2979 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
2980 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2983 ObjectMapper mapper = getObjectMapper();
2985 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2986 StringBuilder stringBuilder = new StringBuilder();
2988 while( ( line = reader.readLine() ) != null ) {
2989 stringBuilder.append( line );
2991 LOGwriteEndingTrace(responseCode, "SUCCESS", stringBuilder.toString());
2993 } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
2994 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
2997 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2998 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
2999 throw new AAIServiceException(responseCode, errorresponse);
3002 } catch(AAIServiceException aaiexc) {
3004 } catch (Exception exc) {
3005 LOG.warn("deleteRelationshipList", exc);
3006 throw new AAIServiceException(exc);
3008 if(inputStream != null){
3010 inputStream.close();
3011 } catch(Exception exc) {
3019 public static ObjectMapper getObjectMapper() {
3020 ObjectMapper mapper = new ObjectMapper();
3021 AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance());
3022 AnnotationIntrospector secondary = new JacksonAnnotationIntrospector();
3023 mapper.setAnnotationIntrospector(AnnotationIntrospector.pair(introspector, secondary));
3024 mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
3025 mapper.setSerializationInclusion(Include.NON_NULL);
3029 public void logMetricRequest(String requestId, String targetServiceName, String msg, String path){
3030 String svcInstanceId = "";
3031 String svcName = null;
3032 String partnerName = null;
3033 String targetEntity = "A&AI";
3034 String targetVirtualEntity = null;
3036 targetServiceName = "";
3038 ml.logRequest(svcInstanceId, svcName, partnerName, targetEntity, targetServiceName, targetVirtualEntity, msg);
3041 public void logMetricResponse(String requestId, int responseCode, String responseDescription){
3042 ml.logResponse(responseCode < 400 ? "SUCCESS" : "FAILURE", Integer.toString(responseCode), responseDescription);
3045 public void logKeyError(String keys){
3046 LOG.error("Atleast one of the keys [" + keys + "] should have been populated. This will cause a NPE.");
3054 public QueryStatus save(String resource, boolean force, boolean localOnly, String key, Map<String, String> params, String prefix, SvcLogicContext ctx)
3055 throws SvcLogicException {
3056 String normResource = resource.split(":")[0];
3058 switch(normResource){
3059 case "custom-query":
3060 case "formatted-query":
3061 case "generic-query":
3065 case "l2-bridge-sbg":
3066 case "l2-bridge-bgf":
3072 if(key.contains("selflink =")) {
3075 if(!key.contains(String.format("%s.", normResource))) {
3076 key = rewriteKey(resource, key, ctx);
3079 return super.save(resource, force, localOnly, key, params, prefix, ctx);
3083 public QueryStatus query(String resource, boolean localOnly, String select, String key, String prefix, String orderBy, SvcLogicContext ctx)
3084 throws SvcLogicException {
3085 String normResource = resource.split(":")[0];
3087 switch(normResource){
3088 case "formatted-query":
3089 case "generic-query":
3093 case "l2-bridge-sbg":
3094 case "l2-bridge-bgf":
3100 if(key.contains("selflink =")) {
3103 if(!key.contains(String.format("%s.", normResource))) {
3104 key = rewriteKey(resource, key, ctx);
3108 return super.query(resource, localOnly, select, key, prefix, orderBy, ctx);
3112 public QueryStatus delete(String resource, String key, SvcLogicContext ctx) throws SvcLogicException {
3113 String normResource = resource.split(":")[0];
3115 switch(normResource){
3116 case "formatted-query":
3117 case "generic-query":
3121 case "l2-bridge-sbg":
3122 case "l2-bridge-bgf":
3128 if(key.contains("selflink =")) {
3131 if(!key.contains(String.format("%s.", normResource))) {
3132 key = rewriteKey(resource, key, ctx);
3136 return super.delete(resource, key, ctx);
3140 public QueryStatus update(String resource, String key, Map<String, String> params, String prefix, SvcLogicContext ctx) throws SvcLogicException {
3141 String normResource = resource.split(":")[0];
3143 switch(normResource){
3144 case "formatted-query":
3145 case "generic-query":
3149 case "l2-bridge-sbg":
3150 case "l2-bridge-bgf":
3156 if(key.contains("selflink =")) {
3159 if(!key.contains(String.format("%s.", normResource))) {
3160 key = rewriteKey(resource, key, ctx);
3164 return super.update(resource, key, params, prefix, ctx);
3167 private String rewriteKey(String resource, String key, SvcLogicContext ctx) {
3168 LOG.info("AAI Deprecation - the format of request key is no longer supported. Please rewrite this key : " + key);
3170 String normResource = resource.split(":")[0];
3171 Class<? extends AAIDatum> clazz = null;
3173 clazz = AAIRequest.getClassFromResource(normResource) ;
3174 } catch (ClassNotFoundException e) {
3175 LOG.warn("AAIRequest does not support class: " + e.getMessage());
3181 List<String> fieldAnnotatedNames = new LinkedList<>();
3183 Field[] fields = clazz.getDeclaredFields();
3184 for(Field field : fields) {
3185 String fieldName = field.getName();
3186 XmlElement annotation = field.getAnnotation(XmlElement.class);
3187 if(annotation == null)
3189 String primaryId = annotation.name();
3190 if("##default".equals(primaryId)) {
3191 primaryId = fieldName;
3193 fieldAnnotatedNames.add(primaryId);
3196 HashMap<String, String> nameValues = AAIServiceUtils.keyToHashMap(key, ctx);
3197 Set<String> keyset = nameValues.keySet();
3198 for(String keyName : keyset) {
3199 if(keyName.contains("."))
3202 String tmpKeyName = keyName.replaceAll("_", "-");
3203 String valueToSubstitute = String.format("%s =", tmpKeyName);
3204 if(fieldAnnotatedNames.contains(tmpKeyName) && key.contains(valueToSubstitute)) {
3205 key = key.replace(valueToSubstitute, String.format("%s.%s =", normResource, tmpKeyName));
3215 public String getPathTemplateForResource(String resoourceName, String keys, SvcLogicContext ctx) throws MalformedURLException {
3216 return AAIServiceUtils.getPathForResource(resoourceName, StringUtils.join(keys, " AND "), ctx);
3220 public boolean isDeprecatedFormat(String resource, HashMap<String, String> nameValues) {
3221 return !AAIServiceUtils.isValidFormat(resource, nameValues);
3224 public AAIRequest getRequestFromResource(String resoourceName) {
3225 return AAIRequest.getRequestFromResource(resoourceName);
3229 * @see org.openecomp.sdnc.sli.aai.haha#query(org.openecomp.sdnc.sli.aai.AAIRequest)
3232 public String query(AAIRequest request) throws AAIServiceException {
3233 return executor.get(request);
3237 * @see org.openecomp.sdnc.sli.aai.haha#save(org.openecomp.sdnc.sli.aai.AAIRequest)
3240 public String save(AAIRequest request) throws AAIServiceException {
3241 return executor.post(request);
3244 public boolean update(AAIRequest request, String resourceVersion) throws AAIServiceException {
3245 return executor.patch(request, resourceVersion);
3249 * @see org.openecomp.sdnc.sli.aai.haha#delete(org.openecomp.sdnc.sli.aai.AAIRequest, java.lang.String)
3252 public boolean delete(AAIRequest request, String resourceVersion) throws AAIServiceException {
3253 return executor.patch(request, resourceVersion);