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.ws.rs.core.UriBuilder;
71 import javax.xml.bind.annotation.XmlElement;
73 import org.apache.commons.codec.binary.Base64;
74 import org.apache.commons.lang3.StringUtils;
75 import org.onap.ccsdk.sli.core.sli.ConfigurationException;
76 import org.onap.ccsdk.sli.core.sli.MetricLogger;
77 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
78 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
79 import org.onap.ccsdk.sli.core.sli.SvcLogicResource;
80 import org.openecomp.aai.inventory.v11.AvailabilityZone;
81 import org.openecomp.aai.inventory.v11.Complex;
82 import org.openecomp.aai.inventory.v11.CtagPool;
83 import org.openecomp.aai.inventory.v11.DvsSwitch;
84 import org.openecomp.aai.inventory.v11.GenericVnf;
85 import org.openecomp.aai.inventory.v11.L3Network;
86 import org.openecomp.aai.inventory.v11.OamNetwork;
87 import org.openecomp.aai.inventory.v11.PInterface;
88 import org.openecomp.aai.inventory.v11.PhysicalLink;
89 import org.openecomp.aai.inventory.v11.Pserver;
90 import org.openecomp.aai.inventory.v11.ResultData;
91 import org.openecomp.aai.inventory.v11.SearchResults;
92 import org.openecomp.aai.inventory.v11.Service;
93 import org.openecomp.aai.inventory.v11.ServiceInstance;
94 import org.openecomp.aai.inventory.v11.SitePairSet;
95 import org.openecomp.aai.inventory.v11.Tenant;
96 import org.openecomp.aai.inventory.v11.Vce;
97 import org.openecomp.aai.inventory.v11.VnfImage;
98 import org.openecomp.aai.inventory.v11.VnfImages;
99 import org.openecomp.aai.inventory.v11.Vpe;
100 import org.openecomp.aai.inventory.v11.VplsPe;
101 import org.openecomp.aai.inventory.v11.VpnBinding;
102 import org.openecomp.aai.inventory.v11.Vserver;
103 import org.onap.ccsdk.sli.adaptors.aai.data.AAIDatum;
104 import org.onap.ccsdk.sli.adaptors.aai.data.ErrorResponse;
105 import org.onap.ccsdk.sli.adaptors.aai.data.RequestError;
106 import org.onap.ccsdk.sli.adaptors.aai.data.ResourceVersion;
107 import org.onap.ccsdk.sli.adaptors.aai.data.ServiceException;
108 import org.onap.ccsdk.sli.adaptors.aai.data.notify.NotifyEvent;
109 import org.onap.ccsdk.sli.adaptors.aai.data.v1507.VServer;
110 import org.slf4j.Logger;
111 import org.slf4j.LoggerFactory;
112 import org.slf4j.MDC;
114 import com.fasterxml.jackson.annotation.JsonInclude.Include;
115 import com.fasterxml.jackson.databind.AnnotationIntrospector;
116 import com.fasterxml.jackson.databind.DeserializationFeature;
117 import com.fasterxml.jackson.databind.ObjectMapper;
118 import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector;
119 import com.fasterxml.jackson.databind.type.TypeFactory;
120 import com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector;
121 import com.sun.jersey.api.client.config.DefaultClientConfig;
122 import com.sun.jersey.client.urlconnection.HTTPSProperties;
125 public class AAIService extends AAIDeclarations implements AAIClient, SvcLogicResource {
127 public static final String AAICLIENT_PROPERTIES = "/aaiclient.properties";
128 public static final String PATH_PROPERTIES = "/aai-path.properties";
130 private static final Logger LOG = LoggerFactory.getLogger(AAIService.class);
132 private final String truststore_path;
133 private final String truststore_password;
134 private final String keystore_path;
135 private final String keystore_password;
136 private final Boolean ignore_certificate_host_error;
138 private final String target_uri;
139 private final String query_path;
141 private final String network_vserver_path;
143 private final String svc_instance_path;
144 private final String svc_inst_qry_path;
146 private final String vnf_image_query_path;
148 private final String param_service_type; //= "service-type";
150 private final String ubb_notify_path;
151 private final String selflink_avpn;
152 private final String selflink_fqdn;
154 private final String p_interface_path;
156 private final String service_path;
157 private final String site_pair_set_path;
159 private final int connection_timeout;
160 private final int read_timeout;
163 private final String query_nodes_path;
164 private final String update_path;
166 private final String application_id;
168 // authentication credentials
169 private String user_name;
170 private String user_password;
173 private final boolean runtimeOSGI;
175 private SSLContext CTX;
177 private final MetricLogger ml = new MetricLogger();
179 private final AAIRequestExecutor executor;
181 public AAIService(URL propURL) {
182 LOG.info("Entered AAIService.ctor");
184 String runtime = System.getProperty("aaiclient.runtime");
185 if("OSGI".equals(runtime)) {
191 Properties props = null;
193 props = initialize(propURL);
194 AAIRequest.setProperties(props, this);
196 } catch(Exception exc){
197 LOG.error("AicAAIResource.static", exc);
200 executor = new AAIRequestExecutor();
202 user_name = props.getProperty(CLIENT_NAME);
203 user_password = props.getProperty(CLIENT_PWWD);
205 if(user_name == null || user_name.isEmpty()){
206 LOG.debug("Basic user name is not set");
208 if(user_password == null || user_password.isEmpty()) {
209 LOG.debug("Basic password is not set");
212 truststore_path = props.getProperty(TRUSTSTORE_PATH);
213 truststore_password = props.getProperty(TRUSTSTORE_PSSWD);
214 keystore_path = props.getProperty(KEYSTORE_PATH);
215 keystore_password = props.getProperty(KEYSTORE_PSSWD);
217 target_uri = props.getProperty(TARGET_URI);
218 query_path = props.getProperty(QUERY_PATH);
219 update_path = props.getProperty(UPDATE_PATH);
221 String applicationId =props.getProperty(APPLICATION_ID);
222 if(applicationId == null || applicationId.isEmpty()) {
223 applicationId = "SDNC";
225 application_id = applicationId;
227 // connection timeout
228 int tmpConnectionTimeout = 30000;
229 int tmpReadTimeout = 30000;
232 String tmpValue = null;
233 tmpValue = props.getProperty(CONNECTION_TIMEOUT, "30000");
234 tmpConnectionTimeout = Integer.parseInt(tmpValue);
235 tmpValue = props.getProperty(READ_TIMEOUT, "30000");
236 tmpReadTimeout = Integer.parseInt(tmpValue);
237 } catch(Exception exc) {
238 LOG.error("Failed setting connection timeout", exc);
239 tmpConnectionTimeout = 30000;
240 tmpReadTimeout = 30000;
242 connection_timeout = tmpConnectionTimeout;
243 read_timeout = tmpReadTimeout;
245 network_vserver_path =props.getProperty(NETWORK_VSERVER_PATH);
247 svc_instance_path = props.getProperty(SVC_INSTANCE_PATH);
248 svc_inst_qry_path = props.getProperty(SVC_INST_QRY_PATH);
249 param_service_type = props.getProperty(PARAM_SERVICE_TYPE, "service-type");
252 p_interface_path = props.getProperty(P_INTERFACE_PATH);
254 vnf_image_query_path = props.getProperty(VNF_IMAGE_QUERY_PATH);
256 ubb_notify_path = props.getProperty(UBB_NOTIFY_PATH);
257 selflink_avpn = props.getProperty(SELFLINK_AVPN);
258 selflink_fqdn = props.getProperty(SELFLINK_FQDN);
260 service_path = props.getProperty(SERVICE_PATH);
262 site_pair_set_path = props.getProperty(SITE_PAIR_SET_PATH);
264 query_nodes_path = props.getProperty(QUERY_NODES_PATH);
266 String iche = props.getProperty(CERTIFICATE_HOST_ERROR);
267 boolean host_error = false;
268 if(iche != null && !iche.isEmpty()) {
269 host_error = Boolean.valueOf(iche);
272 ignore_certificate_host_error = host_error;
274 HttpsURLConnection.setDefaultHostnameVerifier( new HostnameVerifier(){
275 public boolean verify(String string,SSLSession ssls) {
276 return ignore_certificate_host_error;
280 if(truststore_path != null && truststore_password != null && (new File(truststore_path)).exists()) {
281 System.setProperty("javax.net.ssl.trustStore", truststore_path);
282 System.setProperty("javax.net.ssl.trustStorePassword", truststore_password);
285 if(keystore_path != null && keystore_password != null && (new File(keystore_path)).exists()) {
286 DefaultClientConfig config = new DefaultClientConfig();
287 //both jersey and HttpURLConnection can use this
288 SSLContext ctx = null;
290 ctx = SSLContext.getInstance("TLS");
292 KeyManagerFactory kmf = null;
294 String def = "SunX509";
295 String storeType = "PKCS12";
296 def = KeyStore.getDefaultType();
297 kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
298 FileInputStream fin = new FileInputStream(keystore_path);
300 String extension = keystore_path.substring(keystore_path.lastIndexOf(".") + 1);
301 if("JKS".equalsIgnoreCase(extension)) {
304 KeyStore ks = KeyStore.getInstance(storeType);
306 char[] pwd = keystore_password.toCharArray();
309 } catch (Exception ex) {
310 LOG.error("AAIResource", ex);
313 ctx.init(kmf.getKeyManagers(), null, null);
314 config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties( new HostnameVerifier() {
316 public boolean verify( String s, SSLSession sslSession ) {
317 return ignore_certificate_host_error;
322 LOG.debug("SSLContext created");
324 } catch (KeyManagementException | NoSuchAlgorithmException exc) {
325 LOG.error("AAIResource", exc);
329 LOG.info("AAIResource.ctor initialized.");
332 Field methodsField = HttpURLConnection.class.getDeclaredField("methods");
333 methodsField.setAccessible(true);
334 // get the methods field modifiers
335 Field modifiersField = Field.class.getDeclaredField("modifiers");
336 // bypass the "private" modifier
337 modifiersField.setAccessible(true);
339 // remove the "final" modifier
340 modifiersField.setInt(methodsField, methodsField.getModifiers() & ~Modifier.FINAL);
342 /* valid HTTP methods */
344 "GET", "POST", "HEAD", "OPTIONS", "PUT", "DELETE", "TRACE", "PATCH"
346 // set the new methods - including patch
347 methodsField.set(null, methods);
349 } catch (SecurityException | IllegalArgumentException | IllegalAccessException | NoSuchFieldException e) {
355 public void cleanUp() {
361 * @param http_req_url
366 protected HttpURLConnection getConfiguredConnection(URL http_req_url, String method) throws Exception {
367 HttpURLConnection con = (HttpURLConnection) http_req_url.openConnection();
369 // Set up the connection properties
370 con.setRequestProperty( "Connection", "close" );
371 con.setDoInput(true);
372 con.setDoOutput(true);
373 con.setUseCaches(false);
374 con.setConnectTimeout( connection_timeout );
375 con.setReadTimeout( read_timeout );
376 con.setRequestMethod( method );
377 con.setRequestProperty( "Accept", "application/json" );
378 con.setRequestProperty( "Content-Type", "PATCH".equalsIgnoreCase(method) ? "application/merge-patch+json" : "application/json" );
379 con.setRequestProperty("X-FromAppId", application_id);
380 con.setRequestProperty("X-TransactionId",TransactionIdTracker.getNextTransactionId());
381 String mlId = ml.getRequestID();
382 if(mlId != null && !mlId.isEmpty()) {
383 LOG.debug(String.format("MetricLogger requestId = %s", mlId));
384 con.setRequestProperty(MetricLogger.REQUEST_ID, mlId);
386 LOG.debug("MetricLogger requestId is null");
389 if(user_name != null && !user_name.isEmpty() && user_password != null && !user_password.isEmpty()) {
390 String basicAuth = "Basic " + new String(Base64.encodeBase64((user_name + ":" + user_password).getBytes()));
391 con.setRequestProperty ("Authorization", basicAuth);
394 if(con instanceof HttpsURLConnection && CTX != null) {
395 SSLSocketFactory sockFact = CTX.getSocketFactory();
396 HttpsURLConnection.class.cast(con).setSSLSocketFactory( sockFact );
403 public GenericVnf requestGenericVnfData(String vnf_id) throws AAIServiceException {
404 GenericVnf response = null;
407 AAIRequest request = AAIRequest.getRequestFromResource("generic-vnf");
408 request.addRequestProperty("generic-vnf.vnf-id", vnf_id);
409 String rv = executor.get(request);
411 ObjectMapper mapper = getObjectMapper();
412 response = mapper.readValue(rv, GenericVnf.class);
414 } catch(AAIServiceException aaiexc) {
416 } catch (Exception exc) {
417 LOG.warn(Object.class.getClass().getEnclosingMethod().getName(), exc);
418 throw new AAIServiceException(exc);
426 public boolean postGenericVnfData(String vnf_id, GenericVnf data) throws AAIServiceException {
428 AAIRequest request = AAIRequest.getRequestFromResource("generic-vnf");
429 request.addRequestProperty("generic-vnf.vnf-id", vnf_id);
430 request.setRequestObject(data);
431 Object response = executor.post(request);
433 } catch(AAIServiceException aaiexc) {
435 } catch (Exception exc) {
436 LOG.warn("requestGenericVnfData", exc);
437 throw new AAIServiceException(exc);
442 public boolean deleteGenericVnfData(String vnf_id, String resourceVersion) throws AAIServiceException {
443 boolean response = false;
446 AAIRequest request = AAIRequest.getRequestFromResource("generic-vnf");
447 request.addRequestProperty("generic-vnf.vnf-id", vnf_id);
448 response = executor.delete(request, resourceVersion);
449 } catch(AAIServiceException aaiexc) {
451 } catch (Exception exc) {
452 LOG.warn("deleteGenericVnfData", exc);
453 throw new AAIServiceException(exc);
459 * @see org.onap.ccsdk.sli.adaptors.resource.aic.AnAIClient#requestSdnZoneQuery(java.lang.String, java.lang.String, java.lang.String)
462 public Vce requestNetworkVceData(String vnf_id) throws AAIServiceException {
465 AAIRequest request = AAIRequest.getRequestFromResource("vce");
466 request.addRequestProperty("vce.vnf-id", vnf_id);
467 String rv = executor.get(request);
469 ObjectMapper mapper = getObjectMapper();
470 response = mapper.readValue(rv, Vce.class);
472 } catch(AAIServiceException aaiexc) {
474 } catch (Exception exc) {
475 LOG.warn(Object.class.getClass().getEnclosingMethod().getName(), exc);
476 throw new AAIServiceException(exc);
484 * @see org.onap.ccsdk.sli.adaptors.resource.aic.AnAIClient#requestSdnZoneQuery(java.lang.String, java.lang.String, java.lang.String)
487 public boolean deleteNetworkVceData(String vnf_id, String resourceVersion) throws AAIServiceException {
488 boolean response = false;
491 AAIRequest request = AAIRequest.getRequestFromResource("vce");
492 request.addRequestProperty("vce.vnf-id", vnf_id);
493 response = executor.delete(request, resourceVersion);
494 } catch(AAIServiceException aaiexc) {
496 } catch (Exception exc) {
497 LOG.warn("deleteNetworkVceData", exc);
498 throw new AAIServiceException(exc);
504 * @see org.onap.ccsdk.sli.adaptors.resource.aic.AnAIClient#postNetworkVceData(java.lang.String, org.onap.ccsdk.sli.adaptors.resource.aic.aai.VCERequest)
507 public boolean postNetworkVceData(String vnf_id, Vce data) throws AAIServiceException {
509 AAIRequest request = AAIRequest.getRequestFromResource("vce");
510 request.addRequestProperty("vce.vnf-id", vnf_id);
511 request.setRequestObject(data);
512 Object response = executor.post(request);
514 } catch(AAIServiceException aaiexc) {
516 } catch (Exception exc) {
517 LOG.warn("requestGenericVnfData", exc);
518 throw new AAIServiceException(exc);
524 public SearchResults requestServiceInstanceURL(String svc_instance_id) throws AAIServiceException {
525 SearchResults response = null;
526 InputStream inputStream = null;
529 String path = svc_inst_qry_path;
530 path = path.replace("{svc-instance-id}", encodeQuery(svc_instance_id));
532 String request_url = target_uri+path;
533 URL http_req_url = new URL(request_url);
535 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.GET);
537 LOGwriteFirstTrace(HttpMethod.GET, http_req_url.toString());
538 LOGwriteDateTrace("svc_instance_id", svc_instance_id);
541 int responseCode = con.getResponseCode();
542 if (responseCode == HttpURLConnection.HTTP_OK) {
543 inputStream = con.getInputStream();
545 inputStream = con.getErrorStream();
548 // Process the response
549 LOG.debug("HttpURLConnection result:" + responseCode);
550 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
551 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
553 ObjectMapper mapper = getObjectMapper();
555 if (responseCode == HttpURLConnection.HTTP_OK) {
556 response = mapper.readValue(reader, SearchResults.class);
557 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, "SUCCESS", mapper.writeValueAsString(response));
558 } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
559 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
562 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
563 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
564 throw new AAIServiceException(responseCode, errorresponse);
567 } catch(AAIServiceException aaiexc) {
569 } catch (Exception exc) {
570 LOG.warn("requestServiceInstanceURL", exc);
571 throw new AAIServiceException(exc);
573 if(inputStream != null){
576 } catch(Exception exc) {
584 public ServiceInstance requestServiceInterfaceData(String customer_id, String service_type, String svc_instance_id) throws AAIServiceException {
585 ServiceInstance response = null;
588 AAIRequest request = AAIRequest.getRequestFromResource("service-instance");
589 request.addRequestProperty("customer.global-customer-id", customer_id);
590 request.addRequestProperty("service-subscription.service-type", service_type);
591 request.addRequestProperty("service-instance.service-instance-id", svc_instance_id);
593 String rv = executor.get(request);
595 ObjectMapper mapper = getObjectMapper();
596 response = mapper.readValue(rv, ServiceInstance.class);
598 } catch(AAIServiceException aaiexc) {
600 } catch (Exception exc) {
601 LOG.warn("requestServiceInterfaceData", exc);
602 throw new AAIServiceException(exc);
608 public boolean postServiceInterfaceData(String customer_id, String service_type, String svc_instance_id, ServiceInstance data) throws AAIServiceException {
610 AAIRequest request = AAIRequest.getRequestFromResource("service-instance");
611 request.addRequestProperty("customer.global-customer-id", customer_id);
612 request.addRequestProperty("service-subscription.service-type", service_type);
613 request.addRequestProperty("service-instance.service-instance-id", svc_instance_id);
614 request.setRequestObject(data);
615 Object response = executor.post(request);
617 } catch(AAIServiceException aaiexc) {
619 } catch (Exception exc) {
620 LOG.warn("requestGenericVnfData", exc);
621 throw new AAIServiceException(exc);
626 private static Properties initialize(URL url ) throws ConfigurationException {
629 throw new NullPointerException();
632 InputStream is = null;
633 Properties props = new Properties();
636 if(LOG.isDebugEnabled())
637 LOG.info("Property file is: " + url.toString());
639 is = url.openStream();
642 if(LOG.isDebugEnabled()) {
643 LOG.info("Properties loaded: " + props.size());
644 Enumeration<Object> en = props.keys();
646 while(en.hasMoreElements()) {
647 String key = (String)en.nextElement();
648 String property = props.getProperty(key);
649 LOG.debug(key + " : " + property);
652 } catch (Exception e) {
653 throw new ConfigurationException("Could not load properties file.", e);
658 static class TransactionIdTracker {
659 // protected static AtomicLong tracker = new AtomicLong();
661 public static String getNextTransactionId() {
662 // Check if RequestId exists as MDC. If not, create new.
663 String transactionId = MDC.get("RequestId");
664 if ("".equals(transactionId) || transactionId == null) {
665 transactionId = UUID.randomUUID().toString();
666 LOG.info("Missing requestID. Assigned " + transactionId);
667 MDC.put("RequestId", transactionId);
669 return transactionId;
674 protected void LOGwriteFirstTrace(String method, String url) {
675 String time = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").format(System.currentTimeMillis());
676 LOG.info("A&AI transaction :");
677 LOG.info("Request Time : " + time + ", Method : " + method);
678 LOG.info("Request URL : "+ url);
681 protected void LOGwriteDateTrace(String name, String data) {
682 LOG.info("Input - " + name + " : " + data);
685 protected void LOGwriteEndingTrace(int response_code, String comment, String data) {
686 LOG.info("Response code : " + response_code +", " + comment);
687 LOG.info(String.format("Response data : %s", data));
690 protected String encodeQuery(String param) throws UnsupportedEncodingException {
691 return URLEncoder.encode(param, "UTF-8").replace("+", "%20");
694 private String encodeCustomerURL(final String selection)
696 String encrypted_url = selection;
698 "/aai/v11/business/customers/customer/(.+)/service-subscriptions/service-subscription/(.+)/service-instances/service-instance/(.+)/";
699 Pattern pattern = Pattern.compile(apnpattern);
702 URL url = new URL(selection);
703 String path = url.getPath();
705 LOG.info("Trying to match apn to <" + path + ">");
707 Matcher matcher = pattern.matcher(path);
709 while(matcher.find()) {
710 String customer = matcher.group(1);
711 String subscription = matcher.group(2);
712 String service = matcher.group(3);
714 encrypted_url = selection.replace(customer, encodeQuery(customer));
715 encrypted_url = encrypted_url.replace(subscription, encodeQuery(subscription));
716 encrypted_url = encrypted_url.replace(service, encodeQuery(service));
718 } catch (Exception e) {
722 return encrypted_url;
726 public VplsPe requestNetworkVplsPeData(String equipment_name)throws AAIServiceException {
727 VplsPe response = null;
730 AAIRequest request = AAIRequest.getRequestFromResource("vpls-pe");
731 request.addRequestProperty("vpls-pe.equipment-name", equipment_name);
733 String rv = executor.get(request);
735 ObjectMapper mapper = getObjectMapper();
736 response = mapper.readValue(rv, VplsPe.class);
738 } catch(AAIServiceException aaiexc) {
740 } catch (Exception exc) {
741 LOG.warn(Object.class.getClass().getEnclosingMethod().getName(),
743 throw new AAIServiceException(exc);
749 public boolean postNetworkVplsPeData(String equipment_name, VplsPe data) throws AAIServiceException {
751 AAIRequest request = AAIRequest.getRequestFromResource("vpls-pe");
752 request.addRequestProperty("vpls-pe.equipment-name", equipment_name);
753 request.setRequestObject(data);
754 Object response = executor.post(request);
756 } catch(AAIServiceException aaiexc) {
758 } catch (Exception exc) {
759 LOG.warn("requestGenericVnfData", exc);
760 throw new AAIServiceException(exc);
765 public boolean deleteNetworkVplsPeData(String vnf_id, String resourceVersion) throws AAIServiceException {
766 boolean response = false;
769 AAIRequest request = AAIRequest.getRequestFromResource("vpls-pe");
770 request.addRequestProperty("vpls-pe.equipment-name", vnf_id);
771 response = executor.delete(request, resourceVersion);
772 } catch(AAIServiceException aaiexc) {
774 } catch (Exception exc) {
775 LOG.warn("deleteNetworkVplsPeData", exc);
776 throw new AAIServiceException(exc);
782 public Complex requestNetworkComplexData(String pLocId) throws AAIServiceException {
783 Complex response = null;
786 AAIRequest request = AAIRequest.getRequestFromResource("complex");
787 request.addRequestProperty("complex.physical-location-id", pLocId);
789 String rv = executor.get(request);
791 ObjectMapper mapper = getObjectMapper();
792 response = mapper.readValue(rv, Complex.class);
794 } catch(AAIServiceException aaiexc) {
796 } catch (Exception exc) {
797 LOG.warn("requestNetworkComplexData", exc);
798 throw new AAIServiceException(exc);
804 public boolean postNetworkComplexData(String vnf_id, Complex data) throws AAIServiceException {
806 AAIRequest request = AAIRequest.getRequestFromResource("complex");
807 request.addRequestProperty("complex.physical-location-id", vnf_id);
808 request.setRequestObject(data);
809 Object response = executor.post(request);
811 } catch(AAIServiceException aaiexc) {
813 } catch (Exception exc) {
814 LOG.warn("postNetworkComplexData", exc);
815 throw new AAIServiceException(exc);
820 public boolean deleteNetworkComplexData(String pLocId, String resourceVersion) throws AAIServiceException {
821 boolean response = false;
824 AAIRequest request = AAIRequest.getRequestFromResource("complex");
825 request.addRequestProperty("complex.physical-location-id", pLocId);
827 response = executor.delete(request, resourceVersion);
829 } catch(AAIServiceException aaiexc) {
831 } catch (Exception exc) {
832 LOG.warn("deleteNetworkComplexData", exc);
833 throw new AAIServiceException(exc);
840 * @see org.openecomp.sdnct.sli.aai.AAIClient#requestVServersData(java.lang.String, java.lang.String)
843 public Vserver requestVServerData(String tenantId, String vserverId, String cloudOwner, String cloudRegionId) throws AAIServiceException {
844 Vserver response = null;
847 AAIRequest request = AAIRequest.getRequestFromResource("vserver");
848 request.addRequestProperty("cloud-region.cloud-owner", cloudOwner);
849 request.addRequestProperty("cloud-region.cloud-region-id", cloudRegionId);
850 request.addRequestProperty("tenant.tenant-id", tenantId);
851 request.addRequestProperty("vserver.vserver-id", vserverId);
853 String rv = executor.get(request);
855 ObjectMapper mapper = getObjectMapper();
856 response = mapper.readValue(rv, Vserver.class);
858 } catch(AAIServiceException aaiexc) {
860 } catch (Exception exc) {
861 LOG.warn(Object.class.getClass().getEnclosingMethod().getName(), exc);
862 throw new AAIServiceException(exc);
869 public boolean postVServerData(String tenantId, String vserverId, String cloudOwner, String cloudRegionId, Vserver data) throws AAIServiceException {
871 AAIRequest request = AAIRequest.getRequestFromResource("vserver");
872 request.addRequestProperty("cloud-region.cloud-owner", cloudOwner);
873 request.addRequestProperty("cloud-region.cloud-region-id", cloudRegionId);
874 request.addRequestProperty("tenant.tenant-id", tenantId);
875 request.addRequestProperty("vserver.vserver-id", vserverId);
876 request.setRequestObject(data);
877 Object response = executor.post(request);
879 } catch(AAIServiceException aaiexc) {
881 } catch (Exception exc) {
882 LOG.warn("postNetworkComplexData", exc);
883 throw new AAIServiceException(exc);
888 public boolean deleteVServerData(String tenant_id, String vserver_id, String cloudOwner, String cloudRegionId, String resourceVersion) throws AAIServiceException {
889 boolean response = false;
890 InputStream inputStream = null;
893 String local_network_complexes_path = network_vserver_path.replace("{tenant-id}", encodeQuery(tenant_id));
894 local_network_complexes_path = local_network_complexes_path.replace("{vserver-id}", encodeQuery(vserver_id));
895 local_network_complexes_path = local_network_complexes_path.replace("{cloud-owner}", encodeQuery(cloudOwner));
896 local_network_complexes_path = local_network_complexes_path.replace("{cloud-region-id}", encodeQuery(cloudRegionId));
898 String request_url = target_uri+local_network_complexes_path;
899 if(resourceVersion!=null) {
900 request_url = request_url +"?resource-version="+resourceVersion;
902 URL http_req_url = new URL(request_url);
904 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.DELETE);
906 LOGwriteFirstTrace(HttpMethod.DELETE, http_req_url.toString());
907 LOGwriteDateTrace("tenant_id", tenant_id);
908 LOGwriteDateTrace("vserver_id", vserver_id);
909 LOGwriteDateTrace("cloud-owner", cloudOwner);
910 LOGwriteDateTrace("cloud-region-id", cloudRegionId);
913 int responseCode = con.getResponseCode();
914 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
915 inputStream = con.getInputStream();
917 inputStream = con.getErrorStream();
920 // Process the response
921 LOG.debug("HttpURLConnection result:" + responseCode);
922 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
923 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
926 ObjectMapper mapper = getObjectMapper();
928 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
929 StringBuilder stringBuilder = new StringBuilder();
931 while( ( line = reader.readLine() ) != null ) {
932 stringBuilder.append( line );
934 LOGwriteEndingTrace(responseCode, "SUCCESS", stringBuilder.toString());
936 } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
937 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
940 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
941 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
942 throw new AAIServiceException(responseCode, errorresponse);
945 } catch(AAIServiceException aaiexc) {
947 } catch (Exception exc) {
948 LOG.warn("deleteVServerData", exc);
949 throw new AAIServiceException(exc);
951 if(inputStream != null){
954 } catch(Exception exc) {
965 * @see org.onap.ccsdk.sli.adaptors.aai.AAIClient#requestCtagPoolData(String)
968 public CtagPool requestCtagPoolData(String physical_location_id, String target_pe, String availability_zone_name) throws AAIServiceException {
969 CtagPool response = null;
972 AAIRequest request = AAIRequest.getRequestFromResource("ctag-pool");
974 request.addRequestProperty("ctag-pool.target-pe", target_pe);
975 request.addRequestProperty("ctag-pool.availability-zone-name", availability_zone_name);
976 request.addRequestProperty("complex.physical-location-id", physical_location_id);
978 String rv = executor.get(request);
980 ObjectMapper mapper = getObjectMapper();
981 response = mapper.readValue(rv, CtagPool.class);
983 } catch(AAIServiceException aaiexc) {
985 } catch (Exception exc) {
986 LOG.warn("requestNetworkVceData", exc);
987 throw new AAIServiceException(exc);
992 //==================== DvsSwitch ======================
994 public DvsSwitch requestDvsSwitchData(String vnf_id) throws AAIServiceException {
995 DvsSwitch response = null;
998 AAIRequest request = AAIRequest.getRequestFromResource("dvs-switch");
999 request.addRequestProperty("dvs-switch.switch-name", vnf_id);
1001 String rv = executor.get(request);
1003 ObjectMapper mapper = getObjectMapper();
1004 response = mapper.readValue(rv, DvsSwitch.class);
1006 } catch(AAIServiceException aaiexc) {
1008 } catch (Exception exc) {
1009 LOG.warn("requestDvsSwitchData", exc);
1010 throw new AAIServiceException(exc);
1016 public boolean postDvsSwitchData(String switch_name, DvsSwitch data) throws AAIServiceException {
1018 AAIRequest request = AAIRequest.getRequestFromResource("dvs-switch");
1019 request.addRequestProperty("dvs-switch.switch-name", switch_name);
1020 request.setRequestObject(data);
1021 Object response = executor.post(request);
1023 } catch(AAIServiceException aaiexc) {
1025 } catch (Exception exc) {
1026 LOG.warn(Object.class.getClass().getEnclosingMethod().getName(), exc);
1027 throw new AAIServiceException(exc);
1032 public boolean deleteDvsSwitchData(String vnf_id, String resourceVersion) throws AAIServiceException {
1033 boolean response = false;
1036 AAIRequest request = AAIRequest.getRequestFromResource("dvs-switch");
1037 request.addRequestProperty("dvs-switch.switch-name", vnf_id);
1038 response = executor.delete(request, resourceVersion);
1039 } catch(AAIServiceException aaiexc) {
1041 } catch (Exception exc) {
1042 LOG.warn("deleteDvsSwitchData", exc);
1043 throw new AAIServiceException(exc);
1047 //================== End of DvsSwitch =================
1048 //==================== PhysicalLink ======================
1050 public PhysicalLink requestPhysicalLinkData(String linkName) throws AAIServiceException {
1051 PhysicalLink response = null;
1054 AAIRequest request = AAIRequest.getRequestFromResource("physical-link");
1055 request.addRequestProperty("physical-link.link-name", linkName);
1057 String rv = executor.get(request);
1059 ObjectMapper mapper = getObjectMapper();
1060 response = mapper.readValue(rv, PhysicalLink.class);
1062 } catch(AAIServiceException aaiexc) {
1064 } catch (Exception exc) {
1065 LOG.warn("requestPhysicalLinkData", exc);
1066 throw new AAIServiceException(exc);
1072 public boolean postPhysicalLinkData(String linkName, PhysicalLink data) throws AAIServiceException {
1074 AAIRequest request = AAIRequest.getRequestFromResource("physical-link");
1075 request.addRequestProperty("physical-link.link-name", linkName);
1076 request.setRequestObject(data);
1077 Object response = executor.post(request);
1079 } catch(AAIServiceException aaiexc) {
1081 } catch (Exception exc) {
1082 LOG.warn(Object.class.getClass().getEnclosingMethod().getName(), exc);
1083 throw new AAIServiceException(exc);
1088 public boolean deletePhysicalLinkData(String linkName, String resourceVersion) throws AAIServiceException {
1089 boolean response = false;
1092 AAIRequest request = AAIRequest.getRequestFromResource("physical-link");
1093 request.addRequestProperty("physical-link.link-name", linkName);
1094 response = executor.delete(request, resourceVersion);
1095 } catch(AAIServiceException aaiexc) {
1097 } catch (Exception exc) {
1098 LOG.warn("deletePhysicalLinkData", exc);
1099 throw new AAIServiceException(exc);
1103 //================== End of PhysicalLink =================
1104 //==================== PInterface ======================
1106 public PInterface requestPInterfaceData(String hostname, String interfaceName) throws AAIServiceException {
1107 PInterface response = null;
1110 AAIRequest request = new PInterfaceRequest();
1111 request.addRequestProperty(PInterfaceRequest.PINTERFACE_INTERFACE_NAME, interfaceName);
1112 request.addRequestProperty(PInterfaceRequest.PSERVER_HOSTNAME, hostname);
1113 String rv = executor.get(request);
1115 ObjectMapper mapper = getObjectMapper();
1116 response = mapper.readValue(rv, PInterface.class);
1118 } catch(AAIServiceException aaiexc) {
1120 } catch (Exception exc) {
1121 LOG.warn(Object.class.getClass().getEnclosingMethod().getName(), exc);
1122 throw new AAIServiceException(exc);
1128 public boolean postPInterfaceData(String hostname, String interfaceName, PInterface request) throws AAIServiceException {
1129 InputStream inputStream = null;
1133 ObjectMapper mapper = getObjectMapper();
1134 String json_text = mapper.writeValueAsString(request);
1136 SSLSocketFactory sockFact = CTX.getSocketFactory();
1138 String request_url = target_uri+p_interface_path;
1139 String encoded_vnf = encodeQuery(hostname);
1140 request_url = request_url.replace("{hostname}", encoded_vnf) ;
1141 encoded_vnf = encodeQuery(interfaceName);
1142 request_url = request_url.replace("{interface-name}", encoded_vnf) ;
1143 URL http_req_url = new URL(request_url);
1145 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.PUT);
1147 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
1148 osw.write(json_text);
1153 LOGwriteFirstTrace("PUT", request_url);
1154 LOGwriteDateTrace("hostname", hostname);
1155 LOGwriteDateTrace("interface-name", interfaceName);
1156 LOGwriteDateTrace("PInterface", json_text);
1159 int responseCode = con.getResponseCode();
1160 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1161 inputStream = con.getInputStream();
1163 inputStream = con.getErrorStream();
1166 // Process the response
1167 BufferedReader reader;
1169 reader = new BufferedReader( new InputStreamReader( inputStream ) );
1171 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1172 StringBuilder stringBuilder = new StringBuilder();
1174 while( ( line = reader.readLine() ) != null ) {
1175 stringBuilder.append( line );
1177 LOGwriteEndingTrace(responseCode, "SUCCESS", (stringBuilder.length() > 0) ? stringBuilder.toString() : "{no-data}");
1180 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
1181 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
1183 throw new AAIServiceException(responseCode, errorresponse);
1185 } catch(AAIServiceException aaiexc) {
1187 } catch (Exception exc) {
1188 LOG.warn("postPInterfaceData", exc);
1189 throw new AAIServiceException(exc);
1192 if(inputStream != null)
1193 inputStream.close();
1194 } catch (Exception exc) {
1201 public boolean deletePInterfaceData(String hostname, String interfaceName, String resourceVersion) throws AAIServiceException {
1202 boolean response = false;
1205 AAIRequest request = AAIRequest.getRequestFromResource("p-interface");
1206 request.addRequestProperty("p-interface.interface-name", interfaceName);
1207 request.addRequestProperty("pserver.hostname", hostname);
1208 response = executor.delete(request, resourceVersion);
1209 } catch(AAIServiceException aaiexc) {
1211 } catch (Exception exc) {
1212 LOG.warn("deletePInterfaceData", exc);
1213 throw new AAIServiceException(exc);
1217 //================== End of PInterface =================
1218 //==================== SitePairSet ======================
1220 public SitePairSet requestSitePairSetData(String sitePairSetId) throws AAIServiceException {
1221 SitePairSet response = null;
1224 AAIRequest request = AAIRequest.getRequestFromResource("site-pair-set");
1225 request.addRequestProperty("site-pair-set.site-pair-set-id", sitePairSetId);
1226 String rv = executor.get(request);
1228 ObjectMapper mapper = getObjectMapper();
1229 response = mapper.readValue(rv, SitePairSet.class);
1231 } catch(AAIServiceException aaiexc) {
1233 } catch (Exception exc) {
1234 LOG.warn(Object.class.getClass().getEnclosingMethod().getName(), exc);
1235 throw new AAIServiceException(exc);
1241 public boolean postSitePairSetData(String linkName, SitePairSet request) throws AAIServiceException {
1242 InputStream inputStream = null;
1246 ObjectMapper mapper = getObjectMapper();
1247 String json_text = mapper.writeValueAsString(request);
1249 SSLSocketFactory sockFact = CTX.getSocketFactory();
1251 String request_url = target_uri+site_pair_set_path;
1252 String encoded_vnf = encodeQuery(linkName);
1253 request_url = request_url.replace("{site-pair-set-id}", encoded_vnf) ;
1254 URL http_req_url = new URL(request_url);
1256 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.PUT);
1258 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
1259 osw.write(json_text);
1264 LOGwriteFirstTrace("PUT", request_url);
1265 LOGwriteDateTrace("link-name", linkName);
1266 LOGwriteDateTrace("SitePairSet", json_text);
1269 int responseCode = con.getResponseCode();
1270 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1271 inputStream = con.getInputStream();
1273 inputStream = con.getErrorStream();
1276 // Process the response
1277 BufferedReader reader;
1279 reader = new BufferedReader( new InputStreamReader( inputStream ) );
1281 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1282 StringBuilder stringBuilder = new StringBuilder();
1284 while( ( line = reader.readLine() ) != null ) {
1285 stringBuilder.append( line );
1287 LOGwriteEndingTrace(responseCode, "SUCCESS", (stringBuilder.length() > 0) ? stringBuilder.toString() : "{no-data}");
1290 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
1291 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
1293 throw new AAIServiceException(responseCode, errorresponse);
1295 } catch(AAIServiceException aaiexc) {
1297 } catch (Exception exc) {
1298 LOG.warn("postSitePairSetData", exc);
1299 throw new AAIServiceException(exc);
1302 if(inputStream != null)
1303 inputStream.close();
1304 } catch (Exception exc) {
1311 public boolean deleteSitePairSetData(String linkName, String resourceVersion) throws AAIServiceException {
1312 boolean response = false;
1315 AAIRequest request = AAIRequest.getRequestFromResource("site-pair-set");
1316 request.addRequestProperty("site-pair-set.site-pair-set-id", linkName);
1317 response = executor.delete(request, resourceVersion);
1318 } catch(AAIServiceException aaiexc) {
1320 } catch (Exception exc) {
1321 LOG.warn("deleteSitePairSetData", exc);
1322 throw new AAIServiceException(exc);
1327 //================== End of SitePairSet =================
1328 //==================== Service ======================
1330 public Service requestServiceData(String serviceId) throws AAIServiceException {
1331 Service response = null;
1334 AAIRequest request = AAIRequest.getRequestFromResource("service");
1335 request.addRequestProperty("service.service-id", serviceId);
1338 String rv = executor.get(request);
1340 ObjectMapper mapper = getObjectMapper();
1341 response = mapper.readValue(rv, Service.class);
1343 } catch(AAIServiceException aaiexc) {
1345 } catch (Exception exc) {
1346 LOG.warn("requestServiceData", exc);
1347 throw new AAIServiceException(exc);
1353 public boolean postServiceData(String linkName, Service request) throws AAIServiceException {
1354 InputStream inputStream = null;
1358 ObjectMapper mapper = getObjectMapper();
1359 String json_text = mapper.writeValueAsString(request);
1361 SSLSocketFactory sockFact = CTX.getSocketFactory();
1363 String request_url = target_uri+service_path;
1364 String encoded_vnf = encodeQuery(linkName);
1365 request_url = request_url.replace("{service-id}", encoded_vnf) ;
1366 URL http_req_url = new URL(request_url);
1368 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.PUT);
1370 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
1371 osw.write(json_text);
1376 LOGwriteFirstTrace("PUT", request_url);
1377 LOGwriteDateTrace("service-id", linkName);
1378 LOGwriteDateTrace("Service", json_text);
1381 int responseCode = con.getResponseCode();
1382 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1383 inputStream = con.getInputStream();
1385 inputStream = con.getErrorStream();
1388 // Process the response
1389 BufferedReader reader;
1391 reader = new BufferedReader( new InputStreamReader( inputStream ) );
1393 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1394 StringBuilder stringBuilder = new StringBuilder();
1396 while( ( line = reader.readLine() ) != null ) {
1397 stringBuilder.append( line );
1399 LOGwriteEndingTrace(responseCode, "SUCCESS", (stringBuilder.length() > 0) ? stringBuilder.toString() : "{no-data}");
1402 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
1403 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
1405 throw new AAIServiceException(responseCode, errorresponse);
1407 } catch(AAIServiceException aaiexc) {
1409 } catch (Exception exc) {
1410 LOG.warn("postServiceData", exc);
1411 throw new AAIServiceException(exc);
1414 if(inputStream != null)
1415 inputStream.close();
1416 } catch (Exception exc) {
1423 public boolean deleteServiceData(String service_id, String resourceVersion) throws AAIServiceException {
1424 boolean response = false;
1427 AAIRequest request = AAIRequest.getRequestFromResource("service");
1428 request.addRequestProperty("service.service-id", service_id);
1429 response = executor.delete(request, resourceVersion);
1430 } catch(AAIServiceException aaiexc) {
1432 } catch (Exception exc) {
1433 LOG.warn("deleteServiceData", exc);
1434 throw new AAIServiceException(exc);
1439 //================== End of Service =================
1445 public VServer dataChangeRequestVServerData(URL url) throws AAIServiceException {
1448 throw new NullPointerException();
1451 return this.getResource(url.toString(), VServer.class);
1455 public Pserver dataChangeRequestPServerData(URL url) throws AAIServiceException {
1458 throw new NullPointerException();
1461 return this.getResource(url.toString(), Pserver.class);
1465 public CtagPool dataChangeRequestCtagPoolData(URL url) throws AAIServiceException {
1468 throw new NullPointerException();
1471 return this.getResource(url.toString(), CtagPool.class);
1475 public VplsPe dataChangeRequestVplsPeData(URL url) throws AAIServiceException {
1478 throw new NullPointerException();
1481 return this.getResource(url.toString(), VplsPe.class);
1485 public DvsSwitch dataChangeRequestDvsSwitchData(URL url) throws AAIServiceException {
1488 throw new NullPointerException();
1491 return this.getResource(url.toString(), DvsSwitch.class);
1495 public OamNetwork dataChangeRequestOAMNetworkData(URL url) throws AAIServiceException {
1498 throw new NullPointerException();
1501 return this.getResource(url.toString(), OamNetwork.class);
1505 public AvailabilityZone dataChangeRequestAvailabilityZoneData(URL url) throws AAIServiceException {
1508 throw new NullPointerException();
1511 return this.getResource(url.toString(), AvailabilityZone.class);
1515 public Complex dataChangeRequestComplexData(URL url) throws AAIServiceException {
1518 throw new NullPointerException();
1521 return this.getResource(url.toString(), Complex.class);
1526 public boolean dataChangeDeleteVServerData(URL url) throws AAIServiceException {
1529 throw new NullPointerException();
1532 return deleteAAIEntity(url, Object.class.getClass().getEnclosingMethod()
1537 public boolean dataChangeDeleteCtagPoolData(URL url) throws AAIServiceException {
1540 throw new NullPointerException();
1543 return deleteAAIEntity(url, Object.class.getClass().getEnclosingMethod()
1548 public boolean dataChangeDeleteVplsPeData(URL url) throws AAIServiceException {
1551 throw new NullPointerException();
1554 return deleteAAIEntity(url, Object.class.getClass().getEnclosingMethod()
1559 public boolean dataChangeDeleteVpeData(URL url) throws AAIServiceException {
1562 throw new NullPointerException();
1565 return deleteAAIEntity(url, Object.class.getClass().getEnclosingMethod()
1570 public boolean dataChangeDeleteDvsSwitchData(URL url) throws AAIServiceException {
1573 throw new NullPointerException();
1576 return deleteAAIEntity(url, Object.class.getClass().getEnclosingMethod()
1581 public boolean dataChangeDeleteOAMNetworkData(URL url) throws AAIServiceException {
1584 throw new NullPointerException();
1587 return deleteAAIEntity(url, Object.class.getClass().getEnclosingMethod()
1590 //Availability-Zone:
1592 public boolean dataChangeDeleteAvailabilityZoneData(URL url) throws AAIServiceException {
1595 throw new NullPointerException();
1598 return deleteAAIEntity(url, Object.class.getClass().getEnclosingMethod()
1603 public boolean dataChangeDeleteComplexData(URL url) throws AAIServiceException {
1606 throw new NullPointerException();
1609 return deleteAAIEntity(url, Object.class.getClass().getEnclosingMethod()
1613 private boolean deleteAAIEntity(URL url, String caller) throws AAIServiceException {
1616 throw new NullPointerException();
1619 boolean response = false;
1620 InputStream inputStream = null;
1623 URL http_req_url = url;
1625 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.DELETE);
1627 LOGwriteFirstTrace("DELETE", http_req_url.toString());
1631 int responseCode = con.getResponseCode();
1632 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1633 inputStream = con.getInputStream();
1635 inputStream = con.getErrorStream();
1638 // Process the response
1639 LOG.debug("HttpURLConnection result:" + responseCode);
1640 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
1641 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
1644 ObjectMapper mapper = getObjectMapper();
1646 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1647 StringBuilder stringBuilder = new StringBuilder();
1649 while( ( line = reader.readLine() ) != null ) {
1650 stringBuilder.append( line );
1652 LOGwriteEndingTrace(responseCode, "SUCCESS", stringBuilder.toString());
1654 } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
1655 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
1658 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
1659 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
1660 throw new AAIServiceException(responseCode, errorresponse);
1663 } catch(AAIServiceException aaiexc) {
1665 } catch (Exception exc) {
1666 LOG.warn(caller, exc);
1667 throw new AAIServiceException(exc);
1669 if(inputStream != null){
1671 inputStream.close();
1672 } catch(Exception exc) {
1681 * Generic method to GET json data from an A&AI callback URL.
1682 * Then convert that json to an Object.
1683 * If successful the Object is attempted to be cast to the type parameter.
1686 * callback url for A&AI
1688 * the class of object that A&AI will return
1689 * @return the object created from json or null if the response code is not 200
1691 * @throws AAIServiceException
1692 * if empty or null key and or type or there's an error with processing
1694 public <T> T dataChangeRequestAaiData(String key, Class<T> type) throws AAIServiceException {
1695 if (StringUtils.isEmpty(key) || type == null) {
1696 throw new AAIServiceException("Key is empty or null and or type is null");
1701 SvcLogicContext ctx = new SvcLogicContext();
1702 if(!key.contains(" = ") && isValidURL(key)) {
1703 key = String.format("selflink = '%s'", key);
1705 if(!key.contains(" = ") && isValidURI(key)) {
1706 key = String.format("resource-path = '%s'", key);
1709 HashMap<String, String> nameValues = AAIServiceUtils.keyToHashMap(key, ctx);
1711 SelfLinkRequest request = new SelfLinkRequest(type);
1712 request.processRequestPathValues(nameValues);
1713 Object obj = this.getExecutor().query(request, type);
1714 response = type.cast(obj);
1716 return response != null ? type.cast(response) : response;
1720 public Pserver requestPServerData(String hostname) throws AAIServiceException {
1721 Pserver response = null;
1724 AAIRequest request = AAIRequest.getRequestFromResource("pserver");
1725 request.addRequestProperty("pserver.hostname", hostname);
1728 String rv = executor.get(request);
1730 ObjectMapper mapper = getObjectMapper();
1731 response = mapper.readValue(rv, Pserver.class);
1733 } catch(AAIServiceException aaiexc) {
1735 } catch (Exception exc) {
1736 LOG.warn("requestPServerData", exc);
1737 throw new AAIServiceException(exc);
1743 public boolean postPServerData(String hostname, Pserver data) throws AAIServiceException {
1745 AAIRequest request = AAIRequest.getRequestFromResource("pserver");
1746 request.addRequestProperty("pserver.hostname", hostname);
1747 request.setRequestObject(data);
1748 Object response = executor.post(request);
1750 } catch(AAIServiceException aaiexc) {
1752 } catch (Exception exc) {
1753 LOG.warn(Object.class.getClass().getEnclosingMethod().getName(), exc);
1754 throw new AAIServiceException(exc);
1759 public boolean deletePServerData(String hostname, String resourceVersion) throws AAIServiceException {
1760 boolean response = false;
1763 AAIRequest request = AAIRequest.getRequestFromResource("pserver");
1764 request.addRequestProperty("pserver.hostname", hostname);
1765 response = executor.delete(request, resourceVersion);
1766 } catch(AAIServiceException aaiexc) {
1768 } catch (Exception exc) {
1769 LOG.warn("deletePServerData", exc);
1770 throw new AAIServiceException(exc);
1778 public L3Network requestL3NetworkData(String networkId) throws AAIServiceException {
1779 L3Network response = null;
1782 AAIRequest request = AAIRequest.getRequestFromResource("l3-network");
1783 request.addRequestProperty("l3-network.network-id", networkId);
1785 String rv = executor.get(request);
1787 ObjectMapper mapper = getObjectMapper();
1788 response = mapper.readValue(rv, L3Network.class);
1790 } catch(AAIServiceException aaiexc) {
1792 } catch (Exception exc) {
1793 LOG.warn("requestL3NetworkData", exc);
1794 throw new AAIServiceException(exc);
1800 public L3Network requestL3NetworkQueryByName(String networkName) throws AAIServiceException {
1801 L3Network response = null;
1804 AAIRequest request = AAIRequest.getRequestFromResource("l3-network");
1805 request.addRequestProperty("l3-network.network-name", networkName);
1807 String rv = executor.get(request);
1809 ObjectMapper mapper = getObjectMapper();
1810 response = mapper.readValue(rv, L3Network.class);
1813 } catch(AAIServiceException aaiexc) {
1815 } catch (Exception exc) {
1816 LOG.warn("requestL3NetworkQueryByName", exc);
1817 throw new AAIServiceException(exc);
1823 public boolean postL3NetworkData(String networkId, L3Network data) throws AAIServiceException {
1825 AAIRequest request = AAIRequest.getRequestFromResource("l3-network");
1826 request.addRequestProperty("l3-network.network-id", networkId);
1827 request.setRequestObject(data);
1828 Object response = executor.post(request);
1830 } catch(AAIServiceException aaiexc) {
1832 } catch (Exception exc) {
1833 LOG.warn(Object.class.getClass().getEnclosingMethod().getName(), exc);
1834 throw new AAIServiceException(exc);
1839 public boolean deleteL3NetworkData(String networkId, String resourceVersion) throws AAIServiceException {
1840 boolean response = false;
1843 AAIRequest request = AAIRequest.getRequestFromResource("l3-network");
1844 request.addRequestProperty("l3-network.network-id", networkId);
1845 response = executor.delete(request, resourceVersion);
1846 } catch(AAIServiceException aaiexc) {
1848 } catch (Exception exc) {
1849 LOG.warn("deleteL3NetworkData", exc);
1850 throw new AAIServiceException(exc);
1858 public VpnBinding requestVpnBindingData(String vpnId) throws AAIServiceException {
1859 VpnBinding response = null;
1862 AAIRequest request = AAIRequest.getRequestFromResource("vpn-binding");
1863 request.addRequestProperty("vpn-binding.vpn-id", vpnId);
1865 String rv = executor.get(request);
1867 ObjectMapper mapper = getObjectMapper();
1868 response = mapper.readValue(rv, VpnBinding.class);
1870 } catch(AAIServiceException aaiexc) {
1872 } catch (Exception exc) {
1873 LOG.warn("requestVpnBindingData", exc);
1874 throw new AAIServiceException(exc);
1880 public boolean deleteVpnBindingData(String vpnId, String resourceVersion) throws AAIServiceException {
1881 boolean response = false;
1884 AAIRequest request = AAIRequest.getRequestFromResource("vpn-binding");
1885 request.addRequestProperty("vpn-binding.vpn-id", vpnId);
1886 response = executor.delete(request, resourceVersion);
1887 } catch(AAIServiceException aaiexc) {
1889 } catch (Exception exc) {
1890 LOG.warn("deleteVpnBindingData", exc);
1891 throw new AAIServiceException(exc);
1898 public VnfImage requestVnfImageData(String vnf_image_uuid) throws AAIServiceException {
1899 VnfImage response = null;
1902 AAIRequest request = AAIRequest.getRequestFromResource("vnf-image");
1903 request.addRequestProperty("vnf-image.vnf-image-uuid", vnf_image_uuid);
1905 String rv = executor.get(request);
1907 ObjectMapper mapper = getObjectMapper();
1908 response = mapper.readValue(rv, VnfImage.class);
1910 } catch(AAIServiceException aaiexc) {
1912 } catch (Exception exc) {
1913 LOG.warn("requestVnfImageData", exc);
1914 throw new AAIServiceException(exc);
1920 public VnfImage requestVnfImageDataByVendorModel(String vendor, String model) throws AAIServiceException {
1921 return requestVnfImageDataByVendorModelVersion(vendor, model, null);
1925 public VnfImage requestVnfImageDataByVendorModelVersion(String vendor, String model, String version) throws AAIServiceException
1927 List<VnfImage> responseList = new ArrayList<VnfImage>();
1928 VnfImage response = null;
1929 InputStream inputStream = null;
1932 String request_url = target_uri+vnf_image_query_path + (version==null? "": "&application-version={application_version}");
1933 request_url = request_url.replace("{application_vendor}", encodeQuery(vendor)) ;
1934 request_url = request_url.replace("{application_model}", encodeQuery(model)) ;
1935 if(version != null) {
1936 request_url = request_url.replace("{application_version}", encodeQuery(version)) ;
1938 URL http_req_url = new URL(request_url);
1940 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.GET);
1942 LOGwriteFirstTrace(HttpMethod.GET, http_req_url.toString());
1943 LOGwriteDateTrace("application_vendor", vendor);
1944 LOGwriteDateTrace("application_model", model);
1945 if(version != null) {
1946 LOGwriteDateTrace("application_version", version);
1950 int responseCode = con.getResponseCode();
1951 if (responseCode == HttpURLConnection.HTTP_OK) {
1952 inputStream = con.getInputStream();
1954 inputStream = con.getErrorStream();
1957 // Process the response
1958 LOG.debug("HttpURLConnection result:" + responseCode);
1959 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
1960 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
1962 ObjectMapper mapper = getObjectMapper();
1964 if (responseCode == HttpURLConnection.HTTP_OK) {
1965 response = mapper.readValue(reader, VnfImage.class);
1966 String original_buffer = mapper.writeValueAsString(response);
1967 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, "SUCCESS", original_buffer);
1968 if(response.getApplicationVendor() == null /*&& response.getAdditionalProperties() != null && !response.getAdditionalProperties().isEmpty()*/){
1969 LOG.warn("A List of multiple VNF-IMAGE entries has been returned");
1970 VnfImages listOfObjects = mapper.readValue(original_buffer, VnfImages.class);
1971 if(!listOfObjects.getVnfImage().isEmpty()) {
1972 response = listOfObjects.getVnfImage().get(0);
1975 } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
1976 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
1979 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
1980 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
1981 throw new AAIServiceException(responseCode, errorresponse);
1984 } catch(AAIServiceException aaiexc) {
1986 } catch (Exception exc) {
1987 LOG.warn("requestVnfImageData", exc);
1988 throw new AAIServiceException(exc);
1990 if(inputStream != null){
1992 inputStream.close();
1993 } catch(Exception exc) {
2002 public boolean sendNotify(NotifyEvent event, String serviceInstanceId, String pathCode) throws AAIServiceException {
2003 InputStream inputStream = null;
2007 String selfLink = selflink_fqdn;
2008 if(SELFLINK_AVPN != null && SELFLINK_AVPN.equals(pathCode)) {
2009 selfLink = selflink_avpn;
2011 selfLink = selfLink.replace("{service-instance-id}", encodeQuery(serviceInstanceId));
2012 event.setSelflink(selfLink);
2014 ObjectMapper mapper = getObjectMapper();
2015 String json_text = mapper.writeValueAsString(event);
2017 SSLSocketFactory sockFact = CTX.getSocketFactory();
2019 String request_url = target_uri+ubb_notify_path;
2020 URL http_req_url = new URL(request_url);
2022 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.PUT);
2024 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
2025 osw.write(json_text);
2030 LOGwriteFirstTrace("PUT", request_url);
2031 LOGwriteDateTrace("NotifyEvent", json_text);
2034 int responseCode = con.getResponseCode();
2035 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2036 inputStream = con.getInputStream();
2038 inputStream = con.getErrorStream();
2041 // Process the response
2042 BufferedReader reader;
2044 reader = new BufferedReader( new InputStreamReader( inputStream ) );
2046 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2047 StringBuilder stringBuilder = new StringBuilder();
2049 while( ( line = reader.readLine() ) != null ) {
2050 stringBuilder.append( line );
2052 LOGwriteEndingTrace(responseCode, "SUCCESS", (stringBuilder.length() > 0) ? stringBuilder.toString() :
2056 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2057 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
2059 throw new AAIServiceException(responseCode, errorresponse);
2061 } catch(AAIServiceException aaiexc) {
2063 } catch (Exception exc) {
2064 LOG.warn("sendNotify", exc);
2065 throw new AAIServiceException(exc);
2068 if(inputStream != null)
2069 inputStream.close();
2070 } catch (Exception exc) {
2077 public SearchResults requestNodeQuery(String node_type, String entityIdentifier, String entityName) throws AAIServiceException {
2078 SearchResults response = null;
2079 InputStream inputStream = null;
2082 String request_url = target_uri+query_nodes_path;
2083 request_url = request_url.replace("{node-type}", encodeQuery(node_type)) ;
2084 request_url = request_url.replace("{entity-identifier}", entityIdentifier) ;
2085 request_url = request_url.replace("{entity-name}", encodeQuery(entityName)) ;
2086 URL http_req_url = new URL(request_url);
2088 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.GET);
2090 LOGwriteFirstTrace(HttpMethod.GET, http_req_url.toString());
2091 LOGwriteDateTrace("node_type", node_type);
2092 LOGwriteDateTrace("vnf_name", entityName);
2095 int responseCode = con.getResponseCode();
2096 if (responseCode == HttpURLConnection.HTTP_OK) {
2097 inputStream = con.getInputStream();
2099 inputStream = con.getErrorStream();
2102 // Process the response
2103 LOG.debug("HttpURLConnection result:" + responseCode);
2104 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
2105 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2107 ObjectMapper mapper = getObjectMapper();
2109 if (responseCode == HttpURLConnection.HTTP_OK) {
2110 response = mapper.readValue(reader, SearchResults.class);
2111 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, "SUCCESS", mapper.writeValueAsString(response));
2112 } else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
2113 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
2116 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2117 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
2118 throw new AAIServiceException(responseCode, errorresponse);
2121 } catch(AAIServiceException aaiexc) {
2123 } catch (Exception exc) {
2124 LOG.warn("requestNodeQuery", exc);
2125 throw new AAIServiceException(exc);
2127 if(inputStream != null){
2129 inputStream.close();
2130 } catch(Exception exc) {
2141 public String requestDataByURL(URL url) throws AAIServiceException {
2144 throw new NullPointerException();
2147 String response = null;
2148 InputStream inputStream = null;
2151 URL http_req_url = url;
2153 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.GET);
2155 LOGwriteFirstTrace(HttpMethod.GET, http_req_url.toString());
2158 int responseCode = con.getResponseCode();
2159 if (responseCode == HttpURLConnection.HTTP_OK) {
2160 inputStream = con.getInputStream();
2162 inputStream = con.getErrorStream();
2165 // Process the response
2166 LOG.debug("HttpURLConnection result:" + responseCode);
2167 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
2168 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2170 ObjectMapper mapper = getObjectMapper();
2172 if (responseCode == HttpURLConnection.HTTP_OK) {
2173 StringBuilder stringBuilder = new StringBuilder("\n");
2175 while( ( line = reader.readLine() ) != null ) {
2176 stringBuilder.append( line );
2178 LOG.info(stringBuilder.toString());
2179 // response = mapper.readValue(reader, String.class);
2180 response = stringBuilder.toString();
2181 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, "SUCCESS", mapper.writeValueAsString(response));
2182 } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
2183 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
2186 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2187 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
2188 throw new AAIServiceException(responseCode, errorresponse);
2191 } catch(AAIServiceException aaiexc) {
2193 } catch (Exception exc) {
2194 LOG.warn("requestNetworkVceData", exc);
2195 throw new AAIServiceException(exc);
2197 if(inputStream != null){
2199 inputStream.close();
2200 } catch(Exception exc) {
2210 public GenericVnf requestGenericVnfeNodeQuery(String vnf_name) throws AAIServiceException {
2212 if(vnf_name == null) {
2213 throw new NullPointerException();
2216 GenericVnf entity = null;
2217 SearchResults resp = this.requestNodeQuery("generic-vnf", "vnf-name", vnf_name);
2219 List<ResultData> resultDataList = resp.getResultData();
2222 for (ResultData datum : resultDataList) {
2223 String data_type = datum.getResourceType();
2224 URL url = new URL(datum.getResourceLink());
2225 entity = this.getResource(url.toString(), GenericVnf.class);
2230 LOG.error("Caught exception", e);
2236 public Vserver requestVServerDataByURL(URL url) throws AAIServiceException {
2239 throw new NullPointerException();
2242 Vserver entity = null;
2245 entity = this.getResource(url.toString(), Vserver.class);
2246 } catch (AAIServiceException exc) {
2248 } catch (Exception e) {
2249 throw new AAIServiceException(e);
2255 public URL requestVserverURLNodeQuery(String vserver_name) throws AAIServiceException {
2257 if(vserver_name == null) {
2258 throw new NullPointerException();
2262 SearchResults resp = this.requestNodeQuery("vserver", "vserver-name", vserver_name);
2264 List<ResultData> resultDataList = resp.getResultData();
2267 for (ResultData datum : resultDataList) {
2268 String data_type = datum.getResourceType();
2269 String resourceLink = datum.getResourceLink();
2270 if(!resourceLink.isEmpty() && !resourceLink.toLowerCase().startsWith("http")) {
2271 resourceLink = (new EchoRequest()).target_uri + resourceLink;
2273 entity = new URL(resourceLink);
2275 } catch (Exception e) {
2276 throw new AAIServiceException(e);
2281 class AAIRequestExecutor implements AAIExecutorInterface {
2284 public String get(AAIRequest request) throws AAIServiceException {
2285 String response = null;
2286 InputStream inputStream = null;
2287 HttpURLConnection con = null;
2288 URL requestUrl = null;
2290 String requestId = UUID.randomUUID().toString();
2291 StringBuilder errorStringBuilder = new StringBuilder();
2295 if(request.getRequestObject() != null) {
2296 requestUrl = request.getRequestUrl(HttpMethod.POST, null);
2297 requestUrl = appendDepth(requestUrl, request);
2298 con = getConfiguredConnection(requestUrl, HttpMethod.POST);
2299 String json_text = request.toJSONString();
2300 LOGwriteDateTrace("data", json_text);
2301 logMetricRequest(requestId, "POST "+requestUrl.getPath(), json_text, requestUrl.getPath());
2302 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
2303 osw.write(json_text);
2306 requestUrl = request.getRequestUrl(HttpMethod.GET, null);
2307 requestUrl = appendDepth(requestUrl, request);
2308 con = getConfiguredConnection(requestUrl, HttpMethod.GET);
2309 logMetricRequest(requestId, "GET "+requestUrl.getPath(), "", requestUrl.getPath());
2313 String responseMessage = con.getResponseMessage();
2314 int responseCode = con.getResponseCode();
2315 if (responseCode == HttpURLConnection.HTTP_OK) {
2316 inputStream = con.getInputStream();
2318 inputStream = con.getErrorStream();
2321 // Process the response
2322 LOG.debug("HttpURLConnection result:" + responseCode + " : " + responseMessage);
2323 logMetricResponse(requestId, responseCode, responseMessage);
2325 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
2326 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2328 ObjectMapper mapper = getObjectMapper();
2330 if (responseCode == HttpURLConnection.HTTP_OK) {
2331 StringBuilder stringBuilder = new StringBuilder();
2333 while( ( line = reader.readLine() ) != null ) {
2334 stringBuilder.append( line );
2336 response = stringBuilder.toString();
2338 Object object = mapper.readValue(response, Object.class);
2339 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, responseMessage, mapper.writeValueAsString(object));
2340 } catch(Exception exc) {
2341 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, responseMessage, mapper.writeValueAsString(response));
2343 } else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
2344 LOGwriteEndingTrace(responseCode, responseMessage, "Entry does not exist.");
2345 ErrorResponse errorresponse = null;
2347 errorresponse = mapper.readValue(reader, ErrorResponse.class);
2348 } catch(Exception exc) {
2349 errorresponse = new ErrorResponse();
2350 RequestError requestError = new RequestError();
2351 ServiceException serviceException = new ServiceException();
2352 serviceException.setText("Entry does not exist.");
2353 requestError.setServiceException(serviceException);
2354 errorresponse.setRequestError(requestError );
2356 throw new AAIServiceException(responseCode, errorresponse);
2357 } else if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
2358 StringBuilder stringBuilder = new StringBuilder();
2360 while( ( line = reader.readLine() ) != null ) {
2361 stringBuilder.append( line );
2363 LOGwriteEndingTrace(responseCode, responseMessage, stringBuilder.toString());
2364 ServiceException serviceException = new ServiceException();
2365 serviceException.setMessageId("HTTP_UNAUTHORIZED");
2366 serviceException.setText(stringBuilder.toString());
2367 RequestError requestError = new RequestError();
2368 requestError.setServiceException(serviceException);
2369 ErrorResponse errorresponse = new ErrorResponse();
2370 errorresponse.setRequestError(requestError);
2371 throw new AAIServiceException(responseCode, errorresponse);
2373 // StringBuilder errorStringBuilder = new StringBuilder();
2375 while( ( line = reader.readLine() ) != null ) {
2376 errorStringBuilder.append("\n").append( line );
2379 ErrorResponse errorresponse = mapper.readValue(errorStringBuilder.toString(), ErrorResponse.class);
2380 // ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2381 LOGwriteEndingTrace(responseCode, responseMessage, mapper.writeValueAsString(errorresponse));
2382 throw new AAIServiceException(responseCode, errorresponse);
2385 } catch(AAIServiceException aaiexc) {
2387 } catch (Exception exc) {
2388 LOG.warn(errorStringBuilder.toString(), exc);
2389 throw new AAIServiceException(exc);
2391 if(inputStream != null){
2393 inputStream.close();
2394 } catch(Exception exc) {
2402 private URL appendDepth(URL requestUrl, AAIRequest request) throws MalformedURLException {
2404 String depth = request.requestProperties.getProperty("depth", "1");
2405 String path = requestUrl.toString();
2406 if(path.contains("?depth=") || path.contains("&depth=")) {
2409 if(path.contains("?")) {
2410 path = String.format("%s&depth=%s", path, depth);
2412 path = String.format("%s?depth=%s", path, depth);
2414 return new URL(path);
2419 public String post(AAIRequest request) throws AAIServiceException {
2420 InputStream inputStream = null;
2421 String requestId = UUID.randomUUID().toString();
2424 String resourceVersion = null;
2425 AAIDatum instance = request.getRequestObject();
2427 Method getResourceVersionMethod = instance.getClass().getMethod("getResourceVersion");
2428 if(getResourceVersionMethod != null){
2430 getResourceVersionMethod.setAccessible(true);
2431 Object object = getResourceVersionMethod.invoke(instance);
2433 resourceVersion = object.toString();
2434 } catch (InvocationTargetException x) {
2435 Throwable cause = x.getCause();
2439 URL requestUrl = null;
2440 HttpURLConnection con = getConfiguredConnection(requestUrl = request.getRequestUrl(HttpMethod.PUT, resourceVersion), HttpMethod.PUT);
2441 ObjectMapper mapper = getObjectMapper();
2442 String json_text = request.toJSONString();
2444 LOGwriteDateTrace("data", json_text);
2445 logMetricRequest(requestId, "PUT "+requestUrl.getPath(), json_text, requestUrl.getPath());
2447 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
2448 osw.write(json_text);
2452 String responseMessage = con.getResponseMessage();
2453 int responseCode = con.getResponseCode();
2454 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2455 inputStream = con.getInputStream();
2457 inputStream = con.getErrorStream();
2460 LOG.debug("HttpURLConnection result:" + responseCode + " : " + responseMessage);
2461 logMetricResponse(requestId,responseCode, responseMessage);
2463 // Process the response
2464 BufferedReader reader;
2466 reader = new BufferedReader( new InputStreamReader( inputStream ) );
2467 mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
2469 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2470 StringBuilder stringBuilder = new StringBuilder();
2472 while( ( line = reader.readLine() ) != null ) {
2473 stringBuilder.append( line );
2475 LOGwriteEndingTrace(responseCode, responseMessage, (stringBuilder != null) ? stringBuilder.toString() : "{no-data}");
2476 return stringBuilder.toString();
2478 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2479 LOGwriteEndingTrace(responseCode, responseMessage, mapper.writeValueAsString(errorresponse));
2481 throw new AAIServiceException(responseCode, errorresponse);
2483 } catch(AAIServiceException aaiexc) {
2485 } catch (Exception exc) {
2486 LOG.warn("AAIRequestExecutor.post", exc);
2487 throw new AAIServiceException(exc);
2490 if(inputStream != null)
2491 inputStream.close();
2492 } catch (Exception exc) {
2499 public Boolean delete(AAIRequest request, String resourceVersion) throws AAIServiceException {
2500 Boolean response = null;
2501 InputStream inputStream = null;
2502 String requestId = UUID.randomUUID().toString();
2504 if(resourceVersion == null) {
2505 throw new AAIServiceException("resource-version is required for DELETE request");
2509 URL requestUrl = null;
2510 HttpURLConnection conn = getConfiguredConnection(requestUrl = request.getRequestUrl(HttpMethod.DELETE, resourceVersion), HttpMethod.DELETE);
2511 logMetricRequest(requestId, "DELETE "+requestUrl.getPath(), "", requestUrl.getPath());
2512 conn.setDoOutput(true);
2515 String responseMessage = conn.getResponseMessage();
2516 int responseCode = conn.getResponseCode();
2517 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2518 inputStream = conn.getInputStream();
2520 inputStream = conn.getErrorStream();
2523 // Process the response
2524 LOG.debug("HttpURLConnection result:" + responseCode + " : " + responseMessage);
2525 logMetricResponse(requestId,responseCode, responseMessage);
2527 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
2528 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2531 ObjectMapper mapper = getObjectMapper();
2533 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2534 StringBuilder stringBuilder = new StringBuilder();
2536 while( ( line = reader.readLine() ) != null ) {
2537 stringBuilder.append( line );
2539 LOGwriteEndingTrace(responseCode, responseMessage, stringBuilder.toString());
2541 } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
2542 LOGwriteEndingTrace(responseCode, responseMessage, "Entry does not exist.");
2545 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2546 LOGwriteEndingTrace(responseCode, responseMessage, mapper.writeValueAsString(errorresponse));
2547 throw new AAIServiceException(responseCode, errorresponse);
2549 } catch(AAIServiceException aaiexc) {
2551 } catch (Exception exc) {
2552 LOG.warn("delete", exc);
2553 throw new AAIServiceException(exc);
2555 if(inputStream != null){
2557 inputStream.close();
2558 } catch(Exception exc) {
2567 public Object query(AAIRequest request, Class clas) throws AAIServiceException {
2568 Object response = null;
2569 InputStream inputStream = null;
2570 HttpURLConnection con = null;
2571 URL requestUrl = null;
2572 String requestId = UUID.randomUUID().toString();
2575 requestUrl = request.getRequestQueryUrl(HttpMethod.GET);
2576 con = getConfiguredConnection(requestUrl , HttpMethod.GET);
2577 logMetricRequest(requestId, "GET "+requestUrl.getPath(), "", requestUrl.getPath());
2580 String responseMessage = con.getResponseMessage();
2581 int responseCode = con.getResponseCode();
2582 if (responseCode == HttpURLConnection.HTTP_OK) {
2583 inputStream = con.getInputStream();
2585 inputStream = con.getErrorStream();
2588 logMetricResponse(requestId,responseCode, responseMessage);
2589 ObjectMapper mapper = getObjectMapper();
2591 if (responseCode == HttpURLConnection.HTTP_OK) {
2592 // Process the response
2593 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2594 response = mapper.readValue(reader, clas);
2595 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, "SUCCESS", mapper.writeValueAsString(response));
2596 } else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
2597 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
2600 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2601 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2602 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
2603 throw new AAIServiceException(responseCode, errorresponse);
2606 } catch(AAIServiceException aaiexc) {
2608 } catch (Exception exc) {
2609 LOG.warn("GET", exc);
2610 throw new AAIServiceException(exc);
2612 if(inputStream != null){
2614 inputStream.close();
2615 } catch(Exception exc) {
2625 public Boolean patch(AAIRequest request, String resourceVersion) throws AAIServiceException {
2626 InputStream inputStream = null;
2627 String requestId = UUID.randomUUID().toString();
2630 AAIDatum instance = request.getRequestObject();
2631 if(instance instanceof ResourceVersion) {
2632 resourceVersion = ((ResourceVersion)instance).getResourceVersion();
2635 URL requestUrl = null;
2636 HttpURLConnection con = getConfiguredConnection(requestUrl = request.getRequestUrl("PATCH", resourceVersion), "PATCH");
2637 ObjectMapper mapper = getObjectMapper();
2638 String json_text = request.toJSONString();
2640 LOGwriteDateTrace("data", json_text);
2641 logMetricRequest(requestId, "PATCH "+requestUrl.getPath(), json_text, requestUrl.getPath());
2643 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
2644 osw.write(json_text);
2648 String responseMessage = con.getResponseMessage();
2649 int responseCode = con.getResponseCode();
2650 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2651 inputStream = con.getInputStream();
2653 inputStream = con.getErrorStream();
2656 LOG.info("HttpURLConnection result: " + responseCode + " : " + responseMessage);
2657 logMetricResponse(requestId,responseCode, responseMessage);
2659 // Process the response
2660 BufferedReader reader;
2662 reader = new BufferedReader( new InputStreamReader( inputStream ) );
2663 mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
2665 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2666 StringBuilder stringBuilder = new StringBuilder();
2668 while( ( line = reader.readLine() ) != null ) {
2669 stringBuilder.append( line );
2671 LOGwriteEndingTrace(responseCode, responseMessage,
2672 (stringBuilder.length() > 0) ? stringBuilder.toString() : "{no-data}");
2675 StringBuilder stringBuilder = new StringBuilder();
2677 while( ( line = reader.readLine() ) != null ) {
2678 stringBuilder.append("\n").append( line );
2680 LOG.info(stringBuilder.toString());
2683 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2684 LOGwriteEndingTrace(responseCode, responseMessage, mapper.writeValueAsString(errorresponse));
2686 throw new AAIServiceException(responseCode, errorresponse);
2688 } catch(AAIServiceException aaiexc) {
2690 } catch (Exception exc) {
2691 LOG.warn("AAIRequestExecutor.patch", exc);
2692 throw new AAIServiceException(exc);
2695 if(inputStream != null)
2696 inputStream.close();
2697 } catch (Exception exc) {
2705 public Tenant requestTenantData(String tenant_id, String cloudOwner, String cloudRegionId) throws AAIServiceException {
2706 Tenant response = null;
2709 AAIRequest request = AAIRequest.getRequestFromResource("tenant");
2710 request.addRequestProperty("tenant.tenant-id", tenant_id);
2711 request.addRequestProperty("cloud-region.cloud-owner", cloudOwner);
2712 request.addRequestProperty("cloud-region.cloud-region-id", cloudRegionId);
2714 String rv = executor.get(request);
2716 ObjectMapper mapper = getObjectMapper();
2717 response = mapper.readValue(rv, Tenant.class);
2719 } catch(AAIServiceException aaiexc) {
2721 } catch (Exception exc) {
2722 LOG.warn("requestTenantData", exc);
2723 throw new AAIServiceException(exc);
2730 public Tenant requestTenantDataByName(String tenant_name, String cloudOwner, String cloudRegionId) throws AAIServiceException {
2731 Tenant response = null;
2734 AAIRequest request = AAIRequest.getRequestFromResource("tenant");
2735 request.addRequestProperty("tenant.tenant-name", tenant_name);
2736 request.addRequestProperty("cloud-region.cloud-owner", cloudOwner);
2737 request.addRequestProperty("cloud-region.cloud-region-id", cloudRegionId);
2738 Object rv = executor.query(request, Tenant.class);
2740 return (Tenant)null;
2742 response = (Tenant)rv;
2743 } catch(AAIServiceException aaiexc) {
2745 } catch (Exception exc) {
2746 LOG.warn("requestTenantDataByName", exc);
2747 throw new AAIServiceException(exc);
2755 public boolean postTenantData(String tenant_id, String cloudOwner, String cloudRegionId, Tenant tenannt) throws AAIServiceException {
2757 AAIRequest request = AAIRequest.getRequestFromResource("tenant");
2758 request.addRequestProperty("tenant.tenant-id", tenant_id);
2759 request.addRequestProperty("cloud-region.cloud-owner", cloudOwner);
2760 request.addRequestProperty("cloud-region.cloud-region-id", cloudRegionId);
2761 request.setRequestObject(tenannt);
2762 Object response = executor.post(request);
2764 } catch(AAIServiceException aaiexc) {
2766 } catch (Exception exc) {
2767 LOG.warn("postTenantData", exc);
2768 throw new AAIServiceException(exc);
2774 public String getTenantIdFromVserverUrl(URL url) {
2776 String path = url.getPath();
2778 String[] split = path.split("/tenants/tenant/");
2779 if(split.length > 1) {
2780 split = split[1].split("/");
2788 public String getCloudOwnerFromVserverUrl(URL url) {
2790 String path = url.getPath();
2792 String[] split = path.split("/cloud-regions/cloud-region/");
2793 if(split.length > 1) {
2794 split = split[1].split("/");
2802 public String getCloudRegionFromVserverUrl(URL url) {
2804 String path = url.getPath();
2806 String[] split = path.split("/cloud-regions/cloud-region/");
2807 if(split.length > 1) {
2808 split = split[1].split("/");
2816 public String getVServerIdFromVserverUrl(URL url, String tenantId) {
2817 String pattern = network_vserver_path;
2818 pattern = pattern.replace("{tenant-id}", tenantId);
2820 int end = pattern.indexOf("{vserver-id}");
2821 String prefix = pattern.substring(0, end);
2823 String path = url.getPath();
2825 if(path.startsWith(prefix)) {
2826 path = path.substring(prefix.length());
2832 protected Logger getLogger(){
2838 public AAIRequestExecutor getExecutor() {
2843 * Creates a current time stamp in UTC i.e. 2016-03-08T22:15:13.343Z.
2844 * If there are any parameters the values are appended to the time stamp.
2847 * values to be appended to current time stamp
2849 * used to set an attribute for a DG
2850 * @throws SvcLogicException
2852 public void setStatusMethod(Map<String, String> parameters, SvcLogicContext ctx) throws SvcLogicException {
2854 throw new SvcLogicException("SvcLogicContext is null.");
2857 StringBuilder sb = new StringBuilder();
2858 sb.append(String.format("%tFT%<tTZ", Calendar.getInstance(TimeZone.getTimeZone("Z")))).append(" - ");
2860 for (Entry<String, String> entry : parameters.entrySet()) {
2861 sb.append(entry.getValue()).append(" ");
2864 if (sb.length() > 0) {
2865 sb.setLength(sb.length() - 2);
2868 ctx.setAttribute("aai-summary-status-message", sb.toString());
2869 LOG.info("aai-summary-status-message: " + sb.toString());
2873 * Generic method to GET json data from an A&AI using key structure.
2874 * Then convert that json to an Object.
2875 * If successful the Object is attempted to be cast to the type parameter.
2878 * key identifying the resource to be retrieved from AAI
2880 * the class of object that A&AI will return
2881 * @return the object created from json or null if the response code is not 200
2883 * @throws AAIServiceException
2884 * if empty or null key and or type or there's an error with processing
2887 public <T> T getResource(String key, Class<T> type) throws AAIServiceException {
2888 if (StringUtils.isEmpty(key) || type == null) {
2889 throw new AAIServiceException("Key is empty or null and or type is null");
2894 SvcLogicContext ctx = new SvcLogicContext();
2895 if(!key.contains(" = ")) {
2896 if(isValidURL(key)) {
2897 key = String.format("selflink = '%s'", key);
2898 } else if(isValidURI(key)) {
2899 key = String.format("resource-path = '%s'", key);
2905 HashMap<String, String> nameValues = AAIServiceUtils.keyToHashMap(key, ctx);
2907 AAIRequest request = new SelfLinkRequest(type);
2908 if(nameValues.containsKey(PathRequest.RESOURCE_PATH.replaceAll("-", "_"))) {
2909 request = new PathRequest(type);
2912 request.processRequestPathValues(nameValues);
2913 Object obj = this.getExecutor().query(request, type);
2914 response = type.cast(obj);
2916 return response != null ? type.cast(response) : response;
2919 public boolean isValidURL(String url) {
2925 } catch (MalformedURLException e) {
2931 } catch (URISyntaxException e) {
2939 public boolean isValidURI(String url) {
2945 } catch (URISyntaxException e) {
2953 protected boolean deleteRelationshipList(URL httpReqUrl, String json_text) throws AAIServiceException {
2954 if(httpReqUrl == null) {
2955 throw new NullPointerException();
2958 boolean response = false;
2959 InputStream inputStream = null;
2962 HttpURLConnection con = getConfiguredConnection(httpReqUrl, HttpMethod.DELETE);
2964 // SSLSocketFactory sockFact = CTX.getSocketFactory();
2965 // con.setSSLSocketFactory( sockFact );
2966 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
2967 osw.write(json_text);
2972 LOGwriteFirstTrace("DELETE", httpReqUrl.toString());
2973 LOGwriteDateTrace("data", json_text);
2976 int responseCode = con.getResponseCode();
2977 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2978 inputStream = con.getInputStream();
2980 inputStream = con.getErrorStream();
2983 // Process the response
2984 LOG.debug("HttpURLConnection result:" + responseCode);
2985 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
2986 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2989 ObjectMapper mapper = getObjectMapper();
2991 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2992 StringBuilder stringBuilder = new StringBuilder();
2994 while( ( line = reader.readLine() ) != null ) {
2995 stringBuilder.append( line );
2997 LOGwriteEndingTrace(responseCode, "SUCCESS", stringBuilder.toString());
2999 } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
3000 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
3003 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
3004 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
3005 throw new AAIServiceException(responseCode, errorresponse);
3008 } catch(AAIServiceException aaiexc) {
3010 } catch (Exception exc) {
3011 LOG.warn("deleteRelationshipList", exc);
3012 throw new AAIServiceException(exc);
3014 if(inputStream != null){
3016 inputStream.close();
3017 } catch(Exception exc) {
3025 public static ObjectMapper getObjectMapper() {
3026 ObjectMapper mapper = new ObjectMapper();
3027 AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance());
3028 AnnotationIntrospector secondary = new JacksonAnnotationIntrospector();
3029 mapper.setAnnotationIntrospector(AnnotationIntrospector.pair(introspector, secondary));
3030 mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
3031 mapper.setSerializationInclusion(Include.NON_NULL);
3035 public void logMetricRequest(String requestId, String targetServiceName, String msg, String path){
3036 String svcInstanceId = "";
3037 String svcName = null;
3038 String partnerName = null;
3039 String targetEntity = "A&AI";
3040 String targetVirtualEntity = null;
3042 targetServiceName = "";
3044 ml.logRequest(svcInstanceId, svcName, partnerName, targetEntity, targetServiceName, targetVirtualEntity, msg);
3047 public void logMetricResponse(String requestId, int responseCode, String responseDescription){
3048 ml.logResponse(responseCode < 400 ? "SUCCESS" : "FAILURE", Integer.toString(responseCode), responseDescription);
3051 public void logKeyError(String keys){
3052 LOG.error("Atleast one of the keys [" + keys + "] should have been populated. This will cause a NPE.");
3060 public QueryStatus save(String resource, boolean force, boolean localOnly, String key, Map<String, String> params, String prefix, SvcLogicContext ctx)
3061 throws SvcLogicException {
3062 String normResource = resource.split(":")[0];
3064 switch(normResource){
3065 case "custom-query":
3066 case "formatted-query":
3067 case "generic-query":
3071 case "l2-bridge-sbg":
3072 case "l2-bridge-bgf":
3078 if(key.contains("selflink =")) {
3081 if(!key.contains(String.format("%s.", normResource))) {
3082 key = rewriteKey(resource, key, ctx);
3085 return super.save(resource, force, localOnly, key, params, prefix, ctx);
3089 public QueryStatus query(String resource, boolean localOnly, String select, String key, String prefix, String orderBy, SvcLogicContext ctx)
3090 throws SvcLogicException {
3091 String normResource = resource.split(":")[0];
3093 switch(normResource){
3094 case "formatted-query":
3095 case "generic-query":
3099 case "l2-bridge-sbg":
3100 case "l2-bridge-bgf":
3106 if(key.contains("selflink =")) {
3109 if(!key.contains(String.format("%s.", normResource))) {
3110 key = rewriteKey(resource, key, ctx);
3114 return super.query(resource, localOnly, select, key, prefix, orderBy, ctx);
3118 public QueryStatus delete(String resource, String key, SvcLogicContext ctx) throws SvcLogicException {
3119 String normResource = resource.split(":")[0];
3121 switch(normResource){
3122 case "formatted-query":
3123 case "generic-query":
3127 case "l2-bridge-sbg":
3128 case "l2-bridge-bgf":
3134 if(key.contains("selflink =")) {
3137 if(!key.contains(String.format("%s.", normResource))) {
3138 key = rewriteKey(resource, key, ctx);
3142 return super.delete(resource, key, ctx);
3146 public QueryStatus update(String resource, String key, Map<String, String> params, String prefix, SvcLogicContext ctx) throws SvcLogicException {
3147 String normResource = resource.split(":")[0];
3149 switch(normResource){
3150 case "formatted-query":
3151 case "generic-query":
3155 case "l2-bridge-sbg":
3156 case "l2-bridge-bgf":
3162 if(key.contains("selflink =")) {
3165 if(!key.contains(String.format("%s.", normResource))) {
3166 key = rewriteKey(resource, key, ctx);
3170 return super.update(resource, key, params, prefix, ctx);
3173 private String rewriteKey(String resource, String key, SvcLogicContext ctx) {
3174 LOG.info("AAI Deprecation - the format of request key is no longer supported. Please rewrite this key : " + key);
3176 String normResource = resource.split(":")[0];
3177 Class<? extends AAIDatum> clazz = null;
3179 clazz = AAIRequest.getClassFromResource(normResource) ;
3180 } catch (ClassNotFoundException e) {
3181 LOG.warn("AAIRequest does not support class: " + e.getMessage());
3187 List<String> fieldAnnotatedNames = new LinkedList<>();
3189 Field[] fields = clazz.getDeclaredFields();
3190 for(Field field : fields) {
3191 String fieldName = field.getName();
3192 XmlElement annotation = field.getAnnotation(XmlElement.class);
3193 if(annotation == null)
3195 String primaryId = annotation.name();
3196 if("##default".equals(primaryId)) {
3197 primaryId = fieldName;
3199 fieldAnnotatedNames.add(primaryId);
3202 HashMap<String, String> nameValues = AAIServiceUtils.keyToHashMap(key, ctx);
3203 Set<String> keyset = nameValues.keySet();
3204 for(String keyName : keyset) {
3205 if(keyName.contains("."))
3208 String tmpKeyName = keyName.replaceAll("_", "-");
3209 String valueToSubstitute = String.format("%s =", tmpKeyName);
3210 if(fieldAnnotatedNames.contains(tmpKeyName) && key.contains(valueToSubstitute)) {
3211 key = key.replace(valueToSubstitute, String.format("%s.%s =", normResource, tmpKeyName));
3221 public String getPathTemplateForResource(String resoourceName, String keys, SvcLogicContext ctx) throws MalformedURLException {
3222 return AAIServiceUtils.getPathForResource(resoourceName, StringUtils.join(keys, " AND "), ctx);
3226 public boolean isDeprecatedFormat(String resource, HashMap<String, String> nameValues) {
3227 return !AAIServiceUtils.isValidFormat(resource, nameValues);
3230 public AAIRequest getRequestFromResource(String resoourceName) {
3231 return AAIRequest.getRequestFromResource(resoourceName);
3235 * @see org.openecomp.sdnc.sli.aai.haha#query(org.openecomp.sdnc.sli.aai.AAIRequest)
3238 public String query(AAIRequest request) throws AAIServiceException {
3239 return executor.get(request);
3243 * @see org.openecomp.sdnc.sli.aai.haha#save(org.openecomp.sdnc.sli.aai.AAIRequest)
3246 public String save(AAIRequest request) throws AAIServiceException {
3247 return executor.post(request);
3250 public boolean update(AAIRequest request, String resourceVersion) throws AAIServiceException {
3251 return executor.patch(request, resourceVersion);
3255 * @see org.openecomp.sdnc.sli.aai.haha#delete(org.openecomp.sdnc.sli.aai.AAIRequest, java.lang.String)
3258 public boolean delete(AAIRequest request, String resourceVersion) throws AAIServiceException {
3259 return executor.patch(request, resourceVersion);