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 truststorePath;
130 private final String truststorePassword;
131 private final String keystorePath;
132 private final String keystorePassword;
133 private final Boolean ignoreCertificateHostError;
135 private final String target_uri;
136 private final String queryPath;
138 private final String networkVserverPath;
140 private final String svcInstancePath;
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 truststorePath = props.getProperty(TRUSTSTORE_PATH);
210 truststorePassword = props.getProperty(TRUSTSTORE_PSSWD);
211 keystorePath = props.getProperty(KEYSTORE_PATH);
212 keystorePassword = props.getProperty(KEYSTORE_PSSWD);
214 target_uri = props.getProperty(TARGET_URI);
215 queryPath = 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 networkVserverPath =props.getProperty(NETWORK_VSERVER_PATH);
244 svcInstancePath = 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 ignoreCertificateHostError = host_error;
271 HttpsURLConnection.setDefaultHostnameVerifier( new HostnameVerifier(){
272 public boolean verify(String string,SSLSession ssls) {
273 return ignoreCertificateHostError;
277 if(truststorePath != null && truststorePassword != null && (new File(truststorePath)).exists()) {
278 System.setProperty("javax.net.ssl.trustStore", truststorePath);
279 System.setProperty("javax.net.ssl.trustStorePassword", truststorePassword);
282 if(keystorePath != null && keystorePassword != null && (new File(keystorePath)).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(keystorePath)){
291 String def = "SunX509";
292 String storeType = "PKCS12";
293 def = KeyStore.getDefaultType();
294 kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
296 String extension = keystorePath.substring(keystorePath.lastIndexOf(".") + 1);
297 if("JKS".equalsIgnoreCase(extension)) {
300 KeyStore ks = KeyStore.getInstance(storeType);
302 char[] pwd = keystorePassword.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 ignoreCertificateHostError;
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");
384 con.setRequestProperty("Transfer-Encoding","chunked");
386 if(user_name != null && !user_name.isEmpty() && user_password != null && !user_password.isEmpty()) {
387 String basicAuth = "Basic " + new String(Base64.encodeBase64((user_name + ":" + user_password).getBytes()));
388 con.setRequestProperty ("Authorization", basicAuth);
391 if(con instanceof HttpsURLConnection && CTX != null) {
392 SSLSocketFactory sockFact = CTX.getSocketFactory();
393 HttpsURLConnection.class.cast(con).setSSLSocketFactory( sockFact );
400 public GenericVnf requestGenericVnfData(String vnf_id) throws AAIServiceException {
401 GenericVnf response = null;
404 AAIRequest request = AAIRequest.getRequestFromResource("generic-vnf");
405 request.addRequestProperty("generic-vnf.vnf-id", vnf_id);
406 String rv = executor.get(request);
408 ObjectMapper mapper = getObjectMapper();
409 response = mapper.readValue(rv, GenericVnf.class);
411 } catch(AAIServiceException aaiexc) {
413 } catch (Exception exc) {
414 LOG.warn(Object.class.getClass().getEnclosingMethod().getName(), exc);
415 throw new AAIServiceException(exc);
423 public boolean postGenericVnfData(String vnf_id, GenericVnf data) throws AAIServiceException {
425 AAIRequest request = AAIRequest.getRequestFromResource("generic-vnf");
426 request.addRequestProperty("generic-vnf.vnf-id", vnf_id);
427 request.setRequestObject(data);
428 Object response = executor.post(request);
430 } catch(AAIServiceException aaiexc) {
432 } catch (Exception exc) {
433 LOG.warn("requestGenericVnfData", exc);
434 throw new AAIServiceException(exc);
439 public boolean deleteGenericVnfData(String vnf_id, String resourceVersion) throws AAIServiceException {
440 boolean response = false;
443 AAIRequest request = AAIRequest.getRequestFromResource("generic-vnf");
444 request.addRequestProperty("generic-vnf.vnf-id", vnf_id);
445 response = executor.delete(request, resourceVersion);
446 } catch(AAIServiceException aaiexc) {
448 } catch (Exception exc) {
449 LOG.warn("deleteGenericVnfData", exc);
450 throw new AAIServiceException(exc);
456 * @see org.onap.ccsdk.sli.adaptors.resource.aic.AnAIClient#requestSdnZoneQuery(java.lang.String, java.lang.String, java.lang.String)
459 public Vce requestNetworkVceData(String vnf_id) throws AAIServiceException {
462 AAIRequest request = AAIRequest.getRequestFromResource("vce");
463 request.addRequestProperty("vce.vnf-id", vnf_id);
464 String rv = executor.get(request);
466 ObjectMapper mapper = getObjectMapper();
467 response = mapper.readValue(rv, Vce.class);
469 } catch(AAIServiceException aaiexc) {
471 } catch (Exception exc) {
472 LOG.warn(Object.class.getClass().getEnclosingMethod().getName(), exc);
473 throw new AAIServiceException(exc);
481 * @see org.onap.ccsdk.sli.adaptors.resource.aic.AnAIClient#requestSdnZoneQuery(java.lang.String, java.lang.String, java.lang.String)
484 public boolean deleteNetworkVceData(String vnf_id, String resourceVersion) throws AAIServiceException {
485 boolean response = false;
488 AAIRequest request = AAIRequest.getRequestFromResource("vce");
489 request.addRequestProperty("vce.vnf-id", vnf_id);
490 response = executor.delete(request, resourceVersion);
491 } catch(AAIServiceException aaiexc) {
493 } catch (Exception exc) {
494 LOG.warn("deleteNetworkVceData", exc);
495 throw new AAIServiceException(exc);
501 * @see org.onap.ccsdk.sli.adaptors.resource.aic.AnAIClient#postNetworkVceData(java.lang.String, org.onap.ccsdk.sli.adaptors.resource.aic.aai.VCERequest)
504 public boolean postNetworkVceData(String vnf_id, Vce data) throws AAIServiceException {
506 AAIRequest request = AAIRequest.getRequestFromResource("vce");
507 request.addRequestProperty("vce.vnf-id", vnf_id);
508 request.setRequestObject(data);
509 Object response = executor.post(request);
511 } catch(AAIServiceException aaiexc) {
513 } catch (Exception exc) {
514 LOG.warn("requestGenericVnfData", exc);
515 throw new AAIServiceException(exc);
521 public SearchResults requestServiceInstanceURL(String svc_instance_id) throws AAIServiceException {
522 SearchResults response = null;
523 InputStream inputStream = null;
526 String path = svc_inst_qry_path;
527 path = path.replace("{svc-instance-id}", encodeQuery(svc_instance_id));
529 String request_url = target_uri+path;
530 URL http_req_url = new URL(request_url);
532 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.GET);
534 LOGwriteFirstTrace(HttpMethod.GET, http_req_url.toString());
535 LOGwriteDateTrace("svc_instance_id", svc_instance_id);
538 int responseCode = con.getResponseCode();
539 if (responseCode == HttpURLConnection.HTTP_OK) {
540 inputStream = con.getInputStream();
542 inputStream = con.getErrorStream();
545 // Process the response
546 LOG.debug("HttpURLConnection result:" + responseCode);
547 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
548 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
550 ObjectMapper mapper = getObjectMapper();
552 if (responseCode == HttpURLConnection.HTTP_OK) {
553 response = mapper.readValue(reader, SearchResults.class);
554 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, "SUCCESS", mapper.writeValueAsString(response));
555 } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
556 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
559 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
560 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
561 throw new AAIServiceException(responseCode, errorresponse);
564 } catch(AAIServiceException aaiexc) {
566 } catch (Exception exc) {
567 LOG.warn("requestServiceInstanceURL", exc);
568 throw new AAIServiceException(exc);
570 if(inputStream != null){
573 } catch(Exception exc) {
581 public ServiceInstance requestServiceInterfaceData(String customer_id, String service_type, String svc_instance_id) throws AAIServiceException {
582 ServiceInstance response = null;
585 AAIRequest request = AAIRequest.getRequestFromResource("service-instance");
586 request.addRequestProperty("customer.global-customer-id", customer_id);
587 request.addRequestProperty("service-subscription.service-type", service_type);
588 request.addRequestProperty("service-instance.service-instance-id", svc_instance_id);
590 String rv = executor.get(request);
592 ObjectMapper mapper = getObjectMapper();
593 response = mapper.readValue(rv, ServiceInstance.class);
595 } catch(AAIServiceException aaiexc) {
597 } catch (Exception exc) {
598 LOG.warn("requestServiceInterfaceData", exc);
599 throw new AAIServiceException(exc);
605 public boolean postServiceInterfaceData(String customer_id, String service_type, String svc_instance_id, ServiceInstance data) throws AAIServiceException {
607 AAIRequest request = AAIRequest.getRequestFromResource("service-instance");
608 request.addRequestProperty("customer.global-customer-id", customer_id);
609 request.addRequestProperty("service-subscription.service-type", service_type);
610 request.addRequestProperty("service-instance.service-instance-id", svc_instance_id);
611 request.setRequestObject(data);
612 Object response = executor.post(request);
614 } catch(AAIServiceException aaiexc) {
616 } catch (Exception exc) {
617 LOG.warn("requestGenericVnfData", exc);
618 throw new AAIServiceException(exc);
623 private static Properties initialize(URL url ) throws ConfigurationException {
626 throw new NullPointerException();
629 InputStream is = null;
630 Properties props = new Properties();
633 if(LOG.isDebugEnabled())
634 LOG.info("Property file is: " + url.toString());
636 is = url.openStream();
639 if(LOG.isDebugEnabled()) {
640 LOG.info("Properties loaded: " + props.size());
641 Enumeration<Object> en = props.keys();
643 while(en.hasMoreElements()) {
644 String key = (String)en.nextElement();
645 String property = props.getProperty(key);
646 LOG.debug(key + " : " + property);
649 } catch (Exception e) {
650 throw new ConfigurationException("Could not load properties file.", e);
655 static class TransactionIdTracker {
656 // protected static AtomicLong tracker = new AtomicLong();
658 public static String getNextTransactionId() {
659 // Check if RequestId exists as MDC. If not, create new.
660 String transactionId = MDC.get("RequestId");
661 if ("".equals(transactionId) || transactionId == null) {
662 transactionId = UUID.randomUUID().toString();
663 LOG.info("Missing requestID. Assigned " + transactionId);
664 MDC.put("RequestId", transactionId);
666 return transactionId;
671 protected void LOGwriteFirstTrace(String method, String url) {
672 String time = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").format(System.currentTimeMillis());
673 LOG.info("A&AI transaction :");
674 LOG.info("Request Time : " + time + ", Method : " + method);
675 LOG.info("Request URL : "+ url);
678 protected void LOGwriteDateTrace(String name, String data) {
679 LOG.info("Input - " + name + " : " + data);
682 protected void LOGwriteEndingTrace(int response_code, String comment, String data) {
683 LOG.info("Response code : " + response_code +", " + comment);
684 LOG.info(String.format("Response data : %s", data));
687 protected String encodeQuery(String param) throws UnsupportedEncodingException {
688 return URLEncoder.encode(param, "UTF-8").replace("+", "%20");
691 private String encodeCustomerURL(final String selection)
693 String encrypted_url = selection;
695 "/aai/v11/business/customers/customer/(.+)/service-subscriptions/service-subscription/(.+)/service-instances/service-instance/(.+)/";
696 Pattern pattern = Pattern.compile(apnpattern);
699 URL url = new URL(selection);
700 String path = url.getPath();
702 LOG.info("Trying to match apn to <" + path + ">");
704 Matcher matcher = pattern.matcher(path);
706 while(matcher.find()) {
707 String customer = matcher.group(1);
708 String subscription = matcher.group(2);
709 String service = matcher.group(3);
711 encrypted_url = selection.replace(customer, encodeQuery(customer));
712 encrypted_url = encrypted_url.replace(subscription, encodeQuery(subscription));
713 encrypted_url = encrypted_url.replace(service, encodeQuery(service));
715 } catch (Exception e) {
719 return encrypted_url;
723 public VplsPe requestNetworkVplsPeData(String equipment_name)throws AAIServiceException {
724 VplsPe response = null;
727 AAIRequest request = AAIRequest.getRequestFromResource("vpls-pe");
728 request.addRequestProperty("vpls-pe.equipment-name", equipment_name);
730 String rv = executor.get(request);
732 ObjectMapper mapper = getObjectMapper();
733 response = mapper.readValue(rv, VplsPe.class);
735 } catch(AAIServiceException aaiexc) {
737 } catch (Exception exc) {
738 LOG.warn(Object.class.getClass().getEnclosingMethod().getName(),
740 throw new AAIServiceException(exc);
746 public boolean postNetworkVplsPeData(String equipment_name, VplsPe data) throws AAIServiceException {
748 AAIRequest request = AAIRequest.getRequestFromResource("vpls-pe");
749 request.addRequestProperty("vpls-pe.equipment-name", equipment_name);
750 request.setRequestObject(data);
751 Object response = executor.post(request);
753 } catch(AAIServiceException aaiexc) {
755 } catch (Exception exc) {
756 LOG.warn("requestGenericVnfData", exc);
757 throw new AAIServiceException(exc);
762 public boolean deleteNetworkVplsPeData(String vnf_id, String resourceVersion) throws AAIServiceException {
763 boolean response = false;
766 AAIRequest request = AAIRequest.getRequestFromResource("vpls-pe");
767 request.addRequestProperty("vpls-pe.equipment-name", vnf_id);
768 response = executor.delete(request, resourceVersion);
769 } catch(AAIServiceException aaiexc) {
771 } catch (Exception exc) {
772 LOG.warn("deleteNetworkVplsPeData", exc);
773 throw new AAIServiceException(exc);
779 public Complex requestNetworkComplexData(String pLocId) throws AAIServiceException {
780 Complex response = null;
783 AAIRequest request = AAIRequest.getRequestFromResource("complex");
784 request.addRequestProperty("complex.physical-location-id", pLocId);
786 String rv = executor.get(request);
788 ObjectMapper mapper = getObjectMapper();
789 response = mapper.readValue(rv, Complex.class);
791 } catch(AAIServiceException aaiexc) {
793 } catch (Exception exc) {
794 LOG.warn("requestNetworkComplexData", exc);
795 throw new AAIServiceException(exc);
801 public boolean postNetworkComplexData(String vnf_id, Complex data) throws AAIServiceException {
803 AAIRequest request = AAIRequest.getRequestFromResource("complex");
804 request.addRequestProperty("complex.physical-location-id", vnf_id);
805 request.setRequestObject(data);
806 Object response = executor.post(request);
808 } catch(AAIServiceException aaiexc) {
810 } catch (Exception exc) {
811 LOG.warn("postNetworkComplexData", exc);
812 throw new AAIServiceException(exc);
817 public boolean deleteNetworkComplexData(String pLocId, String resourceVersion) throws AAIServiceException {
818 boolean response = false;
821 AAIRequest request = AAIRequest.getRequestFromResource("complex");
822 request.addRequestProperty("complex.physical-location-id", pLocId);
824 response = executor.delete(request, resourceVersion);
826 } catch(AAIServiceException aaiexc) {
828 } catch (Exception exc) {
829 LOG.warn("deleteNetworkComplexData", exc);
830 throw new AAIServiceException(exc);
837 * @see org.openecomp.sdnct.sli.aai.AAIClient#requestVServersData(java.lang.String, java.lang.String)
840 public Vserver requestVServerData(String tenantId, String vserverId, String cloudOwner, String cloudRegionId) throws AAIServiceException {
841 Vserver response = null;
844 AAIRequest request = AAIRequest.getRequestFromResource("vserver");
845 request.addRequestProperty("cloud-region.cloud-owner", cloudOwner);
846 request.addRequestProperty("cloud-region.cloud-region-id", cloudRegionId);
847 request.addRequestProperty("tenant.tenant-id", tenantId);
848 request.addRequestProperty("vserver.vserver-id", vserverId);
850 String rv = executor.get(request);
852 ObjectMapper mapper = getObjectMapper();
853 response = mapper.readValue(rv, Vserver.class);
855 } catch(AAIServiceException aaiexc) {
857 } catch (Exception exc) {
858 LOG.warn(Object.class.getClass().getEnclosingMethod().getName(), exc);
859 throw new AAIServiceException(exc);
866 public boolean postVServerData(String tenantId, String vserverId, String cloudOwner, String cloudRegionId, Vserver data) throws AAIServiceException {
868 AAIRequest request = AAIRequest.getRequestFromResource("vserver");
869 request.addRequestProperty("cloud-region.cloud-owner", cloudOwner);
870 request.addRequestProperty("cloud-region.cloud-region-id", cloudRegionId);
871 request.addRequestProperty("tenant.tenant-id", tenantId);
872 request.addRequestProperty("vserver.vserver-id", vserverId);
873 request.setRequestObject(data);
874 Object response = executor.post(request);
876 } catch(AAIServiceException aaiexc) {
878 } catch (Exception exc) {
879 LOG.warn("postNetworkComplexData", exc);
880 throw new AAIServiceException(exc);
885 public boolean deleteVServerData(String tenant_id, String vserver_id, String cloudOwner, String cloudRegionId, String resourceVersion) throws AAIServiceException {
886 boolean response = false;
889 AAIRequest request = AAIRequest.getRequestFromResource("vserver");
891 request.addRequestProperty("vserver.vserver-id", vserver_id);
892 request.addRequestProperty("tenant.tenant-id", tenant_id);
893 request.addRequestProperty("cloud-region.cloud-owner", cloudOwner);
894 request.addRequestProperty("cloud-region.cloud-region-id",cloudRegionId);
896 response = executor.delete(request, resourceVersion);
898 } catch(AAIServiceException aaiexc) {
900 } catch (Exception exc) {
901 LOG.warn("deleteVServerData", exc);
902 throw new AAIServiceException(exc);
910 * @see org.onap.ccsdk.sli.adaptors.aai.AAIClient#requestCtagPoolData(String)
913 public CtagPool requestCtagPoolData(String physical_location_id, String target_pe, String availability_zone_name) throws AAIServiceException {
914 CtagPool response = null;
917 AAIRequest request = AAIRequest.getRequestFromResource("ctag-pool");
919 request.addRequestProperty("ctag-pool.target-pe", target_pe);
920 request.addRequestProperty("ctag-pool.availability-zone-name", availability_zone_name);
921 request.addRequestProperty("complex.physical-location-id", physical_location_id);
923 String rv = executor.get(request);
925 ObjectMapper mapper = getObjectMapper();
926 response = mapper.readValue(rv, CtagPool.class);
928 } catch(AAIServiceException aaiexc) {
930 } catch (Exception exc) {
931 LOG.warn("requestNetworkVceData", exc);
932 throw new AAIServiceException(exc);
937 //==================== DvsSwitch ======================
939 public DvsSwitch requestDvsSwitchData(String vnf_id) throws AAIServiceException {
940 DvsSwitch response = null;
943 AAIRequest request = AAIRequest.getRequestFromResource("dvs-switch");
944 request.addRequestProperty("dvs-switch.switch-name", vnf_id);
946 String rv = executor.get(request);
948 ObjectMapper mapper = getObjectMapper();
949 response = mapper.readValue(rv, DvsSwitch.class);
951 } catch(AAIServiceException aaiexc) {
953 } catch (Exception exc) {
954 LOG.warn("requestDvsSwitchData", exc);
955 throw new AAIServiceException(exc);
961 public boolean postDvsSwitchData(String switch_name, DvsSwitch data) throws AAIServiceException {
963 AAIRequest request = AAIRequest.getRequestFromResource("dvs-switch");
964 request.addRequestProperty("dvs-switch.switch-name", switch_name);
965 request.setRequestObject(data);
966 Object response = executor.post(request);
968 } catch(AAIServiceException aaiexc) {
970 } catch (Exception exc) {
971 LOG.warn(Object.class.getClass().getEnclosingMethod().getName(), exc);
972 throw new AAIServiceException(exc);
977 public boolean deleteDvsSwitchData(String vnf_id, String resourceVersion) throws AAIServiceException {
978 boolean response = false;
981 AAIRequest request = AAIRequest.getRequestFromResource("dvs-switch");
982 request.addRequestProperty("dvs-switch.switch-name", vnf_id);
983 response = executor.delete(request, resourceVersion);
984 } catch(AAIServiceException aaiexc) {
986 } catch (Exception exc) {
987 LOG.warn("deleteDvsSwitchData", exc);
988 throw new AAIServiceException(exc);
992 //================== End of DvsSwitch =================
993 //==================== PhysicalLink ======================
995 public PhysicalLink requestPhysicalLinkData(String linkName) throws AAIServiceException {
996 PhysicalLink response = null;
999 AAIRequest request = AAIRequest.getRequestFromResource("physical-link");
1000 request.addRequestProperty("physical-link.link-name", linkName);
1002 String rv = executor.get(request);
1004 ObjectMapper mapper = getObjectMapper();
1005 response = mapper.readValue(rv, PhysicalLink.class);
1007 } catch(AAIServiceException aaiexc) {
1009 } catch (Exception exc) {
1010 LOG.warn("requestPhysicalLinkData", exc);
1011 throw new AAIServiceException(exc);
1017 public boolean postPhysicalLinkData(String linkName, PhysicalLink data) throws AAIServiceException {
1019 AAIRequest request = AAIRequest.getRequestFromResource("physical-link");
1020 request.addRequestProperty("physical-link.link-name", linkName);
1021 request.setRequestObject(data);
1022 Object response = executor.post(request);
1024 } catch(AAIServiceException aaiexc) {
1026 } catch (Exception exc) {
1027 LOG.warn(Object.class.getClass().getEnclosingMethod().getName(), exc);
1028 throw new AAIServiceException(exc);
1033 public boolean deletePhysicalLinkData(String linkName, String resourceVersion) throws AAIServiceException {
1034 boolean response = false;
1037 AAIRequest request = AAIRequest.getRequestFromResource("physical-link");
1038 request.addRequestProperty("physical-link.link-name", linkName);
1039 response = executor.delete(request, resourceVersion);
1040 } catch(AAIServiceException aaiexc) {
1042 } catch (Exception exc) {
1043 LOG.warn("deletePhysicalLinkData", exc);
1044 throw new AAIServiceException(exc);
1048 //================== End of PhysicalLink =================
1049 //==================== PInterface ======================
1051 public PInterface requestPInterfaceData(String hostname, String interfaceName) throws AAIServiceException {
1052 PInterface response = null;
1055 AAIRequest request = AAIRequest.getRequestFromResource("p-interface");
1056 request.addRequestProperty("p-interface.interface-name", interfaceName);
1057 request.addRequestProperty("pserver.hostname", hostname);
1058 String rv = executor.get(request);
1060 ObjectMapper mapper = getObjectMapper();
1061 response = mapper.readValue(rv, PInterface.class);
1063 } catch(AAIServiceException aaiexc) {
1065 } catch (Exception exc) {
1066 LOG.warn(Object.class.getClass().getEnclosingMethod().getName(), exc);
1067 throw new AAIServiceException(exc);
1073 public boolean postPInterfaceData(String hostname, String interfaceName, PInterface request) throws AAIServiceException {
1074 InputStream inputStream = null;
1078 ObjectMapper mapper = getObjectMapper();
1079 String json_text = mapper.writeValueAsString(request);
1081 SSLSocketFactory sockFact = CTX.getSocketFactory();
1083 String request_url = target_uri+p_interface_path;
1084 String encoded_vnf = encodeQuery(hostname);
1085 request_url = request_url.replace("{hostname}", encoded_vnf) ;
1086 encoded_vnf = encodeQuery(interfaceName);
1087 request_url = request_url.replace("{interface-name}", encoded_vnf) ;
1088 URL http_req_url = new URL(request_url);
1090 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.PUT);
1092 if (json_text != null) {
1093 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
1094 osw.write(json_text);
1099 LOGwriteFirstTrace("PUT", request_url);
1100 LOGwriteDateTrace("hostname", hostname);
1101 LOGwriteDateTrace("interface-name", interfaceName);
1102 LOGwriteDateTrace("PInterface", json_text);
1105 int responseCode = con.getResponseCode();
1106 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1107 inputStream = con.getInputStream();
1109 inputStream = con.getErrorStream();
1112 // Process the response
1113 BufferedReader reader;
1115 reader = new BufferedReader( new InputStreamReader( inputStream ) );
1117 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1118 StringBuilder stringBuilder = new StringBuilder();
1120 while( ( line = reader.readLine() ) != null ) {
1121 stringBuilder.append( line );
1123 LOGwriteEndingTrace(responseCode, "SUCCESS", (stringBuilder.length() > 0) ? stringBuilder.toString() : "{no-data}");
1126 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
1127 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
1129 throw new AAIServiceException(responseCode, errorresponse);
1131 } catch(AAIServiceException aaiexc) {
1133 } catch (Exception exc) {
1134 LOG.warn("postPInterfaceData", exc);
1135 throw new AAIServiceException(exc);
1138 if(inputStream != null)
1139 inputStream.close();
1140 } catch (Exception exc) {
1147 public boolean deletePInterfaceData(String hostname, String interfaceName, String resourceVersion) throws AAIServiceException {
1148 boolean response = false;
1151 AAIRequest request = AAIRequest.getRequestFromResource("p-interface");
1152 request.addRequestProperty("p-interface.interface-name", interfaceName);
1153 request.addRequestProperty("pserver.hostname", hostname);
1154 response = executor.delete(request, resourceVersion);
1155 } catch(AAIServiceException aaiexc) {
1157 } catch (Exception exc) {
1158 LOG.warn("deletePInterfaceData", exc);
1159 throw new AAIServiceException(exc);
1163 //================== End of PInterface =================
1164 //==================== SitePairSet ======================
1166 public SitePairSet requestSitePairSetData(String sitePairSetId) throws AAIServiceException {
1167 SitePairSet response = null;
1170 AAIRequest request = AAIRequest.getRequestFromResource("site-pair-set");
1171 request.addRequestProperty("site-pair-set.site-pair-set-id", sitePairSetId);
1172 String rv = executor.get(request);
1174 ObjectMapper mapper = getObjectMapper();
1175 response = mapper.readValue(rv, SitePairSet.class);
1177 } catch(AAIServiceException aaiexc) {
1179 } catch (Exception exc) {
1180 LOG.warn(Object.class.getClass().getEnclosingMethod().getName(), exc);
1181 throw new AAIServiceException(exc);
1187 public boolean postSitePairSetData(String linkName, SitePairSet request) throws AAIServiceException {
1188 InputStream inputStream = null;
1192 ObjectMapper mapper = getObjectMapper();
1193 String json_text = mapper.writeValueAsString(request);
1195 SSLSocketFactory sockFact = CTX.getSocketFactory();
1197 String request_url = target_uri+site_pair_set_path;
1198 String encoded_vnf = encodeQuery(linkName);
1199 request_url = request_url.replace("{site-pair-set-id}", encoded_vnf) ;
1200 URL http_req_url = new URL(request_url);
1202 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.PUT);
1204 if (json_text != null) {
1205 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
1206 osw.write(json_text);
1211 LOGwriteFirstTrace("PUT", request_url);
1212 LOGwriteDateTrace("link-name", linkName);
1213 LOGwriteDateTrace("SitePairSet", json_text);
1216 int responseCode = con.getResponseCode();
1217 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1218 inputStream = con.getInputStream();
1220 inputStream = con.getErrorStream();
1223 // Process the response
1224 BufferedReader reader;
1226 reader = new BufferedReader( new InputStreamReader( inputStream ) );
1228 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1229 StringBuilder stringBuilder = new StringBuilder();
1231 while( ( line = reader.readLine() ) != null ) {
1232 stringBuilder.append( line );
1234 LOGwriteEndingTrace(responseCode, "SUCCESS", (stringBuilder.length() > 0) ? stringBuilder.toString() : "{no-data}");
1237 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
1238 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
1240 throw new AAIServiceException(responseCode, errorresponse);
1242 } catch(AAIServiceException aaiexc) {
1244 } catch (Exception exc) {
1245 LOG.warn("postSitePairSetData", exc);
1246 throw new AAIServiceException(exc);
1249 if(inputStream != null)
1250 inputStream.close();
1251 } catch (Exception exc) {
1258 public boolean deleteSitePairSetData(String linkName, String resourceVersion) throws AAIServiceException {
1259 boolean response = false;
1262 AAIRequest request = AAIRequest.getRequestFromResource("site-pair-set");
1263 request.addRequestProperty("site-pair-set.site-pair-set-id", linkName);
1264 response = executor.delete(request, resourceVersion);
1265 } catch(AAIServiceException aaiexc) {
1267 } catch (Exception exc) {
1268 LOG.warn("deleteSitePairSetData", exc);
1269 throw new AAIServiceException(exc);
1274 //================== End of SitePairSet =================
1275 //==================== Service ======================
1277 public Service requestServiceData(String serviceId) throws AAIServiceException {
1278 Service response = null;
1281 AAIRequest request = AAIRequest.getRequestFromResource("service");
1282 request.addRequestProperty("service.service-id", serviceId);
1285 String rv = executor.get(request);
1287 ObjectMapper mapper = getObjectMapper();
1288 response = mapper.readValue(rv, Service.class);
1290 } catch(AAIServiceException aaiexc) {
1292 } catch (Exception exc) {
1293 LOG.warn("requestServiceData", exc);
1294 throw new AAIServiceException(exc);
1300 public boolean postServiceData(String linkName, Service request) throws AAIServiceException {
1301 InputStream inputStream = null;
1305 ObjectMapper mapper = getObjectMapper();
1306 String json_text = mapper.writeValueAsString(request);
1308 SSLSocketFactory sockFact = CTX.getSocketFactory();
1310 String request_url = target_uri+service_path;
1311 String encoded_vnf = encodeQuery(linkName);
1312 request_url = request_url.replace("{service-id}", encoded_vnf) ;
1313 URL http_req_url = new URL(request_url);
1315 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.PUT);
1317 if (json_text != null) {
1318 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
1319 osw.write(json_text);
1324 LOGwriteFirstTrace("PUT", request_url);
1325 LOGwriteDateTrace("service-id", linkName);
1326 LOGwriteDateTrace("Service", json_text);
1329 int responseCode = con.getResponseCode();
1330 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1331 inputStream = con.getInputStream();
1333 inputStream = con.getErrorStream();
1336 // Process the response
1337 BufferedReader reader;
1339 reader = new BufferedReader( new InputStreamReader( inputStream ) );
1341 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1342 StringBuilder stringBuilder = new StringBuilder();
1344 while( ( line = reader.readLine() ) != null ) {
1345 stringBuilder.append( line );
1347 LOGwriteEndingTrace(responseCode, "SUCCESS", (stringBuilder.length() > 0) ? stringBuilder.toString() : "{no-data}");
1350 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
1351 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
1353 throw new AAIServiceException(responseCode, errorresponse);
1355 } catch(AAIServiceException aaiexc) {
1357 } catch (Exception exc) {
1358 LOG.warn("postServiceData", exc);
1359 throw new AAIServiceException(exc);
1362 if(inputStream != null)
1363 inputStream.close();
1364 } catch (Exception exc) {
1371 public boolean deleteServiceData(String service_id, String resourceVersion) throws AAIServiceException {
1372 boolean response = false;
1375 AAIRequest request = AAIRequest.getRequestFromResource("service");
1376 request.addRequestProperty("service.service-id", service_id);
1377 response = executor.delete(request, resourceVersion);
1378 } catch(AAIServiceException aaiexc) {
1380 } catch (Exception exc) {
1381 LOG.warn("deleteServiceData", exc);
1382 throw new AAIServiceException(exc);
1387 //================== End of Service =================
1391 public Vserver dataChangeRequestVServerData(URL url) throws AAIServiceException {
1394 throw new NullPointerException();
1397 return this.getResource(url.toString(), Vserver.class);
1401 public Pserver dataChangeRequestPServerData(URL url) throws AAIServiceException {
1404 throw new NullPointerException();
1407 return this.getResource(url.toString(), Pserver.class);
1411 public CtagPool dataChangeRequestCtagPoolData(URL url) throws AAIServiceException {
1414 throw new NullPointerException();
1417 return this.getResource(url.toString(), CtagPool.class);
1421 public VplsPe dataChangeRequestVplsPeData(URL url) throws AAIServiceException {
1424 throw new NullPointerException();
1427 return this.getResource(url.toString(), VplsPe.class);
1431 public DvsSwitch dataChangeRequestDvsSwitchData(URL url) throws AAIServiceException {
1434 throw new NullPointerException();
1437 return this.getResource(url.toString(), DvsSwitch.class);
1441 public OamNetwork dataChangeRequestOAMNetworkData(URL url) throws AAIServiceException {
1444 throw new NullPointerException();
1447 return this.getResource(url.toString(), OamNetwork.class);
1451 public AvailabilityZone dataChangeRequestAvailabilityZoneData(URL url) throws AAIServiceException {
1454 throw new NullPointerException();
1457 return this.getResource(url.toString(), AvailabilityZone.class);
1461 public Complex dataChangeRequestComplexData(URL url) throws AAIServiceException {
1464 throw new NullPointerException();
1467 return this.getResource(url.toString(), Complex.class);
1472 public boolean dataChangeDeleteVServerData(URL url) throws AAIServiceException {
1475 throw new NullPointerException();
1478 return deleteAAIEntity(url, Object.class.getClass().getEnclosingMethod()
1483 public boolean dataChangeDeleteCtagPoolData(URL url) throws AAIServiceException {
1486 throw new NullPointerException();
1489 return deleteAAIEntity(url, Object.class.getClass().getEnclosingMethod()
1494 public boolean dataChangeDeleteVplsPeData(URL url) throws AAIServiceException {
1497 throw new NullPointerException();
1500 return deleteAAIEntity(url, Object.class.getClass().getEnclosingMethod()
1505 public boolean dataChangeDeleteVpeData(URL url) throws AAIServiceException {
1508 throw new NullPointerException();
1511 return deleteAAIEntity(url, Object.class.getClass().getEnclosingMethod()
1516 public boolean dataChangeDeleteDvsSwitchData(URL url) throws AAIServiceException {
1519 throw new NullPointerException();
1522 return deleteAAIEntity(url, Object.class.getClass().getEnclosingMethod()
1527 public boolean dataChangeDeleteOAMNetworkData(URL url) throws AAIServiceException {
1530 throw new NullPointerException();
1533 return deleteAAIEntity(url, Object.class.getClass().getEnclosingMethod()
1536 //Availability-Zone:
1538 public boolean dataChangeDeleteAvailabilityZoneData(URL url) throws AAIServiceException {
1541 throw new NullPointerException();
1544 return deleteAAIEntity(url, Object.class.getClass().getEnclosingMethod()
1549 public boolean dataChangeDeleteComplexData(URL url) throws AAIServiceException {
1552 throw new NullPointerException();
1555 return deleteAAIEntity(url, Object.class.getClass().getEnclosingMethod()
1559 private boolean deleteAAIEntity(URL url, String caller) throws AAIServiceException {
1562 throw new NullPointerException();
1565 boolean response = false;
1566 InputStream inputStream = null;
1569 URL http_req_url = url;
1571 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.DELETE);
1573 LOGwriteFirstTrace("DELETE", http_req_url.toString());
1577 int responseCode = con.getResponseCode();
1578 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1579 inputStream = con.getInputStream();
1581 inputStream = con.getErrorStream();
1584 // Process the response
1585 LOG.debug("HttpURLConnection result:" + responseCode);
1586 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
1587 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
1590 ObjectMapper mapper = getObjectMapper();
1592 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1593 StringBuilder stringBuilder = new StringBuilder();
1595 while( ( line = reader.readLine() ) != null ) {
1596 stringBuilder.append( line );
1598 LOGwriteEndingTrace(responseCode, "SUCCESS", stringBuilder.toString());
1600 } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
1601 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
1604 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
1605 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
1606 throw new AAIServiceException(responseCode, errorresponse);
1609 } catch(AAIServiceException aaiexc) {
1611 } catch (Exception exc) {
1612 LOG.warn(caller, exc);
1613 throw new AAIServiceException(exc);
1615 if(inputStream != null){
1617 inputStream.close();
1618 } catch(Exception exc) {
1627 * Generic method to GET json data from an A&AI callback URL.
1628 * Then convert that json to an Object.
1629 * If successful the Object is attempted to be cast to the type parameter.
1632 * callback url for A&AI
1634 * the class of object that A&AI will return
1635 * @return the object created from json or null if the response code is not 200
1637 * @throws AAIServiceException
1638 * if empty or null key and or type or there's an error with processing
1640 public <T> T dataChangeRequestAaiData(String key, Class<T> type) throws AAIServiceException {
1641 if (StringUtils.isEmpty(key) || type == null) {
1642 throw new AAIServiceException("Key is empty or null and or type is null");
1647 SvcLogicContext ctx = new SvcLogicContext();
1648 if(!key.contains(" = ") && isValidURL(key)) {
1649 key = String.format("selflink = '%s'", key);
1651 if(!key.contains(" = ") && isValidURI(key)) {
1652 key = String.format("resource-path = '%s'", key);
1655 HashMap<String, String> nameValues = AAIServiceUtils.keyToHashMap(key, ctx);
1657 SelfLinkRequest request = new SelfLinkRequest(type);
1658 request.processRequestPathValues(nameValues);
1659 Object obj = this.getExecutor().query(request, type);
1660 response = type.cast(obj);
1662 return response != null ? type.cast(response) : response;
1666 public Pserver requestPServerData(String hostname) throws AAIServiceException {
1667 Pserver response = null;
1670 AAIRequest request = AAIRequest.getRequestFromResource("pserver");
1671 request.addRequestProperty("pserver.hostname", hostname);
1674 String rv = executor.get(request);
1676 ObjectMapper mapper = getObjectMapper();
1677 response = mapper.readValue(rv, Pserver.class);
1679 } catch(AAIServiceException aaiexc) {
1681 } catch (Exception exc) {
1682 LOG.warn("requestPServerData", exc);
1683 throw new AAIServiceException(exc);
1689 public boolean postPServerData(String hostname, Pserver data) throws AAIServiceException {
1691 AAIRequest request = AAIRequest.getRequestFromResource("pserver");
1692 request.addRequestProperty("pserver.hostname", hostname);
1693 request.setRequestObject(data);
1694 Object response = executor.post(request);
1696 } catch(AAIServiceException aaiexc) {
1698 } catch (Exception exc) {
1699 LOG.warn(Object.class.getClass().getEnclosingMethod().getName(), exc);
1700 throw new AAIServiceException(exc);
1705 public boolean deletePServerData(String hostname, String resourceVersion) throws AAIServiceException {
1706 boolean response = false;
1709 AAIRequest request = AAIRequest.getRequestFromResource("pserver");
1710 request.addRequestProperty("pserver.hostname", hostname);
1711 response = executor.delete(request, resourceVersion);
1712 } catch(AAIServiceException aaiexc) {
1714 } catch (Exception exc) {
1715 LOG.warn("deletePServerData", exc);
1716 throw new AAIServiceException(exc);
1724 public L3Network requestL3NetworkData(String networkId) throws AAIServiceException {
1725 L3Network response = null;
1728 AAIRequest request = AAIRequest.getRequestFromResource("l3-network");
1729 request.addRequestProperty("l3-network.network-id", networkId);
1731 String rv = executor.get(request);
1733 ObjectMapper mapper = getObjectMapper();
1734 response = mapper.readValue(rv, L3Network.class);
1736 } catch(AAIServiceException aaiexc) {
1738 } catch (Exception exc) {
1739 LOG.warn("requestL3NetworkData", exc);
1740 throw new AAIServiceException(exc);
1746 public L3Network requestL3NetworkQueryByName(String networkName) throws AAIServiceException {
1747 L3Network response = null;
1750 AAIRequest request = AAIRequest.getRequestFromResource("l3-network");
1751 request.addRequestProperty("l3-network.network-name", networkName);
1753 String rv = executor.get(request);
1755 ObjectMapper mapper = getObjectMapper();
1756 response = mapper.readValue(rv, L3Network.class);
1759 } catch(AAIServiceException aaiexc) {
1761 } catch (Exception exc) {
1762 LOG.warn("requestL3NetworkQueryByName", exc);
1763 throw new AAIServiceException(exc);
1769 public boolean postL3NetworkData(String networkId, L3Network data) throws AAIServiceException {
1771 AAIRequest request = AAIRequest.getRequestFromResource("l3-network");
1772 request.addRequestProperty("l3-network.network-id", networkId);
1773 request.setRequestObject(data);
1774 Object response = executor.post(request);
1776 } catch(AAIServiceException aaiexc) {
1778 } catch (Exception exc) {
1779 LOG.warn(Object.class.getClass().getEnclosingMethod().getName(), exc);
1780 throw new AAIServiceException(exc);
1785 public boolean deleteL3NetworkData(String networkId, String resourceVersion) throws AAIServiceException {
1786 boolean response = false;
1789 AAIRequest request = AAIRequest.getRequestFromResource("l3-network");
1790 request.addRequestProperty("l3-network.network-id", networkId);
1791 response = executor.delete(request, resourceVersion);
1792 } catch(AAIServiceException aaiexc) {
1794 } catch (Exception exc) {
1795 LOG.warn("deleteL3NetworkData", exc);
1796 throw new AAIServiceException(exc);
1804 public VpnBinding requestVpnBindingData(String vpnId) throws AAIServiceException {
1805 VpnBinding response = null;
1808 AAIRequest request = AAIRequest.getRequestFromResource("vpn-binding");
1809 request.addRequestProperty("vpn-binding.vpn-id", vpnId);
1811 String rv = executor.get(request);
1813 ObjectMapper mapper = getObjectMapper();
1814 response = mapper.readValue(rv, VpnBinding.class);
1816 } catch(AAIServiceException aaiexc) {
1818 } catch (Exception exc) {
1819 LOG.warn("requestVpnBindingData", exc);
1820 throw new AAIServiceException(exc);
1826 public boolean deleteVpnBindingData(String vpnId, String resourceVersion) throws AAIServiceException {
1827 boolean response = false;
1830 AAIRequest request = AAIRequest.getRequestFromResource("vpn-binding");
1831 request.addRequestProperty("vpn-binding.vpn-id", vpnId);
1832 response = executor.delete(request, resourceVersion);
1833 } catch(AAIServiceException aaiexc) {
1835 } catch (Exception exc) {
1836 LOG.warn("deleteVpnBindingData", exc);
1837 throw new AAIServiceException(exc);
1844 public VnfImage requestVnfImageData(String vnf_image_uuid) throws AAIServiceException {
1845 VnfImage response = null;
1848 AAIRequest request = AAIRequest.getRequestFromResource("vnf-image");
1849 request.addRequestProperty("vnf-image.vnf-image-uuid", vnf_image_uuid);
1851 String rv = executor.get(request);
1853 ObjectMapper mapper = getObjectMapper();
1854 response = mapper.readValue(rv, VnfImage.class);
1856 } catch(AAIServiceException aaiexc) {
1858 } catch (Exception exc) {
1859 LOG.warn("requestVnfImageData", exc);
1860 throw new AAIServiceException(exc);
1866 public VnfImage requestVnfImageDataByVendorModel(String vendor, String model) throws AAIServiceException {
1867 return requestVnfImageDataByVendorModelVersion(vendor, model, null);
1871 public VnfImage requestVnfImageDataByVendorModelVersion(String vendor, String model, String version) throws AAIServiceException
1873 List<VnfImage> responseList = new ArrayList<VnfImage>();
1874 VnfImage response = null;
1875 InputStream inputStream = null;
1878 String request_url = target_uri+vnf_image_query_path + (version==null? "": "&application-version={application_version}");
1879 request_url = request_url.replace("{application_vendor}", encodeQuery(vendor)) ;
1880 request_url = request_url.replace("{application_model}", encodeQuery(model)) ;
1881 if(version != null) {
1882 request_url = request_url.replace("{application_version}", encodeQuery(version)) ;
1884 URL http_req_url = new URL(request_url);
1886 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.GET);
1888 LOGwriteFirstTrace(HttpMethod.GET, http_req_url.toString());
1889 LOGwriteDateTrace("application_vendor", vendor);
1890 LOGwriteDateTrace("application_model", model);
1891 if(version != null) {
1892 LOGwriteDateTrace("application_version", version);
1896 int responseCode = con.getResponseCode();
1897 if (responseCode == HttpURLConnection.HTTP_OK) {
1898 inputStream = con.getInputStream();
1900 inputStream = con.getErrorStream();
1903 // Process the response
1904 LOG.debug("HttpURLConnection result:" + responseCode);
1905 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
1906 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
1908 ObjectMapper mapper = getObjectMapper();
1910 if (responseCode == HttpURLConnection.HTTP_OK) {
1911 response = mapper.readValue(reader, VnfImage.class);
1912 String original_buffer = mapper.writeValueAsString(response);
1913 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, "SUCCESS", original_buffer);
1914 if(response.getApplicationVendor() == null /*&& response.getAdditionalProperties() != null && !response.getAdditionalProperties().isEmpty()*/){
1915 LOG.warn("A List of multiple VNF-IMAGE entries has been returned");
1916 VnfImages listOfObjects = mapper.readValue(original_buffer, VnfImages.class);
1917 if(!listOfObjects.getVnfImage().isEmpty()) {
1918 response = listOfObjects.getVnfImage().get(0);
1921 } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
1922 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
1925 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
1926 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
1927 throw new AAIServiceException(responseCode, errorresponse);
1930 } catch(AAIServiceException aaiexc) {
1932 } catch (Exception exc) {
1933 LOG.warn("requestVnfImageData", exc);
1934 throw new AAIServiceException(exc);
1936 if(inputStream != null){
1938 inputStream.close();
1939 } catch(Exception exc) {
1948 public boolean sendNotify(NotifyEvent event, String serviceInstanceId, String pathCode) throws AAIServiceException {
1949 InputStream inputStream = null;
1953 String selfLink = selflink_fqdn;
1954 if(SELFLINK_AVPN != null && SELFLINK_AVPN.equals(pathCode)) {
1955 selfLink = selflink_avpn;
1957 selfLink = selfLink.replace("{service-instance-id}", encodeQuery(serviceInstanceId));
1958 event.setSelflink(selfLink);
1960 ObjectMapper mapper = getObjectMapper();
1961 String json_text = mapper.writeValueAsString(event);
1963 SSLSocketFactory sockFact = CTX.getSocketFactory();
1965 String request_url = target_uri+ubb_notify_path;
1966 URL http_req_url = new URL(request_url);
1968 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.PUT);
1970 if (json_text != null) {
1971 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
1972 osw.write(json_text);
1977 LOGwriteFirstTrace("PUT", request_url);
1978 LOGwriteDateTrace("NotifyEvent", json_text);
1981 int responseCode = con.getResponseCode();
1982 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1983 inputStream = con.getInputStream();
1985 inputStream = con.getErrorStream();
1988 // Process the response
1989 BufferedReader reader;
1991 reader = new BufferedReader( new InputStreamReader( inputStream ) );
1993 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1994 StringBuilder stringBuilder = new StringBuilder();
1996 while( ( line = reader.readLine() ) != null ) {
1997 stringBuilder.append( line );
1999 LOGwriteEndingTrace(responseCode, "SUCCESS", (stringBuilder.length() > 0) ? stringBuilder.toString() :
2003 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2004 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
2006 throw new AAIServiceException(responseCode, errorresponse);
2008 } catch(AAIServiceException aaiexc) {
2010 } catch (Exception exc) {
2011 LOG.warn("sendNotify", exc);
2012 throw new AAIServiceException(exc);
2015 if(inputStream != null)
2016 inputStream.close();
2017 } catch (Exception exc) {
2024 public SearchResults requestNodeQuery(String node_type, String entityIdentifier, String entityName) throws AAIServiceException {
2025 SearchResults response = null;
2026 InputStream inputStream = null;
2029 String request_url = target_uri+query_nodes_path;
2030 request_url = request_url.replace("{node-type}", encodeQuery(node_type)) ;
2031 request_url = request_url.replace("{entity-identifier}", entityIdentifier) ;
2032 request_url = request_url.replace("{entity-name}", encodeQuery(entityName)) ;
2033 URL http_req_url = new URL(request_url);
2035 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.GET);
2037 LOGwriteFirstTrace(HttpMethod.GET, http_req_url.toString());
2038 LOGwriteDateTrace("node_type", node_type);
2039 LOGwriteDateTrace("vnf_name", entityName);
2042 int responseCode = con.getResponseCode();
2043 if (responseCode == HttpURLConnection.HTTP_OK) {
2044 inputStream = con.getInputStream();
2046 inputStream = con.getErrorStream();
2049 // Process the response
2050 LOG.debug("HttpURLConnection result:" + responseCode);
2051 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
2052 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2054 ObjectMapper mapper = getObjectMapper();
2056 if (responseCode == HttpURLConnection.HTTP_OK) {
2057 response = mapper.readValue(reader, SearchResults.class);
2058 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, "SUCCESS", mapper.writeValueAsString(response));
2059 } else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
2060 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
2063 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2064 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
2065 throw new AAIServiceException(responseCode, errorresponse);
2068 } catch(AAIServiceException aaiexc) {
2070 } catch (Exception exc) {
2071 LOG.warn("requestNodeQuery", exc);
2072 throw new AAIServiceException(exc);
2074 if(inputStream != null){
2076 inputStream.close();
2077 } catch(Exception exc) {
2088 public String requestDataByURL(URL url) throws AAIServiceException {
2091 throw new NullPointerException();
2094 String response = null;
2095 InputStream inputStream = null;
2098 URL http_req_url = url;
2100 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.GET);
2102 LOGwriteFirstTrace(HttpMethod.GET, http_req_url.toString());
2105 int responseCode = con.getResponseCode();
2106 if (responseCode == HttpURLConnection.HTTP_OK) {
2107 inputStream = con.getInputStream();
2109 inputStream = con.getErrorStream();
2112 // Process the response
2113 LOG.debug("HttpURLConnection result:" + responseCode);
2114 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
2115 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2117 ObjectMapper mapper = getObjectMapper();
2119 if (responseCode == HttpURLConnection.HTTP_OK) {
2120 StringBuilder stringBuilder = new StringBuilder("\n");
2122 while( ( line = reader.readLine() ) != null ) {
2123 stringBuilder.append( line );
2125 LOG.info(stringBuilder.toString());
2126 // response = mapper.readValue(reader, String.class);
2127 response = stringBuilder.toString();
2128 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, "SUCCESS", mapper.writeValueAsString(response));
2129 } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
2130 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
2133 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2134 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
2135 throw new AAIServiceException(responseCode, errorresponse);
2138 } catch(AAIServiceException aaiexc) {
2140 } catch (Exception exc) {
2141 LOG.warn("requestNetworkVceData", exc);
2142 throw new AAIServiceException(exc);
2144 if(inputStream != null){
2146 inputStream.close();
2147 } catch(Exception exc) {
2157 public GenericVnf requestGenericVnfeNodeQuery(String vnf_name) throws AAIServiceException {
2159 if(vnf_name == null) {
2160 throw new NullPointerException();
2163 GenericVnf entity = null;
2164 SearchResults resp = this.requestNodeQuery("generic-vnf", "vnf-name", vnf_name);
2166 List<ResultData> resultDataList = resp.getResultData();
2169 for (ResultData datum : resultDataList) {
2170 String data_type = datum.getResourceType();
2171 URL url = new URL(datum.getResourceLink());
2172 entity = this.getResource(url.toString(), GenericVnf.class);
2177 LOG.error("Caught exception", e);
2183 public Vserver requestVServerDataByURL(URL url) throws AAIServiceException {
2186 throw new NullPointerException();
2189 Vserver entity = null;
2192 entity = this.getResource(url.toString(), Vserver.class);
2193 } catch (AAIServiceException exc) {
2195 } catch (Exception e) {
2196 throw new AAIServiceException(e);
2202 public URL requestVserverURLNodeQuery(String vserver_name) throws AAIServiceException {
2204 if(vserver_name == null) {
2205 throw new NullPointerException();
2209 SearchResults resp = this.requestNodeQuery("vserver", "vserver-name", vserver_name);
2211 List<ResultData> resultDataList = resp.getResultData();
2214 for (ResultData datum : resultDataList) {
2215 String data_type = datum.getResourceType();
2216 String resourceLink = datum.getResourceLink();
2217 if(!resourceLink.isEmpty() && !resourceLink.toLowerCase().startsWith("http")) {
2218 resourceLink = (new EchoRequest()).targetUri + resourceLink;
2220 entity = new URL(resourceLink);
2222 } catch (Exception e) {
2223 throw new AAIServiceException(e);
2228 class AAIRequestExecutor implements AAIExecutorInterface {
2231 public String get(AAIRequest request) throws AAIServiceException {
2232 String response = null;
2233 InputStream inputStream = null;
2234 HttpURLConnection con = null;
2235 URL requestUrl = null;
2237 String requestId = UUID.randomUUID().toString();
2238 StringBuilder errorStringBuilder = new StringBuilder();
2242 if(request.getRequestObject() != null) {
2243 requestUrl = request.getRequestUrl(HttpMethod.POST, null);
2244 requestUrl = appendDepth(requestUrl, request);
2245 con = getConfiguredConnection(requestUrl, HttpMethod.POST);
2246 String json_text = request.toJSONString();
2247 LOGwriteDateTrace("data", json_text);
2248 logMetricRequest(requestId, "POST "+requestUrl.getPath(), json_text, requestUrl.getPath());
2249 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
2250 osw.write(json_text);
2253 requestUrl = request.getRequestUrl(HttpMethod.GET, null);
2254 requestUrl = appendDepth(requestUrl, request);
2255 con = getConfiguredConnection(requestUrl, HttpMethod.GET);
2256 logMetricRequest(requestId, "GET "+requestUrl.getPath(), "", requestUrl.getPath());
2260 String responseMessage = con.getResponseMessage();
2261 int responseCode = con.getResponseCode();
2262 if (responseCode == HttpURLConnection.HTTP_OK) {
2263 inputStream = con.getInputStream();
2265 inputStream = con.getErrorStream();
2268 // Process the response
2269 LOG.debug("HttpURLConnection result:" + responseCode + " : " + responseMessage);
2270 logMetricResponse(requestId, responseCode, responseMessage);
2272 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
2273 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2275 ObjectMapper mapper = getObjectMapper();
2277 if (responseCode == HttpURLConnection.HTTP_OK) {
2278 StringBuilder stringBuilder = new StringBuilder();
2280 while( ( line = reader.readLine() ) != null ) {
2281 stringBuilder.append( line );
2283 response = stringBuilder.toString();
2285 Object object = mapper.readValue(response, Object.class);
2286 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, responseMessage, mapper.writeValueAsString(object));
2287 } catch(Exception exc) {
2288 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, responseMessage, mapper.writeValueAsString(response));
2290 } else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
2291 LOGwriteEndingTrace(responseCode, responseMessage, "Entry does not exist.");
2292 ErrorResponse errorresponse = null;
2294 errorresponse = mapper.readValue(reader, ErrorResponse.class);
2295 } catch(Exception exc) {
2296 errorresponse = new ErrorResponse();
2297 RequestError requestError = new RequestError();
2298 ServiceException serviceException = new ServiceException();
2299 serviceException.setText("Entry does not exist.");
2300 requestError.setServiceException(serviceException);
2301 errorresponse.setRequestError(requestError );
2303 throw new AAIServiceException(responseCode, errorresponse);
2304 } else if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
2305 StringBuilder stringBuilder = new StringBuilder();
2307 while( ( line = reader.readLine() ) != null ) {
2308 stringBuilder.append( line );
2310 LOGwriteEndingTrace(responseCode, responseMessage, stringBuilder.toString());
2311 ServiceException serviceException = new ServiceException();
2312 serviceException.setMessageId("HTTP_UNAUTHORIZED");
2313 serviceException.setText(stringBuilder.toString());
2314 RequestError requestError = new RequestError();
2315 requestError.setServiceException(serviceException);
2316 ErrorResponse errorresponse = new ErrorResponse();
2317 errorresponse.setRequestError(requestError);
2318 throw new AAIServiceException(responseCode, errorresponse);
2320 // StringBuilder errorStringBuilder = new StringBuilder();
2322 while( ( line = reader.readLine() ) != null ) {
2323 errorStringBuilder.append("\n").append( line );
2326 ErrorResponse errorresponse = mapper.readValue(errorStringBuilder.toString(), ErrorResponse.class);
2327 // ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2328 LOGwriteEndingTrace(responseCode, responseMessage, mapper.writeValueAsString(errorresponse));
2329 throw new AAIServiceException(responseCode, errorresponse);
2332 } catch(AAIServiceException aaiexc) {
2334 } catch (Exception exc) {
2335 LOG.warn(errorStringBuilder.toString(), exc);
2336 throw new AAIServiceException(exc);
2341 if(inputStream != null){
2343 inputStream.close();
2344 } catch(Exception exc) {
2352 private URL appendDepth(URL requestUrl, AAIRequest request) throws MalformedURLException {
2354 String depth = request.requestProperties.getProperty("depth", "1");
2355 String path = requestUrl.toString();
2356 if(path.contains("?depth=") || path.contains("&depth=")) {
2359 if(path.contains("?")) {
2360 path = String.format("%s&depth=%s", path, depth);
2362 path = String.format("%s?depth=%s", path, depth);
2364 return new URL(path);
2369 public String post(AAIRequest request) throws AAIServiceException {
2370 InputStream inputStream = null;
2371 String requestId = UUID.randomUUID().toString();
2372 HttpURLConnection con = null;
2375 String resourceVersion = null;
2376 AAIDatum instance = request.getRequestObject();
2378 Method getResourceVersionMethod = instance.getClass().getMethod("getResourceVersion");
2379 if(getResourceVersionMethod != null){
2381 getResourceVersionMethod.setAccessible(true);
2382 Object object = getResourceVersionMethod.invoke(instance);
2384 resourceVersion = object.toString();
2385 } catch (InvocationTargetException x) {
2386 Throwable cause = x.getCause();
2390 URL requestUrl = null;
2391 con = getConfiguredConnection(requestUrl = request.getRequestUrl(HttpMethod.PUT, resourceVersion), HttpMethod.PUT);
2392 ObjectMapper mapper = getObjectMapper();
2393 String json_text = request.toJSONString();
2395 LOGwriteDateTrace("data", json_text);
2396 logMetricRequest(requestId, "PUT "+requestUrl.getPath(), json_text, requestUrl.getPath());
2398 if (json_text != null) {
2399 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
2400 osw.write(json_text);
2404 String responseMessage = con.getResponseMessage();
2405 int responseCode = con.getResponseCode();
2406 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2407 inputStream = con.getInputStream();
2409 inputStream = con.getErrorStream();
2412 LOG.debug("HttpURLConnection result:" + responseCode + " : " + responseMessage);
2413 logMetricResponse(requestId,responseCode, responseMessage);
2415 // Process the response
2416 BufferedReader reader;
2418 reader = new BufferedReader( new InputStreamReader( inputStream ) );
2419 mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
2421 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2422 StringBuilder stringBuilder = new StringBuilder();
2424 while( ( line = reader.readLine() ) != null ) {
2425 stringBuilder.append( line );
2427 LOGwriteEndingTrace(responseCode, responseMessage, (stringBuilder != null) ? stringBuilder.toString() : "{no-data}");
2428 return stringBuilder.toString();
2430 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2431 LOGwriteEndingTrace(responseCode, responseMessage, mapper.writeValueAsString(errorresponse));
2433 throw new AAIServiceException(responseCode, errorresponse);
2435 } catch(AAIServiceException aaiexc) {
2437 } catch (Exception exc) {
2438 LOG.warn("AAIRequestExecutor.post", exc);
2439 throw new AAIServiceException(exc);
2445 if(inputStream != null)
2446 inputStream.close();
2447 } catch (Exception exc) {
2454 public Boolean delete(AAIRequest request, String resourceVersion) throws AAIServiceException {
2455 Boolean response = null;
2456 InputStream inputStream = null;
2457 String requestId = UUID.randomUUID().toString();
2459 if(resourceVersion == null) {
2460 throw new AAIServiceException("resource-version is required for DELETE request");
2464 URL requestUrl = null;
2465 HttpURLConnection conn = getConfiguredConnection(requestUrl = request.getRequestUrl(HttpMethod.DELETE, resourceVersion), HttpMethod.DELETE);
2466 logMetricRequest(requestId, "DELETE "+requestUrl.getPath(), "", requestUrl.getPath());
2467 conn.setDoOutput(true);
2470 String responseMessage = conn.getResponseMessage();
2471 int responseCode = conn.getResponseCode();
2472 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2473 inputStream = conn.getInputStream();
2475 inputStream = conn.getErrorStream();
2478 // Process the response
2479 LOG.debug("HttpURLConnection result:" + responseCode + " : " + responseMessage);
2480 logMetricResponse(requestId,responseCode, responseMessage);
2482 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
2483 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2486 ObjectMapper mapper = getObjectMapper();
2488 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2489 StringBuilder stringBuilder = new StringBuilder();
2491 while( ( line = reader.readLine() ) != null ) {
2492 stringBuilder.append( line );
2494 LOGwriteEndingTrace(responseCode, responseMessage, stringBuilder.toString());
2496 } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
2497 LOGwriteEndingTrace(responseCode, responseMessage, "Entry does not exist.");
2500 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2501 LOGwriteEndingTrace(responseCode, responseMessage, mapper.writeValueAsString(errorresponse));
2502 throw new AAIServiceException(responseCode, errorresponse);
2504 } catch(AAIServiceException aaiexc) {
2506 } catch (Exception exc) {
2507 LOG.warn("delete", exc);
2508 throw new AAIServiceException(exc);
2510 if(inputStream != null){
2512 inputStream.close();
2513 } catch(Exception exc) {
2522 public Object query(AAIRequest request, Class clas) throws AAIServiceException {
2523 Object response = null;
2524 InputStream inputStream = null;
2525 HttpURLConnection con = null;
2526 URL requestUrl = null;
2527 String requestId = UUID.randomUUID().toString();
2530 requestUrl = request.getRequestQueryUrl(HttpMethod.GET);
2531 con = getConfiguredConnection(requestUrl , HttpMethod.GET);
2532 logMetricRequest(requestId, "GET "+requestUrl.getPath(), "", requestUrl.getPath());
2535 String responseMessage = con.getResponseMessage();
2536 int responseCode = con.getResponseCode();
2537 if (responseCode == HttpURLConnection.HTTP_OK) {
2538 inputStream = con.getInputStream();
2540 inputStream = con.getErrorStream();
2543 logMetricResponse(requestId,responseCode, responseMessage);
2544 ObjectMapper mapper = getObjectMapper();
2546 if (responseCode == HttpURLConnection.HTTP_OK) {
2547 // Process the response
2548 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2549 response = mapper.readValue(reader, clas);
2550 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, "SUCCESS", mapper.writeValueAsString(response));
2551 } else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
2552 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
2555 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2556 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2557 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
2558 throw new AAIServiceException(responseCode, errorresponse);
2561 } catch(AAIServiceException aaiexc) {
2563 } catch (Exception exc) {
2564 LOG.warn("GET", exc);
2565 throw new AAIServiceException(exc);
2567 if(inputStream != null){
2569 inputStream.close();
2570 } catch(Exception exc) {
2582 public Boolean patch(AAIRequest request, String resourceVersion) throws AAIServiceException {
2583 InputStream inputStream = null;
2584 String requestId = UUID.randomUUID().toString();
2587 AAIDatum instance = request.getRequestObject();
2588 if(instance instanceof ResourceVersion) {
2589 resourceVersion = ((ResourceVersion)instance).getResourceVersion();
2592 URL requestUrl = null;
2593 HttpURLConnection con = getConfiguredConnection(requestUrl = request.getRequestUrl("PATCH", resourceVersion), "PATCH");
2594 ObjectMapper mapper = getObjectMapper();
2595 String json_text = request.toJSONString();
2597 LOGwriteDateTrace("data", json_text);
2598 logMetricRequest(requestId, "PATCH "+requestUrl.getPath(), json_text, requestUrl.getPath());
2600 if (json_text != null) {
2601 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
2602 osw.write(json_text);
2608 String responseMessage = con.getResponseMessage();
2609 int responseCode = con.getResponseCode();
2610 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2611 inputStream = con.getInputStream();
2613 inputStream = con.getErrorStream();
2616 LOG.info("HttpURLConnection result: " + responseCode + " : " + responseMessage);
2617 logMetricResponse(requestId,responseCode, responseMessage);
2619 // Process the response
2620 BufferedReader reader;
2622 reader = new BufferedReader( new InputStreamReader( inputStream ) );
2623 mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
2625 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2626 StringBuilder stringBuilder = new StringBuilder();
2628 while( ( line = reader.readLine() ) != null ) {
2629 stringBuilder.append( line );
2631 LOGwriteEndingTrace(responseCode, responseMessage,
2632 (stringBuilder.length() > 0) ? stringBuilder.toString() : "{no-data}");
2635 StringBuilder stringBuilder = new StringBuilder();
2637 while( ( line = reader.readLine() ) != null ) {
2638 stringBuilder.append("\n").append( line );
2640 LOG.info(stringBuilder.toString());
2643 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2644 LOGwriteEndingTrace(responseCode, responseMessage, mapper.writeValueAsString(errorresponse));
2646 throw new AAIServiceException(responseCode, errorresponse);
2648 } catch(AAIServiceException aaiexc) {
2650 } catch (Exception exc) {
2651 LOG.warn("AAIRequestExecutor.patch", exc);
2652 throw new AAIServiceException(exc);
2655 if(inputStream != null)
2656 inputStream.close();
2657 } catch (Exception exc) {
2665 public Tenant requestTenantData(String tenant_id, String cloudOwner, String cloudRegionId) throws AAIServiceException {
2666 Tenant response = null;
2669 AAIRequest request = AAIRequest.getRequestFromResource("tenant");
2670 request.addRequestProperty("tenant.tenant-id", tenant_id);
2671 request.addRequestProperty("cloud-region.cloud-owner", cloudOwner);
2672 request.addRequestProperty("cloud-region.cloud-region-id", cloudRegionId);
2674 String rv = executor.get(request);
2676 ObjectMapper mapper = getObjectMapper();
2677 response = mapper.readValue(rv, Tenant.class);
2679 } catch(AAIServiceException aaiexc) {
2681 } catch (Exception exc) {
2682 LOG.warn("requestTenantData", exc);
2683 throw new AAIServiceException(exc);
2690 public Tenant requestTenantDataByName(String tenant_name, String cloudOwner, String cloudRegionId) throws AAIServiceException {
2691 Tenant response = null;
2694 AAIRequest request = AAIRequest.getRequestFromResource("tenant");
2695 request.addRequestProperty("tenant.tenant-name", tenant_name);
2696 request.addRequestProperty("cloud-region.cloud-owner", cloudOwner);
2697 request.addRequestProperty("cloud-region.cloud-region-id", cloudRegionId);
2698 Object rv = executor.query(request, Tenant.class);
2700 return (Tenant)null;
2702 response = (Tenant)rv;
2703 } catch(AAIServiceException aaiexc) {
2705 } catch (Exception exc) {
2706 LOG.warn("requestTenantDataByName", exc);
2707 throw new AAIServiceException(exc);
2715 public boolean postTenantData(String tenant_id, String cloudOwner, String cloudRegionId, Tenant tenannt) throws AAIServiceException {
2717 AAIRequest request = AAIRequest.getRequestFromResource("tenant");
2718 request.addRequestProperty("tenant.tenant-id", tenant_id);
2719 request.addRequestProperty("cloud-region.cloud-owner", cloudOwner);
2720 request.addRequestProperty("cloud-region.cloud-region-id", cloudRegionId);
2721 request.setRequestObject(tenannt);
2722 Object response = executor.post(request);
2724 } catch(AAIServiceException aaiexc) {
2726 } catch (Exception exc) {
2727 LOG.warn("postTenantData", exc);
2728 throw new AAIServiceException(exc);
2734 public String getTenantIdFromVserverUrl(URL url) {
2736 String path = url.getPath();
2738 String[] split = path.split("/tenants/tenant/");
2739 if(split.length > 1) {
2740 split = split[1].split("/");
2748 public String getCloudOwnerFromVserverUrl(URL url) {
2750 String path = url.getPath();
2752 String[] split = path.split("/cloud-regions/cloud-region/");
2753 if(split.length > 1) {
2754 split = split[1].split("/");
2762 public String getCloudRegionFromVserverUrl(URL url) {
2764 String path = url.getPath();
2766 String[] split = path.split("/cloud-regions/cloud-region/");
2767 if(split.length > 1) {
2768 split = split[1].split("/");
2776 public String getVServerIdFromVserverUrl(URL url, String tenantId) {
2777 String pattern = networkVserverPath;
2778 pattern = pattern.replace("{tenant-id}", tenantId);
2780 int end = pattern.indexOf("{vserver-id}");
2781 String prefix = pattern.substring(0, end);
2783 String path = url.getPath();
2785 if(path.startsWith(prefix)) {
2786 path = path.substring(prefix.length());
2792 protected Logger getLogger(){
2798 public AAIRequestExecutor getExecutor() {
2803 * Creates a current time stamp in UTC i.e. 2016-03-08T22:15:13.343Z.
2804 * If there are any parameters the values are appended to the time stamp.
2807 * values to be appended to current time stamp
2809 * used to set an attribute for a DG
2810 * @throws SvcLogicException
2812 public void setStatusMethod(Map<String, String> parameters, SvcLogicContext ctx) throws SvcLogicException {
2814 throw new SvcLogicException("SvcLogicContext is null.");
2817 StringBuilder sb = new StringBuilder();
2818 sb.append(String.format("%tFT%<tTZ", Calendar.getInstance(TimeZone.getTimeZone("Z")))).append(" - ");
2820 for (Entry<String, String> entry : parameters.entrySet()) {
2821 sb.append(entry.getValue()).append(" ");
2824 if (sb.length() > 0) {
2825 sb.setLength(sb.length() - 2);
2828 ctx.setAttribute("aai-summary-status-message", sb.toString());
2829 LOG.info("aai-summary-status-message: " + sb.toString());
2833 * Generic method to GET json data from an A&AI using key structure.
2834 * Then convert that json to an Object.
2835 * If successful the Object is attempted to be cast to the type parameter.
2838 * key identifying the resource to be retrieved from AAI
2840 * the class of object that A&AI will return
2841 * @return the object created from json or null if the response code is not 200
2843 * @throws AAIServiceException
2844 * if empty or null key and or type or there's an error with processing
2847 public <T> T getResource(String key, Class<T> type) throws AAIServiceException {
2848 if (StringUtils.isEmpty(key) || type == null) {
2849 throw new AAIServiceException("Key is empty or null and or type is null");
2854 SvcLogicContext ctx = new SvcLogicContext();
2855 if(!key.contains(" = ")) {
2856 if(isValidURL(key)) {
2857 key = String.format("selflink = '%s'", key);
2858 } else if(isValidURI(key)) {
2859 key = String.format("resource-path = '%s'", key);
2865 HashMap<String, String> nameValues = AAIServiceUtils.keyToHashMap(key, ctx);
2867 AAIRequest request = new SelfLinkRequest(type);
2868 if(nameValues.containsKey(PathRequest.RESOURCE_PATH.replaceAll("-", "_"))) {
2869 request = new PathRequest(type);
2872 request.processRequestPathValues(nameValues);
2873 Object obj = this.getExecutor().query(request, type);
2874 response = type.cast(obj);
2876 return response != null ? type.cast(response) : response;
2879 public boolean isValidURL(String url) {
2885 } catch (MalformedURLException e) {
2891 } catch (URISyntaxException e) {
2899 public boolean isValidURI(String url) {
2905 } catch (URISyntaxException e) {
2913 protected boolean deleteList(URL httpReqUrl, String json_text) throws AAIServiceException {
2914 if(httpReqUrl == null) {
2915 throw new NullPointerException();
2918 boolean response = false;
2919 InputStream inputStream = null;
2922 HttpURLConnection con = getConfiguredConnection(httpReqUrl, HttpMethod.DELETE);
2924 // SSLSocketFactory sockFact = CTX.getSocketFactory();
2925 // con.setSSLSocketFactory( sockFact );
2926 if (json_text != null) {
2927 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
2928 osw.write(json_text);
2933 LOGwriteFirstTrace("DELETE", httpReqUrl.toString());
2934 LOGwriteDateTrace("data", json_text);
2937 int responseCode = con.getResponseCode();
2938 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2939 inputStream = con.getInputStream();
2941 inputStream = con.getErrorStream();
2944 // Process the response
2945 LOG.debug("HttpURLConnection result:" + responseCode);
2946 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
2947 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2950 ObjectMapper mapper = getObjectMapper();
2952 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2953 StringBuilder stringBuilder = new StringBuilder();
2955 while( ( line = reader.readLine() ) != null ) {
2956 stringBuilder.append( line );
2958 LOGwriteEndingTrace(responseCode, "SUCCESS", stringBuilder.toString());
2960 } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
2961 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
2964 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2965 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
2966 throw new AAIServiceException(responseCode, errorresponse);
2969 } catch(AAIServiceException aaiexc) {
2971 } catch (Exception exc) {
2972 LOG.warn("deleteList", exc);
2973 throw new AAIServiceException(exc);
2975 if(inputStream != null){
2977 inputStream.close();
2978 } catch(Exception exc) {
2986 public static ObjectMapper getObjectMapper() {
2987 ObjectMapper mapper = new ObjectMapper();
2988 AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance());
2989 AnnotationIntrospector secondary = new JacksonAnnotationIntrospector();
2990 mapper.setAnnotationIntrospector(AnnotationIntrospector.pair(introspector, secondary));
2991 mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
2992 mapper.setSerializationInclusion(Include.NON_NULL);
2996 public void logMetricRequest(String requestId, String targetServiceName, String msg, String path){
2997 String svcInstanceId = "";
2998 String svcName = null;
2999 String partnerName = null;
3000 String targetEntity = "A&AI";
3001 String targetVirtualEntity = null;
3003 targetServiceName = "";
3005 ml.logRequest(svcInstanceId, svcName, partnerName, targetEntity, targetServiceName, targetVirtualEntity, msg);
3008 public void logMetricResponse(String requestId, int responseCode, String responseDescription){
3009 ml.logResponse(responseCode < 400 ? "SUCCESS" : "FAILURE", Integer.toString(responseCode), responseDescription);
3012 public void logKeyError(String keys){
3013 LOG.error("Atleast one of the keys [" + keys + "] should have been populated. This will cause a NPE.");
3021 public QueryStatus save(String resource, boolean force, boolean localOnly, String key, Map<String, String> params, String prefix, SvcLogicContext ctx)
3022 throws SvcLogicException {
3023 String normResource = resource.split(":")[0];
3025 switch(normResource){
3026 case "custom-query":
3027 case "formatted-query":
3028 case "generic-query":
3032 case "l2-bridge-sbg":
3033 case "l2-bridge-bgf":
3039 if(key.contains("selflink =")) {
3042 if(!key.contains(String.format("%s.", normResource))) {
3043 key = rewriteKey(resource, key, ctx);
3046 return super.save(resource, force, localOnly, key, params, prefix, ctx);
3050 public QueryStatus query(String resource, boolean localOnly, String select, String key, String prefix, String orderBy, SvcLogicContext ctx)
3051 throws SvcLogicException {
3052 String normResource = resource.split(":")[0];
3054 switch(normResource){
3055 case "formatted-query":
3056 case "generic-query":
3060 case "l2-bridge-sbg":
3061 case "l2-bridge-bgf":
3067 if(key.contains("selflink =")) {
3070 if(!key.contains(String.format("%s.", normResource))) {
3071 key = rewriteKey(resource, key, ctx);
3075 return super.query(resource, localOnly, select, key, prefix, orderBy, ctx);
3079 public QueryStatus delete(String resource, String key, SvcLogicContext ctx) throws SvcLogicException {
3080 String normResource = resource.split(":")[0];
3082 switch(normResource){
3083 case "formatted-query":
3084 case "generic-query":
3088 case "l2-bridge-sbg":
3089 case "l2-bridge-bgf":
3095 if(key.contains("selflink =")) {
3098 if(!key.contains(String.format("%s.", normResource))) {
3099 key = rewriteKey(resource, key, ctx);
3103 return super.delete(resource, key, ctx);
3107 public QueryStatus update(String resource, String key, Map<String, String> params, String prefix, SvcLogicContext ctx) throws SvcLogicException {
3108 String normResource = resource.split(":")[0];
3110 switch(normResource){
3111 case "formatted-query":
3112 case "generic-query":
3116 case "l2-bridge-sbg":
3117 case "l2-bridge-bgf":
3123 if(key.contains("selflink =")) {
3126 if(!key.contains(String.format("%s.", normResource))) {
3127 key = rewriteKey(resource, key, ctx);
3131 return super.update(resource, key, params, prefix, ctx);
3134 private String rewriteKey(String resource, String key, SvcLogicContext ctx) {
3135 LOG.info("AAI Deprecation - the format of request key is no longer supported. Please rewrite this key : " + key);
3137 String normResource = resource.split(":")[0];
3138 Class<? extends AAIDatum> clazz = null;
3140 clazz = AAIRequest.getClassFromResource(normResource) ;
3141 } catch (ClassNotFoundException e) {
3142 LOG.warn("AAIRequest does not support class: " + e.getMessage());
3148 List<String> fieldAnnotatedNames = new LinkedList<>();
3150 Field[] fields = clazz.getDeclaredFields();
3151 for(Field field : fields) {
3152 String fieldName = field.getName();
3153 XmlElement annotation = field.getAnnotation(XmlElement.class);
3154 if(annotation == null)
3156 String primaryId = annotation.name();
3157 if("##default".equals(primaryId)) {
3158 primaryId = fieldName;
3160 fieldAnnotatedNames.add(primaryId);
3163 HashMap<String, String> nameValues = AAIServiceUtils.keyToHashMap(key, ctx);
3164 Set<String> keyset = nameValues.keySet();
3165 for(String keyName : keyset) {
3166 if(keyName.contains("."))
3169 String tmpKeyName = keyName.replaceAll("_", "-");
3170 String valueToSubstitute = String.format("%s =", tmpKeyName);
3171 if(fieldAnnotatedNames.contains(tmpKeyName) && key.contains(valueToSubstitute)) {
3172 key = key.replace(valueToSubstitute, String.format("%s.%s =", normResource, tmpKeyName));
3182 public String getPathTemplateForResource(String resoourceName, String keys, SvcLogicContext ctx) throws MalformedURLException {
3183 return AAIServiceUtils.getPathForResource(resoourceName, StringUtils.join(keys, " AND "), ctx);
3187 public boolean isDeprecatedFormat(String resource, HashMap<String, String> nameValues) {
3188 return !AAIServiceUtils.isValidFormat(resource, nameValues);
3191 public AAIRequest getRequestFromResource(String resoourceName) {
3192 return AAIRequest.getRequestFromResource(resoourceName);
3196 * @see org.openecomp.sdnc.sli.aai.haha#query(org.openecomp.sdnc.sli.aai.AAIRequest)
3199 public String query(AAIRequest request) throws AAIServiceException {
3200 return executor.get(request);
3204 * @see org.openecomp.sdnc.sli.aai.haha#save(org.openecomp.sdnc.sli.aai.AAIRequest)
3207 public String save(AAIRequest request) throws AAIServiceException {
3208 return executor.post(request);
3211 public boolean update(AAIRequest request, String resourceVersion) throws AAIServiceException {
3212 return executor.patch(request, resourceVersion);
3216 * @see org.openecomp.sdnc.sli.aai.haha#delete(org.openecomp.sdnc.sli.aai.AAIRequest, java.lang.String)
3219 public boolean delete(AAIRequest request, String resourceVersion) throws AAIServiceException {
3220 return executor.patch(request, resourceVersion);