2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 ONAP 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;
113 import com.fasterxml.jackson.annotation.JsonInclude.Include;
114 import com.fasterxml.jackson.databind.AnnotationIntrospector;
115 import com.fasterxml.jackson.databind.DeserializationFeature;
116 import com.fasterxml.jackson.databind.ObjectMapper;
117 import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector;
118 import com.fasterxml.jackson.databind.type.TypeFactory;
119 import com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector;
120 import com.sun.jersey.api.client.config.DefaultClientConfig;
121 import com.sun.jersey.client.urlconnection.HTTPSProperties;
124 public class AAIService extends AAIDeclarations implements AAIClient, SvcLogicResource {
126 public static final String AAICLIENT_PROPERTIES = "/aaiclient.properties";
127 public static final String PATH_PROPERTIES = "/aai-path.properties";
129 private static final Logger LOG = LoggerFactory.getLogger(AAIService.class);
131 private final String truststore_path;
132 private final String truststore_password;
133 private final String keystore_path;
134 private final String keystore_password;
135 private final Boolean ignore_certificate_host_error;
137 private final String target_uri;
138 private final String query_path; // = "sdn-zone-query";
140 private final String network_vserver_path;
142 private final String svc_instance_path;
143 private final String svc_inst_qry_path;
145 private final String vnf_image_query_path;
147 private final String param_service_type; //= "service-type";
149 private final String ubb_notify_path;
150 private final String selflink_avpn;
151 private final String selflink_fqdn;
153 private final String p_interface_path;
155 private final String service_path;
156 private final String site_pair_set_path;
158 private final int connection_timeout;
159 private final int read_timeout;
162 private final String query_nodes_path;
163 private final String update_path;
165 private final String application_id;
167 // authentication credentials
168 private String user_name;
169 private String user_password;
172 private final boolean runtimeOSGI;
174 private SSLContext CTX;
176 private final MetricLogger ml = new MetricLogger();
178 private final AAIRequestExecutor executor;
180 public AAIService(URL propURL) {
181 LOG.info("Entered AAIService.ctor");
183 String runtime = System.getProperty("aaiclient.runtime");
184 if(runtime != null && runtime.equals("OSGI")) {
190 Properties props = null;
192 props = initialize(propURL);
193 AAIRequest.setProperties(props, this);
195 } catch(Exception exc){
196 LOG.error("AicAAIResource.static", exc);
199 executor = new AAIRequestExecutor();
201 user_name = props.getProperty(CLIENT_NAME);
202 user_password = props.getProperty(CLIENT_PWWD);
204 if(user_name == null || user_name.isEmpty()){
205 LOG.debug("Basic user name is not set");
207 if(user_password == null || user_password.isEmpty()) {
208 LOG.debug("Basic password is not set");
211 truststore_path = props.getProperty(TRUSTSTORE_PATH);
212 truststore_password = props.getProperty(TRUSTSTORE_PSSWD);
213 keystore_path = props.getProperty(KEYSTORE_PATH);
214 keystore_password = props.getProperty(KEYSTORE_PSSWD);
216 target_uri = props.getProperty(TARGET_URI);
217 query_path = props.getProperty(QUERY_PATH);
218 update_path = props.getProperty(UPDATE_PATH);
220 String applicationId =props.getProperty(APPLICATION_ID);
221 if(applicationId == null || applicationId.isEmpty()) {
222 applicationId = "SDNC";
224 application_id = applicationId;
226 // connection timeout
227 int tmpConnectionTimeout = 30000;
228 int tmpReadTimeout = 30000;
231 String tmpValue = null;
232 tmpValue = props.getProperty(CONNECTION_TIMEOUT, "30000");
233 tmpConnectionTimeout = Integer.parseInt(tmpValue);
234 tmpValue = props.getProperty(READ_TIMEOUT, "30000");
235 tmpReadTimeout = Integer.parseInt(tmpValue);
236 } catch(Exception exc) {
237 LOG.error("Failed setting connection timeout", exc);
238 tmpConnectionTimeout = 30000;
239 tmpReadTimeout = 30000;
241 connection_timeout = tmpConnectionTimeout;
242 read_timeout = tmpReadTimeout;
244 network_vserver_path =props.getProperty(NETWORK_VSERVER_PATH);
246 svc_instance_path = props.getProperty(SVC_INSTANCE_PATH); // "/aai/v1/business/customers/customer/{customer-id}/service-subscriptions/service-subscription/{service-type}/service-instances");
247 // "/aai/v1/business/customers/customer/ma9181-203-customerid/service-subscriptions/service-subscription/ma9181%20Hosted%20Voice/service-instances";
249 // 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");
250 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");
253 param_service_type = props.getProperty(PARAM_SERVICE_TYPE, "service-type");
256 p_interface_path = props.getProperty(P_INTERFACE_PATH);
258 vnf_image_query_path = props.getProperty(VNF_IMAGE_QUERY_PATH);
260 ubb_notify_path = props.getProperty(UBB_NOTIFY_PATH);
261 selflink_avpn = props.getProperty(SELFLINK_AVPN);
262 selflink_fqdn = props.getProperty(SELFLINK_FQDN);
264 service_path = props.getProperty(SERVICE_PATH);
266 site_pair_set_path = props.getProperty(SITE_PAIR_SET_PATH);
268 query_nodes_path = props.getProperty(QUERY_NODES_PATH);
270 String iche = props.getProperty(CERTIFICATE_HOST_ERROR);
271 boolean host_error = false;
272 if(iche != null && !iche.isEmpty()) {
273 host_error = Boolean.valueOf(iche);
276 ignore_certificate_host_error = host_error;
278 HttpsURLConnection.setDefaultHostnameVerifier( new HostnameVerifier(){
279 public boolean verify(String string,SSLSession ssls) {
280 return ignore_certificate_host_error;
284 if(truststore_path != null && truststore_password != null && (new File(truststore_path)).exists()) {
285 System.setProperty("javax.net.ssl.trustStore", truststore_path);
286 System.setProperty("javax.net.ssl.trustStorePassword", truststore_password);
289 if(keystore_path != null && keystore_password != null && (new File(keystore_path)).exists())
291 DefaultClientConfig config = new DefaultClientConfig();
292 //both jersey and HttpURLConnection can use this
293 SSLContext ctx = null;
295 ctx = SSLContext.getInstance("TLS");
297 KeyManagerFactory kmf = null;
299 String def = "SunX509";
300 String storeType = "PKCS12";
301 def = KeyStore.getDefaultType();
302 kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
303 FileInputStream fin = new FileInputStream(keystore_path);
304 // KeyStore ks = KeyStore.getInstance("PKCS12");
306 String extension = keystore_path.substring(keystore_path.lastIndexOf(".") + 1);
308 if(extension != null && !extension.isEmpty() && extension.equalsIgnoreCase("JKS")) {
311 KeyStore ks = KeyStore.getInstance(storeType);
313 char[] pwd = keystore_password.toCharArray();
316 } catch (Exception ex) {
317 LOG.error("AAIResource", ex);
320 ctx.init(kmf.getKeyManagers(), null, null);
321 config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties( new HostnameVerifier() {
323 public boolean verify( String s, SSLSession sslSession ) {
324 return ignore_certificate_host_error;
329 LOG.debug("SSLContext created");
331 } catch (KeyManagementException | NoSuchAlgorithmException exc) {
332 LOG.error("AAIResource", exc);
336 LOG.info("AAIResource.ctor initialized.");
339 Field methodsField = HttpURLConnection.class.getDeclaredField("methods");
340 methodsField.setAccessible(true);
341 // get the methods field modifiers
342 Field modifiersField = Field.class.getDeclaredField("modifiers");
343 // bypass the "private" modifier
344 modifiersField.setAccessible(true);
346 // remove the "final" modifier
347 modifiersField.setInt(methodsField, methodsField.getModifiers() & ~Modifier.FINAL);
349 /* valid HTTP methods */
351 "GET", "POST", "HEAD", "OPTIONS", "PUT", "DELETE", "TRACE", "PATCH"
353 // set the new methods - including patch
354 methodsField.set(null, methods);
356 } catch (SecurityException | IllegalArgumentException | IllegalAccessException | NoSuchFieldException e) {
362 public void cleanUp() {
368 * @param http_req_url
373 protected HttpURLConnection getConfiguredConnection(URL http_req_url, String method) throws Exception {
374 HttpURLConnection con = (HttpURLConnection) http_req_url.openConnection();
376 // Set up the connection properties
377 con.setRequestProperty( "Connection", "close" );
378 con.setDoInput(true);
379 con.setDoOutput(true);
380 con.setUseCaches(false);
381 con.setConnectTimeout( connection_timeout );
382 con.setReadTimeout( read_timeout );
383 con.setRequestMethod( method );
384 con.setRequestProperty( "Accept", "application/json" );
385 con.setRequestProperty( "Content-Type", "PATCH".equalsIgnoreCase(method) ? "application/merge-patch+json" : "application/json" );
386 con.setRequestProperty("X-FromAppId", application_id);
387 con.setRequestProperty("X-TransactionId",TransactionIdTracker.getNextTransactionId());
388 String mlId = ml.getRequestID();
389 if(mlId != null && !mlId.isEmpty()) {
390 LOG.debug(String.format("MetricLogger requestId = %s", mlId));
391 con.setRequestProperty(MetricLogger.REQUEST_ID, mlId);
393 LOG.debug("MetricLogger requestId is null");
396 if(user_name != null && !user_name.isEmpty() && user_password != null && !user_password.isEmpty()) {
397 String basicAuth = "Basic " + new String(Base64.encodeBase64((user_name + ":" + user_password).getBytes()));
398 con.setRequestProperty ("Authorization", basicAuth);
401 if(con instanceof HttpsURLConnection && CTX != null) {
402 SSLSocketFactory sockFact = CTX.getSocketFactory();
403 HttpsURLConnection.class.cast(con).setSSLSocketFactory( sockFact );
410 public GenericVnf requestGenericVnfData(String vnf_id) throws AAIServiceException {
411 GenericVnf response = null;
414 AAIRequest request = AAIRequest.getRequestFromResource("generic-vnf");
415 request.addRequestProperty("generic-vnf.vnf-id", vnf_id);
416 String rv = executor.get(request);
418 ObjectMapper mapper = getObjectMapper();
419 response = mapper.readValue(rv, GenericVnf.class);
421 } catch(AAIServiceException aaiexc) {
423 } catch (Exception exc) {
424 LOG.warn(new Object(){}.getClass().getEnclosingMethod().getName(), exc);
425 throw new AAIServiceException(exc);
433 public boolean postGenericVnfData(String vnf_id, GenericVnf data) throws AAIServiceException {
435 AAIRequest request = AAIRequest.getRequestFromResource("generic-vnf");
436 request.addRequestProperty("generic-vnf.vnf-id", vnf_id);
437 request.setRequestObject(data);
438 Object response = executor.post(request);
440 } catch(AAIServiceException aaiexc) {
442 } catch (Exception exc) {
443 LOG.warn("requestGenericVnfData", exc);
444 throw new AAIServiceException(exc);
449 public boolean deleteGenericVnfData(String vnf_id, String resourceVersion) throws AAIServiceException {
450 boolean response = false;
453 AAIRequest request = AAIRequest.getRequestFromResource("generic-vnf");
454 request.addRequestProperty("generic-vnf.vnf-id", vnf_id);
455 response = executor.delete(request, resourceVersion);
456 } catch(AAIServiceException aaiexc) {
458 } catch (Exception exc) {
459 LOG.warn("deleteGenericVnfData", exc);
460 throw new AAIServiceException(exc);
466 * @see org.onap.ccsdk.sli.adaptors.resource.aic.AnAIClient#requestSdnZoneQuery(java.lang.String, java.lang.String, java.lang.String)
469 public Vce requestNetworkVceData(String vnf_id) throws AAIServiceException {
472 AAIRequest request = AAIRequest.getRequestFromResource("vce");
473 request.addRequestProperty("vce.vnf-id", vnf_id);
474 String rv = executor.get(request);
476 ObjectMapper mapper = getObjectMapper();
477 response = mapper.readValue(rv, Vce.class);
479 } catch(AAIServiceException aaiexc) {
481 } catch (Exception exc) {
482 LOG.warn(new Object(){}.getClass().getEnclosingMethod().getName(), exc);
483 throw new AAIServiceException(exc);
491 * @see org.onap.ccsdk.sli.adaptors.resource.aic.AnAIClient#requestSdnZoneQuery(java.lang.String, java.lang.String, java.lang.String)
494 public boolean deleteNetworkVceData(String vnf_id, String resourceVersion) throws AAIServiceException {
495 boolean response = false;
498 AAIRequest request = AAIRequest.getRequestFromResource("vce");
499 request.addRequestProperty("vce.vnf-id", vnf_id);
500 response = executor.delete(request, resourceVersion);
501 } catch(AAIServiceException aaiexc) {
503 } catch (Exception exc) {
504 LOG.warn("deleteNetworkVceData", exc);
505 throw new AAIServiceException(exc);
511 * @see org.onap.ccsdk.sli.adaptors.resource.aic.AnAIClient#postNetworkVceData(java.lang.String, org.onap.ccsdk.sli.adaptors.resource.aic.aai.VCERequest)
514 public boolean postNetworkVceData(String vnf_id, Vce data) throws AAIServiceException {
516 AAIRequest request = AAIRequest.getRequestFromResource("vce");
517 request.addRequestProperty("vce.vnf-id", vnf_id);
518 request.setRequestObject(data);
519 Object response = executor.post(request);
521 } catch(AAIServiceException aaiexc) {
523 } catch (Exception exc) {
524 LOG.warn("requestGenericVnfData", exc);
525 throw new AAIServiceException(exc);
531 public SearchResults requestServiceInstanceURL(String svc_instance_id) throws AAIServiceException {
532 SearchResults response = null;
533 InputStream inputStream = null;
536 String path = svc_inst_qry_path;
537 path = path.replace("{svc-instance-id}", encodeQuery(svc_instance_id));
539 String request_url = target_uri+path;
540 URL http_req_url = new URL(request_url);
542 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.GET);
544 LOGwriteFirstTrace(HttpMethod.GET, http_req_url.toString());
545 LOGwriteDateTrace("svc_instance_id", svc_instance_id);
548 int responseCode = con.getResponseCode();
549 if (responseCode == HttpURLConnection.HTTP_OK) {
550 inputStream = con.getInputStream();
552 inputStream = con.getErrorStream();
555 // Process the response
556 LOG.debug("HttpURLConnection result:" + responseCode);
557 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
558 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
560 ObjectMapper mapper = getObjectMapper();
562 if (responseCode == HttpURLConnection.HTTP_OK) {
563 // StringBuilder stringBuilder = new StringBuilder("\n");
564 // String line = null;
565 // while( ( line = reader.readLine() ) != null ) {
566 // stringBuilder.append("\n").append( line );
568 // LOG.info(stringBuilder.toString());
569 response = mapper.readValue(reader, SearchResults.class);
570 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, "SUCCESS", mapper.writeValueAsString(response));
571 } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
572 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
575 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
576 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
577 throw new AAIServiceException(responseCode, errorresponse);
580 } catch(AAIServiceException aaiexc) {
582 } catch (Exception exc) {
583 LOG.warn("requestServiceInstanceURL", exc);
584 throw new AAIServiceException(exc);
586 if(inputStream != null){
589 } 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 // long id = tracker.getAndIncrement();
677 // String transactionId = String.format("N%016X", id);
678 String transactionId = UUID.randomUUID().toString();
679 return transactionId;
684 protected void LOGwriteFirstTrace(String method, String url) {
685 String time = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").format(System.currentTimeMillis());
686 LOG.info("A&AI transaction :");
687 LOG.info("Request Time : " + time + ", Method : " + method);
688 LOG.info("Request URL : "+ url);
691 protected void LOGwriteDateTrace(String name, String data) {
692 LOG.info("Input - " + name + " : " + data);
695 protected void LOGwriteEndingTrace(int response_code, String comment, String data) {
696 LOG.info("Response code : " + response_code +", " + comment);
697 LOG.info(String.format("Response data : %s", data));
700 protected String encodeQuery(String param) throws UnsupportedEncodingException {
701 return URLEncoder.encode(param, "UTF-8").replace("+", "%20");
704 private String encodeCustomerURL(final String selection)
706 String encrypted_url = selection;
708 "/aai/v11/business/customers/customer/(.+)/service-subscriptions/service-subscription/(.+)/service-instances/service-instance/(.+)/";
709 Pattern pattern = Pattern.compile(apnpattern);
712 URL url = new URL(selection);
713 String path = url.getPath();
715 LOG.info("Trying to match apn to <" + path + ">");
717 Matcher matcher = pattern.matcher(path);
719 while(matcher.find()) {
720 String customer = matcher.group(1);
721 String subscription = matcher.group(2);
722 String service = matcher.group(3);
724 encrypted_url = selection.replace(customer, encodeQuery(customer));
725 encrypted_url = encrypted_url.replace(subscription, encodeQuery(subscription));
726 encrypted_url = encrypted_url.replace(service, encodeQuery(service));
728 } catch (Exception e) {
732 return encrypted_url;
736 public Vpe requestNetworkVpeData(String vnf_id) throws AAIServiceException {
740 AAIRequest request = AAIRequest.getRequestFromResource("vpe");
741 request.addRequestProperty("vpe.vnf-id", vnf_id);
742 String rv = executor.get(request);
744 ObjectMapper mapper = getObjectMapper();
745 response = mapper.readValue(rv, Vpe.class);
747 } catch(AAIServiceException aaiexc) {
749 } catch (Exception exc) {
750 LOG.warn(new Object(){}.getClass().getEnclosingMethod().getName(), exc);
751 throw new AAIServiceException(exc);
757 public boolean postNetworkVpeData(String vnf_id, Vpe data) throws AAIServiceException {
759 AAIRequest request = AAIRequest.getRequestFromResource("vpe");
760 request.addRequestProperty("vpe.vnf-id", vnf_id);
761 request.setRequestObject(data);
762 Object response = executor.post(request);
764 } catch(AAIServiceException aaiexc) {
766 } catch (Exception exc) {
767 LOG.warn(new Object(){}.getClass().getEnclosingMethod().getName(), exc);
768 throw new AAIServiceException(exc);
773 public boolean deleteNetworkVpeData(String vnf_id, String resourceVersion) throws AAIServiceException {
774 boolean response = false;
777 AAIRequest request = AAIRequest.getRequestFromResource("vpe");
778 request.addRequestProperty("vpe.vnf-id", vnf_id);
779 response = executor.delete(request, resourceVersion);
780 } catch(AAIServiceException aaiexc) {
782 } catch (Exception exc) {
783 LOG.warn(new Object(){}.getClass().getEnclosingMethod().getName(), exc);
784 throw new AAIServiceException(exc);
790 public VplsPe requestNetworkVplsPeData(String equipment_name)throws AAIServiceException {
791 VplsPe response = null;
794 AAIRequest request = AAIRequest.getRequestFromResource("vpls-pe");
795 request.addRequestProperty("vpls-pe.equipment-name", equipment_name);
797 String rv = executor.get(request);
799 ObjectMapper mapper = getObjectMapper();
800 response = mapper.readValue(rv, VplsPe.class);
802 } catch(AAIServiceException aaiexc) {
804 } catch (Exception exc) {
805 LOG.warn(new Object(){}.getClass().getEnclosingMethod().getName(), exc);
806 throw new AAIServiceException(exc);
812 public boolean postNetworkVplsPeData(String equipment_name, VplsPe data) throws AAIServiceException {
814 AAIRequest request = AAIRequest.getRequestFromResource("vpls-pe");
815 request.addRequestProperty("vpls-pe.equipment-name", equipment_name);
816 request.setRequestObject(data);
817 Object response = executor.post(request);
819 } catch(AAIServiceException aaiexc) {
821 } catch (Exception exc) {
822 LOG.warn("requestGenericVnfData", exc);
823 throw new AAIServiceException(exc);
828 public boolean deleteNetworkVplsPeData(String vnf_id, String resourceVersion) throws AAIServiceException {
829 boolean response = false;
832 AAIRequest request = AAIRequest.getRequestFromResource("vpls-pe");
833 request.addRequestProperty("vpls-pe.equipment-name", vnf_id);
834 response = executor.delete(request, resourceVersion);
835 } catch(AAIServiceException aaiexc) {
837 } catch (Exception exc) {
838 LOG.warn("deleteNetworkVplsPeData", exc);
839 throw new AAIServiceException(exc);
845 public Complex requestNetworkComplexData(String pLocId) throws AAIServiceException {
846 Complex response = null;
847 InputStream inputStream = null;
850 AAIRequest request = AAIRequest.getRequestFromResource("complex");
851 request.addRequestProperty("complex.physical-location-id", pLocId);
853 String rv = executor.get(request);
855 ObjectMapper mapper = getObjectMapper();
856 response = mapper.readValue(rv, Complex.class);
858 } catch(AAIServiceException aaiexc) {
860 } catch (Exception exc) {
861 LOG.warn("requestNetworkComplexData", exc);
862 throw new AAIServiceException(exc);
864 if(inputStream != null){
867 } catch(Exception exc) {
876 public boolean postNetworkComplexData(String vnf_id, Complex data) throws AAIServiceException {
878 AAIRequest request = AAIRequest.getRequestFromResource("complex");
879 request.addRequestProperty("complex.physical-location-id", vnf_id);
880 request.setRequestObject(data);
881 Object response = executor.post(request);
883 } catch(AAIServiceException aaiexc) {
885 } catch (Exception exc) {
886 LOG.warn("postNetworkComplexData", exc);
887 throw new AAIServiceException(exc);
892 public boolean deleteNetworkComplexData(String pLocId, String resourceVersion) throws AAIServiceException {
893 boolean response = false;
896 AAIRequest request = AAIRequest.getRequestFromResource("complex");
897 request.addRequestProperty("complex.physical-location-id", pLocId);
899 response = executor.delete(request, resourceVersion);
901 } catch(AAIServiceException aaiexc) {
903 } catch (Exception exc) {
904 LOG.warn("deleteNetworkComplexData", exc);
905 throw new AAIServiceException(exc);
912 * @see org.openecomp.sdnct.sli.aai.AAIClient#requestVServersData(java.lang.String, java.lang.String)
915 public Vserver requestVServerData(String tenantId, String vserverId, String cloudOwner, String cloudRegionId) throws AAIServiceException {
916 Vserver response = null;
919 AAIRequest request = AAIRequest.getRequestFromResource("vserver");
920 request.addRequestProperty("cloud-region.cloud-owner", cloudOwner);
921 request.addRequestProperty("cloud-region.cloud-region-id", cloudRegionId);
922 request.addRequestProperty("tenant.tenant-id", tenantId);
923 request.addRequestProperty("vserver.vserver-id", vserverId);
925 String rv = executor.get(request);
927 ObjectMapper mapper = getObjectMapper();
928 response = mapper.readValue(rv, Vserver.class);
930 } catch(AAIServiceException aaiexc) {
932 } catch (Exception exc) {
933 LOG.warn(new Object(){}.getClass().getEnclosingMethod().getName(), exc);
934 throw new AAIServiceException(exc);
941 public boolean postVServerData(String tenantId, String vserverId, String cloudOwner, String cloudRegionId, Vserver data) throws AAIServiceException {
943 AAIRequest request = AAIRequest.getRequestFromResource("vserver");
944 request.addRequestProperty("cloud-region.cloud-owner", cloudOwner);
945 request.addRequestProperty("cloud-region.cloud-region-id", cloudRegionId);
946 request.addRequestProperty("tenant.tenant-id", tenantId);
947 request.addRequestProperty("vserver.vserver-id", vserverId);
948 request.setRequestObject(data);
949 Object response = executor.post(request);
951 } catch(AAIServiceException aaiexc) {
953 } catch (Exception exc) {
954 LOG.warn("postNetworkComplexData", exc);
955 throw new AAIServiceException(exc);
960 public boolean deleteVServerData(String tenant_id, String vserver_id, String cloudOwner, String cloudRegionId, String resourceVersion) throws AAIServiceException {
961 boolean response = false;
962 InputStream inputStream = null;
965 String local_network_complexes_path = network_vserver_path.replace("{tenant-id}", encodeQuery(tenant_id));
966 local_network_complexes_path = local_network_complexes_path.replace("{vserver-id}", encodeQuery(vserver_id));
967 local_network_complexes_path = local_network_complexes_path.replace("{cloud-owner}", encodeQuery(cloudOwner));
968 local_network_complexes_path = local_network_complexes_path.replace("{cloud-region-id}", encodeQuery(cloudRegionId));
970 String request_url = target_uri+local_network_complexes_path;
971 if(resourceVersion!=null) {
972 request_url = request_url +"?resource-version="+resourceVersion;
974 URL http_req_url = new URL(request_url);
976 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.DELETE);
978 LOGwriteFirstTrace(HttpMethod.DELETE, http_req_url.toString());
979 LOGwriteDateTrace("tenant_id", tenant_id);
980 LOGwriteDateTrace("vserver_id", vserver_id);
981 LOGwriteDateTrace("cloud-owner", cloudOwner);
982 LOGwriteDateTrace("cloud-region-id", cloudRegionId);
985 int responseCode = con.getResponseCode();
986 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
987 inputStream = con.getInputStream();
989 inputStream = con.getErrorStream();
992 // Process the response
993 LOG.debug("HttpURLConnection result:" + responseCode);
994 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
995 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
998 ObjectMapper mapper = getObjectMapper();
1000 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1001 StringBuilder stringBuilder = new StringBuilder();
1003 while( ( line = reader.readLine() ) != null ) {
1004 stringBuilder.append( line );
1006 LOGwriteEndingTrace(responseCode, "SUCCESS", stringBuilder.toString());
1008 } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
1009 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
1012 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
1013 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
1014 throw new AAIServiceException(responseCode, errorresponse);
1017 } catch(AAIServiceException aaiexc) {
1019 } catch (Exception exc) {
1020 LOG.warn("deleteVServerData", exc);
1021 throw new AAIServiceException(exc);
1023 if(inputStream != null){
1025 inputStream.close();
1026 } catch(Exception exc) {
1037 * @see org.onap.ccsdk.sli.adaptors.aai.AAIClient#requestCtagPoolData(String)
1040 public CtagPool requestCtagPoolData(String physical_location_id, String target_pe, String availability_zone_name) throws AAIServiceException {
1041 CtagPool response = null;
1044 AAIRequest request = AAIRequest.getRequestFromResource("ctag-pool");
1046 request.addRequestProperty("ctag-pool.target-pe", target_pe);
1047 request.addRequestProperty("ctag-pool.availability-zone-name", availability_zone_name);
1048 request.addRequestProperty("complex.physical-location-id", physical_location_id);
1050 String rv = executor.get(request);
1052 ObjectMapper mapper = getObjectMapper();
1053 response = mapper.readValue(rv, CtagPool.class);
1055 } catch(AAIServiceException aaiexc) {
1057 } catch (Exception exc) {
1058 LOG.warn("requestNetworkVceData", exc);
1059 throw new AAIServiceException(exc);
1064 //==================== DvsSwitch ======================
1066 public DvsSwitch requestDvsSwitchData(String vnf_id) throws AAIServiceException {
1067 DvsSwitch response = null;
1068 InputStream inputStream = null;
1071 AAIRequest request = AAIRequest.getRequestFromResource("dvs-switch");
1072 request.addRequestProperty("dvs-switch.switch-name", vnf_id);
1074 String rv = executor.get(request);
1076 ObjectMapper mapper = getObjectMapper();
1077 response = mapper.readValue(rv, DvsSwitch.class);
1079 } catch(AAIServiceException aaiexc) {
1081 } catch (Exception exc) {
1082 LOG.warn("requestDvsSwitchData", exc);
1083 throw new AAIServiceException(exc);
1085 if(inputStream != null){
1087 inputStream.close();
1088 } catch(Exception exc) {
1097 public boolean postDvsSwitchData(String switch_name, DvsSwitch data) throws AAIServiceException {
1099 AAIRequest request = AAIRequest.getRequestFromResource("dvs-switch");
1100 request.addRequestProperty("dvs-switch.switch-name", switch_name);
1101 request.setRequestObject(data);
1102 Object response = executor.post(request);
1104 } catch(AAIServiceException aaiexc) {
1106 } catch (Exception exc) {
1107 LOG.warn(new Object(){}.getClass().getEnclosingMethod().getName(), exc);
1108 throw new AAIServiceException(exc);
1113 public boolean deleteDvsSwitchData(String vnf_id, String resourceVersion) throws AAIServiceException {
1114 boolean response = false;
1115 InputStream inputStream = null;
1118 AAIRequest request = AAIRequest.getRequestFromResource("dvs-switch");
1119 request.addRequestProperty("dvs-switch.switch-name", vnf_id);
1120 response = executor.delete(request, resourceVersion);
1121 } catch(AAIServiceException aaiexc) {
1123 } catch (Exception exc) {
1124 LOG.warn("deleteDvsSwitchData", exc);
1125 throw new AAIServiceException(exc);
1129 //================== End of DvsSwitch =================
1130 //==================== PhysicalLink ======================
1132 public PhysicalLink requestPhysicalLinkData(String linkName) throws AAIServiceException {
1133 PhysicalLink response = null;
1136 AAIRequest request = AAIRequest.getRequestFromResource("physical-link");
1137 request.addRequestProperty("physical-link.link-name", linkName);
1139 String rv = executor.get(request);
1141 ObjectMapper mapper = getObjectMapper();
1142 response = mapper.readValue(rv, PhysicalLink.class);
1144 } catch(AAIServiceException aaiexc) {
1146 } catch (Exception exc) {
1147 LOG.warn("requestPhysicalLinkData", exc);
1148 throw new AAIServiceException(exc);
1154 public boolean postPhysicalLinkData(String linkName, PhysicalLink data) throws AAIServiceException {
1156 AAIRequest request = AAIRequest.getRequestFromResource("physical-link");
1157 request.addRequestProperty("physical-link.link-name", linkName);
1158 request.setRequestObject(data);
1159 Object response = executor.post(request);
1161 } catch(AAIServiceException aaiexc) {
1163 } catch (Exception exc) {
1164 LOG.warn(new Object(){}.getClass().getEnclosingMethod().getName(), exc);
1165 throw new AAIServiceException(exc);
1170 public boolean deletePhysicalLinkData(String linkName, String resourceVersion) throws AAIServiceException {
1171 boolean response = false;
1174 AAIRequest request = AAIRequest.getRequestFromResource("physical-link");
1175 request.addRequestProperty("physical-link.link-name", linkName);
1176 response = executor.delete(request, resourceVersion);
1177 } catch(AAIServiceException aaiexc) {
1179 } catch (Exception exc) {
1180 LOG.warn("deletePhysicalLinkData", exc);
1181 throw new AAIServiceException(exc);
1185 //================== End of PhysicalLink =================
1186 //==================== PInterface ======================
1188 public PInterface requestPInterfaceData(String hostname, String interfaceName) throws AAIServiceException {
1189 PInterface response = null;
1192 AAIRequest request = new PInterfaceRequest();
1193 request.addRequestProperty(PInterfaceRequest.PINTERFACE_INTERFACE_NAME, interfaceName);
1194 request.addRequestProperty(PInterfaceRequest.PSERVER_HOSTNAME, hostname);
1195 String rv = executor.get(request);
1197 ObjectMapper mapper = getObjectMapper();
1198 response = mapper.readValue(rv, PInterface.class);
1200 } catch(AAIServiceException aaiexc) {
1202 } catch (Exception exc) {
1203 LOG.warn(new Object(){}.getClass().getEnclosingMethod().getName(), exc);
1204 throw new AAIServiceException(exc);
1210 public boolean postPInterfaceData(String hostname, String interfaceName, PInterface request) throws AAIServiceException {
1211 InputStream inputStream = null;
1215 ObjectMapper mapper = getObjectMapper();
1216 String json_text = mapper.writeValueAsString(request);
1218 SSLSocketFactory sockFact = CTX.getSocketFactory();
1220 String request_url = target_uri+p_interface_path;
1221 String encoded_vnf = encodeQuery(hostname);
1222 request_url = request_url.replace("{hostname}", encoded_vnf) ;
1223 encoded_vnf = encodeQuery(interfaceName);
1224 request_url = request_url.replace("{interface-name}", encoded_vnf) ;
1225 URL http_req_url = new URL(request_url);
1227 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.PUT);
1229 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
1230 osw.write(json_text);
1235 LOGwriteFirstTrace("PUT", request_url);
1236 LOGwriteDateTrace("hostname", hostname);
1237 LOGwriteDateTrace("interface-name", interfaceName);
1238 LOGwriteDateTrace("PInterface", json_text);
1241 int responseCode = con.getResponseCode();
1242 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1243 inputStream = con.getInputStream();
1245 inputStream = con.getErrorStream();
1248 // Process the response
1249 BufferedReader reader;
1251 reader = new BufferedReader( new InputStreamReader( inputStream ) );
1253 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1254 StringBuilder stringBuilder = new StringBuilder();
1256 while( ( line = reader.readLine() ) != null ) {
1257 stringBuilder.append( line );
1259 LOGwriteEndingTrace(responseCode, "SUCCESS", (stringBuilder != null) ? stringBuilder.toString() : "{no-data}");
1262 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
1263 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
1265 throw new AAIServiceException(responseCode, errorresponse);
1267 } catch(AAIServiceException aaiexc) {
1269 } catch (Exception exc) {
1270 LOG.warn("postPInterfaceData", exc);
1271 throw new AAIServiceException(exc);
1274 if(inputStream != null)
1275 inputStream.close();
1276 } catch (Exception exc) {
1283 public boolean deletePInterfaceData(String hostname, String interfaceName, String resourceVersion) throws AAIServiceException {
1284 boolean response = false;
1287 AAIRequest request = AAIRequest.getRequestFromResource("p-interface");
1288 request.addRequestProperty("p-interface.interface-name", interfaceName);
1289 request.addRequestProperty("pserver.hostname", hostname);
1290 response = executor.delete(request, resourceVersion);
1291 } catch(AAIServiceException aaiexc) {
1293 } catch (Exception exc) {
1294 LOG.warn("deletePInterfaceData", exc);
1295 throw new AAIServiceException(exc);
1299 //================== End of PInterface =================
1300 //==================== SitePairSet ======================
1302 public SitePairSet requestSitePairSetData(String sitePairSetId) throws AAIServiceException {
1303 SitePairSet response = null;
1306 AAIRequest request = AAIRequest.getRequestFromResource("site-pair-set");
1307 request.addRequestProperty("site-pair-set.site-pair-set-id", sitePairSetId);
1308 String rv = executor.get(request);
1310 ObjectMapper mapper = getObjectMapper();
1311 response = mapper.readValue(rv, SitePairSet.class);
1313 } catch(AAIServiceException aaiexc) {
1315 } catch (Exception exc) {
1316 LOG.warn(new Object(){}.getClass().getEnclosingMethod().getName(), exc);
1317 throw new AAIServiceException(exc);
1323 public boolean postSitePairSetData(String linkName, SitePairSet request) throws AAIServiceException {
1324 InputStream inputStream = null;
1328 ObjectMapper mapper = getObjectMapper();
1329 String json_text = mapper.writeValueAsString(request);
1331 SSLSocketFactory sockFact = CTX.getSocketFactory();
1333 String request_url = target_uri+site_pair_set_path;
1334 String encoded_vnf = encodeQuery(linkName);
1335 request_url = request_url.replace("{site-pair-set-id}", encoded_vnf) ;
1336 URL http_req_url = new URL(request_url);
1338 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.PUT);
1340 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
1341 osw.write(json_text);
1346 LOGwriteFirstTrace("PUT", request_url);
1347 LOGwriteDateTrace("link-name", linkName);
1348 LOGwriteDateTrace("SitePairSet", json_text);
1351 int responseCode = con.getResponseCode();
1352 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1353 inputStream = con.getInputStream();
1355 inputStream = con.getErrorStream();
1358 // Process the response
1359 BufferedReader reader;
1361 reader = new BufferedReader( new InputStreamReader( inputStream ) );
1363 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1364 StringBuilder stringBuilder = new StringBuilder();
1366 while( ( line = reader.readLine() ) != null ) {
1367 stringBuilder.append( line );
1369 LOGwriteEndingTrace(responseCode, "SUCCESS", (stringBuilder != null) ? stringBuilder.toString() : "{no-data}");
1372 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
1373 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
1375 throw new AAIServiceException(responseCode, errorresponse);
1377 } catch(AAIServiceException aaiexc) {
1379 } catch (Exception exc) {
1380 LOG.warn("postSitePairSetData", exc);
1381 throw new AAIServiceException(exc);
1384 if(inputStream != null)
1385 inputStream.close();
1386 } catch (Exception exc) {
1393 public boolean deleteSitePairSetData(String linkName, String resourceVersion) throws AAIServiceException {
1394 boolean response = false;
1397 AAIRequest request = AAIRequest.getRequestFromResource("site-pair-set");
1398 request.addRequestProperty("site-pair-set.site-pair-set-id", linkName);
1399 response = executor.delete(request, resourceVersion);
1400 } catch(AAIServiceException aaiexc) {
1402 } catch (Exception exc) {
1403 LOG.warn("deleteSitePairSetData", exc);
1404 throw new AAIServiceException(exc);
1409 //================== End of SitePairSet =================
1410 //==================== Service ======================
1412 public Service requestServiceData(String serviceId) throws AAIServiceException {
1413 Service response = null;
1414 InputStream inputStream = null;
1417 AAIRequest request = AAIRequest.getRequestFromResource("service");
1418 request.addRequestProperty("service.service-id", serviceId);
1421 String rv = executor.get(request);
1423 ObjectMapper mapper = getObjectMapper();
1424 response = mapper.readValue(rv, Service.class);
1426 } catch(AAIServiceException aaiexc) {
1428 } catch (Exception exc) {
1429 LOG.warn("requestServiceData", exc);
1430 throw new AAIServiceException(exc);
1436 public boolean postServiceData(String linkName, Service request) throws AAIServiceException {
1437 InputStream inputStream = null;
1441 ObjectMapper mapper = getObjectMapper();
1442 String json_text = mapper.writeValueAsString(request);
1444 SSLSocketFactory sockFact = CTX.getSocketFactory();
1446 String request_url = target_uri+service_path;
1447 String encoded_vnf = encodeQuery(linkName);
1448 request_url = request_url.replace("{service-id}", encoded_vnf) ;
1449 URL http_req_url = new URL(request_url);
1451 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.PUT);
1453 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
1454 osw.write(json_text);
1459 LOGwriteFirstTrace("PUT", request_url);
1460 LOGwriteDateTrace("service-id", linkName);
1461 LOGwriteDateTrace("Service", json_text);
1464 int responseCode = con.getResponseCode();
1465 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1466 inputStream = con.getInputStream();
1468 inputStream = con.getErrorStream();
1471 // Process the response
1472 BufferedReader reader;
1474 reader = new BufferedReader( new InputStreamReader( inputStream ) );
1476 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1477 StringBuilder stringBuilder = new StringBuilder();
1479 while( ( line = reader.readLine() ) != null ) {
1480 stringBuilder.append( line );
1482 LOGwriteEndingTrace(responseCode, "SUCCESS", (stringBuilder != null) ? stringBuilder.toString() : "{no-data}");
1485 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
1486 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
1488 throw new AAIServiceException(responseCode, errorresponse);
1490 } catch(AAIServiceException aaiexc) {
1492 } catch (Exception exc) {
1493 LOG.warn("postServiceData", exc);
1494 throw new AAIServiceException(exc);
1497 if(inputStream != null)
1498 inputStream.close();
1499 } catch (Exception exc) {
1506 public boolean deleteServiceData(String service_id, String resourceVersion) throws AAIServiceException {
1507 boolean response = false;
1510 AAIRequest request = AAIRequest.getRequestFromResource("service");
1511 request.addRequestProperty("service.service-id", service_id);
1512 response = executor.delete(request, resourceVersion);
1513 } catch(AAIServiceException aaiexc) {
1515 } catch (Exception exc) {
1516 LOG.warn("deleteServiceData", exc);
1517 throw new AAIServiceException(exc);
1522 //================== End of Service =================
1528 public VServer dataChangeRequestVServerData(URL url) throws AAIServiceException {
1531 throw new NullPointerException();
1534 return this.getResource(url.toString(), VServer.class);
1538 public Pserver dataChangeRequestPServerData(URL url) throws AAIServiceException {
1541 throw new NullPointerException();
1544 return this.getResource(url.toString(), Pserver.class);
1548 public CtagPool dataChangeRequestCtagPoolData(URL url) throws AAIServiceException {
1551 throw new NullPointerException();
1554 return this.getResource(url.toString(), CtagPool.class);
1558 public VplsPe dataChangeRequestVplsPeData(URL url) throws AAIServiceException {
1561 throw new NullPointerException();
1564 return this.getResource(url.toString(), VplsPe.class);
1568 public Vpe dataChangeRequestVpeData(URL url) throws AAIServiceException {
1571 throw new NullPointerException();
1574 return this.getResource(url.toString(), Vpe.class);
1578 public DvsSwitch dataChangeRequestDvsSwitchData(URL url) throws AAIServiceException {
1581 throw new NullPointerException();
1584 return this.getResource(url.toString(), DvsSwitch.class);
1588 public OamNetwork dataChangeRequestOAMNetworkData(URL url) throws AAIServiceException {
1591 throw new NullPointerException();
1594 return this.getResource(url.toString(), OamNetwork.class);
1598 public AvailabilityZone dataChangeRequestAvailabilityZoneData(URL url) throws AAIServiceException {
1601 throw new NullPointerException();
1604 return this.getResource(url.toString(), AvailabilityZone.class);
1608 public Complex dataChangeRequestComplexData(URL url) throws AAIServiceException {
1611 throw new NullPointerException();
1614 return this.getResource(url.toString(), Complex.class);
1618 public boolean dataChangeDeleteVServerData(URL url) throws AAIServiceException {
1621 throw new NullPointerException();
1624 return deleteAAIEntity(url, new Object(){}.getClass().getEnclosingMethod().getName());
1627 public boolean dataChangeDeleteCtagPoolData(URL url) throws AAIServiceException {
1630 throw new NullPointerException();
1633 return deleteAAIEntity(url, new Object(){}.getClass().getEnclosingMethod().getName());
1636 public boolean dataChangeDeleteVplsPeData(URL url) throws AAIServiceException {
1639 throw new NullPointerException();
1642 return deleteAAIEntity(url, new Object(){}.getClass().getEnclosingMethod().getName());
1645 public boolean dataChangeDeleteVpeData(URL url) throws AAIServiceException {
1648 throw new NullPointerException();
1651 return deleteAAIEntity(url, new Object(){}.getClass().getEnclosingMethod().getName());
1654 public boolean dataChangeDeleteDvsSwitchData(URL url) throws AAIServiceException {
1657 throw new NullPointerException();
1660 return deleteAAIEntity(url, new Object(){}.getClass().getEnclosingMethod().getName());
1663 public boolean dataChangeDeleteOAMNetworkData(URL url) throws AAIServiceException {
1666 throw new NullPointerException();
1669 return deleteAAIEntity(url, new Object(){}.getClass().getEnclosingMethod().getName());
1671 //Availability-Zone:
1672 public boolean dataChangeDeleteAvailabilityZoneData(URL url) throws AAIServiceException {
1675 throw new NullPointerException();
1678 return deleteAAIEntity(url, new Object(){}.getClass().getEnclosingMethod().getName());
1681 public boolean dataChangeDeleteComplexData(URL url) throws AAIServiceException {
1684 throw new NullPointerException();
1687 return deleteAAIEntity(url, new Object(){}.getClass().getEnclosingMethod().getName());
1690 private boolean deleteAAIEntity(URL url, String caller) throws AAIServiceException {
1693 throw new NullPointerException();
1696 boolean response = false;
1697 InputStream inputStream = null;
1700 URL http_req_url = url;
1702 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.DELETE);
1704 // SSLSocketFactory sockFact = CTX.getSocketFactory();
1705 // con.setSSLSocketFactory( sockFact );
1707 LOGwriteFirstTrace("DELETE", http_req_url.toString());
1711 int responseCode = con.getResponseCode();
1712 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1713 inputStream = con.getInputStream();
1715 inputStream = con.getErrorStream();
1718 // Process the response
1719 LOG.debug("HttpURLConnection result:" + responseCode);
1720 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
1721 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
1724 ObjectMapper mapper = getObjectMapper();
1726 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1727 StringBuilder stringBuilder = new StringBuilder();
1729 while( ( line = reader.readLine() ) != null ) {
1730 stringBuilder.append( line );
1732 LOGwriteEndingTrace(responseCode, "SUCCESS", stringBuilder.toString());
1734 } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
1735 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
1738 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
1739 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
1740 throw new AAIServiceException(responseCode, errorresponse);
1743 } catch(AAIServiceException aaiexc) {
1745 } catch (Exception exc) {
1746 LOG.warn(caller, exc);
1747 throw new AAIServiceException(exc);
1749 if(inputStream != null){
1751 inputStream.close();
1752 } catch(Exception exc) {
1761 * Generic method to GET json data from an A&AI callback URL.
1762 * Then convert that json to an Object.
1763 * If successful the Object is attempted to be cast to the type parameter.
1766 * callback url for A&AI
1768 * the class of object that A&AI will return
1769 * @return the object created from json or null if the response code is not 200
1771 * @throws AAIServiceException
1772 * if empty or null key and or type or there's an error with processing
1774 public <T> T dataChangeRequestAaiData(String key, Class<T> type) throws AAIServiceException {
1775 if (StringUtils.isEmpty(key) || type == null) {
1776 throw new AAIServiceException("Key is empty or null and or type is null");
1781 SvcLogicContext ctx = new SvcLogicContext();
1782 if(!key.contains(" = ") && isValidURL(key)) {
1783 key = String.format("selflink = '%s'", key);
1785 if(!key.contains(" = ") && isValidURI(key)) {
1786 key = String.format("resource-path = '%s'", key);
1789 HashMap<String, String> nameValues = AAIServiceUtils.keyToHashMap(key, ctx);
1791 SelfLinkRequest request = new SelfLinkRequest(type);
1792 request.processRequestPathValues(nameValues);
1793 Object obj = this.getExecutor().query(request, type);
1794 response = type.cast(obj);
1796 return response != null ? type.cast(response) : response;
1800 public Pserver requestPServerData(String hostname) throws AAIServiceException {
1801 Pserver response = null;
1802 InputStream inputStream = null;
1805 AAIRequest request = AAIRequest.getRequestFromResource("pserver");
1806 request.addRequestProperty("pserver.hostname", hostname);
1809 String rv = executor.get(request);
1811 ObjectMapper mapper = getObjectMapper();
1812 response = mapper.readValue(rv, Pserver.class);
1814 } catch(AAIServiceException aaiexc) {
1816 } catch (Exception exc) {
1817 LOG.warn("requestPServerData", exc);
1818 throw new AAIServiceException(exc);
1824 public boolean postPServerData(String hostname, Pserver data) throws AAIServiceException {
1826 AAIRequest request = AAIRequest.getRequestFromResource("pserver");
1827 request.addRequestProperty("pserver.hostname", hostname);
1828 request.setRequestObject(data);
1829 Object response = executor.post(request);
1831 } catch(AAIServiceException aaiexc) {
1833 } catch (Exception exc) {
1834 LOG.warn(new Object(){}.getClass().getEnclosingMethod().getName(), exc);
1835 throw new AAIServiceException(exc);
1840 public boolean deletePServerData(String hostname, String resourceVersion) throws AAIServiceException {
1841 boolean response = false;
1844 AAIRequest request = AAIRequest.getRequestFromResource("pserver");
1845 request.addRequestProperty("pserver.hostname", hostname);
1846 response = executor.delete(request, resourceVersion);
1847 } catch(AAIServiceException aaiexc) {
1849 } catch (Exception exc) {
1850 LOG.warn("deletePServerData", exc);
1851 throw new AAIServiceException(exc);
1859 public L3Network requestL3NetworkData(String networkId) throws AAIServiceException {
1860 L3Network response = null;
1861 InputStream inputStream = null;
1864 AAIRequest request = AAIRequest.getRequestFromResource("l3-network");
1865 request.addRequestProperty("l3-network.network-id", networkId);
1867 String rv = executor.get(request);
1869 ObjectMapper mapper = getObjectMapper();
1870 response = mapper.readValue(rv, L3Network.class);
1872 } catch(AAIServiceException aaiexc) {
1874 } catch (Exception exc) {
1875 LOG.warn("requestL3NetworkData", exc);
1876 throw new AAIServiceException(exc);
1882 public L3Network requestL3NetworkQueryByName(String networkName) throws AAIServiceException {
1883 L3Network response = null;
1884 InputStream inputStream = null;
1887 AAIRequest request = AAIRequest.getRequestFromResource("l3-network");
1888 request.addRequestProperty("l3-network.network-name", networkName);
1890 String rv = executor.get(request);
1892 ObjectMapper mapper = getObjectMapper();
1893 response = mapper.readValue(rv, L3Network.class);
1896 } catch(AAIServiceException aaiexc) {
1898 } catch (Exception exc) {
1899 LOG.warn("requestL3NetworkQueryByName", exc);
1900 throw new AAIServiceException(exc);
1902 if(inputStream != null){
1904 inputStream.close();
1905 } catch(Exception exc) {
1914 public boolean postL3NetworkData(String networkId, L3Network data) throws AAIServiceException {
1916 AAIRequest request = AAIRequest.getRequestFromResource("l3-network");
1917 request.addRequestProperty("l3-network.network-id", networkId);
1918 request.setRequestObject(data);
1919 Object response = executor.post(request);
1921 } catch(AAIServiceException aaiexc) {
1923 } catch (Exception exc) {
1924 LOG.warn(new Object(){}.getClass().getEnclosingMethod().getName(), exc);
1925 throw new AAIServiceException(exc);
1930 public boolean deleteL3NetworkData(String networkId, String resourceVersion) throws AAIServiceException {
1931 boolean response = false;
1934 AAIRequest request = AAIRequest.getRequestFromResource("l3-network");
1935 request.addRequestProperty("l3-network.network-id", networkId);
1936 response = executor.delete(request, resourceVersion);
1937 } catch(AAIServiceException aaiexc) {
1939 } catch (Exception exc) {
1940 LOG.warn("deleteL3NetworkData", exc);
1941 throw new AAIServiceException(exc);
1949 public VpnBinding requestVpnBindingData(String vpnId) throws AAIServiceException {
1950 VpnBinding response = null;
1953 AAIRequest request = AAIRequest.getRequestFromResource("vpn-binding");
1954 request.addRequestProperty("vpn-binding.vpn-id", vpnId);
1956 String rv = executor.get(request);
1958 ObjectMapper mapper = getObjectMapper();
1959 response = mapper.readValue(rv, VpnBinding.class);
1961 } catch(AAIServiceException aaiexc) {
1963 } catch (Exception exc) {
1964 LOG.warn("requestVpnBindingData", exc);
1965 throw new AAIServiceException(exc);
1971 public boolean deleteVpnBindingData(String vpnId, String resourceVersion) throws AAIServiceException {
1972 boolean response = false;
1975 AAIRequest request = AAIRequest.getRequestFromResource("vpn-binding");
1976 request.addRequestProperty("vpn-binding.vpn-id", vpnId);
1977 response = executor.delete(request, resourceVersion);
1978 } catch(AAIServiceException aaiexc) {
1980 } catch (Exception exc) {
1981 LOG.warn("deleteVpnBindingData", exc);
1982 throw new AAIServiceException(exc);
1989 public VnfImage requestVnfImageData(String vnf_image_uuid) throws AAIServiceException {
1990 VnfImage response = null;
1993 AAIRequest request = AAIRequest.getRequestFromResource("vnf-image");
1994 request.addRequestProperty("vnf-image.vnf-image-uuid", vnf_image_uuid);
1996 String rv = executor.get(request);
1998 ObjectMapper mapper = getObjectMapper();
1999 response = mapper.readValue(rv, VnfImage.class);
2001 } catch(AAIServiceException aaiexc) {
2003 } catch (Exception exc) {
2004 LOG.warn("requestVnfImageData", exc);
2005 throw new AAIServiceException(exc);
2011 public VnfImage requestVnfImageDataByVendorModel(String vendor, String model) throws AAIServiceException {
2012 return requestVnfImageDataByVendorModelVersion(vendor, model, null);
2016 public VnfImage requestVnfImageDataByVendorModelVersion(String vendor, String model, String version) throws AAIServiceException
2018 List<VnfImage> responseList = new ArrayList<VnfImage>();
2019 VnfImage response = null;
2020 InputStream inputStream = null;
2023 String request_url = target_uri+vnf_image_query_path + (version==null? "": "&application-version={application_version}");
2024 request_url = request_url.replace("{application_vendor}", encodeQuery(vendor)) ;
2025 request_url = request_url.replace("{application_model}", encodeQuery(model)) ;
2026 if(version != null) {
2027 request_url = request_url.replace("{application_version}", encodeQuery(version)) ;
2029 URL http_req_url = new URL(request_url);
2031 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.GET);
2033 LOGwriteFirstTrace(HttpMethod.GET, http_req_url.toString());
2034 LOGwriteDateTrace("application_vendor", vendor);
2035 LOGwriteDateTrace("application_model", model);
2036 if(version != null) {
2037 LOGwriteDateTrace("application_version", version);
2041 int responseCode = con.getResponseCode();
2042 if (responseCode == HttpURLConnection.HTTP_OK) {
2043 inputStream = con.getInputStream();
2045 inputStream = con.getErrorStream();
2048 // Process the response
2049 LOG.debug("HttpURLConnection result:" + responseCode);
2050 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
2051 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2053 ObjectMapper mapper = getObjectMapper();
2055 if (responseCode == HttpURLConnection.HTTP_OK) {
2056 // StringBuilder stringBuilder = new StringBuilder("\n");
2057 // String line = null;
2058 // while( ( line = reader.readLine() ) != null ) {
2059 // stringBuilder.append("\n").append( line );
2061 // LOG.info(stringBuilder.toString());
2062 response = mapper.readValue(reader, VnfImage.class);
2063 String original_buffer = mapper.writeValueAsString(response);
2064 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, "SUCCESS", original_buffer);
2065 if(response.getApplicationVendor() == null /*&& response.getAdditionalProperties() != null && !response.getAdditionalProperties().isEmpty()*/){
2066 LOG.warn("A List of multiple VNF-IMAGE entries has been returned");
2067 VnfImages listOfObjects = mapper.readValue(original_buffer, VnfImages.class);
2068 if(!listOfObjects.getVnfImage().isEmpty()) {
2069 response = listOfObjects.getVnfImage().get(0);
2072 } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
2073 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
2076 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2077 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
2078 throw new AAIServiceException(responseCode, errorresponse);
2081 } catch(AAIServiceException aaiexc) {
2083 } catch (Exception exc) {
2084 LOG.warn("requestVnfImageData", exc);
2085 throw new AAIServiceException(exc);
2087 if(inputStream != null){
2089 inputStream.close();
2090 } catch(Exception exc) {
2099 public boolean sendNotify(NotifyEvent event, String serviceInstanceId, String pathCode) throws AAIServiceException {
2100 InputStream inputStream = null;
2104 String selfLink = selflink_fqdn;
2105 if(SELFLINK_AVPN != null && SELFLINK_AVPN.equals(pathCode)) {
2106 selfLink = selflink_avpn;
2108 selfLink = selfLink.replace("{service-instance-id}", encodeQuery(serviceInstanceId));
2109 event.setSelflink(selfLink);
2111 ObjectMapper mapper = getObjectMapper();
2112 String json_text = mapper.writeValueAsString(event);
2114 SSLSocketFactory sockFact = CTX.getSocketFactory();
2116 String request_url = target_uri+ubb_notify_path;
2117 URL http_req_url = new URL(request_url);
2119 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.PUT);
2121 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
2122 osw.write(json_text);
2127 LOGwriteFirstTrace("PUT", request_url);
2128 LOGwriteDateTrace("NotifyEvent", json_text);
2131 int responseCode = con.getResponseCode();
2132 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2133 inputStream = con.getInputStream();
2135 inputStream = con.getErrorStream();
2138 // Process the response
2139 BufferedReader reader;
2141 reader = new BufferedReader( new InputStreamReader( inputStream ) );
2143 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2144 StringBuilder stringBuilder = new StringBuilder();
2146 while( ( line = reader.readLine() ) != null ) {
2147 stringBuilder.append( line );
2149 LOGwriteEndingTrace(responseCode, "SUCCESS", (stringBuilder != null) ? stringBuilder.toString() : "{no-data}");
2152 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2153 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
2155 throw new AAIServiceException(responseCode, errorresponse);
2157 } catch(AAIServiceException aaiexc) {
2159 } catch (Exception exc) {
2160 LOG.warn("sendNotify", exc);
2161 throw new AAIServiceException(exc);
2164 if(inputStream != null)
2165 inputStream.close();
2166 } catch (Exception exc) {
2173 public SearchResults requestNodeQuery(String node_type, String entityIdentifier, String entityName) throws AAIServiceException {
2174 SearchResults response = null;
2175 InputStream inputStream = null;
2178 String request_url = target_uri+query_nodes_path;
2179 request_url = request_url.replace("{node-type}", encodeQuery(node_type)) ;
2180 request_url = request_url.replace("{entity-identifier}", entityIdentifier) ;
2181 request_url = request_url.replace("{entity-name}", encodeQuery(entityName)) ;
2182 URL http_req_url = new URL(request_url);
2184 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.GET);
2186 LOGwriteFirstTrace(HttpMethod.GET, http_req_url.toString());
2187 LOGwriteDateTrace("node_type", node_type);
2188 LOGwriteDateTrace("vnf_name", entityName);
2191 int responseCode = con.getResponseCode();
2192 if (responseCode == HttpURLConnection.HTTP_OK) {
2193 inputStream = con.getInputStream();
2195 inputStream = con.getErrorStream();
2198 // Process the response
2199 LOG.debug("HttpURLConnection result:" + responseCode);
2200 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
2201 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2203 ObjectMapper mapper = getObjectMapper();
2205 if (responseCode == HttpURLConnection.HTTP_OK) {
2206 response = mapper.readValue(reader, SearchResults.class);
2207 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, "SUCCESS", mapper.writeValueAsString(response));
2208 } else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
2209 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
2212 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2213 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
2214 throw new AAIServiceException(responseCode, errorresponse);
2217 } catch(AAIServiceException aaiexc) {
2219 } catch (Exception exc) {
2220 LOG.warn("requestNodeQuery", exc);
2221 throw new AAIServiceException(exc);
2223 if(inputStream != null){
2225 inputStream.close();
2226 } catch(Exception exc) {
2237 public String requestDataByURL(URL url) throws AAIServiceException {
2240 throw new NullPointerException();
2243 String response = null;
2244 InputStream inputStream = null;
2247 URL http_req_url = url;
2249 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.GET);
2251 LOGwriteFirstTrace(HttpMethod.GET, http_req_url.toString());
2254 int responseCode = con.getResponseCode();
2255 if (responseCode == HttpURLConnection.HTTP_OK) {
2256 inputStream = con.getInputStream();
2258 inputStream = con.getErrorStream();
2261 // Process the response
2262 LOG.debug("HttpURLConnection result:" + responseCode);
2263 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
2264 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2266 ObjectMapper mapper = getObjectMapper();
2268 if (responseCode == HttpURLConnection.HTTP_OK) {
2269 StringBuilder stringBuilder = new StringBuilder("\n");
2271 while( ( line = reader.readLine() ) != null ) {
2272 stringBuilder.append( line );
2274 LOG.info(stringBuilder.toString());
2275 // response = mapper.readValue(reader, String.class);
2276 response = stringBuilder.toString();
2277 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, "SUCCESS", mapper.writeValueAsString(response));
2278 } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
2279 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
2282 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2283 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
2284 throw new AAIServiceException(responseCode, errorresponse);
2287 } catch(AAIServiceException aaiexc) {
2289 } catch (Exception exc) {
2290 LOG.warn("requestNetworkVceData", exc);
2291 throw new AAIServiceException(exc);
2293 if(inputStream != null){
2295 inputStream.close();
2296 } catch(Exception exc) {
2306 public GenericVnf requestGenericVnfeNodeQuery(String vnf_name) throws AAIServiceException {
2308 if(vnf_name == null) {
2309 throw new NullPointerException();
2312 GenericVnf entity = null;
2313 SearchResults resp = this.requestNodeQuery("generic-vnf", "vnf-name", vnf_name);
2315 List<ResultData> resultDataList = resp.getResultData();
2318 for (ResultData datum : resultDataList) {
2319 String data_type = datum.getResourceType();
2320 URL url = new URL(datum.getResourceLink());
2321 entity = this.getResource(url.toString(), GenericVnf.class);
2326 LOG.error("Caught exception", e);
2332 public Vserver requestVServerDataByURL(URL url) throws AAIServiceException {
2335 throw new NullPointerException();
2338 Vserver entity = null;
2341 entity = this.getResource(url.toString(), Vserver.class);
2342 } catch (AAIServiceException exc) {
2344 } catch (Exception e) {
2345 throw new AAIServiceException(e);
2351 public URL requestVserverURLNodeQuery(String vserver_name) throws AAIServiceException {
2353 if(vserver_name == null) {
2354 throw new NullPointerException();
2358 SearchResults resp = this.requestNodeQuery("vserver", "vserver-name", vserver_name);
2360 List<ResultData> resultDataList = resp.getResultData();
2363 for (ResultData datum : resultDataList) {
2364 String data_type = datum.getResourceType();
2365 String resourceLink = datum.getResourceLink();
2366 if(!resourceLink.isEmpty() && !resourceLink.toLowerCase().startsWith("http")) {
2367 resourceLink = (new EchoRequest()).target_uri + resourceLink;
2369 entity = new URL(resourceLink);
2371 } catch (Exception e) {
2372 throw new AAIServiceException(e);
2377 class AAIRequestExecutor implements AAIExecutorInterface {
2380 public String get(AAIRequest request) throws AAIServiceException {
2381 String response = null;
2382 InputStream inputStream = null;
2383 HttpURLConnection con = null;
2384 URL requestUrl = null;
2386 String requestId = UUID.randomUUID().toString();
2387 StringBuilder errorStringBuilder = new StringBuilder();
2391 if(request.getRequestObject() != null) {
2392 requestUrl = request.getRequestUrl(HttpMethod.POST, null);
2393 requestUrl = appendDepth(requestUrl, request);
2394 con = getConfiguredConnection(requestUrl, HttpMethod.POST);
2395 String json_text = request.toJSONString();
2396 LOGwriteDateTrace("data", json_text);
2397 logMetricRequest(requestId, "POST "+requestUrl.getPath(), json_text, requestUrl.getPath());
2398 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
2399 osw.write(json_text);
2402 requestUrl = request.getRequestUrl(HttpMethod.GET, null);
2403 requestUrl = appendDepth(requestUrl, request);
2404 con = getConfiguredConnection(requestUrl, HttpMethod.GET);
2405 logMetricRequest(requestId, "GET "+requestUrl.getPath(), "", requestUrl.getPath());
2409 String responseMessage = con.getResponseMessage();
2410 int responseCode = con.getResponseCode();
2411 if (responseCode == HttpURLConnection.HTTP_OK) {
2412 inputStream = con.getInputStream();
2414 inputStream = con.getErrorStream();
2417 // Process the response
2418 LOG.debug("HttpURLConnection result:" + responseCode + " : " + responseMessage);
2419 logMetricResponse(requestId, responseCode, responseMessage);
2421 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
2422 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2424 ObjectMapper mapper = getObjectMapper();
2426 if (responseCode == HttpURLConnection.HTTP_OK) {
2427 StringBuilder stringBuilder = new StringBuilder();
2429 while( ( line = reader.readLine() ) != null ) {
2430 stringBuilder.append( line );
2432 response = stringBuilder.toString();
2434 Object object = mapper.readValue(response, Object.class);
2435 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, responseMessage, mapper.writeValueAsString(object));
2436 } catch(Exception exc) {
2437 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, responseMessage, mapper.writeValueAsString(response));
2439 } else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
2440 LOGwriteEndingTrace(responseCode, responseMessage, "Entry does not exist.");
2441 ErrorResponse errorresponse = null;
2443 errorresponse = mapper.readValue(reader, ErrorResponse.class);
2444 } catch(Exception exc) {
2445 errorresponse = new ErrorResponse();
2446 RequestError requestError = new RequestError();
2447 ServiceException serviceException = new ServiceException();
2448 serviceException.setText("Entry does not exist.");
2449 requestError.setServiceException(serviceException);
2450 errorresponse.setRequestError(requestError );
2452 throw new AAIServiceException(responseCode, errorresponse);
2453 } else if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
2454 StringBuilder stringBuilder = new StringBuilder();
2456 while( ( line = reader.readLine() ) != null ) {
2457 stringBuilder.append( line );
2459 LOGwriteEndingTrace(responseCode, responseMessage, stringBuilder.toString());
2460 ServiceException serviceException = new ServiceException();
2461 serviceException.setMessageId("HTTP_UNAUTHORIZED");
2462 serviceException.setText(stringBuilder.toString());
2463 RequestError requestError = new RequestError();
2464 requestError.setServiceException(serviceException);
2465 ErrorResponse errorresponse = new ErrorResponse();
2466 errorresponse.setRequestError(requestError);
2467 throw new AAIServiceException(responseCode, errorresponse);
2469 // StringBuilder errorStringBuilder = new StringBuilder();
2471 while( ( line = reader.readLine() ) != null ) {
2472 errorStringBuilder.append("\n").append( line );
2475 ErrorResponse errorresponse = mapper.readValue(errorStringBuilder.toString(), ErrorResponse.class);
2476 // ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2477 LOGwriteEndingTrace(responseCode, responseMessage, mapper.writeValueAsString(errorresponse));
2478 throw new AAIServiceException(responseCode, errorresponse);
2481 } catch(AAIServiceException aaiexc) {
2483 } catch (Exception exc) {
2484 LOG.warn(errorStringBuilder.toString(), exc);
2485 throw new AAIServiceException(exc);
2487 if(inputStream != null){
2489 inputStream.close();
2490 } catch(Exception exc) {
2498 private URL appendDepth(URL requestUrl, AAIRequest request) throws MalformedURLException {
2500 String depth = request.requestProperties.getProperty("depth", "1");
2501 String path = requestUrl.toString();
2502 if(path.contains("?depth=") || path.contains("&depth=")) {
2505 if(path.contains("?")) {
2506 path = String.format("%s&depth=%s", path, depth);
2508 path = String.format("%s?depth=%s", path, depth);
2510 return new URL(path);
2515 public String post(AAIRequest request) throws AAIServiceException {
2516 InputStream inputStream = null;
2517 String requestId = UUID.randomUUID().toString();
2520 String resourceVersion = null;
2521 AAIDatum instance = request.getRequestObject();
2523 Method getResourceVersionMethod = instance.getClass().getMethod("getResourceVersion");
2524 if(getResourceVersionMethod != null){
2526 getResourceVersionMethod.setAccessible(true);
2527 Object object = getResourceVersionMethod.invoke(instance);
2529 resourceVersion = object.toString();
2530 } catch (InvocationTargetException x) {
2531 Throwable cause = x.getCause();
2535 URL requestUrl = null;
2536 HttpURLConnection con = getConfiguredConnection(requestUrl = request.getRequestUrl(HttpMethod.PUT, resourceVersion), HttpMethod.PUT);
2537 ObjectMapper mapper = getObjectMapper();
2538 String json_text = request.toJSONString();
2540 LOGwriteDateTrace("data", json_text);
2541 logMetricRequest(requestId, "PUT "+requestUrl.getPath(), json_text, requestUrl.getPath());
2543 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
2544 osw.write(json_text);
2548 String responseMessage = con.getResponseMessage();
2549 int responseCode = con.getResponseCode();
2550 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2551 inputStream = con.getInputStream();
2553 inputStream = con.getErrorStream();
2556 LOG.debug("HttpURLConnection result:" + responseCode + " : " + responseMessage);
2557 logMetricResponse(requestId,responseCode, responseMessage);
2559 // Process the response
2560 BufferedReader reader;
2562 reader = new BufferedReader( new InputStreamReader( inputStream ) );
2563 mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
2565 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2566 StringBuilder stringBuilder = new StringBuilder();
2568 while( ( line = reader.readLine() ) != null ) {
2569 stringBuilder.append( line );
2571 LOGwriteEndingTrace(responseCode, responseMessage, (stringBuilder != null) ? stringBuilder.toString() : "{no-data}");
2572 return stringBuilder.toString();
2574 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2575 LOGwriteEndingTrace(responseCode, responseMessage, mapper.writeValueAsString(errorresponse));
2577 throw new AAIServiceException(responseCode, errorresponse);
2579 } catch(AAIServiceException aaiexc) {
2581 } catch (Exception exc) {
2582 LOG.warn("AAIRequestExecutor.post", exc);
2583 throw new AAIServiceException(exc);
2586 if(inputStream != null)
2587 inputStream.close();
2588 } catch (Exception exc) {
2595 public Boolean delete(AAIRequest request, String resourceVersion) throws AAIServiceException {
2596 Boolean response = null;
2597 InputStream inputStream = null;
2598 String requestId = UUID.randomUUID().toString();
2600 if(resourceVersion == null) {
2601 throw new AAIServiceException("resource-version is required for DELETE request");
2605 URL requestUrl = null;
2606 HttpURLConnection conn = getConfiguredConnection(requestUrl = request.getRequestUrl(HttpMethod.DELETE, resourceVersion), HttpMethod.DELETE);
2607 logMetricRequest(requestId, "DELETE "+requestUrl.getPath(), "", requestUrl.getPath());
2608 conn.setDoOutput(true);
2609 // if(request.isDeleteDataRequired()) {
2610 // String json_text = request.toJSONString();
2612 // LOGwriteDateTrace("data", json_text);
2613 // OutputStream os = con.getOutputStream();
2614 // OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
2615 // osw.write(json_text);
2620 String responseMessage = conn.getResponseMessage();
2621 int responseCode = conn.getResponseCode();
2622 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2623 inputStream = conn.getInputStream();
2625 inputStream = conn.getErrorStream();
2628 // Process the response
2629 LOG.debug("HttpURLConnection result:" + responseCode + " : " + responseMessage);
2630 logMetricResponse(requestId,responseCode, responseMessage);
2632 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
2633 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2636 ObjectMapper mapper = getObjectMapper();
2638 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2639 StringBuilder stringBuilder = new StringBuilder();
2641 while( ( line = reader.readLine() ) != null ) {
2642 stringBuilder.append( line );
2644 LOGwriteEndingTrace(responseCode, responseMessage, stringBuilder.toString());
2646 } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
2647 LOGwriteEndingTrace(responseCode, responseMessage, "Entry does not exist.");
2650 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2651 LOGwriteEndingTrace(responseCode, responseMessage, mapper.writeValueAsString(errorresponse));
2652 throw new AAIServiceException(responseCode, errorresponse);
2654 } catch(AAIServiceException aaiexc) {
2656 } catch (Exception exc) {
2657 LOG.warn("delete", exc);
2658 throw new AAIServiceException(exc);
2660 if(inputStream != null){
2662 inputStream.close();
2663 } catch(Exception exc) {
2672 public Object query(AAIRequest request, Class clas) throws AAIServiceException {
2673 Object response = null;
2674 InputStream inputStream = null;
2675 HttpURLConnection con = null;
2676 URL requestUrl = null;
2677 String requestId = UUID.randomUUID().toString();
2680 con = getConfiguredConnection(requestUrl = request.getRequestQueryUrl(HttpMethod.GET), HttpMethod.GET);
2681 logMetricRequest(requestId, "GET "+requestUrl.getPath(), "", requestUrl.getPath());
2684 String responseMessage = con.getResponseMessage();
2685 int responseCode = con.getResponseCode();
2686 if (responseCode == HttpURLConnection.HTTP_OK) {
2687 inputStream = con.getInputStream();
2689 inputStream = con.getErrorStream();
2692 logMetricResponse(requestId,responseCode, responseMessage);
2693 ObjectMapper mapper = getObjectMapper();
2695 if (responseCode == HttpURLConnection.HTTP_OK) {
2696 // Process the response
2697 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2698 response = mapper.readValue(reader, clas);
2699 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, "SUCCESS", mapper.writeValueAsString(response));
2700 } else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
2701 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
2704 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2705 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2706 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
2707 throw new AAIServiceException(responseCode, errorresponse);
2710 } catch(AAIServiceException aaiexc) {
2712 } catch (Exception exc) {
2713 LOG.warn("GET", exc);
2714 throw new AAIServiceException(exc);
2716 if(inputStream != null){
2718 inputStream.close();
2719 } catch(Exception exc) {
2729 public Boolean patch(AAIRequest request, String resourceVersion) throws AAIServiceException {
2730 InputStream inputStream = null;
2731 String requestId = UUID.randomUUID().toString();
2734 AAIDatum instance = request.getRequestObject();
2735 if(instance instanceof ResourceVersion) {
2736 resourceVersion = ((ResourceVersion)instance).getResourceVersion();
2739 URL requestUrl = null;
2740 HttpURLConnection con = getConfiguredConnection(requestUrl = request.getRequestUrl("PATCH", resourceVersion), "PATCH");
2741 ObjectMapper mapper = getObjectMapper();
2742 String json_text = request.toJSONString();
2744 LOGwriteDateTrace("data", json_text);
2745 logMetricRequest(requestId, "PATCH "+requestUrl.getPath(), json_text, requestUrl.getPath());
2747 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
2748 osw.write(json_text);
2752 String responseMessage = con.getResponseMessage();
2753 int responseCode = con.getResponseCode();
2754 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2755 inputStream = con.getInputStream();
2757 inputStream = con.getErrorStream();
2760 LOG.info("HttpURLConnection result: " + responseCode + " : " + responseMessage);
2761 logMetricResponse(requestId,responseCode, responseMessage);
2763 // Process the response
2764 BufferedReader reader;
2766 reader = new BufferedReader( new InputStreamReader( inputStream ) );
2767 mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
2769 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2770 StringBuilder stringBuilder = new StringBuilder();
2772 while( ( line = reader.readLine() ) != null ) {
2773 stringBuilder.append( line );
2775 LOGwriteEndingTrace(responseCode, responseMessage, (stringBuilder != null) ? stringBuilder.toString() : "{no-data}");
2778 StringBuilder stringBuilder = new StringBuilder();
2780 while( ( line = reader.readLine() ) != null ) {
2781 stringBuilder.append("\n").append( line );
2783 LOG.info(stringBuilder.toString());
2786 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2787 LOGwriteEndingTrace(responseCode, responseMessage, mapper.writeValueAsString(errorresponse));
2789 throw new AAIServiceException(responseCode, errorresponse);
2791 } catch(AAIServiceException aaiexc) {
2793 } catch (Exception exc) {
2794 LOG.warn("AAIRequestExecutor.patch", exc);
2795 throw new AAIServiceException(exc);
2798 if(inputStream != null)
2799 inputStream.close();
2800 } catch (Exception exc) {
2808 public Tenant requestTenantData(String tenant_id, String cloudOwner, String cloudRegionId) throws AAIServiceException {
2809 Tenant response = null;
2812 AAIRequest request = AAIRequest.getRequestFromResource("tenant");
2813 request.addRequestProperty("tenant.tenant-id", tenant_id);
2814 request.addRequestProperty("cloud-region.cloud-owner", cloudOwner);
2815 request.addRequestProperty("cloud-region.cloud-region-id", cloudRegionId);
2817 String rv = executor.get(request);
2819 ObjectMapper mapper = getObjectMapper();
2820 response = mapper.readValue(rv, Tenant.class);
2822 } catch(AAIServiceException aaiexc) {
2824 } catch (Exception exc) {
2825 LOG.warn("requestTenantData", exc);
2826 throw new AAIServiceException(exc);
2833 public Tenant requestTenantDataByName(String tenant_name, String cloudOwner, String cloudRegionId) throws AAIServiceException {
2834 Tenant response = null;
2837 AAIRequest request = AAIRequest.getRequestFromResource("tenant");
2838 request.addRequestProperty("tenant.tenant-name", tenant_name);
2839 request.addRequestProperty("cloud-region.cloud-owner", cloudOwner);
2840 request.addRequestProperty("cloud-region.cloud-region-id", cloudRegionId);
2841 Object rv = executor.query(request, Tenant.class);
2843 return (Tenant)null;
2845 response = (Tenant)rv;
2846 } catch(AAIServiceException aaiexc) {
2848 } catch (Exception exc) {
2849 LOG.warn("requestTenantDataByName", exc);
2850 throw new AAIServiceException(exc);
2858 public boolean postTenantData(String tenant_id, String cloudOwner, String cloudRegionId, Tenant tenannt) throws AAIServiceException {
2860 AAIRequest request = AAIRequest.getRequestFromResource("tenant");
2861 request.addRequestProperty("tenant.tenant-id", tenant_id);
2862 request.addRequestProperty("cloud-region.cloud-owner", cloudOwner);
2863 request.addRequestProperty("cloud-region.cloud-region-id", cloudRegionId);
2864 request.setRequestObject(tenannt);
2865 Object response = executor.post(request);
2867 } catch(AAIServiceException aaiexc) {
2869 } catch (Exception exc) {
2870 LOG.warn("postTenantData", exc);
2871 throw new AAIServiceException(exc);
2877 public String getTenantIdFromVserverUrl(URL url) {
2879 String path = url.getPath();
2881 String[] split = path.split("/tenants/tenant/");
2882 if(split.length > 1) {
2883 split = split[1].split("/");
2891 public String getCloudOwnerFromVserverUrl(URL url) {
2893 String path = url.getPath();
2895 String[] split = path.split("/cloud-regions/cloud-region/");
2896 if(split.length > 1) {
2897 split = split[1].split("/");
2905 public String getCloudRegionFromVserverUrl(URL url) {
2907 String path = url.getPath();
2909 String[] split = path.split("/cloud-regions/cloud-region/");
2910 if(split.length > 1) {
2911 split = split[1].split("/");
2919 public String getVServerIdFromVserverUrl(URL url, String tenantId) {
2920 String pattern = network_vserver_path;
2921 pattern = pattern.replace("{tenant-id}", tenantId);
2923 int end = pattern.indexOf("{vserver-id}");
2924 String prefix = pattern.substring(0, end);
2926 String path = url.getPath();
2928 if(path.startsWith(prefix)) {
2929 path = path.substring(prefix.length());
2935 protected Logger getLogger(){
2941 public AAIRequestExecutor getExecutor() {
2946 * Creates a current time stamp in UTC i.e. 2016-03-08T22:15:13.343Z.
2947 * If there are any parameters the values are appended to the time stamp.
2950 * values to be appended to current time stamp
2952 * used to set an attribute for a DG
2953 * @throws SvcLogicException
2955 public void setStatusMethod(Map<String, String> parameters, SvcLogicContext ctx) throws SvcLogicException {
2957 throw new SvcLogicException("SvcLogicContext is null.");
2960 StringBuilder sb = new StringBuilder();
2961 sb.append(String.format("%tFT%<tTZ", Calendar.getInstance(TimeZone.getTimeZone("Z")))).append(" - ");
2963 for (Entry<String, String> entry : parameters.entrySet()) {
2964 sb.append(entry.getValue()).append(" ");
2967 if (sb.length() > 0) {
2968 sb.setLength(sb.length() - 2);
2971 ctx.setAttribute("aai-summary-status-message", sb.toString());
2972 LOG.info("aai-summary-status-message: " + sb.toString());
2976 * Generic method to GET json data from an A&AI using key structure.
2977 * Then convert that json to an Object.
2978 * If successful the Object is attempted to be cast to the type parameter.
2981 * key identifying the resource to be retrieved from AAI
2983 * the class of object that A&AI will return
2984 * @return the object created from json or null if the response code is not 200
2986 * @throws AAIServiceException
2987 * if empty or null key and or type or there's an error with processing
2990 public <T> T getResource(String key, Class<T> type) throws AAIServiceException {
2991 if (StringUtils.isEmpty(key) || type == null) {
2992 throw new AAIServiceException("Key is empty or null and or type is null");
2997 SvcLogicContext ctx = new SvcLogicContext();
2998 if(!key.contains(" = ")) {
2999 if(isValidURL(key)) {
3000 key = String.format("selflink = '%s'", key);
3001 } else if(isValidURI(key)) {
3002 key = String.format("resource-path = '%s'", key);
3008 HashMap<String, String> nameValues = AAIServiceUtils.keyToHashMap(key, ctx);
3010 AAIRequest request = new SelfLinkRequest(type);
3011 if(nameValues.containsKey(PathRequest.RESOURCE_PATH.replaceAll("-", "_"))) {
3012 request = new PathRequest(type);
3015 request.processRequestPathValues(nameValues);
3016 Object obj = this.getExecutor().query(request, type);
3017 response = type.cast(obj);
3019 return response != null ? type.cast(response) : response;
3022 public boolean isValidURL(String url) {
3028 } catch (MalformedURLException e) {
3034 } catch (URISyntaxException e) {
3042 public boolean isValidURI(String url) {
3048 } catch (URISyntaxException e) {
3057 protected boolean deleteRelationshipList(URL httpReqUrl, String json_text) throws AAIServiceException {
3058 if(httpReqUrl == null) {
3059 throw new NullPointerException();
3062 boolean response = false;
3063 InputStream inputStream = null;
3066 HttpURLConnection con = getConfiguredConnection(httpReqUrl, HttpMethod.DELETE);
3068 // SSLSocketFactory sockFact = CTX.getSocketFactory();
3069 // con.setSSLSocketFactory( sockFact );
3070 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
3071 osw.write(json_text);
3076 LOGwriteFirstTrace("DELETE", httpReqUrl.toString());
3077 LOGwriteDateTrace("data", json_text);
3080 int responseCode = con.getResponseCode();
3081 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
3082 inputStream = con.getInputStream();
3084 inputStream = con.getErrorStream();
3087 // Process the response
3088 LOG.debug("HttpURLConnection result:" + responseCode);
3089 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
3090 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
3093 ObjectMapper mapper = getObjectMapper();
3095 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
3096 StringBuilder stringBuilder = new StringBuilder();
3098 while( ( line = reader.readLine() ) != null ) {
3099 stringBuilder.append( line );
3101 LOGwriteEndingTrace(responseCode, "SUCCESS", stringBuilder.toString());
3103 } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
3104 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
3107 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
3108 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
3109 throw new AAIServiceException(responseCode, errorresponse);
3112 } catch(AAIServiceException aaiexc) {
3114 } catch (Exception exc) {
3115 LOG.warn("deleteRelationshipList", exc);
3116 throw new AAIServiceException(exc);
3118 if(inputStream != null){
3120 inputStream.close();
3121 } catch(Exception exc) {
3129 public static ObjectMapper getObjectMapper() {
3130 ObjectMapper mapper = new ObjectMapper();
3131 AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance());
3132 AnnotationIntrospector secondary = new JacksonAnnotationIntrospector();
3133 mapper.setAnnotationIntrospector(AnnotationIntrospector.pair(introspector, secondary));
3134 mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
3135 mapper.setSerializationInclusion(Include.NON_NULL);
3139 public void logMetricRequest(String requestId, String targetServiceName, String msg, String path){
3140 String svcInstanceId = "";
3141 String svcName = null;
3142 String partnerName = null;
3143 String targetEntity = "A&AI";
3144 String targetVirtualEntity = null;
3146 targetServiceName = "";
3148 ml.logRequest(svcInstanceId, svcName, partnerName, targetEntity, targetServiceName, targetVirtualEntity, msg);
3151 public void logMetricResponse(String requestId, int responseCode, String responseDescription){
3152 ml.logResponse(responseCode < 400 ? "SUCCESS" : "FAILURE", Integer.toString(responseCode), responseDescription);
3155 public void logKeyError(String keys){
3156 LOG.error("Atleast one of the keys [" + keys + "] should have been populated. This will cause a NPE.");
3164 public QueryStatus save(String resource, boolean force, boolean localOnly, String key, Map<String, String> params, String prefix, SvcLogicContext ctx)
3165 throws SvcLogicException {
3166 String normResource = resource.split(":")[0];
3168 switch(normResource){
3169 case "formatted-query":
3170 case "generic-query":
3174 case "l2-bridge-sbg":
3175 case "l2-bridge-bgf":
3181 if(key.contains("selflink =")) {
3184 if(!key.contains(String.format("%s.", normResource))) {
3185 key = rewriteKey(resource, key, ctx);
3188 return super.save(resource, force, localOnly, key, params, prefix, ctx);
3192 public QueryStatus query(String resource, boolean localOnly, String select, String key, String prefix, String orderBy, SvcLogicContext ctx)
3193 throws SvcLogicException {
3194 String normResource = resource.split(":")[0];
3196 switch(normResource){
3197 case "formatted-query":
3198 case "generic-query":
3202 case "l2-bridge-sbg":
3203 case "l2-bridge-bgf":
3209 if(key.contains("selflink =")) {
3212 if(!key.contains(String.format("%s.", normResource))) {
3213 key = rewriteKey(resource, key, ctx);
3217 return super.query(resource, localOnly, select, key, prefix, orderBy, ctx);
3221 public QueryStatus delete(String resource, String key, SvcLogicContext ctx) throws SvcLogicException {
3222 String normResource = resource.split(":")[0];
3224 switch(normResource){
3225 case "formatted-query":
3226 case "generic-query":
3230 case "l2-bridge-sbg":
3231 case "l2-bridge-bgf":
3237 if(key.contains("selflink =")) {
3240 if(!key.contains(String.format("%s.", normResource))) {
3241 key = rewriteKey(resource, key, ctx);
3245 return super.delete(resource, key, ctx);
3249 public QueryStatus update(String resource, String key, Map<String, String> params, String prefix, SvcLogicContext ctx) throws SvcLogicException {
3250 String normResource = resource.split(":")[0];
3252 switch(normResource){
3253 case "formatted-query":
3254 case "generic-query":
3258 case "l2-bridge-sbg":
3259 case "l2-bridge-bgf":
3265 if(key.contains("selflink =")) {
3268 if(!key.contains(String.format("%s.", normResource))) {
3269 key = rewriteKey(resource, key, ctx);
3273 return super.update(resource, key, params, prefix, ctx);
3276 private String rewriteKey(String resource, String key, SvcLogicContext ctx) {
3277 LOG.info("AAI Deprecation - the format of request key is no longer supported. Please rewrite this key : " + key);
3279 String normResource = resource.split(":")[0];
3280 Class<? extends AAIDatum> clazz = null;
3282 clazz = AAIRequest.getClassFromResource(normResource) ;
3283 } catch (ClassNotFoundException e) {
3284 LOG.warn("AAIRequest does not support class: " + e.getMessage());
3290 List<String> fieldAnnotatedNames = new LinkedList<String>();
3292 Field[] fields = clazz.getDeclaredFields();
3293 for(Field field : fields) {
3294 String fieldName = field.getName();
3295 XmlElement annotation = field.getAnnotation(XmlElement.class);
3296 if(annotation == null)
3298 String primaryId = annotation.name();
3299 if("##default".equals(primaryId)) {
3300 primaryId = fieldName;
3302 fieldAnnotatedNames.add(primaryId);
3305 HashMap<String, String> nameValues = AAIServiceUtils.keyToHashMap(key, ctx);
3306 Set<String> keyset = nameValues.keySet();
3307 for(String keyName : keyset) {
3308 if(keyName.contains("."))
3311 String tmpKeyName = keyName.replaceAll("_", "-");
3312 String valueToSubstitute = String.format("%s =", tmpKeyName);
3313 if(fieldAnnotatedNames.contains(tmpKeyName) && key.contains(valueToSubstitute)) {
3314 key = key.replace(valueToSubstitute, String.format("%s.%s =", normResource, tmpKeyName));
3324 public String getPathTemplateForResource(String resoourceName, String keys, SvcLogicContext ctx) throws MalformedURLException {
3325 return AAIServiceUtils.getPathForResource(resoourceName, StringUtils.join(keys, " AND "), ctx);
3329 public boolean isDeprecatedFormat(String resource, HashMap<String, String> nameValues) {
3330 return !AAIServiceUtils.isValidFormat(resource, nameValues);