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; // = "sdn-zone-query";
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); // "/aai/v1/business/customers/customer/{customer-id}/service-subscriptions/service-subscription/{service-type}/service-instances");
248 // "/aai/v1/business/customers/customer/ma9181-203-customerid/service-subscriptions/service-subscription/ma9181%20Hosted%20Voice/service-instances";
250 // svc_inst_qry_path = props.getProperty(SVC_INST_QRY_PATH, "/aai/v1/search/generic-query?key=service-instance.service-instance-id:ma9181-204-instance&start-node-type=service-instance&include=service-instance");
251 svc_inst_qry_path = props.getProperty(SVC_INST_QRY_PATH); // "/aai/v1/search/generic-query?key=service-instance.service-instance-id:{svc-instance-id}&start-node-type=service-instance&include=service-instance");
254 param_service_type = props.getProperty(PARAM_SERVICE_TYPE, "service-type");
257 p_interface_path = props.getProperty(P_INTERFACE_PATH);
259 vnf_image_query_path = props.getProperty(VNF_IMAGE_QUERY_PATH);
261 ubb_notify_path = props.getProperty(UBB_NOTIFY_PATH);
262 selflink_avpn = props.getProperty(SELFLINK_AVPN);
263 selflink_fqdn = props.getProperty(SELFLINK_FQDN);
265 service_path = props.getProperty(SERVICE_PATH);
267 site_pair_set_path = props.getProperty(SITE_PAIR_SET_PATH);
269 query_nodes_path = props.getProperty(QUERY_NODES_PATH);
271 String iche = props.getProperty(CERTIFICATE_HOST_ERROR);
272 boolean host_error = false;
273 if(iche != null && !iche.isEmpty()) {
274 host_error = Boolean.valueOf(iche);
277 ignore_certificate_host_error = host_error;
279 HttpsURLConnection.setDefaultHostnameVerifier( new HostnameVerifier(){
280 public boolean verify(String string,SSLSession ssls) {
281 return ignore_certificate_host_error;
285 if(truststore_path != null && truststore_password != null && (new File(truststore_path)).exists()) {
286 System.setProperty("javax.net.ssl.trustStore", truststore_path);
287 System.setProperty("javax.net.ssl.trustStorePassword", truststore_password);
290 if(keystore_path != null && keystore_password != null && (new File(keystore_path)).exists())
292 DefaultClientConfig config = new DefaultClientConfig();
293 //both jersey and HttpURLConnection can use this
294 SSLContext ctx = null;
296 ctx = SSLContext.getInstance("TLS");
298 KeyManagerFactory kmf = null;
300 String def = "SunX509";
301 String storeType = "PKCS12";
302 def = KeyStore.getDefaultType();
303 kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
304 FileInputStream fin = new FileInputStream(keystore_path);
305 // KeyStore ks = KeyStore.getInstance("PKCS12");
307 String extension = keystore_path.substring(keystore_path.lastIndexOf(".") + 1);
309 if("JKS".equalsIgnoreCase(extension)) {
312 KeyStore ks = KeyStore.getInstance(storeType);
314 char[] pwd = keystore_password.toCharArray();
317 } catch (Exception ex) {
318 LOG.error("AAIResource", ex);
321 ctx.init(kmf.getKeyManagers(), null, null);
322 config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties( new HostnameVerifier() {
324 public boolean verify( String s, SSLSession sslSession ) {
325 return ignore_certificate_host_error;
330 LOG.debug("SSLContext created");
332 } catch (KeyManagementException | NoSuchAlgorithmException exc) {
333 LOG.error("AAIResource", exc);
337 LOG.info("AAIResource.ctor initialized.");
340 Field methodsField = HttpURLConnection.class.getDeclaredField("methods");
341 methodsField.setAccessible(true);
342 // get the methods field modifiers
343 Field modifiersField = Field.class.getDeclaredField("modifiers");
344 // bypass the "private" modifier
345 modifiersField.setAccessible(true);
347 // remove the "final" modifier
348 modifiersField.setInt(methodsField, methodsField.getModifiers() & ~Modifier.FINAL);
350 /* valid HTTP methods */
352 "GET", "POST", "HEAD", "OPTIONS", "PUT", "DELETE", "TRACE", "PATCH"
354 // set the new methods - including patch
355 methodsField.set(null, methods);
357 } catch (SecurityException | IllegalArgumentException | IllegalAccessException | NoSuchFieldException e) {
363 public void cleanUp() {
369 * @param http_req_url
374 protected HttpURLConnection getConfiguredConnection(URL http_req_url, String method) throws Exception {
375 HttpURLConnection con = (HttpURLConnection) http_req_url.openConnection();
377 // Set up the connection properties
378 con.setRequestProperty( "Connection", "close" );
379 con.setDoInput(true);
380 con.setDoOutput(true);
381 con.setUseCaches(false);
382 con.setConnectTimeout( connection_timeout );
383 con.setReadTimeout( read_timeout );
384 con.setRequestMethod( method );
385 con.setRequestProperty( "Accept", "application/json" );
386 con.setRequestProperty( "Content-Type", "PATCH".equalsIgnoreCase(method) ? "application/merge-patch+json" : "application/json" );
387 con.setRequestProperty("X-FromAppId", application_id);
388 con.setRequestProperty("X-TransactionId",TransactionIdTracker.getNextTransactionId());
389 String mlId = ml.getRequestID();
390 if(mlId != null && !mlId.isEmpty()) {
391 LOG.debug(String.format("MetricLogger requestId = %s", mlId));
392 con.setRequestProperty(MetricLogger.REQUEST_ID, mlId);
394 LOG.debug("MetricLogger requestId is null");
397 if(user_name != null && !user_name.isEmpty() && user_password != null && !user_password.isEmpty()) {
398 String basicAuth = "Basic " + new String(Base64.encodeBase64((user_name + ":" + user_password).getBytes()));
399 con.setRequestProperty ("Authorization", basicAuth);
402 if(con instanceof HttpsURLConnection && CTX != null) {
403 SSLSocketFactory sockFact = CTX.getSocketFactory();
404 HttpsURLConnection.class.cast(con).setSSLSocketFactory( sockFact );
411 public GenericVnf requestGenericVnfData(String vnf_id) throws AAIServiceException {
412 GenericVnf response = null;
415 AAIRequest request = AAIRequest.getRequestFromResource("generic-vnf");
416 request.addRequestProperty("generic-vnf.vnf-id", vnf_id);
417 String rv = executor.get(request);
419 ObjectMapper mapper = getObjectMapper();
420 response = mapper.readValue(rv, GenericVnf.class);
422 } catch(AAIServiceException aaiexc) {
424 } catch (Exception exc) {
425 LOG.warn(Object.class.getClass().getEnclosingMethod().getName(), exc);
426 throw new AAIServiceException(exc);
434 public boolean postGenericVnfData(String vnf_id, GenericVnf data) throws AAIServiceException {
436 AAIRequest request = AAIRequest.getRequestFromResource("generic-vnf");
437 request.addRequestProperty("generic-vnf.vnf-id", vnf_id);
438 request.setRequestObject(data);
439 Object response = executor.post(request);
441 } catch(AAIServiceException aaiexc) {
443 } catch (Exception exc) {
444 LOG.warn("requestGenericVnfData", exc);
445 throw new AAIServiceException(exc);
450 public boolean deleteGenericVnfData(String vnf_id, String resourceVersion) throws AAIServiceException {
451 boolean response = false;
454 AAIRequest request = AAIRequest.getRequestFromResource("generic-vnf");
455 request.addRequestProperty("generic-vnf.vnf-id", vnf_id);
456 response = executor.delete(request, resourceVersion);
457 } catch(AAIServiceException aaiexc) {
459 } catch (Exception exc) {
460 LOG.warn("deleteGenericVnfData", exc);
461 throw new AAIServiceException(exc);
467 * @see org.onap.ccsdk.sli.adaptors.resource.aic.AnAIClient#requestSdnZoneQuery(java.lang.String, java.lang.String, java.lang.String)
470 public Vce requestNetworkVceData(String vnf_id) throws AAIServiceException {
473 AAIRequest request = AAIRequest.getRequestFromResource("vce");
474 request.addRequestProperty("vce.vnf-id", vnf_id);
475 String rv = executor.get(request);
477 ObjectMapper mapper = getObjectMapper();
478 response = mapper.readValue(rv, Vce.class);
480 } catch(AAIServiceException aaiexc) {
482 } catch (Exception exc) {
483 LOG.warn(Object.class.getClass().getEnclosingMethod().getName(), exc);
484 throw new AAIServiceException(exc);
492 * @see org.onap.ccsdk.sli.adaptors.resource.aic.AnAIClient#requestSdnZoneQuery(java.lang.String, java.lang.String, java.lang.String)
495 public boolean deleteNetworkVceData(String vnf_id, String resourceVersion) throws AAIServiceException {
496 boolean response = false;
499 AAIRequest request = AAIRequest.getRequestFromResource("vce");
500 request.addRequestProperty("vce.vnf-id", vnf_id);
501 response = executor.delete(request, resourceVersion);
502 } catch(AAIServiceException aaiexc) {
504 } catch (Exception exc) {
505 LOG.warn("deleteNetworkVceData", exc);
506 throw new AAIServiceException(exc);
512 * @see org.onap.ccsdk.sli.adaptors.resource.aic.AnAIClient#postNetworkVceData(java.lang.String, org.onap.ccsdk.sli.adaptors.resource.aic.aai.VCERequest)
515 public boolean postNetworkVceData(String vnf_id, Vce data) throws AAIServiceException {
517 AAIRequest request = AAIRequest.getRequestFromResource("vce");
518 request.addRequestProperty("vce.vnf-id", vnf_id);
519 request.setRequestObject(data);
520 Object response = executor.post(request);
522 } catch(AAIServiceException aaiexc) {
524 } catch (Exception exc) {
525 LOG.warn("requestGenericVnfData", exc);
526 throw new AAIServiceException(exc);
532 public SearchResults requestServiceInstanceURL(String svc_instance_id) throws AAIServiceException {
533 SearchResults response = null;
534 InputStream inputStream = null;
537 String path = svc_inst_qry_path;
538 path = path.replace("{svc-instance-id}", encodeQuery(svc_instance_id));
540 String request_url = target_uri+path;
541 URL http_req_url = new URL(request_url);
543 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.GET);
545 LOGwriteFirstTrace(HttpMethod.GET, http_req_url.toString());
546 LOGwriteDateTrace("svc_instance_id", svc_instance_id);
549 int responseCode = con.getResponseCode();
550 if (responseCode == HttpURLConnection.HTTP_OK) {
551 inputStream = con.getInputStream();
553 inputStream = con.getErrorStream();
556 // Process the response
557 LOG.debug("HttpURLConnection result:" + responseCode);
558 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
559 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
561 ObjectMapper mapper = getObjectMapper();
563 if (responseCode == HttpURLConnection.HTTP_OK) {
564 // StringBuilder stringBuilder = new StringBuilder("\n");
565 // String line = null;
566 // while( ( line = reader.readLine() ) != null ) {
567 // stringBuilder.append("\n").append( line );
569 // LOG.info(stringBuilder.toString());
570 response = mapper.readValue(reader, SearchResults.class);
571 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, "SUCCESS", mapper.writeValueAsString(response));
572 } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
573 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
576 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
577 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
578 throw new AAIServiceException(responseCode, errorresponse);
581 } catch(AAIServiceException aaiexc) {
583 } catch (Exception exc) {
584 LOG.warn("requestServiceInstanceURL", exc);
585 throw new AAIServiceException(exc);
587 if(inputStream != null){
590 } catch(Exception exc) {
598 public ServiceInstance requestServiceInterfaceData(String customer_id, String service_type, String svc_instance_id) throws AAIServiceException {
599 ServiceInstance response = null;
602 AAIRequest request = AAIRequest.getRequestFromResource("service-instance");
603 request.addRequestProperty("customer.global-customer-id", customer_id);
604 request.addRequestProperty("ervice-subscription.service-type", service_type);
605 request.addRequestProperty("service-instance.service-instance-id", svc_instance_id);
607 String rv = executor.get(request);
609 ObjectMapper mapper = getObjectMapper();
610 response = mapper.readValue(rv, ServiceInstance.class);
612 } catch(AAIServiceException aaiexc) {
614 } catch (Exception exc) {
615 LOG.warn("requestServiceInterfaceData", exc);
616 throw new AAIServiceException(exc);
622 public boolean postServiceInterfaceData(String customer_id, String service_type, String svc_instance_id, ServiceInstance data) throws AAIServiceException {
624 AAIRequest request = AAIRequest.getRequestFromResource("service-instance");
625 request.addRequestProperty("customer.customer-id", customer_id);
626 request.addRequestProperty("service-subscription.service-type", service_type);
627 request.addRequestProperty("service-instance.service-instance-id", svc_instance_id);
628 request.setRequestObject(data);
629 Object response = executor.post(request);
631 } catch(AAIServiceException aaiexc) {
633 } catch (Exception exc) {
634 LOG.warn("requestGenericVnfData", exc);
635 throw new AAIServiceException(exc);
640 private static Properties initialize(URL url ) throws ConfigurationException {
643 throw new NullPointerException();
646 InputStream is = null;
647 Properties props = new Properties();
650 if(LOG.isDebugEnabled())
651 LOG.info("Property file is: " + url.toString());
653 is = url.openStream();
656 if(LOG.isDebugEnabled()) {
657 LOG.info("Properties loaded: " + props.size());
658 Enumeration<Object> en = props.keys();
660 while(en.hasMoreElements()) {
661 String key = (String)en.nextElement();
662 String property = props.getProperty(key);
663 LOG.debug(key + " : " + property);
666 } catch (Exception e) {
667 throw new ConfigurationException("Could not load properties file.", e);
672 static class TransactionIdTracker {
673 // protected static AtomicLong tracker = new AtomicLong();
675 public static String getNextTransactionId() {
676 // Check if RequestId exists as MDC. If not, create new.
677 String transactionId = MDC.get("RequestId");
678 if ("".equals(transactionId) || transactionId == null) {
679 transactionId = UUID.randomUUID().toString();
680 LOG.info("Missing requestID. Assigned " + transactionId);
681 MDC.put("RequestId", transactionId);
683 return transactionId;
688 protected void LOGwriteFirstTrace(String method, String url) {
689 String time = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").format(System.currentTimeMillis());
690 LOG.info("A&AI transaction :");
691 LOG.info("Request Time : " + time + ", Method : " + method);
692 LOG.info("Request URL : "+ url);
695 protected void LOGwriteDateTrace(String name, String data) {
696 LOG.info("Input - " + name + " : " + data);
699 protected void LOGwriteEndingTrace(int response_code, String comment, String data) {
700 LOG.info("Response code : " + response_code +", " + comment);
701 LOG.info(String.format("Response data : %s", data));
704 protected String encodeQuery(String param) throws UnsupportedEncodingException {
705 return URLEncoder.encode(param, "UTF-8").replace("+", "%20");
708 private String encodeCustomerURL(final String selection)
710 String encrypted_url = selection;
712 "/aai/v11/business/customers/customer/(.+)/service-subscriptions/service-subscription/(.+)/service-instances/service-instance/(.+)/";
713 Pattern pattern = Pattern.compile(apnpattern);
716 URL url = new URL(selection);
717 String path = url.getPath();
719 LOG.info("Trying to match apn to <" + path + ">");
721 Matcher matcher = pattern.matcher(path);
723 while(matcher.find()) {
724 String customer = matcher.group(1);
725 String subscription = matcher.group(2);
726 String service = matcher.group(3);
728 encrypted_url = selection.replace(customer, encodeQuery(customer));
729 encrypted_url = encrypted_url.replace(subscription, encodeQuery(subscription));
730 encrypted_url = encrypted_url.replace(service, encodeQuery(service));
732 } catch (Exception e) {
736 return encrypted_url;
740 public Vpe requestNetworkVpeData(String vnf_id) throws AAIServiceException {
744 AAIRequest request = AAIRequest.getRequestFromResource("vpe");
745 request.addRequestProperty("vpe.vnf-id", vnf_id);
746 String rv = executor.get(request);
748 ObjectMapper mapper = getObjectMapper();
749 response = mapper.readValue(rv, Vpe.class);
751 } catch(AAIServiceException aaiexc) {
753 } catch (Exception exc) {
754 LOG.warn(Object.class.getClass().getEnclosingMethod().getName(), exc);
755 throw new AAIServiceException(exc);
761 public boolean postNetworkVpeData(String vnf_id, Vpe data) throws AAIServiceException {
763 AAIRequest request = AAIRequest.getRequestFromResource("vpe");
764 request.addRequestProperty("vpe.vnf-id", vnf_id);
765 request.setRequestObject(data);
766 Object response = executor.post(request);
768 } catch(AAIServiceException aaiexc) {
770 } catch (Exception exc) {
771 LOG.warn(Object.class.getClass().getEnclosingMethod().getName(), exc);
772 throw new AAIServiceException(exc);
777 public boolean deleteNetworkVpeData(String vnf_id, String resourceVersion) throws AAIServiceException {
778 boolean response = false;
781 AAIRequest request = AAIRequest.getRequestFromResource("vpe");
782 request.addRequestProperty("vpe.vnf-id", vnf_id);
783 response = executor.delete(request, resourceVersion);
784 } catch(AAIServiceException aaiexc) {
786 } catch (Exception exc) {
787 LOG.warn(Object.class.getClass().getEnclosingMethod().getName(), exc);
788 throw new AAIServiceException(exc);
794 public VplsPe requestNetworkVplsPeData(String equipment_name)throws AAIServiceException {
795 VplsPe response = null;
798 AAIRequest request = AAIRequest.getRequestFromResource("vpls-pe");
799 request.addRequestProperty("vpls-pe.equipment-name", equipment_name);
801 String rv = executor.get(request);
803 ObjectMapper mapper = getObjectMapper();
804 response = mapper.readValue(rv, VplsPe.class);
806 } catch(AAIServiceException aaiexc) {
808 } catch (Exception exc) {
809 LOG.warn(Object.class.getClass().getEnclosingMethod().getName(),
811 throw new AAIServiceException(exc);
817 public boolean postNetworkVplsPeData(String equipment_name, VplsPe data) throws AAIServiceException {
819 AAIRequest request = AAIRequest.getRequestFromResource("vpls-pe");
820 request.addRequestProperty("vpls-pe.equipment-name", equipment_name);
821 request.setRequestObject(data);
822 Object response = executor.post(request);
824 } catch(AAIServiceException aaiexc) {
826 } catch (Exception exc) {
827 LOG.warn("requestGenericVnfData", exc);
828 throw new AAIServiceException(exc);
833 public boolean deleteNetworkVplsPeData(String vnf_id, String resourceVersion) throws AAIServiceException {
834 boolean response = false;
837 AAIRequest request = AAIRequest.getRequestFromResource("vpls-pe");
838 request.addRequestProperty("vpls-pe.equipment-name", vnf_id);
839 response = executor.delete(request, resourceVersion);
840 } catch(AAIServiceException aaiexc) {
842 } catch (Exception exc) {
843 LOG.warn("deleteNetworkVplsPeData", exc);
844 throw new AAIServiceException(exc);
850 public Complex requestNetworkComplexData(String pLocId) throws AAIServiceException {
851 Complex response = null;
854 AAIRequest request = AAIRequest.getRequestFromResource("complex");
855 request.addRequestProperty("complex.physical-location-id", pLocId);
857 String rv = executor.get(request);
859 ObjectMapper mapper = getObjectMapper();
860 response = mapper.readValue(rv, Complex.class);
862 } catch(AAIServiceException aaiexc) {
864 } catch (Exception exc) {
865 LOG.warn("requestNetworkComplexData", exc);
866 throw new AAIServiceException(exc);
872 public boolean postNetworkComplexData(String vnf_id, Complex data) throws AAIServiceException {
874 AAIRequest request = AAIRequest.getRequestFromResource("complex");
875 request.addRequestProperty("complex.physical-location-id", vnf_id);
876 request.setRequestObject(data);
877 Object response = executor.post(request);
879 } catch(AAIServiceException aaiexc) {
881 } catch (Exception exc) {
882 LOG.warn("postNetworkComplexData", exc);
883 throw new AAIServiceException(exc);
888 public boolean deleteNetworkComplexData(String pLocId, String resourceVersion) throws AAIServiceException {
889 boolean response = false;
892 AAIRequest request = AAIRequest.getRequestFromResource("complex");
893 request.addRequestProperty("complex.physical-location-id", pLocId);
895 response = executor.delete(request, resourceVersion);
897 } catch(AAIServiceException aaiexc) {
899 } catch (Exception exc) {
900 LOG.warn("deleteNetworkComplexData", exc);
901 throw new AAIServiceException(exc);
908 * @see org.openecomp.sdnct.sli.aai.AAIClient#requestVServersData(java.lang.String, java.lang.String)
911 public Vserver requestVServerData(String tenantId, String vserverId, String cloudOwner, String cloudRegionId) throws AAIServiceException {
912 Vserver response = null;
915 AAIRequest request = AAIRequest.getRequestFromResource("vserver");
916 request.addRequestProperty("cloud-region.cloud-owner", cloudOwner);
917 request.addRequestProperty("cloud-region.cloud-region-id", cloudRegionId);
918 request.addRequestProperty("tenant.tenant-id", tenantId);
919 request.addRequestProperty("vserver.vserver-id", vserverId);
921 String rv = executor.get(request);
923 ObjectMapper mapper = getObjectMapper();
924 response = mapper.readValue(rv, Vserver.class);
926 } catch(AAIServiceException aaiexc) {
928 } catch (Exception exc) {
929 LOG.warn(Object.class.getClass().getEnclosingMethod().getName(), exc);
930 throw new AAIServiceException(exc);
937 public boolean postVServerData(String tenantId, String vserverId, String cloudOwner, String cloudRegionId, Vserver data) throws AAIServiceException {
939 AAIRequest request = AAIRequest.getRequestFromResource("vserver");
940 request.addRequestProperty("cloud-region.cloud-owner", cloudOwner);
941 request.addRequestProperty("cloud-region.cloud-region-id", cloudRegionId);
942 request.addRequestProperty("tenant.tenant-id", tenantId);
943 request.addRequestProperty("vserver.vserver-id", vserverId);
944 request.setRequestObject(data);
945 Object response = executor.post(request);
947 } catch(AAIServiceException aaiexc) {
949 } catch (Exception exc) {
950 LOG.warn("postNetworkComplexData", exc);
951 throw new AAIServiceException(exc);
956 public boolean deleteVServerData(String tenant_id, String vserver_id, String cloudOwner, String cloudRegionId, String resourceVersion) throws AAIServiceException {
957 boolean response = false;
958 InputStream inputStream = null;
961 String local_network_complexes_path = network_vserver_path.replace("{tenant-id}", encodeQuery(tenant_id));
962 local_network_complexes_path = local_network_complexes_path.replace("{vserver-id}", encodeQuery(vserver_id));
963 local_network_complexes_path = local_network_complexes_path.replace("{cloud-owner}", encodeQuery(cloudOwner));
964 local_network_complexes_path = local_network_complexes_path.replace("{cloud-region-id}", encodeQuery(cloudRegionId));
966 String request_url = target_uri+local_network_complexes_path;
967 if(resourceVersion!=null) {
968 request_url = request_url +"?resource-version="+resourceVersion;
970 URL http_req_url = new URL(request_url);
972 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.DELETE);
974 LOGwriteFirstTrace(HttpMethod.DELETE, http_req_url.toString());
975 LOGwriteDateTrace("tenant_id", tenant_id);
976 LOGwriteDateTrace("vserver_id", vserver_id);
977 LOGwriteDateTrace("cloud-owner", cloudOwner);
978 LOGwriteDateTrace("cloud-region-id", cloudRegionId);
981 int responseCode = con.getResponseCode();
982 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
983 inputStream = con.getInputStream();
985 inputStream = con.getErrorStream();
988 // Process the response
989 LOG.debug("HttpURLConnection result:" + responseCode);
990 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
991 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
994 ObjectMapper mapper = getObjectMapper();
996 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
997 StringBuilder stringBuilder = new StringBuilder();
999 while( ( line = reader.readLine() ) != null ) {
1000 stringBuilder.append( line );
1002 LOGwriteEndingTrace(responseCode, "SUCCESS", stringBuilder.toString());
1004 } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
1005 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
1008 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
1009 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
1010 throw new AAIServiceException(responseCode, errorresponse);
1013 } catch(AAIServiceException aaiexc) {
1015 } catch (Exception exc) {
1016 LOG.warn("deleteVServerData", exc);
1017 throw new AAIServiceException(exc);
1019 if(inputStream != null){
1021 inputStream.close();
1022 } catch(Exception exc) {
1033 * @see org.onap.ccsdk.sli.adaptors.aai.AAIClient#requestCtagPoolData(String)
1036 public CtagPool requestCtagPoolData(String physical_location_id, String target_pe, String availability_zone_name) throws AAIServiceException {
1037 CtagPool response = null;
1040 AAIRequest request = AAIRequest.getRequestFromResource("ctag-pool");
1042 request.addRequestProperty("ctag-pool.target-pe", target_pe);
1043 request.addRequestProperty("ctag-pool.availability-zone-name", availability_zone_name);
1044 request.addRequestProperty("complex.physical-location-id", physical_location_id);
1046 String rv = executor.get(request);
1048 ObjectMapper mapper = getObjectMapper();
1049 response = mapper.readValue(rv, CtagPool.class);
1051 } catch(AAIServiceException aaiexc) {
1053 } catch (Exception exc) {
1054 LOG.warn("requestNetworkVceData", exc);
1055 throw new AAIServiceException(exc);
1060 //==================== DvsSwitch ======================
1062 public DvsSwitch requestDvsSwitchData(String vnf_id) throws AAIServiceException {
1063 DvsSwitch response = null;
1066 AAIRequest request = AAIRequest.getRequestFromResource("dvs-switch");
1067 request.addRequestProperty("dvs-switch.switch-name", vnf_id);
1069 String rv = executor.get(request);
1071 ObjectMapper mapper = getObjectMapper();
1072 response = mapper.readValue(rv, DvsSwitch.class);
1074 } catch(AAIServiceException aaiexc) {
1076 } catch (Exception exc) {
1077 LOG.warn("requestDvsSwitchData", exc);
1078 throw new AAIServiceException(exc);
1084 public boolean postDvsSwitchData(String switch_name, DvsSwitch data) throws AAIServiceException {
1086 AAIRequest request = AAIRequest.getRequestFromResource("dvs-switch");
1087 request.addRequestProperty("dvs-switch.switch-name", switch_name);
1088 request.setRequestObject(data);
1089 Object response = executor.post(request);
1091 } catch(AAIServiceException aaiexc) {
1093 } catch (Exception exc) {
1094 LOG.warn(Object.class.getClass().getEnclosingMethod().getName(), exc);
1095 throw new AAIServiceException(exc);
1100 public boolean deleteDvsSwitchData(String vnf_id, String resourceVersion) throws AAIServiceException {
1101 boolean response = false;
1102 InputStream inputStream = null;
1105 AAIRequest request = AAIRequest.getRequestFromResource("dvs-switch");
1106 request.addRequestProperty("dvs-switch.switch-name", vnf_id);
1107 response = executor.delete(request, resourceVersion);
1108 } catch(AAIServiceException aaiexc) {
1110 } catch (Exception exc) {
1111 LOG.warn("deleteDvsSwitchData", exc);
1112 throw new AAIServiceException(exc);
1116 //================== End of DvsSwitch =================
1117 //==================== PhysicalLink ======================
1119 public PhysicalLink requestPhysicalLinkData(String linkName) throws AAIServiceException {
1120 PhysicalLink response = null;
1123 AAIRequest request = AAIRequest.getRequestFromResource("physical-link");
1124 request.addRequestProperty("physical-link.link-name", linkName);
1126 String rv = executor.get(request);
1128 ObjectMapper mapper = getObjectMapper();
1129 response = mapper.readValue(rv, PhysicalLink.class);
1131 } catch(AAIServiceException aaiexc) {
1133 } catch (Exception exc) {
1134 LOG.warn("requestPhysicalLinkData", exc);
1135 throw new AAIServiceException(exc);
1141 public boolean postPhysicalLinkData(String linkName, PhysicalLink data) throws AAIServiceException {
1143 AAIRequest request = AAIRequest.getRequestFromResource("physical-link");
1144 request.addRequestProperty("physical-link.link-name", linkName);
1145 request.setRequestObject(data);
1146 Object response = executor.post(request);
1148 } catch(AAIServiceException aaiexc) {
1150 } catch (Exception exc) {
1151 LOG.warn(Object.class.getClass().getEnclosingMethod().getName(), exc);
1152 throw new AAIServiceException(exc);
1157 public boolean deletePhysicalLinkData(String linkName, String resourceVersion) throws AAIServiceException {
1158 boolean response = false;
1161 AAIRequest request = AAIRequest.getRequestFromResource("physical-link");
1162 request.addRequestProperty("physical-link.link-name", linkName);
1163 response = executor.delete(request, resourceVersion);
1164 } catch(AAIServiceException aaiexc) {
1166 } catch (Exception exc) {
1167 LOG.warn("deletePhysicalLinkData", exc);
1168 throw new AAIServiceException(exc);
1172 //================== End of PhysicalLink =================
1173 //==================== PInterface ======================
1175 public PInterface requestPInterfaceData(String hostname, String interfaceName) throws AAIServiceException {
1176 PInterface response = null;
1179 AAIRequest request = new PInterfaceRequest();
1180 request.addRequestProperty(PInterfaceRequest.PINTERFACE_INTERFACE_NAME, interfaceName);
1181 request.addRequestProperty(PInterfaceRequest.PSERVER_HOSTNAME, hostname);
1182 String rv = executor.get(request);
1184 ObjectMapper mapper = getObjectMapper();
1185 response = mapper.readValue(rv, PInterface.class);
1187 } catch(AAIServiceException aaiexc) {
1189 } catch (Exception exc) {
1190 LOG.warn(Object.class.getClass().getEnclosingMethod().getName(), exc);
1191 throw new AAIServiceException(exc);
1197 public boolean postPInterfaceData(String hostname, String interfaceName, PInterface request) throws AAIServiceException {
1198 InputStream inputStream = null;
1202 ObjectMapper mapper = getObjectMapper();
1203 String json_text = mapper.writeValueAsString(request);
1205 SSLSocketFactory sockFact = CTX.getSocketFactory();
1207 String request_url = target_uri+p_interface_path;
1208 String encoded_vnf = encodeQuery(hostname);
1209 request_url = request_url.replace("{hostname}", encoded_vnf) ;
1210 encoded_vnf = encodeQuery(interfaceName);
1211 request_url = request_url.replace("{interface-name}", encoded_vnf) ;
1212 URL http_req_url = new URL(request_url);
1214 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.PUT);
1216 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
1217 osw.write(json_text);
1222 LOGwriteFirstTrace("PUT", request_url);
1223 LOGwriteDateTrace("hostname", hostname);
1224 LOGwriteDateTrace("interface-name", interfaceName);
1225 LOGwriteDateTrace("PInterface", json_text);
1228 int responseCode = con.getResponseCode();
1229 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1230 inputStream = con.getInputStream();
1232 inputStream = con.getErrorStream();
1235 // Process the response
1236 BufferedReader reader;
1238 reader = new BufferedReader( new InputStreamReader( inputStream ) );
1240 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1241 StringBuilder stringBuilder = new StringBuilder();
1243 while( ( line = reader.readLine() ) != null ) {
1244 stringBuilder.append( line );
1246 LOGwriteEndingTrace(responseCode, "SUCCESS", (stringBuilder.length() > 0) ? stringBuilder.toString() : "{no-data}");
1249 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
1250 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
1252 throw new AAIServiceException(responseCode, errorresponse);
1254 } catch(AAIServiceException aaiexc) {
1256 } catch (Exception exc) {
1257 LOG.warn("postPInterfaceData", exc);
1258 throw new AAIServiceException(exc);
1261 if(inputStream != null)
1262 inputStream.close();
1263 } catch (Exception exc) {
1270 public boolean deletePInterfaceData(String hostname, String interfaceName, String resourceVersion) throws AAIServiceException {
1271 boolean response = false;
1274 AAIRequest request = AAIRequest.getRequestFromResource("p-interface");
1275 request.addRequestProperty("p-interface.interface-name", interfaceName);
1276 request.addRequestProperty("pserver.hostname", hostname);
1277 response = executor.delete(request, resourceVersion);
1278 } catch(AAIServiceException aaiexc) {
1280 } catch (Exception exc) {
1281 LOG.warn("deletePInterfaceData", exc);
1282 throw new AAIServiceException(exc);
1286 //================== End of PInterface =================
1287 //==================== SitePairSet ======================
1289 public SitePairSet requestSitePairSetData(String sitePairSetId) throws AAIServiceException {
1290 SitePairSet response = null;
1293 AAIRequest request = AAIRequest.getRequestFromResource("site-pair-set");
1294 request.addRequestProperty("site-pair-set.site-pair-set-id", sitePairSetId);
1295 String rv = executor.get(request);
1297 ObjectMapper mapper = getObjectMapper();
1298 response = mapper.readValue(rv, SitePairSet.class);
1300 } catch(AAIServiceException aaiexc) {
1302 } catch (Exception exc) {
1303 LOG.warn(Object.class.getClass().getEnclosingMethod().getName(), exc);
1304 throw new AAIServiceException(exc);
1310 public boolean postSitePairSetData(String linkName, SitePairSet request) throws AAIServiceException {
1311 InputStream inputStream = null;
1315 ObjectMapper mapper = getObjectMapper();
1316 String json_text = mapper.writeValueAsString(request);
1318 SSLSocketFactory sockFact = CTX.getSocketFactory();
1320 String request_url = target_uri+site_pair_set_path;
1321 String encoded_vnf = encodeQuery(linkName);
1322 request_url = request_url.replace("{site-pair-set-id}", encoded_vnf) ;
1323 URL http_req_url = new URL(request_url);
1325 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.PUT);
1327 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
1328 osw.write(json_text);
1333 LOGwriteFirstTrace("PUT", request_url);
1334 LOGwriteDateTrace("link-name", linkName);
1335 LOGwriteDateTrace("SitePairSet", json_text);
1338 int responseCode = con.getResponseCode();
1339 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1340 inputStream = con.getInputStream();
1342 inputStream = con.getErrorStream();
1345 // Process the response
1346 BufferedReader reader;
1348 reader = new BufferedReader( new InputStreamReader( inputStream ) );
1350 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1351 StringBuilder stringBuilder = new StringBuilder();
1353 while( ( line = reader.readLine() ) != null ) {
1354 stringBuilder.append( line );
1356 LOGwriteEndingTrace(responseCode, "SUCCESS", (stringBuilder.length() > 0) ? stringBuilder.toString() : "{no-data}");
1359 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
1360 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
1362 throw new AAIServiceException(responseCode, errorresponse);
1364 } catch(AAIServiceException aaiexc) {
1366 } catch (Exception exc) {
1367 LOG.warn("postSitePairSetData", exc);
1368 throw new AAIServiceException(exc);
1371 if(inputStream != null)
1372 inputStream.close();
1373 } catch (Exception exc) {
1380 public boolean deleteSitePairSetData(String linkName, String resourceVersion) throws AAIServiceException {
1381 boolean response = false;
1384 AAIRequest request = AAIRequest.getRequestFromResource("site-pair-set");
1385 request.addRequestProperty("site-pair-set.site-pair-set-id", linkName);
1386 response = executor.delete(request, resourceVersion);
1387 } catch(AAIServiceException aaiexc) {
1389 } catch (Exception exc) {
1390 LOG.warn("deleteSitePairSetData", exc);
1391 throw new AAIServiceException(exc);
1396 //================== End of SitePairSet =================
1397 //==================== Service ======================
1399 public Service requestServiceData(String serviceId) throws AAIServiceException {
1400 Service response = null;
1401 InputStream inputStream = null;
1404 AAIRequest request = AAIRequest.getRequestFromResource("service");
1405 request.addRequestProperty("service.service-id", serviceId);
1408 String rv = executor.get(request);
1410 ObjectMapper mapper = getObjectMapper();
1411 response = mapper.readValue(rv, Service.class);
1413 } catch(AAIServiceException aaiexc) {
1415 } catch (Exception exc) {
1416 LOG.warn("requestServiceData", exc);
1417 throw new AAIServiceException(exc);
1423 public boolean postServiceData(String linkName, Service request) throws AAIServiceException {
1424 InputStream inputStream = null;
1428 ObjectMapper mapper = getObjectMapper();
1429 String json_text = mapper.writeValueAsString(request);
1431 SSLSocketFactory sockFact = CTX.getSocketFactory();
1433 String request_url = target_uri+service_path;
1434 String encoded_vnf = encodeQuery(linkName);
1435 request_url = request_url.replace("{service-id}", encoded_vnf) ;
1436 URL http_req_url = new URL(request_url);
1438 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.PUT);
1440 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
1441 osw.write(json_text);
1446 LOGwriteFirstTrace("PUT", request_url);
1447 LOGwriteDateTrace("service-id", linkName);
1448 LOGwriteDateTrace("Service", json_text);
1451 int responseCode = con.getResponseCode();
1452 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1453 inputStream = con.getInputStream();
1455 inputStream = con.getErrorStream();
1458 // Process the response
1459 BufferedReader reader;
1461 reader = new BufferedReader( new InputStreamReader( inputStream ) );
1463 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1464 StringBuilder stringBuilder = new StringBuilder();
1466 while( ( line = reader.readLine() ) != null ) {
1467 stringBuilder.append( line );
1469 LOGwriteEndingTrace(responseCode, "SUCCESS", (stringBuilder.length() > 0) ? stringBuilder.toString() : "{no-data}");
1472 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
1473 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
1475 throw new AAIServiceException(responseCode, errorresponse);
1477 } catch(AAIServiceException aaiexc) {
1479 } catch (Exception exc) {
1480 LOG.warn("postServiceData", exc);
1481 throw new AAIServiceException(exc);
1484 if(inputStream != null)
1485 inputStream.close();
1486 } catch (Exception exc) {
1493 public boolean deleteServiceData(String service_id, String resourceVersion) throws AAIServiceException {
1494 boolean response = false;
1497 AAIRequest request = AAIRequest.getRequestFromResource("service");
1498 request.addRequestProperty("service.service-id", service_id);
1499 response = executor.delete(request, resourceVersion);
1500 } catch(AAIServiceException aaiexc) {
1502 } catch (Exception exc) {
1503 LOG.warn("deleteServiceData", exc);
1504 throw new AAIServiceException(exc);
1509 //================== End of Service =================
1515 public VServer dataChangeRequestVServerData(URL url) throws AAIServiceException {
1518 throw new NullPointerException();
1521 return this.getResource(url.toString(), VServer.class);
1525 public Pserver dataChangeRequestPServerData(URL url) throws AAIServiceException {
1528 throw new NullPointerException();
1531 return this.getResource(url.toString(), Pserver.class);
1535 public CtagPool dataChangeRequestCtagPoolData(URL url) throws AAIServiceException {
1538 throw new NullPointerException();
1541 return this.getResource(url.toString(), CtagPool.class);
1545 public VplsPe dataChangeRequestVplsPeData(URL url) throws AAIServiceException {
1548 throw new NullPointerException();
1551 return this.getResource(url.toString(), VplsPe.class);
1555 public Vpe dataChangeRequestVpeData(URL url) throws AAIServiceException {
1558 throw new NullPointerException();
1561 return this.getResource(url.toString(), Vpe.class);
1565 public DvsSwitch dataChangeRequestDvsSwitchData(URL url) throws AAIServiceException {
1568 throw new NullPointerException();
1571 return this.getResource(url.toString(), DvsSwitch.class);
1575 public OamNetwork dataChangeRequestOAMNetworkData(URL url) throws AAIServiceException {
1578 throw new NullPointerException();
1581 return this.getResource(url.toString(), OamNetwork.class);
1585 public AvailabilityZone dataChangeRequestAvailabilityZoneData(URL url) throws AAIServiceException {
1588 throw new NullPointerException();
1591 return this.getResource(url.toString(), AvailabilityZone.class);
1595 public Complex dataChangeRequestComplexData(URL url) throws AAIServiceException {
1598 throw new NullPointerException();
1601 return this.getResource(url.toString(), Complex.class);
1606 public boolean dataChangeDeleteVServerData(URL url) throws AAIServiceException {
1609 throw new NullPointerException();
1612 return deleteAAIEntity(url, Object.class.getClass().getEnclosingMethod()
1617 public boolean dataChangeDeleteCtagPoolData(URL url) throws AAIServiceException {
1620 throw new NullPointerException();
1623 return deleteAAIEntity(url, Object.class.getClass().getEnclosingMethod()
1628 public boolean dataChangeDeleteVplsPeData(URL url) throws AAIServiceException {
1631 throw new NullPointerException();
1634 return deleteAAIEntity(url, Object.class.getClass().getEnclosingMethod()
1639 public boolean dataChangeDeleteVpeData(URL url) throws AAIServiceException {
1642 throw new NullPointerException();
1645 return deleteAAIEntity(url, Object.class.getClass().getEnclosingMethod()
1650 public boolean dataChangeDeleteDvsSwitchData(URL url) throws AAIServiceException {
1653 throw new NullPointerException();
1656 return deleteAAIEntity(url, Object.class.getClass().getEnclosingMethod()
1661 public boolean dataChangeDeleteOAMNetworkData(URL url) throws AAIServiceException {
1664 throw new NullPointerException();
1667 return deleteAAIEntity(url, Object.class.getClass().getEnclosingMethod()
1670 //Availability-Zone:
1672 public boolean dataChangeDeleteAvailabilityZoneData(URL url) throws AAIServiceException {
1675 throw new NullPointerException();
1678 return deleteAAIEntity(url, Object.class.getClass().getEnclosingMethod()
1683 public boolean dataChangeDeleteComplexData(URL url) throws AAIServiceException {
1686 throw new NullPointerException();
1689 return deleteAAIEntity(url, Object.class.getClass().getEnclosingMethod()
1693 private boolean deleteAAIEntity(URL url, String caller) throws AAIServiceException {
1696 throw new NullPointerException();
1699 boolean response = false;
1700 InputStream inputStream = null;
1703 URL http_req_url = url;
1705 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.DELETE);
1707 // SSLSocketFactory sockFact = CTX.getSocketFactory();
1708 // con.setSSLSocketFactory( sockFact );
1710 LOGwriteFirstTrace("DELETE", http_req_url.toString());
1714 int responseCode = con.getResponseCode();
1715 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1716 inputStream = con.getInputStream();
1718 inputStream = con.getErrorStream();
1721 // Process the response
1722 LOG.debug("HttpURLConnection result:" + responseCode);
1723 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
1724 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
1727 ObjectMapper mapper = getObjectMapper();
1729 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1730 StringBuilder stringBuilder = new StringBuilder();
1732 while( ( line = reader.readLine() ) != null ) {
1733 stringBuilder.append( line );
1735 LOGwriteEndingTrace(responseCode, "SUCCESS", stringBuilder.toString());
1737 } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
1738 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
1741 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
1742 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
1743 throw new AAIServiceException(responseCode, errorresponse);
1746 } catch(AAIServiceException aaiexc) {
1748 } catch (Exception exc) {
1749 LOG.warn(caller, exc);
1750 throw new AAIServiceException(exc);
1752 if(inputStream != null){
1754 inputStream.close();
1755 } catch(Exception exc) {
1764 * Generic method to GET json data from an A&AI callback URL.
1765 * Then convert that json to an Object.
1766 * If successful the Object is attempted to be cast to the type parameter.
1769 * callback url for A&AI
1771 * the class of object that A&AI will return
1772 * @return the object created from json or null if the response code is not 200
1774 * @throws AAIServiceException
1775 * if empty or null key and or type or there's an error with processing
1777 public <T> T dataChangeRequestAaiData(String key, Class<T> type) throws AAIServiceException {
1778 if (StringUtils.isEmpty(key) || type == null) {
1779 throw new AAIServiceException("Key is empty or null and or type is null");
1784 SvcLogicContext ctx = new SvcLogicContext();
1785 if(!key.contains(" = ") && isValidURL(key)) {
1786 key = String.format("selflink = '%s'", key);
1788 if(!key.contains(" = ") && isValidURI(key)) {
1789 key = String.format("resource-path = '%s'", key);
1792 HashMap<String, String> nameValues = AAIServiceUtils.keyToHashMap(key, ctx);
1794 SelfLinkRequest request = new SelfLinkRequest(type);
1795 request.processRequestPathValues(nameValues);
1796 Object obj = this.getExecutor().query(request, type);
1797 response = type.cast(obj);
1799 return response != null ? type.cast(response) : response;
1803 public Pserver requestPServerData(String hostname) throws AAIServiceException {
1804 Pserver response = null;
1805 InputStream inputStream = null;
1808 AAIRequest request = AAIRequest.getRequestFromResource("pserver");
1809 request.addRequestProperty("pserver.hostname", hostname);
1812 String rv = executor.get(request);
1814 ObjectMapper mapper = getObjectMapper();
1815 response = mapper.readValue(rv, Pserver.class);
1817 } catch(AAIServiceException aaiexc) {
1819 } catch (Exception exc) {
1820 LOG.warn("requestPServerData", exc);
1821 throw new AAIServiceException(exc);
1827 public boolean postPServerData(String hostname, Pserver data) throws AAIServiceException {
1829 AAIRequest request = AAIRequest.getRequestFromResource("pserver");
1830 request.addRequestProperty("pserver.hostname", hostname);
1831 request.setRequestObject(data);
1832 Object response = executor.post(request);
1834 } catch(AAIServiceException aaiexc) {
1836 } catch (Exception exc) {
1837 LOG.warn(Object.class.getClass().getEnclosingMethod().getName(), exc);
1838 throw new AAIServiceException(exc);
1843 public boolean deletePServerData(String hostname, String resourceVersion) throws AAIServiceException {
1844 boolean response = false;
1847 AAIRequest request = AAIRequest.getRequestFromResource("pserver");
1848 request.addRequestProperty("pserver.hostname", hostname);
1849 response = executor.delete(request, resourceVersion);
1850 } catch(AAIServiceException aaiexc) {
1852 } catch (Exception exc) {
1853 LOG.warn("deletePServerData", exc);
1854 throw new AAIServiceException(exc);
1862 public L3Network requestL3NetworkData(String networkId) throws AAIServiceException {
1863 L3Network response = null;
1864 InputStream inputStream = null;
1867 AAIRequest request = AAIRequest.getRequestFromResource("l3-network");
1868 request.addRequestProperty("l3-network.network-id", networkId);
1870 String rv = executor.get(request);
1872 ObjectMapper mapper = getObjectMapper();
1873 response = mapper.readValue(rv, L3Network.class);
1875 } catch(AAIServiceException aaiexc) {
1877 } catch (Exception exc) {
1878 LOG.warn("requestL3NetworkData", exc);
1879 throw new AAIServiceException(exc);
1885 public L3Network requestL3NetworkQueryByName(String networkName) throws AAIServiceException {
1886 L3Network response = null;
1889 AAIRequest request = AAIRequest.getRequestFromResource("l3-network");
1890 request.addRequestProperty("l3-network.network-name", networkName);
1892 String rv = executor.get(request);
1894 ObjectMapper mapper = getObjectMapper();
1895 response = mapper.readValue(rv, L3Network.class);
1898 } catch(AAIServiceException aaiexc) {
1900 } catch (Exception exc) {
1901 LOG.warn("requestL3NetworkQueryByName", exc);
1902 throw new AAIServiceException(exc);
1908 public boolean postL3NetworkData(String networkId, L3Network data) throws AAIServiceException {
1910 AAIRequest request = AAIRequest.getRequestFromResource("l3-network");
1911 request.addRequestProperty("l3-network.network-id", networkId);
1912 request.setRequestObject(data);
1913 Object response = executor.post(request);
1915 } catch(AAIServiceException aaiexc) {
1917 } catch (Exception exc) {
1918 LOG.warn(Object.class.getClass().getEnclosingMethod().getName(), exc);
1919 throw new AAIServiceException(exc);
1924 public boolean deleteL3NetworkData(String networkId, String resourceVersion) throws AAIServiceException {
1925 boolean response = false;
1928 AAIRequest request = AAIRequest.getRequestFromResource("l3-network");
1929 request.addRequestProperty("l3-network.network-id", networkId);
1930 response = executor.delete(request, resourceVersion);
1931 } catch(AAIServiceException aaiexc) {
1933 } catch (Exception exc) {
1934 LOG.warn("deleteL3NetworkData", exc);
1935 throw new AAIServiceException(exc);
1943 public VpnBinding requestVpnBindingData(String vpnId) throws AAIServiceException {
1944 VpnBinding response = null;
1947 AAIRequest request = AAIRequest.getRequestFromResource("vpn-binding");
1948 request.addRequestProperty("vpn-binding.vpn-id", vpnId);
1950 String rv = executor.get(request);
1952 ObjectMapper mapper = getObjectMapper();
1953 response = mapper.readValue(rv, VpnBinding.class);
1955 } catch(AAIServiceException aaiexc) {
1957 } catch (Exception exc) {
1958 LOG.warn("requestVpnBindingData", exc);
1959 throw new AAIServiceException(exc);
1965 public boolean deleteVpnBindingData(String vpnId, String resourceVersion) throws AAIServiceException {
1966 boolean response = false;
1969 AAIRequest request = AAIRequest.getRequestFromResource("vpn-binding");
1970 request.addRequestProperty("vpn-binding.vpn-id", vpnId);
1971 response = executor.delete(request, resourceVersion);
1972 } catch(AAIServiceException aaiexc) {
1974 } catch (Exception exc) {
1975 LOG.warn("deleteVpnBindingData", exc);
1976 throw new AAIServiceException(exc);
1983 public VnfImage requestVnfImageData(String vnf_image_uuid) throws AAIServiceException {
1984 VnfImage response = null;
1987 AAIRequest request = AAIRequest.getRequestFromResource("vnf-image");
1988 request.addRequestProperty("vnf-image.vnf-image-uuid", vnf_image_uuid);
1990 String rv = executor.get(request);
1992 ObjectMapper mapper = getObjectMapper();
1993 response = mapper.readValue(rv, VnfImage.class);
1995 } catch(AAIServiceException aaiexc) {
1997 } catch (Exception exc) {
1998 LOG.warn("requestVnfImageData", exc);
1999 throw new AAIServiceException(exc);
2005 public VnfImage requestVnfImageDataByVendorModel(String vendor, String model) throws AAIServiceException {
2006 return requestVnfImageDataByVendorModelVersion(vendor, model, null);
2010 public VnfImage requestVnfImageDataByVendorModelVersion(String vendor, String model, String version) throws AAIServiceException
2012 List<VnfImage> responseList = new ArrayList<VnfImage>();
2013 VnfImage response = null;
2014 InputStream inputStream = null;
2017 String request_url = target_uri+vnf_image_query_path + (version==null? "": "&application-version={application_version}");
2018 request_url = request_url.replace("{application_vendor}", encodeQuery(vendor)) ;
2019 request_url = request_url.replace("{application_model}", encodeQuery(model)) ;
2020 if(version != null) {
2021 request_url = request_url.replace("{application_version}", encodeQuery(version)) ;
2023 URL http_req_url = new URL(request_url);
2025 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.GET);
2027 LOGwriteFirstTrace(HttpMethod.GET, http_req_url.toString());
2028 LOGwriteDateTrace("application_vendor", vendor);
2029 LOGwriteDateTrace("application_model", model);
2030 if(version != null) {
2031 LOGwriteDateTrace("application_version", version);
2035 int responseCode = con.getResponseCode();
2036 if (responseCode == HttpURLConnection.HTTP_OK) {
2037 inputStream = con.getInputStream();
2039 inputStream = con.getErrorStream();
2042 // Process the response
2043 LOG.debug("HttpURLConnection result:" + responseCode);
2044 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
2045 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2047 ObjectMapper mapper = getObjectMapper();
2049 if (responseCode == HttpURLConnection.HTTP_OK) {
2050 // StringBuilder stringBuilder = new StringBuilder("\n");
2051 // String line = null;
2052 // while( ( line = reader.readLine() ) != null ) {
2053 // stringBuilder.append("\n").append( line );
2055 // LOG.info(stringBuilder.toString());
2056 response = mapper.readValue(reader, VnfImage.class);
2057 String original_buffer = mapper.writeValueAsString(response);
2058 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, "SUCCESS", original_buffer);
2059 if(response.getApplicationVendor() == null /*&& response.getAdditionalProperties() != null && !response.getAdditionalProperties().isEmpty()*/){
2060 LOG.warn("A List of multiple VNF-IMAGE entries has been returned");
2061 VnfImages listOfObjects = mapper.readValue(original_buffer, VnfImages.class);
2062 if(!listOfObjects.getVnfImage().isEmpty()) {
2063 response = listOfObjects.getVnfImage().get(0);
2066 } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
2067 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
2070 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2071 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
2072 throw new AAIServiceException(responseCode, errorresponse);
2075 } catch(AAIServiceException aaiexc) {
2077 } catch (Exception exc) {
2078 LOG.warn("requestVnfImageData", exc);
2079 throw new AAIServiceException(exc);
2081 if(inputStream != null){
2083 inputStream.close();
2084 } catch(Exception exc) {
2093 public boolean sendNotify(NotifyEvent event, String serviceInstanceId, String pathCode) throws AAIServiceException {
2094 InputStream inputStream = null;
2098 String selfLink = selflink_fqdn;
2099 if(SELFLINK_AVPN != null && SELFLINK_AVPN.equals(pathCode)) {
2100 selfLink = selflink_avpn;
2102 selfLink = selfLink.replace("{service-instance-id}", encodeQuery(serviceInstanceId));
2103 event.setSelflink(selfLink);
2105 ObjectMapper mapper = getObjectMapper();
2106 String json_text = mapper.writeValueAsString(event);
2108 SSLSocketFactory sockFact = CTX.getSocketFactory();
2110 String request_url = target_uri+ubb_notify_path;
2111 URL http_req_url = new URL(request_url);
2113 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.PUT);
2115 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
2116 osw.write(json_text);
2121 LOGwriteFirstTrace("PUT", request_url);
2122 LOGwriteDateTrace("NotifyEvent", json_text);
2125 int responseCode = con.getResponseCode();
2126 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2127 inputStream = con.getInputStream();
2129 inputStream = con.getErrorStream();
2132 // Process the response
2133 BufferedReader reader;
2135 reader = new BufferedReader( new InputStreamReader( inputStream ) );
2137 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2138 StringBuilder stringBuilder = new StringBuilder();
2140 while( ( line = reader.readLine() ) != null ) {
2141 stringBuilder.append( line );
2143 LOGwriteEndingTrace(responseCode, "SUCCESS", (stringBuilder.length() > 0) ? stringBuilder.toString() :
2147 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2148 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
2150 throw new AAIServiceException(responseCode, errorresponse);
2152 } catch(AAIServiceException aaiexc) {
2154 } catch (Exception exc) {
2155 LOG.warn("sendNotify", exc);
2156 throw new AAIServiceException(exc);
2159 if(inputStream != null)
2160 inputStream.close();
2161 } catch (Exception exc) {
2168 public SearchResults requestNodeQuery(String node_type, String entityIdentifier, String entityName) throws AAIServiceException {
2169 SearchResults response = null;
2170 InputStream inputStream = null;
2173 String request_url = target_uri+query_nodes_path;
2174 request_url = request_url.replace("{node-type}", encodeQuery(node_type)) ;
2175 request_url = request_url.replace("{entity-identifier}", entityIdentifier) ;
2176 request_url = request_url.replace("{entity-name}", encodeQuery(entityName)) ;
2177 URL http_req_url = new URL(request_url);
2179 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.GET);
2181 LOGwriteFirstTrace(HttpMethod.GET, http_req_url.toString());
2182 LOGwriteDateTrace("node_type", node_type);
2183 LOGwriteDateTrace("vnf_name", entityName);
2186 int responseCode = con.getResponseCode();
2187 if (responseCode == HttpURLConnection.HTTP_OK) {
2188 inputStream = con.getInputStream();
2190 inputStream = con.getErrorStream();
2193 // Process the response
2194 LOG.debug("HttpURLConnection result:" + responseCode);
2195 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
2196 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2198 ObjectMapper mapper = getObjectMapper();
2200 if (responseCode == HttpURLConnection.HTTP_OK) {
2201 response = mapper.readValue(reader, SearchResults.class);
2202 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, "SUCCESS", mapper.writeValueAsString(response));
2203 } else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
2204 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
2207 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2208 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
2209 throw new AAIServiceException(responseCode, errorresponse);
2212 } catch(AAIServiceException aaiexc) {
2214 } catch (Exception exc) {
2215 LOG.warn("requestNodeQuery", exc);
2216 throw new AAIServiceException(exc);
2218 if(inputStream != null){
2220 inputStream.close();
2221 } catch(Exception exc) {
2232 public String requestDataByURL(URL url) throws AAIServiceException {
2235 throw new NullPointerException();
2238 String response = null;
2239 InputStream inputStream = null;
2242 URL http_req_url = url;
2244 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.GET);
2246 LOGwriteFirstTrace(HttpMethod.GET, http_req_url.toString());
2249 int responseCode = con.getResponseCode();
2250 if (responseCode == HttpURLConnection.HTTP_OK) {
2251 inputStream = con.getInputStream();
2253 inputStream = con.getErrorStream();
2256 // Process the response
2257 LOG.debug("HttpURLConnection result:" + responseCode);
2258 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
2259 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2261 ObjectMapper mapper = getObjectMapper();
2263 if (responseCode == HttpURLConnection.HTTP_OK) {
2264 StringBuilder stringBuilder = new StringBuilder("\n");
2266 while( ( line = reader.readLine() ) != null ) {
2267 stringBuilder.append( line );
2269 LOG.info(stringBuilder.toString());
2270 // response = mapper.readValue(reader, String.class);
2271 response = stringBuilder.toString();
2272 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, "SUCCESS", mapper.writeValueAsString(response));
2273 } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
2274 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
2277 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2278 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
2279 throw new AAIServiceException(responseCode, errorresponse);
2282 } catch(AAIServiceException aaiexc) {
2284 } catch (Exception exc) {
2285 LOG.warn("requestNetworkVceData", exc);
2286 throw new AAIServiceException(exc);
2288 if(inputStream != null){
2290 inputStream.close();
2291 } catch(Exception exc) {
2301 public GenericVnf requestGenericVnfeNodeQuery(String vnf_name) throws AAIServiceException {
2303 if(vnf_name == null) {
2304 throw new NullPointerException();
2307 GenericVnf entity = null;
2308 SearchResults resp = this.requestNodeQuery("generic-vnf", "vnf-name", vnf_name);
2310 List<ResultData> resultDataList = resp.getResultData();
2313 for (ResultData datum : resultDataList) {
2314 String data_type = datum.getResourceType();
2315 URL url = new URL(datum.getResourceLink());
2316 entity = this.getResource(url.toString(), GenericVnf.class);
2321 LOG.error("Caught exception", e);
2327 public Vserver requestVServerDataByURL(URL url) throws AAIServiceException {
2330 throw new NullPointerException();
2333 Vserver entity = null;
2336 entity = this.getResource(url.toString(), Vserver.class);
2337 } catch (AAIServiceException exc) {
2339 } catch (Exception e) {
2340 throw new AAIServiceException(e);
2346 public URL requestVserverURLNodeQuery(String vserver_name) throws AAIServiceException {
2348 if(vserver_name == null) {
2349 throw new NullPointerException();
2353 SearchResults resp = this.requestNodeQuery("vserver", "vserver-name", vserver_name);
2355 List<ResultData> resultDataList = resp.getResultData();
2358 for (ResultData datum : resultDataList) {
2359 String data_type = datum.getResourceType();
2360 String resourceLink = datum.getResourceLink();
2361 if(!resourceLink.isEmpty() && !resourceLink.toLowerCase().startsWith("http")) {
2362 resourceLink = (new EchoRequest()).target_uri + resourceLink;
2364 entity = new URL(resourceLink);
2366 } catch (Exception e) {
2367 throw new AAIServiceException(e);
2372 class AAIRequestExecutor implements AAIExecutorInterface {
2375 public String get(AAIRequest request) throws AAIServiceException {
2376 String response = null;
2377 InputStream inputStream = null;
2378 HttpURLConnection con = null;
2379 URL requestUrl = null;
2381 String requestId = UUID.randomUUID().toString();
2382 StringBuilder errorStringBuilder = new StringBuilder();
2386 if(request.getRequestObject() != null) {
2387 requestUrl = request.getRequestUrl(HttpMethod.POST, null);
2388 requestUrl = appendDepth(requestUrl, request);
2389 con = getConfiguredConnection(requestUrl, HttpMethod.POST);
2390 String json_text = request.toJSONString();
2391 LOGwriteDateTrace("data", json_text);
2392 logMetricRequest(requestId, "POST "+requestUrl.getPath(), json_text, requestUrl.getPath());
2393 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
2394 osw.write(json_text);
2397 requestUrl = request.getRequestUrl(HttpMethod.GET, null);
2398 requestUrl = appendDepth(requestUrl, request);
2399 con = getConfiguredConnection(requestUrl, HttpMethod.GET);
2400 logMetricRequest(requestId, "GET "+requestUrl.getPath(), "", requestUrl.getPath());
2404 String responseMessage = con.getResponseMessage();
2405 int responseCode = con.getResponseCode();
2406 if (responseCode == HttpURLConnection.HTTP_OK) {
2407 inputStream = con.getInputStream();
2409 inputStream = con.getErrorStream();
2412 // Process the response
2413 LOG.debug("HttpURLConnection result:" + responseCode + " : " + responseMessage);
2414 logMetricResponse(requestId, responseCode, responseMessage);
2416 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
2417 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2419 ObjectMapper mapper = getObjectMapper();
2421 if (responseCode == HttpURLConnection.HTTP_OK) {
2422 StringBuilder stringBuilder = new StringBuilder();
2424 while( ( line = reader.readLine() ) != null ) {
2425 stringBuilder.append( line );
2427 response = stringBuilder.toString();
2429 Object object = mapper.readValue(response, Object.class);
2430 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, responseMessage, mapper.writeValueAsString(object));
2431 } catch(Exception exc) {
2432 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, responseMessage, mapper.writeValueAsString(response));
2434 } else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
2435 LOGwriteEndingTrace(responseCode, responseMessage, "Entry does not exist.");
2436 ErrorResponse errorresponse = null;
2438 errorresponse = mapper.readValue(reader, ErrorResponse.class);
2439 } catch(Exception exc) {
2440 errorresponse = new ErrorResponse();
2441 RequestError requestError = new RequestError();
2442 ServiceException serviceException = new ServiceException();
2443 serviceException.setText("Entry does not exist.");
2444 requestError.setServiceException(serviceException);
2445 errorresponse.setRequestError(requestError );
2447 throw new AAIServiceException(responseCode, errorresponse);
2448 } else if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
2449 StringBuilder stringBuilder = new StringBuilder();
2451 while( ( line = reader.readLine() ) != null ) {
2452 stringBuilder.append( line );
2454 LOGwriteEndingTrace(responseCode, responseMessage, stringBuilder.toString());
2455 ServiceException serviceException = new ServiceException();
2456 serviceException.setMessageId("HTTP_UNAUTHORIZED");
2457 serviceException.setText(stringBuilder.toString());
2458 RequestError requestError = new RequestError();
2459 requestError.setServiceException(serviceException);
2460 ErrorResponse errorresponse = new ErrorResponse();
2461 errorresponse.setRequestError(requestError);
2462 throw new AAIServiceException(responseCode, errorresponse);
2464 // StringBuilder errorStringBuilder = new StringBuilder();
2466 while( ( line = reader.readLine() ) != null ) {
2467 errorStringBuilder.append("\n").append( line );
2470 ErrorResponse errorresponse = mapper.readValue(errorStringBuilder.toString(), ErrorResponse.class);
2471 // ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2472 LOGwriteEndingTrace(responseCode, responseMessage, mapper.writeValueAsString(errorresponse));
2473 throw new AAIServiceException(responseCode, errorresponse);
2476 } catch(AAIServiceException aaiexc) {
2478 } catch (Exception exc) {
2479 LOG.warn(errorStringBuilder.toString(), exc);
2480 throw new AAIServiceException(exc);
2482 if(inputStream != null){
2484 inputStream.close();
2485 } catch(Exception exc) {
2493 private URL appendDepth(URL requestUrl, AAIRequest request) throws MalformedURLException {
2495 String depth = request.requestProperties.getProperty("depth", "1");
2496 String path = requestUrl.toString();
2497 if(path.contains("?depth=") || path.contains("&depth=")) {
2500 if(path.contains("?")) {
2501 path = String.format("%s&depth=%s", path, depth);
2503 path = String.format("%s?depth=%s", path, depth);
2505 return new URL(path);
2510 public String post(AAIRequest request) throws AAIServiceException {
2511 InputStream inputStream = null;
2512 String requestId = UUID.randomUUID().toString();
2515 String resourceVersion = null;
2516 AAIDatum instance = request.getRequestObject();
2518 Method getResourceVersionMethod = instance.getClass().getMethod("getResourceVersion");
2519 if(getResourceVersionMethod != null){
2521 getResourceVersionMethod.setAccessible(true);
2522 Object object = getResourceVersionMethod.invoke(instance);
2524 resourceVersion = object.toString();
2525 } catch (InvocationTargetException x) {
2526 Throwable cause = x.getCause();
2530 URL requestUrl = null;
2531 HttpURLConnection con = getConfiguredConnection(requestUrl = request.getRequestUrl(HttpMethod.PUT, resourceVersion), HttpMethod.PUT);
2532 ObjectMapper mapper = getObjectMapper();
2533 String json_text = request.toJSONString();
2535 LOGwriteDateTrace("data", json_text);
2536 logMetricRequest(requestId, "PUT "+requestUrl.getPath(), json_text, requestUrl.getPath());
2538 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
2539 osw.write(json_text);
2543 String responseMessage = con.getResponseMessage();
2544 int responseCode = con.getResponseCode();
2545 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2546 inputStream = con.getInputStream();
2548 inputStream = con.getErrorStream();
2551 LOG.debug("HttpURLConnection result:" + responseCode + " : " + responseMessage);
2552 logMetricResponse(requestId,responseCode, responseMessage);
2554 // Process the response
2555 BufferedReader reader;
2557 reader = new BufferedReader( new InputStreamReader( inputStream ) );
2558 mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
2560 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2561 StringBuilder stringBuilder = new StringBuilder();
2563 while( ( line = reader.readLine() ) != null ) {
2564 stringBuilder.append( line );
2566 LOGwriteEndingTrace(responseCode, responseMessage, (stringBuilder != null) ? stringBuilder.toString() : "{no-data}");
2567 return stringBuilder.toString();
2569 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2570 LOGwriteEndingTrace(responseCode, responseMessage, mapper.writeValueAsString(errorresponse));
2572 throw new AAIServiceException(responseCode, errorresponse);
2574 } catch(AAIServiceException aaiexc) {
2576 } catch (Exception exc) {
2577 LOG.warn("AAIRequestExecutor.post", exc);
2578 throw new AAIServiceException(exc);
2581 if(inputStream != null)
2582 inputStream.close();
2583 } catch (Exception exc) {
2590 public Boolean delete(AAIRequest request, String resourceVersion) throws AAIServiceException {
2591 Boolean response = null;
2592 InputStream inputStream = null;
2593 String requestId = UUID.randomUUID().toString();
2595 if(resourceVersion == null) {
2596 throw new AAIServiceException("resource-version is required for DELETE request");
2600 URL requestUrl = null;
2601 HttpURLConnection conn = getConfiguredConnection(requestUrl = request.getRequestUrl(HttpMethod.DELETE, resourceVersion), HttpMethod.DELETE);
2602 logMetricRequest(requestId, "DELETE "+requestUrl.getPath(), "", requestUrl.getPath());
2603 conn.setDoOutput(true);
2604 // if(request.isDeleteDataRequired()) {
2605 // String json_text = request.toJSONString();
2607 // LOGwriteDateTrace("data", json_text);
2608 // OutputStream os = con.getOutputStream();
2609 // OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
2610 // osw.write(json_text);
2615 String responseMessage = conn.getResponseMessage();
2616 int responseCode = conn.getResponseCode();
2617 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2618 inputStream = conn.getInputStream();
2620 inputStream = conn.getErrorStream();
2623 // Process the response
2624 LOG.debug("HttpURLConnection result:" + responseCode + " : " + responseMessage);
2625 logMetricResponse(requestId,responseCode, responseMessage);
2627 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
2628 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2631 ObjectMapper mapper = getObjectMapper();
2633 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2634 StringBuilder stringBuilder = new StringBuilder();
2636 while( ( line = reader.readLine() ) != null ) {
2637 stringBuilder.append( line );
2639 LOGwriteEndingTrace(responseCode, responseMessage, stringBuilder.toString());
2641 } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
2642 LOGwriteEndingTrace(responseCode, responseMessage, "Entry does not exist.");
2645 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2646 LOGwriteEndingTrace(responseCode, responseMessage, mapper.writeValueAsString(errorresponse));
2647 throw new AAIServiceException(responseCode, errorresponse);
2649 } catch(AAIServiceException aaiexc) {
2651 } catch (Exception exc) {
2652 LOG.warn("delete", exc);
2653 throw new AAIServiceException(exc);
2655 if(inputStream != null){
2657 inputStream.close();
2658 } catch(Exception exc) {
2667 public Object query(AAIRequest request, Class clas) throws AAIServiceException {
2668 Object response = null;
2669 InputStream inputStream = null;
2670 HttpURLConnection con = null;
2671 URL requestUrl = null;
2672 String requestId = UUID.randomUUID().toString();
2675 requestUrl = request.getRequestQueryUrl(HttpMethod.GET);
2676 con = getConfiguredConnection(requestUrl , HttpMethod.GET);
2677 logMetricRequest(requestId, "GET "+requestUrl.getPath(), "", requestUrl.getPath());
2680 String responseMessage = con.getResponseMessage();
2681 int responseCode = con.getResponseCode();
2682 if (responseCode == HttpURLConnection.HTTP_OK) {
2683 inputStream = con.getInputStream();
2685 inputStream = con.getErrorStream();
2688 logMetricResponse(requestId,responseCode, responseMessage);
2689 ObjectMapper mapper = getObjectMapper();
2691 if (responseCode == HttpURLConnection.HTTP_OK) {
2692 // Process the response
2693 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2694 response = mapper.readValue(reader, clas);
2695 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, "SUCCESS", mapper.writeValueAsString(response));
2696 } else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
2697 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
2700 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2701 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2702 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
2703 throw new AAIServiceException(responseCode, errorresponse);
2706 } catch(AAIServiceException aaiexc) {
2708 } catch (Exception exc) {
2709 LOG.warn("GET", exc);
2710 throw new AAIServiceException(exc);
2712 if(inputStream != null){
2714 inputStream.close();
2715 } catch(Exception exc) {
2725 public Boolean patch(AAIRequest request, String resourceVersion) throws AAIServiceException {
2726 InputStream inputStream = null;
2727 String requestId = UUID.randomUUID().toString();
2730 AAIDatum instance = request.getRequestObject();
2731 if(instance instanceof ResourceVersion) {
2732 resourceVersion = ((ResourceVersion)instance).getResourceVersion();
2735 URL requestUrl = null;
2736 HttpURLConnection con = getConfiguredConnection(requestUrl = request.getRequestUrl("PATCH", resourceVersion), "PATCH");
2737 ObjectMapper mapper = getObjectMapper();
2738 String json_text = request.toJSONString();
2740 LOGwriteDateTrace("data", json_text);
2741 logMetricRequest(requestId, "PATCH "+requestUrl.getPath(), json_text, requestUrl.getPath());
2743 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
2744 osw.write(json_text);
2748 String responseMessage = con.getResponseMessage();
2749 int responseCode = con.getResponseCode();
2750 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2751 inputStream = con.getInputStream();
2753 inputStream = con.getErrorStream();
2756 LOG.info("HttpURLConnection result: " + responseCode + " : " + responseMessage);
2757 logMetricResponse(requestId,responseCode, responseMessage);
2759 // Process the response
2760 BufferedReader reader;
2762 reader = new BufferedReader( new InputStreamReader( inputStream ) );
2763 mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
2765 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2766 StringBuilder stringBuilder = new StringBuilder();
2768 while( ( line = reader.readLine() ) != null ) {
2769 stringBuilder.append( line );
2771 LOGwriteEndingTrace(responseCode, responseMessage,
2772 (stringBuilder.length() > 0) ? stringBuilder.toString() : "{no-data}");
2775 StringBuilder stringBuilder = new StringBuilder();
2777 while( ( line = reader.readLine() ) != null ) {
2778 stringBuilder.append("\n").append( line );
2780 LOG.info(stringBuilder.toString());
2783 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2784 LOGwriteEndingTrace(responseCode, responseMessage, mapper.writeValueAsString(errorresponse));
2786 throw new AAIServiceException(responseCode, errorresponse);
2788 } catch(AAIServiceException aaiexc) {
2790 } catch (Exception exc) {
2791 LOG.warn("AAIRequestExecutor.patch", exc);
2792 throw new AAIServiceException(exc);
2795 if(inputStream != null)
2796 inputStream.close();
2797 } catch (Exception exc) {
2805 public Tenant requestTenantData(String tenant_id, String cloudOwner, String cloudRegionId) throws AAIServiceException {
2806 Tenant response = null;
2809 AAIRequest request = AAIRequest.getRequestFromResource("tenant");
2810 request.addRequestProperty("tenant.tenant-id", tenant_id);
2811 request.addRequestProperty("cloud-region.cloud-owner", cloudOwner);
2812 request.addRequestProperty("cloud-region.cloud-region-id", cloudRegionId);
2814 String rv = executor.get(request);
2816 ObjectMapper mapper = getObjectMapper();
2817 response = mapper.readValue(rv, Tenant.class);
2819 } catch(AAIServiceException aaiexc) {
2821 } catch (Exception exc) {
2822 LOG.warn("requestTenantData", exc);
2823 throw new AAIServiceException(exc);
2830 public Tenant requestTenantDataByName(String tenant_name, String cloudOwner, String cloudRegionId) throws AAIServiceException {
2831 Tenant response = null;
2834 AAIRequest request = AAIRequest.getRequestFromResource("tenant");
2835 request.addRequestProperty("tenant.tenant-name", tenant_name);
2836 request.addRequestProperty("cloud-region.cloud-owner", cloudOwner);
2837 request.addRequestProperty("cloud-region.cloud-region-id", cloudRegionId);
2838 Object rv = executor.query(request, Tenant.class);
2840 return (Tenant)null;
2842 response = (Tenant)rv;
2843 } catch(AAIServiceException aaiexc) {
2845 } catch (Exception exc) {
2846 LOG.warn("requestTenantDataByName", exc);
2847 throw new AAIServiceException(exc);
2855 public boolean postTenantData(String tenant_id, String cloudOwner, String cloudRegionId, Tenant tenannt) throws AAIServiceException {
2857 AAIRequest request = AAIRequest.getRequestFromResource("tenant");
2858 request.addRequestProperty("tenant.tenant-id", tenant_id);
2859 request.addRequestProperty("cloud-region.cloud-owner", cloudOwner);
2860 request.addRequestProperty("cloud-region.cloud-region-id", cloudRegionId);
2861 request.setRequestObject(tenannt);
2862 Object response = executor.post(request);
2864 } catch(AAIServiceException aaiexc) {
2866 } catch (Exception exc) {
2867 LOG.warn("postTenantData", exc);
2868 throw new AAIServiceException(exc);
2874 public String getTenantIdFromVserverUrl(URL url) {
2876 String path = url.getPath();
2878 String[] split = path.split("/tenants/tenant/");
2879 if(split.length > 1) {
2880 split = split[1].split("/");
2888 public String getCloudOwnerFromVserverUrl(URL url) {
2890 String path = url.getPath();
2892 String[] split = path.split("/cloud-regions/cloud-region/");
2893 if(split.length > 1) {
2894 split = split[1].split("/");
2902 public String getCloudRegionFromVserverUrl(URL url) {
2904 String path = url.getPath();
2906 String[] split = path.split("/cloud-regions/cloud-region/");
2907 if(split.length > 1) {
2908 split = split[1].split("/");
2916 public String getVServerIdFromVserverUrl(URL url, String tenantId) {
2917 String pattern = network_vserver_path;
2918 pattern = pattern.replace("{tenant-id}", tenantId);
2920 int end = pattern.indexOf("{vserver-id}");
2921 String prefix = pattern.substring(0, end);
2923 String path = url.getPath();
2925 if(path.startsWith(prefix)) {
2926 path = path.substring(prefix.length());
2932 protected Logger getLogger(){
2938 public AAIRequestExecutor getExecutor() {
2943 * Creates a current time stamp in UTC i.e. 2016-03-08T22:15:13.343Z.
2944 * If there are any parameters the values are appended to the time stamp.
2947 * values to be appended to current time stamp
2949 * used to set an attribute for a DG
2950 * @throws SvcLogicException
2952 public void setStatusMethod(Map<String, String> parameters, SvcLogicContext ctx) throws SvcLogicException {
2954 throw new SvcLogicException("SvcLogicContext is null.");
2957 StringBuilder sb = new StringBuilder();
2958 sb.append(String.format("%tFT%<tTZ", Calendar.getInstance(TimeZone.getTimeZone("Z")))).append(" - ");
2960 for (Entry<String, String> entry : parameters.entrySet()) {
2961 sb.append(entry.getValue()).append(" ");
2964 if (sb.length() > 0) {
2965 sb.setLength(sb.length() - 2);
2968 ctx.setAttribute("aai-summary-status-message", sb.toString());
2969 LOG.info("aai-summary-status-message: " + sb.toString());
2973 * Generic method to GET json data from an A&AI using key structure.
2974 * Then convert that json to an Object.
2975 * If successful the Object is attempted to be cast to the type parameter.
2978 * key identifying the resource to be retrieved from AAI
2980 * the class of object that A&AI will return
2981 * @return the object created from json or null if the response code is not 200
2983 * @throws AAIServiceException
2984 * if empty or null key and or type or there's an error with processing
2987 public <T> T getResource(String key, Class<T> type) throws AAIServiceException {
2988 if (StringUtils.isEmpty(key) || type == null) {
2989 throw new AAIServiceException("Key is empty or null and or type is null");
2994 SvcLogicContext ctx = new SvcLogicContext();
2995 if(!key.contains(" = ")) {
2996 if(isValidURL(key)) {
2997 key = String.format("selflink = '%s'", key);
2998 } else if(isValidURI(key)) {
2999 key = String.format("resource-path = '%s'", key);
3005 HashMap<String, String> nameValues = AAIServiceUtils.keyToHashMap(key, ctx);
3007 AAIRequest request = new SelfLinkRequest(type);
3008 if(nameValues.containsKey(PathRequest.RESOURCE_PATH.replaceAll("-", "_"))) {
3009 request = new PathRequest(type);
3012 request.processRequestPathValues(nameValues);
3013 Object obj = this.getExecutor().query(request, type);
3014 response = type.cast(obj);
3016 return response != null ? type.cast(response) : response;
3019 public boolean isValidURL(String url) {
3025 } catch (MalformedURLException e) {
3031 } catch (URISyntaxException e) {
3039 public boolean isValidURI(String url) {
3045 } catch (URISyntaxException e) {
3054 protected boolean deleteRelationshipList(URL httpReqUrl, String json_text) throws AAIServiceException {
3055 if(httpReqUrl == null) {
3056 throw new NullPointerException();
3059 boolean response = false;
3060 InputStream inputStream = null;
3063 HttpURLConnection con = getConfiguredConnection(httpReqUrl, HttpMethod.DELETE);
3065 // SSLSocketFactory sockFact = CTX.getSocketFactory();
3066 // con.setSSLSocketFactory( sockFact );
3067 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
3068 osw.write(json_text);
3073 LOGwriteFirstTrace("DELETE", httpReqUrl.toString());
3074 LOGwriteDateTrace("data", json_text);
3077 int responseCode = con.getResponseCode();
3078 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
3079 inputStream = con.getInputStream();
3081 inputStream = con.getErrorStream();
3084 // Process the response
3085 LOG.debug("HttpURLConnection result:" + responseCode);
3086 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
3087 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
3090 ObjectMapper mapper = getObjectMapper();
3092 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
3093 StringBuilder stringBuilder = new StringBuilder();
3095 while( ( line = reader.readLine() ) != null ) {
3096 stringBuilder.append( line );
3098 LOGwriteEndingTrace(responseCode, "SUCCESS", stringBuilder.toString());
3100 } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
3101 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
3104 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
3105 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
3106 throw new AAIServiceException(responseCode, errorresponse);
3109 } catch(AAIServiceException aaiexc) {
3111 } catch (Exception exc) {
3112 LOG.warn("deleteRelationshipList", exc);
3113 throw new AAIServiceException(exc);
3115 if(inputStream != null){
3117 inputStream.close();
3118 } catch(Exception exc) {
3126 public static ObjectMapper getObjectMapper() {
3127 ObjectMapper mapper = new ObjectMapper();
3128 AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance());
3129 AnnotationIntrospector secondary = new JacksonAnnotationIntrospector();
3130 mapper.setAnnotationIntrospector(AnnotationIntrospector.pair(introspector, secondary));
3131 mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
3132 mapper.setSerializationInclusion(Include.NON_NULL);
3136 public void logMetricRequest(String requestId, String targetServiceName, String msg, String path){
3137 String svcInstanceId = "";
3138 String svcName = null;
3139 String partnerName = null;
3140 String targetEntity = "A&AI";
3141 String targetVirtualEntity = null;
3143 targetServiceName = "";
3145 ml.logRequest(svcInstanceId, svcName, partnerName, targetEntity, targetServiceName, targetVirtualEntity, msg);
3148 public void logMetricResponse(String requestId, int responseCode, String responseDescription){
3149 ml.logResponse(responseCode < 400 ? "SUCCESS" : "FAILURE", Integer.toString(responseCode), responseDescription);
3152 public void logKeyError(String keys){
3153 LOG.error("Atleast one of the keys [" + keys + "] should have been populated. This will cause a NPE.");
3161 public QueryStatus save(String resource, boolean force, boolean localOnly, String key, Map<String, String> params, String prefix, SvcLogicContext ctx)
3162 throws SvcLogicException {
3163 String normResource = resource.split(":")[0];
3165 switch(normResource){
3166 case "formatted-query":
3167 case "generic-query":
3171 case "l2-bridge-sbg":
3172 case "l2-bridge-bgf":
3178 if(key.contains("selflink =")) {
3181 if(!key.contains(String.format("%s.", normResource))) {
3182 key = rewriteKey(resource, key, ctx);
3185 return super.save(resource, force, localOnly, key, params, prefix, ctx);
3189 public QueryStatus query(String resource, boolean localOnly, String select, String key, String prefix, String orderBy, SvcLogicContext ctx)
3190 throws SvcLogicException {
3191 String normResource = resource.split(":")[0];
3193 switch(normResource){
3194 case "formatted-query":
3195 case "generic-query":
3199 case "l2-bridge-sbg":
3200 case "l2-bridge-bgf":
3206 if(key.contains("selflink =")) {
3209 if(!key.contains(String.format("%s.", normResource))) {
3210 key = rewriteKey(resource, key, ctx);
3214 return super.query(resource, localOnly, select, key, prefix, orderBy, ctx);
3218 public QueryStatus delete(String resource, String key, SvcLogicContext ctx) throws SvcLogicException {
3219 String normResource = resource.split(":")[0];
3221 switch(normResource){
3222 case "formatted-query":
3223 case "generic-query":
3227 case "l2-bridge-sbg":
3228 case "l2-bridge-bgf":
3234 if(key.contains("selflink =")) {
3237 if(!key.contains(String.format("%s.", normResource))) {
3238 key = rewriteKey(resource, key, ctx);
3242 return super.delete(resource, key, ctx);
3246 public QueryStatus update(String resource, String key, Map<String, String> params, String prefix, SvcLogicContext ctx) throws SvcLogicException {
3247 String normResource = resource.split(":")[0];
3249 switch(normResource){
3250 case "formatted-query":
3251 case "generic-query":
3255 case "l2-bridge-sbg":
3256 case "l2-bridge-bgf":
3262 if(key.contains("selflink =")) {
3265 if(!key.contains(String.format("%s.", normResource))) {
3266 key = rewriteKey(resource, key, ctx);
3270 return super.update(resource, key, params, prefix, ctx);
3273 private String rewriteKey(String resource, String key, SvcLogicContext ctx) {
3274 LOG.info("AAI Deprecation - the format of request key is no longer supported. Please rewrite this key : " + key);
3276 String normResource = resource.split(":")[0];
3277 Class<? extends AAIDatum> clazz = null;
3279 clazz = AAIRequest.getClassFromResource(normResource) ;
3280 } catch (ClassNotFoundException e) {
3281 LOG.warn("AAIRequest does not support class: " + e.getMessage());
3287 List<String> fieldAnnotatedNames = new LinkedList<>();
3289 Field[] fields = clazz.getDeclaredFields();
3290 for(Field field : fields) {
3291 String fieldName = field.getName();
3292 XmlElement annotation = field.getAnnotation(XmlElement.class);
3293 if(annotation == null)
3295 String primaryId = annotation.name();
3296 if("##default".equals(primaryId)) {
3297 primaryId = fieldName;
3299 fieldAnnotatedNames.add(primaryId);
3302 HashMap<String, String> nameValues = AAIServiceUtils.keyToHashMap(key, ctx);
3303 Set<String> keyset = nameValues.keySet();
3304 for(String keyName : keyset) {
3305 if(keyName.contains("."))
3308 String tmpKeyName = keyName.replaceAll("_", "-");
3309 String valueToSubstitute = String.format("%s =", tmpKeyName);
3310 if(fieldAnnotatedNames.contains(tmpKeyName) && key.contains(valueToSubstitute)) {
3311 key = key.replace(valueToSubstitute, String.format("%s.%s =", normResource, tmpKeyName));
3321 public String getPathTemplateForResource(String resoourceName, String keys, SvcLogicContext ctx) throws MalformedURLException {
3322 return AAIServiceUtils.getPathForResource(resoourceName, StringUtils.join(keys, " AND "), ctx);
3326 public boolean isDeprecatedFormat(String resource, HashMap<String, String> nameValues) {
3327 return !AAIServiceUtils.isValidFormat(resource, nameValues);