2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
22 package org.onap.ccsdk.sli.adaptors.aai;
25 import java.io.BufferedReader;
26 import java.io.ByteArrayInputStream;
28 import java.io.FileInputStream;
29 import java.io.InputStream;
30 import java.io.InputStreamReader;
31 import java.io.OutputStreamWriter;
32 import java.io.UnsupportedEncodingException;
33 import java.lang.reflect.Field;
34 import java.lang.reflect.InvocationTargetException;
35 import java.lang.reflect.Method;
36 import java.lang.reflect.Modifier;
37 import java.net.HttpURLConnection;
38 import java.net.MalformedURLException;
40 import java.net.URISyntaxException;
42 import java.net.URLEncoder;
43 import java.nio.charset.StandardCharsets;
44 import java.security.KeyManagementException;
45 import java.security.KeyStore;
46 import java.security.NoSuchAlgorithmException;
47 import java.text.SimpleDateFormat;
48 import java.util.ArrayList;
49 import java.util.Calendar;
50 import java.util.Enumeration;
51 import java.util.HashMap;
52 import java.util.LinkedList;
53 import java.util.List;
55 import java.util.Map.Entry;
56 import java.util.Properties;
58 import java.util.TimeZone;
59 import java.util.UUID;
60 import java.util.regex.Matcher;
61 import java.util.regex.Pattern;
63 import javax.net.ssl.HostnameVerifier;
64 import javax.net.ssl.HttpsURLConnection;
65 import javax.net.ssl.KeyManagerFactory;
66 import javax.net.ssl.SSLContext;
67 import javax.net.ssl.SSLSession;
68 import javax.net.ssl.SSLSocketFactory;
69 import javax.ws.rs.HttpMethod;
70 import javax.ws.rs.core.UriBuilder;
71 import javax.xml.bind.annotation.XmlElement;
73 import org.apache.commons.codec.binary.Base64;
74 import org.apache.commons.lang3.StringUtils;
75 import org.onap.ccsdk.sli.core.sli.ConfigurationException;
76 import org.onap.ccsdk.sli.core.sli.MetricLogger;
77 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
78 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
79 import org.onap.ccsdk.sli.core.sli.SvcLogicResource;
80 import org.openecomp.aai.inventory.v11.AvailabilityZone;
81 import org.openecomp.aai.inventory.v11.Complex;
82 import org.openecomp.aai.inventory.v11.CtagPool;
83 import org.openecomp.aai.inventory.v11.DvsSwitch;
84 import org.openecomp.aai.inventory.v11.GenericVnf;
85 import org.openecomp.aai.inventory.v11.L3Network;
86 import org.openecomp.aai.inventory.v11.OamNetwork;
87 import org.openecomp.aai.inventory.v11.PInterface;
88 import org.openecomp.aai.inventory.v11.PhysicalLink;
89 import org.openecomp.aai.inventory.v11.Pserver;
90 import org.openecomp.aai.inventory.v11.ResultData;
91 import org.openecomp.aai.inventory.v11.SearchResults;
92 import org.openecomp.aai.inventory.v11.Service;
93 import org.openecomp.aai.inventory.v11.ServiceInstance;
94 import org.openecomp.aai.inventory.v11.SitePairSet;
95 import org.openecomp.aai.inventory.v11.Tenant;
96 import org.openecomp.aai.inventory.v11.Vce;
97 import org.openecomp.aai.inventory.v11.VnfImage;
98 import org.openecomp.aai.inventory.v11.VnfImages;
99 import org.openecomp.aai.inventory.v11.Vpe;
100 import org.openecomp.aai.inventory.v11.VplsPe;
101 import org.openecomp.aai.inventory.v11.VpnBinding;
102 import org.openecomp.aai.inventory.v11.Vserver;
103 import org.onap.ccsdk.sli.adaptors.aai.data.AAIDatum;
104 import org.onap.ccsdk.sli.adaptors.aai.data.ErrorResponse;
105 import org.onap.ccsdk.sli.adaptors.aai.data.RequestError;
106 import org.onap.ccsdk.sli.adaptors.aai.data.ResourceVersion;
107 import org.onap.ccsdk.sli.adaptors.aai.data.ServiceException;
108 import org.onap.ccsdk.sli.adaptors.aai.data.notify.NotifyEvent;
109 import org.onap.ccsdk.sli.adaptors.aai.data.v1507.VServer;
110 import org.slf4j.Logger;
111 import org.slf4j.LoggerFactory;
112 import org.slf4j.MDC;
114 import com.fasterxml.jackson.annotation.JsonInclude.Include;
115 import com.fasterxml.jackson.databind.AnnotationIntrospector;
116 import com.fasterxml.jackson.databind.DeserializationFeature;
117 import com.fasterxml.jackson.databind.ObjectMapper;
118 import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector;
119 import com.fasterxml.jackson.databind.type.TypeFactory;
120 import com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector;
121 import com.sun.jersey.api.client.config.DefaultClientConfig;
122 import com.sun.jersey.client.urlconnection.HTTPSProperties;
125 public class AAIService extends AAIDeclarations implements AAIClient, SvcLogicResource {
127 public static final String AAICLIENT_PROPERTIES = "/aaiclient.properties";
128 public static final String PATH_PROPERTIES = "/aai-path.properties";
130 private static final Logger LOG = LoggerFactory.getLogger(AAIService.class);
132 private final String truststore_path;
133 private final String truststore_password;
134 private final String keystore_path;
135 private final String keystore_password;
136 private final Boolean ignore_certificate_host_error;
138 private final String target_uri;
139 private final String query_path; // = "sdn-zone-query";
141 private final String network_vserver_path;
143 private final String svc_instance_path;
144 private final String svc_inst_qry_path;
146 private final String vnf_image_query_path;
148 private final String param_service_type; //= "service-type";
150 private final String ubb_notify_path;
151 private final String selflink_avpn;
152 private final String selflink_fqdn;
154 private final String p_interface_path;
156 private final String service_path;
157 private final String site_pair_set_path;
159 private final int connection_timeout;
160 private final int read_timeout;
163 private final String query_nodes_path;
164 private final String update_path;
166 private final String application_id;
168 // authentication credentials
169 private String user_name;
170 private String user_password;
173 private final boolean runtimeOSGI;
175 private SSLContext CTX;
177 private final MetricLogger ml = new MetricLogger();
179 private final AAIRequestExecutor executor;
181 public AAIService(URL propURL) {
182 LOG.info("Entered AAIService.ctor");
184 String runtime = System.getProperty("aaiclient.runtime");
185 if(runtime != null && runtime.equals("OSGI")) {
191 Properties props = null;
193 props = initialize(propURL);
194 AAIRequest.setProperties(props, this);
196 } catch(Exception exc){
197 LOG.error("AicAAIResource.static", exc);
200 executor = new AAIRequestExecutor();
202 user_name = props.getProperty(CLIENT_NAME);
203 user_password = props.getProperty(CLIENT_PWWD);
205 if(user_name == null || user_name.isEmpty()){
206 LOG.debug("Basic user name is not set");
208 if(user_password == null || user_password.isEmpty()) {
209 LOG.debug("Basic password is not set");
212 truststore_path = props.getProperty(TRUSTSTORE_PATH);
213 truststore_password = props.getProperty(TRUSTSTORE_PSSWD);
214 keystore_path = props.getProperty(KEYSTORE_PATH);
215 keystore_password = props.getProperty(KEYSTORE_PSSWD);
217 target_uri = props.getProperty(TARGET_URI);
218 query_path = props.getProperty(QUERY_PATH);
219 update_path = props.getProperty(UPDATE_PATH);
221 String applicationId =props.getProperty(APPLICATION_ID);
222 if(applicationId == null || applicationId.isEmpty()) {
223 applicationId = "SDNC";
225 application_id = applicationId;
227 // connection timeout
228 int tmpConnectionTimeout = 30000;
229 int tmpReadTimeout = 30000;
232 String tmpValue = null;
233 tmpValue = props.getProperty(CONNECTION_TIMEOUT, "30000");
234 tmpConnectionTimeout = Integer.parseInt(tmpValue);
235 tmpValue = props.getProperty(READ_TIMEOUT, "30000");
236 tmpReadTimeout = Integer.parseInt(tmpValue);
237 } catch(Exception exc) {
238 LOG.error("Failed setting connection timeout", exc);
239 tmpConnectionTimeout = 30000;
240 tmpReadTimeout = 30000;
242 connection_timeout = tmpConnectionTimeout;
243 read_timeout = tmpReadTimeout;
245 network_vserver_path =props.getProperty(NETWORK_VSERVER_PATH);
247 svc_instance_path = props.getProperty(SVC_INSTANCE_PATH); // "/aai/v1/business/customers/customer/{customer-id}/service-subscriptions/service-subscription/{service-type}/service-instances");
248 // "/aai/v1/business/customers/customer/ma9181-203-customerid/service-subscriptions/service-subscription/ma9181%20Hosted%20Voice/service-instances";
250 // svc_inst_qry_path = props.getProperty(SVC_INST_QRY_PATH, "/aai/v1/search/generic-query?key=service-instance.service-instance-id:ma9181-204-instance&start-node-type=service-instance&include=service-instance");
251 svc_inst_qry_path = props.getProperty(SVC_INST_QRY_PATH); // "/aai/v1/search/generic-query?key=service-instance.service-instance-id:{svc-instance-id}&start-node-type=service-instance&include=service-instance");
254 param_service_type = props.getProperty(PARAM_SERVICE_TYPE, "service-type");
257 p_interface_path = props.getProperty(P_INTERFACE_PATH);
259 vnf_image_query_path = props.getProperty(VNF_IMAGE_QUERY_PATH);
261 ubb_notify_path = props.getProperty(UBB_NOTIFY_PATH);
262 selflink_avpn = props.getProperty(SELFLINK_AVPN);
263 selflink_fqdn = props.getProperty(SELFLINK_FQDN);
265 service_path = props.getProperty(SERVICE_PATH);
267 site_pair_set_path = props.getProperty(SITE_PAIR_SET_PATH);
269 query_nodes_path = props.getProperty(QUERY_NODES_PATH);
271 String iche = props.getProperty(CERTIFICATE_HOST_ERROR);
272 boolean host_error = false;
273 if(iche != null && !iche.isEmpty()) {
274 host_error = Boolean.valueOf(iche);
277 ignore_certificate_host_error = host_error;
279 HttpsURLConnection.setDefaultHostnameVerifier( new HostnameVerifier(){
280 public boolean verify(String string,SSLSession ssls) {
281 return ignore_certificate_host_error;
285 if(truststore_path != null && truststore_password != null && (new File(truststore_path)).exists()) {
286 System.setProperty("javax.net.ssl.trustStore", truststore_path);
287 System.setProperty("javax.net.ssl.trustStorePassword", truststore_password);
290 if(keystore_path != null && keystore_password != null && (new File(keystore_path)).exists())
292 DefaultClientConfig config = new DefaultClientConfig();
293 //both jersey and HttpURLConnection can use this
294 SSLContext ctx = null;
296 ctx = SSLContext.getInstance("TLS");
298 KeyManagerFactory kmf = null;
300 String def = "SunX509";
301 String storeType = "PKCS12";
302 def = KeyStore.getDefaultType();
303 kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
304 FileInputStream fin = new FileInputStream(keystore_path);
305 // KeyStore ks = KeyStore.getInstance("PKCS12");
307 String extension = keystore_path.substring(keystore_path.lastIndexOf(".") + 1);
309 if(extension != null && !extension.isEmpty() && extension.equalsIgnoreCase("JKS")) {
312 KeyStore ks = KeyStore.getInstance(storeType);
314 char[] pwd = keystore_password.toCharArray();
317 } catch (Exception ex) {
318 LOG.error("AAIResource", ex);
321 ctx.init(kmf.getKeyManagers(), null, null);
322 config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties( new HostnameVerifier() {
324 public boolean verify( String s, SSLSession sslSession ) {
325 return ignore_certificate_host_error;
330 LOG.debug("SSLContext created");
332 } catch (KeyManagementException | NoSuchAlgorithmException exc) {
333 LOG.error("AAIResource", exc);
337 LOG.info("AAIResource.ctor initialized.");
340 Field methodsField = HttpURLConnection.class.getDeclaredField("methods");
341 methodsField.setAccessible(true);
342 // get the methods field modifiers
343 Field modifiersField = Field.class.getDeclaredField("modifiers");
344 // bypass the "private" modifier
345 modifiersField.setAccessible(true);
347 // remove the "final" modifier
348 modifiersField.setInt(methodsField, methodsField.getModifiers() & ~Modifier.FINAL);
350 /* valid HTTP methods */
352 "GET", "POST", "HEAD", "OPTIONS", "PUT", "DELETE", "TRACE", "PATCH"
354 // set the new methods - including patch
355 methodsField.set(null, methods);
357 } catch (SecurityException | IllegalArgumentException | IllegalAccessException | NoSuchFieldException e) {
363 public void cleanUp() {
369 * @param http_req_url
374 protected HttpURLConnection getConfiguredConnection(URL http_req_url, String method) throws Exception {
375 HttpURLConnection con = (HttpURLConnection) http_req_url.openConnection();
377 // Set up the connection properties
378 con.setRequestProperty( "Connection", "close" );
379 con.setDoInput(true);
380 con.setDoOutput(true);
381 con.setUseCaches(false);
382 con.setConnectTimeout( connection_timeout );
383 con.setReadTimeout( read_timeout );
384 con.setRequestMethod( method );
385 con.setRequestProperty( "Accept", "application/json" );
386 con.setRequestProperty( "Content-Type", "PATCH".equalsIgnoreCase(method) ? "application/merge-patch+json" : "application/json" );
387 con.setRequestProperty("X-FromAppId", application_id);
388 con.setRequestProperty("X-TransactionId",TransactionIdTracker.getNextTransactionId());
389 String mlId = ml.getRequestID();
390 if(mlId != null && !mlId.isEmpty()) {
391 LOG.debug(String.format("MetricLogger requestId = %s", mlId));
392 con.setRequestProperty(MetricLogger.REQUEST_ID, mlId);
394 LOG.debug("MetricLogger requestId is null");
397 if(user_name != null && !user_name.isEmpty() && user_password != null && !user_password.isEmpty()) {
398 String basicAuth = "Basic " + new String(Base64.encodeBase64((user_name + ":" + user_password).getBytes()));
399 con.setRequestProperty ("Authorization", basicAuth);
402 if(con instanceof HttpsURLConnection && CTX != null) {
403 SSLSocketFactory sockFact = CTX.getSocketFactory();
404 HttpsURLConnection.class.cast(con).setSSLSocketFactory( sockFact );
411 public GenericVnf requestGenericVnfData(String vnf_id) throws AAIServiceException {
412 GenericVnf response = null;
415 AAIRequest request = AAIRequest.getRequestFromResource("generic-vnf");
416 request.addRequestProperty("generic-vnf.vnf-id", vnf_id);
417 String rv = executor.get(request);
419 ObjectMapper mapper = getObjectMapper();
420 response = mapper.readValue(rv, GenericVnf.class);
422 } catch(AAIServiceException aaiexc) {
424 } catch (Exception exc) {
425 LOG.warn(new Object(){}.getClass().getEnclosingMethod().getName(), exc);
426 throw new AAIServiceException(exc);
434 public boolean postGenericVnfData(String vnf_id, GenericVnf data) throws AAIServiceException {
436 AAIRequest request = AAIRequest.getRequestFromResource("generic-vnf");
437 request.addRequestProperty("generic-vnf.vnf-id", vnf_id);
438 request.setRequestObject(data);
439 Object response = executor.post(request);
441 } catch(AAIServiceException aaiexc) {
443 } catch (Exception exc) {
444 LOG.warn("requestGenericVnfData", exc);
445 throw new AAIServiceException(exc);
450 public boolean deleteGenericVnfData(String vnf_id, String resourceVersion) throws AAIServiceException {
451 boolean response = false;
454 AAIRequest request = AAIRequest.getRequestFromResource("generic-vnf");
455 request.addRequestProperty("generic-vnf.vnf-id", vnf_id);
456 response = executor.delete(request, resourceVersion);
457 } catch(AAIServiceException aaiexc) {
459 } catch (Exception exc) {
460 LOG.warn("deleteGenericVnfData", exc);
461 throw new AAIServiceException(exc);
467 * @see org.onap.ccsdk.sli.adaptors.resource.aic.AnAIClient#requestSdnZoneQuery(java.lang.String, java.lang.String, java.lang.String)
470 public Vce requestNetworkVceData(String vnf_id) throws AAIServiceException {
473 AAIRequest request = AAIRequest.getRequestFromResource("vce");
474 request.addRequestProperty("vce.vnf-id", vnf_id);
475 String rv = executor.get(request);
477 ObjectMapper mapper = getObjectMapper();
478 response = mapper.readValue(rv, Vce.class);
480 } catch(AAIServiceException aaiexc) {
482 } catch (Exception exc) {
483 LOG.warn(new Object(){}.getClass().getEnclosingMethod().getName(), exc);
484 throw new AAIServiceException(exc);
492 * @see org.onap.ccsdk.sli.adaptors.resource.aic.AnAIClient#requestSdnZoneQuery(java.lang.String, java.lang.String, java.lang.String)
495 public boolean deleteNetworkVceData(String vnf_id, String resourceVersion) throws AAIServiceException {
496 boolean response = false;
499 AAIRequest request = AAIRequest.getRequestFromResource("vce");
500 request.addRequestProperty("vce.vnf-id", vnf_id);
501 response = executor.delete(request, resourceVersion);
502 } catch(AAIServiceException aaiexc) {
504 } catch (Exception exc) {
505 LOG.warn("deleteNetworkVceData", exc);
506 throw new AAIServiceException(exc);
512 * @see org.onap.ccsdk.sli.adaptors.resource.aic.AnAIClient#postNetworkVceData(java.lang.String, org.onap.ccsdk.sli.adaptors.resource.aic.aai.VCERequest)
515 public boolean postNetworkVceData(String vnf_id, Vce data) throws AAIServiceException {
517 AAIRequest request = AAIRequest.getRequestFromResource("vce");
518 request.addRequestProperty("vce.vnf-id", vnf_id);
519 request.setRequestObject(data);
520 Object response = executor.post(request);
522 } catch(AAIServiceException aaiexc) {
524 } catch (Exception exc) {
525 LOG.warn("requestGenericVnfData", exc);
526 throw new AAIServiceException(exc);
532 public SearchResults requestServiceInstanceURL(String svc_instance_id) throws AAIServiceException {
533 SearchResults response = null;
534 InputStream inputStream = null;
537 String path = svc_inst_qry_path;
538 path = path.replace("{svc-instance-id}", encodeQuery(svc_instance_id));
540 String request_url = target_uri+path;
541 URL http_req_url = new URL(request_url);
543 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.GET);
545 LOGwriteFirstTrace(HttpMethod.GET, http_req_url.toString());
546 LOGwriteDateTrace("svc_instance_id", svc_instance_id);
549 int responseCode = con.getResponseCode();
550 if (responseCode == HttpURLConnection.HTTP_OK) {
551 inputStream = con.getInputStream();
553 inputStream = con.getErrorStream();
556 // Process the response
557 LOG.debug("HttpURLConnection result:" + responseCode);
558 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
559 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
561 ObjectMapper mapper = getObjectMapper();
563 if (responseCode == HttpURLConnection.HTTP_OK) {
564 // StringBuilder stringBuilder = new StringBuilder("\n");
565 // String line = null;
566 // while( ( line = reader.readLine() ) != null ) {
567 // stringBuilder.append("\n").append( line );
569 // LOG.info(stringBuilder.toString());
570 response = mapper.readValue(reader, SearchResults.class);
571 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, "SUCCESS", mapper.writeValueAsString(response));
572 } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
573 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
576 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
577 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
578 throw new AAIServiceException(responseCode, errorresponse);
581 } catch(AAIServiceException aaiexc) {
583 } catch (Exception exc) {
584 LOG.warn("requestServiceInstanceURL", exc);
585 throw new AAIServiceException(exc);
587 if(inputStream != null){
590 } catch(Exception exc) {
599 public ServiceInstance requestServiceInterfaceData(String customer_id, String service_type, String svc_instance_id) throws AAIServiceException {
600 ServiceInstance response = null;
603 AAIRequest request = AAIRequest.getRequestFromResource("service-instance");
604 request.addRequestProperty("customer.global-customer-id", customer_id);
605 request.addRequestProperty("ervice-subscription.service-type", service_type);
606 request.addRequestProperty("service-instance.service-instance-id", svc_instance_id);
608 String rv = executor.get(request);
610 ObjectMapper mapper = getObjectMapper();
611 response = mapper.readValue(rv, ServiceInstance.class);
613 } catch(AAIServiceException aaiexc) {
615 } catch (Exception exc) {
616 LOG.warn("requestServiceInterfaceData", exc);
617 throw new AAIServiceException(exc);
623 public boolean postServiceInterfaceData(String customer_id, String service_type, String svc_instance_id, ServiceInstance data) throws AAIServiceException {
625 AAIRequest request = AAIRequest.getRequestFromResource("service-instance");
626 request.addRequestProperty("customer.customer-id", customer_id);
627 request.addRequestProperty("service-subscription.service-type", service_type);
628 request.addRequestProperty("service-instance.service-instance-id", svc_instance_id);
629 request.setRequestObject(data);
630 Object response = executor.post(request);
632 } catch(AAIServiceException aaiexc) {
634 } catch (Exception exc) {
635 LOG.warn("requestGenericVnfData", exc);
636 throw new AAIServiceException(exc);
641 private static Properties initialize(URL url ) throws ConfigurationException {
644 throw new NullPointerException();
647 InputStream is = null;
648 Properties props = new Properties();
651 if(LOG.isDebugEnabled())
652 LOG.info("Property file is: " + url.toString());
654 is = url.openStream();
657 if(LOG.isDebugEnabled()) {
658 LOG.info("Properties loaded: " + props.size());
659 Enumeration<Object> en = props.keys();
661 while(en.hasMoreElements()) {
662 String key = (String)en.nextElement();
663 String property = props.getProperty(key);
664 LOG.debug(key + " : " + property);
667 } catch (Exception e) {
668 throw new ConfigurationException("Could not load properties file.", e);
673 static class TransactionIdTracker {
674 // protected static AtomicLong tracker = new AtomicLong();
676 public static String getNextTransactionId() {
677 // Check if RequestId exists as MDC. If not, create new.
678 String transactionId = MDC.get("RequestId");
679 if ("".equals(transactionId) || transactionId == null) {
680 transactionId = UUID.randomUUID().toString();
681 LOG.info("Missing requestID. Assigned " + transactionId);
682 MDC.put("RequestId", transactionId);
684 return transactionId;
689 protected void LOGwriteFirstTrace(String method, String url) {
690 String time = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").format(System.currentTimeMillis());
691 LOG.info("A&AI transaction :");
692 LOG.info("Request Time : " + time + ", Method : " + method);
693 LOG.info("Request URL : "+ url);
696 protected void LOGwriteDateTrace(String name, String data) {
697 LOG.info("Input - " + name + " : " + data);
700 protected void LOGwriteEndingTrace(int response_code, String comment, String data) {
701 LOG.info("Response code : " + response_code +", " + comment);
702 LOG.info(String.format("Response data : %s", data));
705 protected String encodeQuery(String param) throws UnsupportedEncodingException {
706 return URLEncoder.encode(param, "UTF-8").replace("+", "%20");
709 private String encodeCustomerURL(final String selection)
711 String encrypted_url = selection;
713 "/aai/v11/business/customers/customer/(.+)/service-subscriptions/service-subscription/(.+)/service-instances/service-instance/(.+)/";
714 Pattern pattern = Pattern.compile(apnpattern);
717 URL url = new URL(selection);
718 String path = url.getPath();
720 LOG.info("Trying to match apn to <" + path + ">");
722 Matcher matcher = pattern.matcher(path);
724 while(matcher.find()) {
725 String customer = matcher.group(1);
726 String subscription = matcher.group(2);
727 String service = matcher.group(3);
729 encrypted_url = selection.replace(customer, encodeQuery(customer));
730 encrypted_url = encrypted_url.replace(subscription, encodeQuery(subscription));
731 encrypted_url = encrypted_url.replace(service, encodeQuery(service));
733 } catch (Exception e) {
737 return encrypted_url;
741 public Vpe requestNetworkVpeData(String vnf_id) throws AAIServiceException {
745 AAIRequest request = AAIRequest.getRequestFromResource("vpe");
746 request.addRequestProperty("vpe.vnf-id", vnf_id);
747 String rv = executor.get(request);
749 ObjectMapper mapper = getObjectMapper();
750 response = mapper.readValue(rv, Vpe.class);
752 } catch(AAIServiceException aaiexc) {
754 } catch (Exception exc) {
755 LOG.warn(new Object(){}.getClass().getEnclosingMethod().getName(), exc);
756 throw new AAIServiceException(exc);
762 public boolean postNetworkVpeData(String vnf_id, Vpe data) throws AAIServiceException {
764 AAIRequest request = AAIRequest.getRequestFromResource("vpe");
765 request.addRequestProperty("vpe.vnf-id", vnf_id);
766 request.setRequestObject(data);
767 Object response = executor.post(request);
769 } catch(AAIServiceException aaiexc) {
771 } catch (Exception exc) {
772 LOG.warn(new Object(){}.getClass().getEnclosingMethod().getName(), exc);
773 throw new AAIServiceException(exc);
778 public boolean deleteNetworkVpeData(String vnf_id, String resourceVersion) throws AAIServiceException {
779 boolean response = false;
782 AAIRequest request = AAIRequest.getRequestFromResource("vpe");
783 request.addRequestProperty("vpe.vnf-id", vnf_id);
784 response = executor.delete(request, resourceVersion);
785 } catch(AAIServiceException aaiexc) {
787 } catch (Exception exc) {
788 LOG.warn(new Object(){}.getClass().getEnclosingMethod().getName(), exc);
789 throw new AAIServiceException(exc);
795 public VplsPe requestNetworkVplsPeData(String equipment_name)throws AAIServiceException {
796 VplsPe response = null;
799 AAIRequest request = AAIRequest.getRequestFromResource("vpls-pe");
800 request.addRequestProperty("vpls-pe.equipment-name", equipment_name);
802 String rv = executor.get(request);
804 ObjectMapper mapper = getObjectMapper();
805 response = mapper.readValue(rv, VplsPe.class);
807 } catch(AAIServiceException aaiexc) {
809 } catch (Exception exc) {
810 LOG.warn(new Object(){}.getClass().getEnclosingMethod().getName(), exc);
811 throw new AAIServiceException(exc);
817 public boolean postNetworkVplsPeData(String equipment_name, VplsPe data) throws AAIServiceException {
819 AAIRequest request = AAIRequest.getRequestFromResource("vpls-pe");
820 request.addRequestProperty("vpls-pe.equipment-name", equipment_name);
821 request.setRequestObject(data);
822 Object response = executor.post(request);
824 } catch(AAIServiceException aaiexc) {
826 } catch (Exception exc) {
827 LOG.warn("requestGenericVnfData", exc);
828 throw new AAIServiceException(exc);
833 public boolean deleteNetworkVplsPeData(String vnf_id, String resourceVersion) throws AAIServiceException {
834 boolean response = false;
837 AAIRequest request = AAIRequest.getRequestFromResource("vpls-pe");
838 request.addRequestProperty("vpls-pe.equipment-name", vnf_id);
839 response = executor.delete(request, resourceVersion);
840 } catch(AAIServiceException aaiexc) {
842 } catch (Exception exc) {
843 LOG.warn("deleteNetworkVplsPeData", exc);
844 throw new AAIServiceException(exc);
850 public Complex requestNetworkComplexData(String pLocId) throws AAIServiceException {
851 Complex response = null;
852 InputStream inputStream = null;
855 AAIRequest request = AAIRequest.getRequestFromResource("complex");
856 request.addRequestProperty("complex.physical-location-id", pLocId);
858 String rv = executor.get(request);
860 ObjectMapper mapper = getObjectMapper();
861 response = mapper.readValue(rv, Complex.class);
863 } catch(AAIServiceException aaiexc) {
865 } catch (Exception exc) {
866 LOG.warn("requestNetworkComplexData", exc);
867 throw new AAIServiceException(exc);
869 if(inputStream != null){
872 } catch(Exception exc) {
881 public boolean postNetworkComplexData(String vnf_id, Complex data) throws AAIServiceException {
883 AAIRequest request = AAIRequest.getRequestFromResource("complex");
884 request.addRequestProperty("complex.physical-location-id", vnf_id);
885 request.setRequestObject(data);
886 Object response = executor.post(request);
888 } catch(AAIServiceException aaiexc) {
890 } catch (Exception exc) {
891 LOG.warn("postNetworkComplexData", exc);
892 throw new AAIServiceException(exc);
897 public boolean deleteNetworkComplexData(String pLocId, String resourceVersion) throws AAIServiceException {
898 boolean response = false;
901 AAIRequest request = AAIRequest.getRequestFromResource("complex");
902 request.addRequestProperty("complex.physical-location-id", pLocId);
904 response = executor.delete(request, resourceVersion);
906 } catch(AAIServiceException aaiexc) {
908 } catch (Exception exc) {
909 LOG.warn("deleteNetworkComplexData", exc);
910 throw new AAIServiceException(exc);
917 * @see org.openecomp.sdnct.sli.aai.AAIClient#requestVServersData(java.lang.String, java.lang.String)
920 public Vserver requestVServerData(String tenantId, String vserverId, String cloudOwner, String cloudRegionId) throws AAIServiceException {
921 Vserver response = null;
924 AAIRequest request = AAIRequest.getRequestFromResource("vserver");
925 request.addRequestProperty("cloud-region.cloud-owner", cloudOwner);
926 request.addRequestProperty("cloud-region.cloud-region-id", cloudRegionId);
927 request.addRequestProperty("tenant.tenant-id", tenantId);
928 request.addRequestProperty("vserver.vserver-id", vserverId);
930 String rv = executor.get(request);
932 ObjectMapper mapper = getObjectMapper();
933 response = mapper.readValue(rv, Vserver.class);
935 } catch(AAIServiceException aaiexc) {
937 } catch (Exception exc) {
938 LOG.warn(new Object(){}.getClass().getEnclosingMethod().getName(), exc);
939 throw new AAIServiceException(exc);
946 public boolean postVServerData(String tenantId, String vserverId, String cloudOwner, String cloudRegionId, Vserver data) throws AAIServiceException {
948 AAIRequest request = AAIRequest.getRequestFromResource("vserver");
949 request.addRequestProperty("cloud-region.cloud-owner", cloudOwner);
950 request.addRequestProperty("cloud-region.cloud-region-id", cloudRegionId);
951 request.addRequestProperty("tenant.tenant-id", tenantId);
952 request.addRequestProperty("vserver.vserver-id", vserverId);
953 request.setRequestObject(data);
954 Object response = executor.post(request);
956 } catch(AAIServiceException aaiexc) {
958 } catch (Exception exc) {
959 LOG.warn("postNetworkComplexData", exc);
960 throw new AAIServiceException(exc);
965 public boolean deleteVServerData(String tenant_id, String vserver_id, String cloudOwner, String cloudRegionId, String resourceVersion) throws AAIServiceException {
966 boolean response = false;
967 InputStream inputStream = null;
970 String local_network_complexes_path = network_vserver_path.replace("{tenant-id}", encodeQuery(tenant_id));
971 local_network_complexes_path = local_network_complexes_path.replace("{vserver-id}", encodeQuery(vserver_id));
972 local_network_complexes_path = local_network_complexes_path.replace("{cloud-owner}", encodeQuery(cloudOwner));
973 local_network_complexes_path = local_network_complexes_path.replace("{cloud-region-id}", encodeQuery(cloudRegionId));
975 String request_url = target_uri+local_network_complexes_path;
976 if(resourceVersion!=null) {
977 request_url = request_url +"?resource-version="+resourceVersion;
979 URL http_req_url = new URL(request_url);
981 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.DELETE);
983 LOGwriteFirstTrace(HttpMethod.DELETE, http_req_url.toString());
984 LOGwriteDateTrace("tenant_id", tenant_id);
985 LOGwriteDateTrace("vserver_id", vserver_id);
986 LOGwriteDateTrace("cloud-owner", cloudOwner);
987 LOGwriteDateTrace("cloud-region-id", cloudRegionId);
990 int responseCode = con.getResponseCode();
991 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
992 inputStream = con.getInputStream();
994 inputStream = con.getErrorStream();
997 // Process the response
998 LOG.debug("HttpURLConnection result:" + responseCode);
999 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
1000 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
1003 ObjectMapper mapper = getObjectMapper();
1005 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1006 StringBuilder stringBuilder = new StringBuilder();
1008 while( ( line = reader.readLine() ) != null ) {
1009 stringBuilder.append( line );
1011 LOGwriteEndingTrace(responseCode, "SUCCESS", stringBuilder.toString());
1013 } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
1014 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
1017 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
1018 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
1019 throw new AAIServiceException(responseCode, errorresponse);
1022 } catch(AAIServiceException aaiexc) {
1024 } catch (Exception exc) {
1025 LOG.warn("deleteVServerData", exc);
1026 throw new AAIServiceException(exc);
1028 if(inputStream != null){
1030 inputStream.close();
1031 } catch(Exception exc) {
1042 * @see org.onap.ccsdk.sli.adaptors.aai.AAIClient#requestCtagPoolData(String)
1045 public CtagPool requestCtagPoolData(String physical_location_id, String target_pe, String availability_zone_name) throws AAIServiceException {
1046 CtagPool response = null;
1049 AAIRequest request = AAIRequest.getRequestFromResource("ctag-pool");
1051 request.addRequestProperty("ctag-pool.target-pe", target_pe);
1052 request.addRequestProperty("ctag-pool.availability-zone-name", availability_zone_name);
1053 request.addRequestProperty("complex.physical-location-id", physical_location_id);
1055 String rv = executor.get(request);
1057 ObjectMapper mapper = getObjectMapper();
1058 response = mapper.readValue(rv, CtagPool.class);
1060 } catch(AAIServiceException aaiexc) {
1062 } catch (Exception exc) {
1063 LOG.warn("requestNetworkVceData", exc);
1064 throw new AAIServiceException(exc);
1069 //==================== DvsSwitch ======================
1071 public DvsSwitch requestDvsSwitchData(String vnf_id) throws AAIServiceException {
1072 DvsSwitch response = null;
1073 InputStream inputStream = null;
1076 AAIRequest request = AAIRequest.getRequestFromResource("dvs-switch");
1077 request.addRequestProperty("dvs-switch.switch-name", vnf_id);
1079 String rv = executor.get(request);
1081 ObjectMapper mapper = getObjectMapper();
1082 response = mapper.readValue(rv, DvsSwitch.class);
1084 } catch(AAIServiceException aaiexc) {
1086 } catch (Exception exc) {
1087 LOG.warn("requestDvsSwitchData", exc);
1088 throw new AAIServiceException(exc);
1090 if(inputStream != null){
1092 inputStream.close();
1093 } catch(Exception exc) {
1102 public boolean postDvsSwitchData(String switch_name, DvsSwitch data) throws AAIServiceException {
1104 AAIRequest request = AAIRequest.getRequestFromResource("dvs-switch");
1105 request.addRequestProperty("dvs-switch.switch-name", switch_name);
1106 request.setRequestObject(data);
1107 Object response = executor.post(request);
1109 } catch(AAIServiceException aaiexc) {
1111 } catch (Exception exc) {
1112 LOG.warn(new Object(){}.getClass().getEnclosingMethod().getName(), exc);
1113 throw new AAIServiceException(exc);
1118 public boolean deleteDvsSwitchData(String vnf_id, String resourceVersion) throws AAIServiceException {
1119 boolean response = false;
1120 InputStream inputStream = null;
1123 AAIRequest request = AAIRequest.getRequestFromResource("dvs-switch");
1124 request.addRequestProperty("dvs-switch.switch-name", vnf_id);
1125 response = executor.delete(request, resourceVersion);
1126 } catch(AAIServiceException aaiexc) {
1128 } catch (Exception exc) {
1129 LOG.warn("deleteDvsSwitchData", exc);
1130 throw new AAIServiceException(exc);
1134 //================== End of DvsSwitch =================
1135 //==================== PhysicalLink ======================
1137 public PhysicalLink requestPhysicalLinkData(String linkName) throws AAIServiceException {
1138 PhysicalLink response = null;
1141 AAIRequest request = AAIRequest.getRequestFromResource("physical-link");
1142 request.addRequestProperty("physical-link.link-name", linkName);
1144 String rv = executor.get(request);
1146 ObjectMapper mapper = getObjectMapper();
1147 response = mapper.readValue(rv, PhysicalLink.class);
1149 } catch(AAIServiceException aaiexc) {
1151 } catch (Exception exc) {
1152 LOG.warn("requestPhysicalLinkData", exc);
1153 throw new AAIServiceException(exc);
1159 public boolean postPhysicalLinkData(String linkName, PhysicalLink data) throws AAIServiceException {
1161 AAIRequest request = AAIRequest.getRequestFromResource("physical-link");
1162 request.addRequestProperty("physical-link.link-name", linkName);
1163 request.setRequestObject(data);
1164 Object response = executor.post(request);
1166 } catch(AAIServiceException aaiexc) {
1168 } catch (Exception exc) {
1169 LOG.warn(new Object(){}.getClass().getEnclosingMethod().getName(), exc);
1170 throw new AAIServiceException(exc);
1175 public boolean deletePhysicalLinkData(String linkName, String resourceVersion) throws AAIServiceException {
1176 boolean response = false;
1179 AAIRequest request = AAIRequest.getRequestFromResource("physical-link");
1180 request.addRequestProperty("physical-link.link-name", linkName);
1181 response = executor.delete(request, resourceVersion);
1182 } catch(AAIServiceException aaiexc) {
1184 } catch (Exception exc) {
1185 LOG.warn("deletePhysicalLinkData", exc);
1186 throw new AAIServiceException(exc);
1190 //================== End of PhysicalLink =================
1191 //==================== PInterface ======================
1193 public PInterface requestPInterfaceData(String hostname, String interfaceName) throws AAIServiceException {
1194 PInterface response = null;
1197 AAIRequest request = new PInterfaceRequest();
1198 request.addRequestProperty(PInterfaceRequest.PINTERFACE_INTERFACE_NAME, interfaceName);
1199 request.addRequestProperty(PInterfaceRequest.PSERVER_HOSTNAME, hostname);
1200 String rv = executor.get(request);
1202 ObjectMapper mapper = getObjectMapper();
1203 response = mapper.readValue(rv, PInterface.class);
1205 } catch(AAIServiceException aaiexc) {
1207 } catch (Exception exc) {
1208 LOG.warn(new Object(){}.getClass().getEnclosingMethod().getName(), exc);
1209 throw new AAIServiceException(exc);
1215 public boolean postPInterfaceData(String hostname, String interfaceName, PInterface request) throws AAIServiceException {
1216 InputStream inputStream = null;
1220 ObjectMapper mapper = getObjectMapper();
1221 String json_text = mapper.writeValueAsString(request);
1223 SSLSocketFactory sockFact = CTX.getSocketFactory();
1225 String request_url = target_uri+p_interface_path;
1226 String encoded_vnf = encodeQuery(hostname);
1227 request_url = request_url.replace("{hostname}", encoded_vnf) ;
1228 encoded_vnf = encodeQuery(interfaceName);
1229 request_url = request_url.replace("{interface-name}", encoded_vnf) ;
1230 URL http_req_url = new URL(request_url);
1232 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.PUT);
1234 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
1235 osw.write(json_text);
1240 LOGwriteFirstTrace("PUT", request_url);
1241 LOGwriteDateTrace("hostname", hostname);
1242 LOGwriteDateTrace("interface-name", interfaceName);
1243 LOGwriteDateTrace("PInterface", json_text);
1246 int responseCode = con.getResponseCode();
1247 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1248 inputStream = con.getInputStream();
1250 inputStream = con.getErrorStream();
1253 // Process the response
1254 BufferedReader reader;
1256 reader = new BufferedReader( new InputStreamReader( inputStream ) );
1258 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1259 StringBuilder stringBuilder = new StringBuilder();
1261 while( ( line = reader.readLine() ) != null ) {
1262 stringBuilder.append( line );
1264 LOGwriteEndingTrace(responseCode, "SUCCESS", (stringBuilder != null) ? stringBuilder.toString() : "{no-data}");
1267 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
1268 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
1270 throw new AAIServiceException(responseCode, errorresponse);
1272 } catch(AAIServiceException aaiexc) {
1274 } catch (Exception exc) {
1275 LOG.warn("postPInterfaceData", exc);
1276 throw new AAIServiceException(exc);
1279 if(inputStream != null)
1280 inputStream.close();
1281 } catch (Exception exc) {
1288 public boolean deletePInterfaceData(String hostname, String interfaceName, String resourceVersion) throws AAIServiceException {
1289 boolean response = false;
1292 AAIRequest request = AAIRequest.getRequestFromResource("p-interface");
1293 request.addRequestProperty("p-interface.interface-name", interfaceName);
1294 request.addRequestProperty("pserver.hostname", hostname);
1295 response = executor.delete(request, resourceVersion);
1296 } catch(AAIServiceException aaiexc) {
1298 } catch (Exception exc) {
1299 LOG.warn("deletePInterfaceData", exc);
1300 throw new AAIServiceException(exc);
1304 //================== End of PInterface =================
1305 //==================== SitePairSet ======================
1307 public SitePairSet requestSitePairSetData(String sitePairSetId) throws AAIServiceException {
1308 SitePairSet response = null;
1311 AAIRequest request = AAIRequest.getRequestFromResource("site-pair-set");
1312 request.addRequestProperty("site-pair-set.site-pair-set-id", sitePairSetId);
1313 String rv = executor.get(request);
1315 ObjectMapper mapper = getObjectMapper();
1316 response = mapper.readValue(rv, SitePairSet.class);
1318 } catch(AAIServiceException aaiexc) {
1320 } catch (Exception exc) {
1321 LOG.warn(new Object(){}.getClass().getEnclosingMethod().getName(), exc);
1322 throw new AAIServiceException(exc);
1328 public boolean postSitePairSetData(String linkName, SitePairSet request) throws AAIServiceException {
1329 InputStream inputStream = null;
1333 ObjectMapper mapper = getObjectMapper();
1334 String json_text = mapper.writeValueAsString(request);
1336 SSLSocketFactory sockFact = CTX.getSocketFactory();
1338 String request_url = target_uri+site_pair_set_path;
1339 String encoded_vnf = encodeQuery(linkName);
1340 request_url = request_url.replace("{site-pair-set-id}", encoded_vnf) ;
1341 URL http_req_url = new URL(request_url);
1343 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.PUT);
1345 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
1346 osw.write(json_text);
1351 LOGwriteFirstTrace("PUT", request_url);
1352 LOGwriteDateTrace("link-name", linkName);
1353 LOGwriteDateTrace("SitePairSet", json_text);
1356 int responseCode = con.getResponseCode();
1357 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1358 inputStream = con.getInputStream();
1360 inputStream = con.getErrorStream();
1363 // Process the response
1364 BufferedReader reader;
1366 reader = new BufferedReader( new InputStreamReader( inputStream ) );
1368 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1369 StringBuilder stringBuilder = new StringBuilder();
1371 while( ( line = reader.readLine() ) != null ) {
1372 stringBuilder.append( line );
1374 LOGwriteEndingTrace(responseCode, "SUCCESS", (stringBuilder != null) ? stringBuilder.toString() : "{no-data}");
1377 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
1378 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
1380 throw new AAIServiceException(responseCode, errorresponse);
1382 } catch(AAIServiceException aaiexc) {
1384 } catch (Exception exc) {
1385 LOG.warn("postSitePairSetData", exc);
1386 throw new AAIServiceException(exc);
1389 if(inputStream != null)
1390 inputStream.close();
1391 } catch (Exception exc) {
1398 public boolean deleteSitePairSetData(String linkName, String resourceVersion) throws AAIServiceException {
1399 boolean response = false;
1402 AAIRequest request = AAIRequest.getRequestFromResource("site-pair-set");
1403 request.addRequestProperty("site-pair-set.site-pair-set-id", linkName);
1404 response = executor.delete(request, resourceVersion);
1405 } catch(AAIServiceException aaiexc) {
1407 } catch (Exception exc) {
1408 LOG.warn("deleteSitePairSetData", exc);
1409 throw new AAIServiceException(exc);
1414 //================== End of SitePairSet =================
1415 //==================== Service ======================
1417 public Service requestServiceData(String serviceId) throws AAIServiceException {
1418 Service response = null;
1419 InputStream inputStream = null;
1422 AAIRequest request = AAIRequest.getRequestFromResource("service");
1423 request.addRequestProperty("service.service-id", serviceId);
1426 String rv = executor.get(request);
1428 ObjectMapper mapper = getObjectMapper();
1429 response = mapper.readValue(rv, Service.class);
1431 } catch(AAIServiceException aaiexc) {
1433 } catch (Exception exc) {
1434 LOG.warn("requestServiceData", exc);
1435 throw new AAIServiceException(exc);
1441 public boolean postServiceData(String linkName, Service request) throws AAIServiceException {
1442 InputStream inputStream = null;
1446 ObjectMapper mapper = getObjectMapper();
1447 String json_text = mapper.writeValueAsString(request);
1449 SSLSocketFactory sockFact = CTX.getSocketFactory();
1451 String request_url = target_uri+service_path;
1452 String encoded_vnf = encodeQuery(linkName);
1453 request_url = request_url.replace("{service-id}", encoded_vnf) ;
1454 URL http_req_url = new URL(request_url);
1456 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.PUT);
1458 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
1459 osw.write(json_text);
1464 LOGwriteFirstTrace("PUT", request_url);
1465 LOGwriteDateTrace("service-id", linkName);
1466 LOGwriteDateTrace("Service", json_text);
1469 int responseCode = con.getResponseCode();
1470 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1471 inputStream = con.getInputStream();
1473 inputStream = con.getErrorStream();
1476 // Process the response
1477 BufferedReader reader;
1479 reader = new BufferedReader( new InputStreamReader( inputStream ) );
1481 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1482 StringBuilder stringBuilder = new StringBuilder();
1484 while( ( line = reader.readLine() ) != null ) {
1485 stringBuilder.append( line );
1487 LOGwriteEndingTrace(responseCode, "SUCCESS", (stringBuilder != null) ? stringBuilder.toString() : "{no-data}");
1490 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
1491 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
1493 throw new AAIServiceException(responseCode, errorresponse);
1495 } catch(AAIServiceException aaiexc) {
1497 } catch (Exception exc) {
1498 LOG.warn("postServiceData", exc);
1499 throw new AAIServiceException(exc);
1502 if(inputStream != null)
1503 inputStream.close();
1504 } catch (Exception exc) {
1511 public boolean deleteServiceData(String service_id, String resourceVersion) throws AAIServiceException {
1512 boolean response = false;
1515 AAIRequest request = AAIRequest.getRequestFromResource("service");
1516 request.addRequestProperty("service.service-id", service_id);
1517 response = executor.delete(request, resourceVersion);
1518 } catch(AAIServiceException aaiexc) {
1520 } catch (Exception exc) {
1521 LOG.warn("deleteServiceData", exc);
1522 throw new AAIServiceException(exc);
1527 //================== End of Service =================
1533 public VServer dataChangeRequestVServerData(URL url) throws AAIServiceException {
1536 throw new NullPointerException();
1539 return this.getResource(url.toString(), VServer.class);
1543 public Pserver dataChangeRequestPServerData(URL url) throws AAIServiceException {
1546 throw new NullPointerException();
1549 return this.getResource(url.toString(), Pserver.class);
1553 public CtagPool dataChangeRequestCtagPoolData(URL url) throws AAIServiceException {
1556 throw new NullPointerException();
1559 return this.getResource(url.toString(), CtagPool.class);
1563 public VplsPe dataChangeRequestVplsPeData(URL url) throws AAIServiceException {
1566 throw new NullPointerException();
1569 return this.getResource(url.toString(), VplsPe.class);
1573 public Vpe dataChangeRequestVpeData(URL url) throws AAIServiceException {
1576 throw new NullPointerException();
1579 return this.getResource(url.toString(), Vpe.class);
1583 public DvsSwitch dataChangeRequestDvsSwitchData(URL url) throws AAIServiceException {
1586 throw new NullPointerException();
1589 return this.getResource(url.toString(), DvsSwitch.class);
1593 public OamNetwork dataChangeRequestOAMNetworkData(URL url) throws AAIServiceException {
1596 throw new NullPointerException();
1599 return this.getResource(url.toString(), OamNetwork.class);
1603 public AvailabilityZone dataChangeRequestAvailabilityZoneData(URL url) throws AAIServiceException {
1606 throw new NullPointerException();
1609 return this.getResource(url.toString(), AvailabilityZone.class);
1613 public Complex dataChangeRequestComplexData(URL url) throws AAIServiceException {
1616 throw new NullPointerException();
1619 return this.getResource(url.toString(), Complex.class);
1623 public boolean dataChangeDeleteVServerData(URL url) throws AAIServiceException {
1626 throw new NullPointerException();
1629 return deleteAAIEntity(url, new Object(){}.getClass().getEnclosingMethod().getName());
1632 public boolean dataChangeDeleteCtagPoolData(URL url) throws AAIServiceException {
1635 throw new NullPointerException();
1638 return deleteAAIEntity(url, new Object(){}.getClass().getEnclosingMethod().getName());
1641 public boolean dataChangeDeleteVplsPeData(URL url) throws AAIServiceException {
1644 throw new NullPointerException();
1647 return deleteAAIEntity(url, new Object(){}.getClass().getEnclosingMethod().getName());
1650 public boolean dataChangeDeleteVpeData(URL url) throws AAIServiceException {
1653 throw new NullPointerException();
1656 return deleteAAIEntity(url, new Object(){}.getClass().getEnclosingMethod().getName());
1659 public boolean dataChangeDeleteDvsSwitchData(URL url) throws AAIServiceException {
1662 throw new NullPointerException();
1665 return deleteAAIEntity(url, new Object(){}.getClass().getEnclosingMethod().getName());
1668 public boolean dataChangeDeleteOAMNetworkData(URL url) throws AAIServiceException {
1671 throw new NullPointerException();
1674 return deleteAAIEntity(url, new Object(){}.getClass().getEnclosingMethod().getName());
1676 //Availability-Zone:
1677 public boolean dataChangeDeleteAvailabilityZoneData(URL url) throws AAIServiceException {
1680 throw new NullPointerException();
1683 return deleteAAIEntity(url, new Object(){}.getClass().getEnclosingMethod().getName());
1686 public boolean dataChangeDeleteComplexData(URL url) throws AAIServiceException {
1689 throw new NullPointerException();
1692 return deleteAAIEntity(url, new Object(){}.getClass().getEnclosingMethod().getName());
1695 private boolean deleteAAIEntity(URL url, String caller) throws AAIServiceException {
1698 throw new NullPointerException();
1701 boolean response = false;
1702 InputStream inputStream = null;
1705 URL http_req_url = url;
1707 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.DELETE);
1709 // SSLSocketFactory sockFact = CTX.getSocketFactory();
1710 // con.setSSLSocketFactory( sockFact );
1712 LOGwriteFirstTrace("DELETE", http_req_url.toString());
1716 int responseCode = con.getResponseCode();
1717 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1718 inputStream = con.getInputStream();
1720 inputStream = con.getErrorStream();
1723 // Process the response
1724 LOG.debug("HttpURLConnection result:" + responseCode);
1725 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
1726 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
1729 ObjectMapper mapper = getObjectMapper();
1731 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1732 StringBuilder stringBuilder = new StringBuilder();
1734 while( ( line = reader.readLine() ) != null ) {
1735 stringBuilder.append( line );
1737 LOGwriteEndingTrace(responseCode, "SUCCESS", stringBuilder.toString());
1739 } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
1740 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
1743 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
1744 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
1745 throw new AAIServiceException(responseCode, errorresponse);
1748 } catch(AAIServiceException aaiexc) {
1750 } catch (Exception exc) {
1751 LOG.warn(caller, exc);
1752 throw new AAIServiceException(exc);
1754 if(inputStream != null){
1756 inputStream.close();
1757 } catch(Exception exc) {
1766 * Generic method to GET json data from an A&AI callback URL.
1767 * Then convert that json to an Object.
1768 * If successful the Object is attempted to be cast to the type parameter.
1771 * callback url for A&AI
1773 * the class of object that A&AI will return
1774 * @return the object created from json or null if the response code is not 200
1776 * @throws AAIServiceException
1777 * if empty or null key and or type or there's an error with processing
1779 public <T> T dataChangeRequestAaiData(String key, Class<T> type) throws AAIServiceException {
1780 if (StringUtils.isEmpty(key) || type == null) {
1781 throw new AAIServiceException("Key is empty or null and or type is null");
1786 SvcLogicContext ctx = new SvcLogicContext();
1787 if(!key.contains(" = ") && isValidURL(key)) {
1788 key = String.format("selflink = '%s'", key);
1790 if(!key.contains(" = ") && isValidURI(key)) {
1791 key = String.format("resource-path = '%s'", key);
1794 HashMap<String, String> nameValues = AAIServiceUtils.keyToHashMap(key, ctx);
1796 SelfLinkRequest request = new SelfLinkRequest(type);
1797 request.processRequestPathValues(nameValues);
1798 Object obj = this.getExecutor().query(request, type);
1799 response = type.cast(obj);
1801 return response != null ? type.cast(response) : response;
1805 public Pserver requestPServerData(String hostname) throws AAIServiceException {
1806 Pserver response = null;
1807 InputStream inputStream = null;
1810 AAIRequest request = AAIRequest.getRequestFromResource("pserver");
1811 request.addRequestProperty("pserver.hostname", hostname);
1814 String rv = executor.get(request);
1816 ObjectMapper mapper = getObjectMapper();
1817 response = mapper.readValue(rv, Pserver.class);
1819 } catch(AAIServiceException aaiexc) {
1821 } catch (Exception exc) {
1822 LOG.warn("requestPServerData", exc);
1823 throw new AAIServiceException(exc);
1829 public boolean postPServerData(String hostname, Pserver data) throws AAIServiceException {
1831 AAIRequest request = AAIRequest.getRequestFromResource("pserver");
1832 request.addRequestProperty("pserver.hostname", hostname);
1833 request.setRequestObject(data);
1834 Object response = executor.post(request);
1836 } catch(AAIServiceException aaiexc) {
1838 } catch (Exception exc) {
1839 LOG.warn(new Object(){}.getClass().getEnclosingMethod().getName(), exc);
1840 throw new AAIServiceException(exc);
1845 public boolean deletePServerData(String hostname, String resourceVersion) throws AAIServiceException {
1846 boolean response = false;
1849 AAIRequest request = AAIRequest.getRequestFromResource("pserver");
1850 request.addRequestProperty("pserver.hostname", hostname);
1851 response = executor.delete(request, resourceVersion);
1852 } catch(AAIServiceException aaiexc) {
1854 } catch (Exception exc) {
1855 LOG.warn("deletePServerData", exc);
1856 throw new AAIServiceException(exc);
1864 public L3Network requestL3NetworkData(String networkId) throws AAIServiceException {
1865 L3Network response = null;
1866 InputStream inputStream = null;
1869 AAIRequest request = AAIRequest.getRequestFromResource("l3-network");
1870 request.addRequestProperty("l3-network.network-id", networkId);
1872 String rv = executor.get(request);
1874 ObjectMapper mapper = getObjectMapper();
1875 response = mapper.readValue(rv, L3Network.class);
1877 } catch(AAIServiceException aaiexc) {
1879 } catch (Exception exc) {
1880 LOG.warn("requestL3NetworkData", exc);
1881 throw new AAIServiceException(exc);
1887 public L3Network requestL3NetworkQueryByName(String networkName) throws AAIServiceException {
1888 L3Network response = null;
1889 InputStream inputStream = null;
1892 AAIRequest request = AAIRequest.getRequestFromResource("l3-network");
1893 request.addRequestProperty("l3-network.network-name", networkName);
1895 String rv = executor.get(request);
1897 ObjectMapper mapper = getObjectMapper();
1898 response = mapper.readValue(rv, L3Network.class);
1901 } catch(AAIServiceException aaiexc) {
1903 } catch (Exception exc) {
1904 LOG.warn("requestL3NetworkQueryByName", exc);
1905 throw new AAIServiceException(exc);
1907 if(inputStream != null){
1909 inputStream.close();
1910 } catch(Exception exc) {
1919 public boolean postL3NetworkData(String networkId, L3Network data) throws AAIServiceException {
1921 AAIRequest request = AAIRequest.getRequestFromResource("l3-network");
1922 request.addRequestProperty("l3-network.network-id", networkId);
1923 request.setRequestObject(data);
1924 Object response = executor.post(request);
1926 } catch(AAIServiceException aaiexc) {
1928 } catch (Exception exc) {
1929 LOG.warn(new Object(){}.getClass().getEnclosingMethod().getName(), exc);
1930 throw new AAIServiceException(exc);
1935 public boolean deleteL3NetworkData(String networkId, String resourceVersion) throws AAIServiceException {
1936 boolean response = false;
1939 AAIRequest request = AAIRequest.getRequestFromResource("l3-network");
1940 request.addRequestProperty("l3-network.network-id", networkId);
1941 response = executor.delete(request, resourceVersion);
1942 } catch(AAIServiceException aaiexc) {
1944 } catch (Exception exc) {
1945 LOG.warn("deleteL3NetworkData", exc);
1946 throw new AAIServiceException(exc);
1954 public VpnBinding requestVpnBindingData(String vpnId) throws AAIServiceException {
1955 VpnBinding response = null;
1958 AAIRequest request = AAIRequest.getRequestFromResource("vpn-binding");
1959 request.addRequestProperty("vpn-binding.vpn-id", vpnId);
1961 String rv = executor.get(request);
1963 ObjectMapper mapper = getObjectMapper();
1964 response = mapper.readValue(rv, VpnBinding.class);
1966 } catch(AAIServiceException aaiexc) {
1968 } catch (Exception exc) {
1969 LOG.warn("requestVpnBindingData", exc);
1970 throw new AAIServiceException(exc);
1976 public boolean deleteVpnBindingData(String vpnId, String resourceVersion) throws AAIServiceException {
1977 boolean response = false;
1980 AAIRequest request = AAIRequest.getRequestFromResource("vpn-binding");
1981 request.addRequestProperty("vpn-binding.vpn-id", vpnId);
1982 response = executor.delete(request, resourceVersion);
1983 } catch(AAIServiceException aaiexc) {
1985 } catch (Exception exc) {
1986 LOG.warn("deleteVpnBindingData", exc);
1987 throw new AAIServiceException(exc);
1994 public VnfImage requestVnfImageData(String vnf_image_uuid) throws AAIServiceException {
1995 VnfImage response = null;
1998 AAIRequest request = AAIRequest.getRequestFromResource("vnf-image");
1999 request.addRequestProperty("vnf-image.vnf-image-uuid", vnf_image_uuid);
2001 String rv = executor.get(request);
2003 ObjectMapper mapper = getObjectMapper();
2004 response = mapper.readValue(rv, VnfImage.class);
2006 } catch(AAIServiceException aaiexc) {
2008 } catch (Exception exc) {
2009 LOG.warn("requestVnfImageData", exc);
2010 throw new AAIServiceException(exc);
2016 public VnfImage requestVnfImageDataByVendorModel(String vendor, String model) throws AAIServiceException {
2017 return requestVnfImageDataByVendorModelVersion(vendor, model, null);
2021 public VnfImage requestVnfImageDataByVendorModelVersion(String vendor, String model, String version) throws AAIServiceException
2023 List<VnfImage> responseList = new ArrayList<VnfImage>();
2024 VnfImage response = null;
2025 InputStream inputStream = null;
2028 String request_url = target_uri+vnf_image_query_path + (version==null? "": "&application-version={application_version}");
2029 request_url = request_url.replace("{application_vendor}", encodeQuery(vendor)) ;
2030 request_url = request_url.replace("{application_model}", encodeQuery(model)) ;
2031 if(version != null) {
2032 request_url = request_url.replace("{application_version}", encodeQuery(version)) ;
2034 URL http_req_url = new URL(request_url);
2036 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.GET);
2038 LOGwriteFirstTrace(HttpMethod.GET, http_req_url.toString());
2039 LOGwriteDateTrace("application_vendor", vendor);
2040 LOGwriteDateTrace("application_model", model);
2041 if(version != null) {
2042 LOGwriteDateTrace("application_version", version);
2046 int responseCode = con.getResponseCode();
2047 if (responseCode == HttpURLConnection.HTTP_OK) {
2048 inputStream = con.getInputStream();
2050 inputStream = con.getErrorStream();
2053 // Process the response
2054 LOG.debug("HttpURLConnection result:" + responseCode);
2055 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
2056 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2058 ObjectMapper mapper = getObjectMapper();
2060 if (responseCode == HttpURLConnection.HTTP_OK) {
2061 // StringBuilder stringBuilder = new StringBuilder("\n");
2062 // String line = null;
2063 // while( ( line = reader.readLine() ) != null ) {
2064 // stringBuilder.append("\n").append( line );
2066 // LOG.info(stringBuilder.toString());
2067 response = mapper.readValue(reader, VnfImage.class);
2068 String original_buffer = mapper.writeValueAsString(response);
2069 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, "SUCCESS", original_buffer);
2070 if(response.getApplicationVendor() == null /*&& response.getAdditionalProperties() != null && !response.getAdditionalProperties().isEmpty()*/){
2071 LOG.warn("A List of multiple VNF-IMAGE entries has been returned");
2072 VnfImages listOfObjects = mapper.readValue(original_buffer, VnfImages.class);
2073 if(!listOfObjects.getVnfImage().isEmpty()) {
2074 response = listOfObjects.getVnfImage().get(0);
2077 } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
2078 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
2081 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2082 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
2083 throw new AAIServiceException(responseCode, errorresponse);
2086 } catch(AAIServiceException aaiexc) {
2088 } catch (Exception exc) {
2089 LOG.warn("requestVnfImageData", exc);
2090 throw new AAIServiceException(exc);
2092 if(inputStream != null){
2094 inputStream.close();
2095 } catch(Exception exc) {
2104 public boolean sendNotify(NotifyEvent event, String serviceInstanceId, String pathCode) throws AAIServiceException {
2105 InputStream inputStream = null;
2109 String selfLink = selflink_fqdn;
2110 if(SELFLINK_AVPN != null && SELFLINK_AVPN.equals(pathCode)) {
2111 selfLink = selflink_avpn;
2113 selfLink = selfLink.replace("{service-instance-id}", encodeQuery(serviceInstanceId));
2114 event.setSelflink(selfLink);
2116 ObjectMapper mapper = getObjectMapper();
2117 String json_text = mapper.writeValueAsString(event);
2119 SSLSocketFactory sockFact = CTX.getSocketFactory();
2121 String request_url = target_uri+ubb_notify_path;
2122 URL http_req_url = new URL(request_url);
2124 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.PUT);
2126 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
2127 osw.write(json_text);
2132 LOGwriteFirstTrace("PUT", request_url);
2133 LOGwriteDateTrace("NotifyEvent", json_text);
2136 int responseCode = con.getResponseCode();
2137 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2138 inputStream = con.getInputStream();
2140 inputStream = con.getErrorStream();
2143 // Process the response
2144 BufferedReader reader;
2146 reader = new BufferedReader( new InputStreamReader( inputStream ) );
2148 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2149 StringBuilder stringBuilder = new StringBuilder();
2151 while( ( line = reader.readLine() ) != null ) {
2152 stringBuilder.append( line );
2154 LOGwriteEndingTrace(responseCode, "SUCCESS", (stringBuilder != null) ? stringBuilder.toString() : "{no-data}");
2157 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2158 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
2160 throw new AAIServiceException(responseCode, errorresponse);
2162 } catch(AAIServiceException aaiexc) {
2164 } catch (Exception exc) {
2165 LOG.warn("sendNotify", exc);
2166 throw new AAIServiceException(exc);
2169 if(inputStream != null)
2170 inputStream.close();
2171 } catch (Exception exc) {
2178 public SearchResults requestNodeQuery(String node_type, String entityIdentifier, String entityName) throws AAIServiceException {
2179 SearchResults response = null;
2180 InputStream inputStream = null;
2183 String request_url = target_uri+query_nodes_path;
2184 request_url = request_url.replace("{node-type}", encodeQuery(node_type)) ;
2185 request_url = request_url.replace("{entity-identifier}", entityIdentifier) ;
2186 request_url = request_url.replace("{entity-name}", encodeQuery(entityName)) ;
2187 URL http_req_url = new URL(request_url);
2189 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.GET);
2191 LOGwriteFirstTrace(HttpMethod.GET, http_req_url.toString());
2192 LOGwriteDateTrace("node_type", node_type);
2193 LOGwriteDateTrace("vnf_name", entityName);
2196 int responseCode = con.getResponseCode();
2197 if (responseCode == HttpURLConnection.HTTP_OK) {
2198 inputStream = con.getInputStream();
2200 inputStream = con.getErrorStream();
2203 // Process the response
2204 LOG.debug("HttpURLConnection result:" + responseCode);
2205 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
2206 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2208 ObjectMapper mapper = getObjectMapper();
2210 if (responseCode == HttpURLConnection.HTTP_OK) {
2211 response = mapper.readValue(reader, SearchResults.class);
2212 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, "SUCCESS", mapper.writeValueAsString(response));
2213 } else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
2214 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
2217 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2218 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
2219 throw new AAIServiceException(responseCode, errorresponse);
2222 } catch(AAIServiceException aaiexc) {
2224 } catch (Exception exc) {
2225 LOG.warn("requestNodeQuery", exc);
2226 throw new AAIServiceException(exc);
2228 if(inputStream != null){
2230 inputStream.close();
2231 } catch(Exception exc) {
2242 public String requestDataByURL(URL url) throws AAIServiceException {
2245 throw new NullPointerException();
2248 String response = null;
2249 InputStream inputStream = null;
2252 URL http_req_url = url;
2254 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.GET);
2256 LOGwriteFirstTrace(HttpMethod.GET, http_req_url.toString());
2259 int responseCode = con.getResponseCode();
2260 if (responseCode == HttpURLConnection.HTTP_OK) {
2261 inputStream = con.getInputStream();
2263 inputStream = con.getErrorStream();
2266 // Process the response
2267 LOG.debug("HttpURLConnection result:" + responseCode);
2268 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
2269 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2271 ObjectMapper mapper = getObjectMapper();
2273 if (responseCode == HttpURLConnection.HTTP_OK) {
2274 StringBuilder stringBuilder = new StringBuilder("\n");
2276 while( ( line = reader.readLine() ) != null ) {
2277 stringBuilder.append( line );
2279 LOG.info(stringBuilder.toString());
2280 // response = mapper.readValue(reader, String.class);
2281 response = stringBuilder.toString();
2282 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, "SUCCESS", mapper.writeValueAsString(response));
2283 } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
2284 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
2287 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2288 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
2289 throw new AAIServiceException(responseCode, errorresponse);
2292 } catch(AAIServiceException aaiexc) {
2294 } catch (Exception exc) {
2295 LOG.warn("requestNetworkVceData", exc);
2296 throw new AAIServiceException(exc);
2298 if(inputStream != null){
2300 inputStream.close();
2301 } catch(Exception exc) {
2311 public GenericVnf requestGenericVnfeNodeQuery(String vnf_name) throws AAIServiceException {
2313 if(vnf_name == null) {
2314 throw new NullPointerException();
2317 GenericVnf entity = null;
2318 SearchResults resp = this.requestNodeQuery("generic-vnf", "vnf-name", vnf_name);
2320 List<ResultData> resultDataList = resp.getResultData();
2323 for (ResultData datum : resultDataList) {
2324 String data_type = datum.getResourceType();
2325 URL url = new URL(datum.getResourceLink());
2326 entity = this.getResource(url.toString(), GenericVnf.class);
2331 LOG.error("Caught exception", e);
2337 public Vserver requestVServerDataByURL(URL url) throws AAIServiceException {
2340 throw new NullPointerException();
2343 Vserver entity = null;
2346 entity = this.getResource(url.toString(), Vserver.class);
2347 } catch (AAIServiceException exc) {
2349 } catch (Exception e) {
2350 throw new AAIServiceException(e);
2356 public URL requestVserverURLNodeQuery(String vserver_name) throws AAIServiceException {
2358 if(vserver_name == null) {
2359 throw new NullPointerException();
2363 SearchResults resp = this.requestNodeQuery("vserver", "vserver-name", vserver_name);
2365 List<ResultData> resultDataList = resp.getResultData();
2368 for (ResultData datum : resultDataList) {
2369 String data_type = datum.getResourceType();
2370 String resourceLink = datum.getResourceLink();
2371 if(!resourceLink.isEmpty() && !resourceLink.toLowerCase().startsWith("http")) {
2372 resourceLink = (new EchoRequest()).target_uri + resourceLink;
2374 entity = new URL(resourceLink);
2376 } catch (Exception e) {
2377 throw new AAIServiceException(e);
2382 class AAIRequestExecutor implements AAIExecutorInterface {
2385 public String get(AAIRequest request) throws AAIServiceException {
2386 String response = null;
2387 InputStream inputStream = null;
2388 HttpURLConnection con = null;
2389 URL requestUrl = null;
2391 String requestId = UUID.randomUUID().toString();
2392 StringBuilder errorStringBuilder = new StringBuilder();
2396 if(request.getRequestObject() != null) {
2397 requestUrl = request.getRequestUrl(HttpMethod.POST, null);
2398 requestUrl = appendDepth(requestUrl, request);
2399 con = getConfiguredConnection(requestUrl, HttpMethod.POST);
2400 String json_text = request.toJSONString();
2401 LOGwriteDateTrace("data", json_text);
2402 logMetricRequest(requestId, "POST "+requestUrl.getPath(), json_text, requestUrl.getPath());
2403 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
2404 osw.write(json_text);
2407 requestUrl = request.getRequestUrl(HttpMethod.GET, null);
2408 requestUrl = appendDepth(requestUrl, request);
2409 con = getConfiguredConnection(requestUrl, HttpMethod.GET);
2410 logMetricRequest(requestId, "GET "+requestUrl.getPath(), "", requestUrl.getPath());
2414 String responseMessage = con.getResponseMessage();
2415 int responseCode = con.getResponseCode();
2416 if (responseCode == HttpURLConnection.HTTP_OK) {
2417 inputStream = con.getInputStream();
2419 inputStream = con.getErrorStream();
2422 // Process the response
2423 LOG.debug("HttpURLConnection result:" + responseCode + " : " + responseMessage);
2424 logMetricResponse(requestId, responseCode, responseMessage);
2426 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
2427 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2429 ObjectMapper mapper = getObjectMapper();
2431 if (responseCode == HttpURLConnection.HTTP_OK) {
2432 StringBuilder stringBuilder = new StringBuilder();
2434 while( ( line = reader.readLine() ) != null ) {
2435 stringBuilder.append( line );
2437 response = stringBuilder.toString();
2439 Object object = mapper.readValue(response, Object.class);
2440 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, responseMessage, mapper.writeValueAsString(object));
2441 } catch(Exception exc) {
2442 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, responseMessage, mapper.writeValueAsString(response));
2444 } else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
2445 LOGwriteEndingTrace(responseCode, responseMessage, "Entry does not exist.");
2446 ErrorResponse errorresponse = null;
2448 errorresponse = mapper.readValue(reader, ErrorResponse.class);
2449 } catch(Exception exc) {
2450 errorresponse = new ErrorResponse();
2451 RequestError requestError = new RequestError();
2452 ServiceException serviceException = new ServiceException();
2453 serviceException.setText("Entry does not exist.");
2454 requestError.setServiceException(serviceException);
2455 errorresponse.setRequestError(requestError );
2457 throw new AAIServiceException(responseCode, errorresponse);
2458 } else if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
2459 StringBuilder stringBuilder = new StringBuilder();
2461 while( ( line = reader.readLine() ) != null ) {
2462 stringBuilder.append( line );
2464 LOGwriteEndingTrace(responseCode, responseMessage, stringBuilder.toString());
2465 ServiceException serviceException = new ServiceException();
2466 serviceException.setMessageId("HTTP_UNAUTHORIZED");
2467 serviceException.setText(stringBuilder.toString());
2468 RequestError requestError = new RequestError();
2469 requestError.setServiceException(serviceException);
2470 ErrorResponse errorresponse = new ErrorResponse();
2471 errorresponse.setRequestError(requestError);
2472 throw new AAIServiceException(responseCode, errorresponse);
2474 // StringBuilder errorStringBuilder = new StringBuilder();
2476 while( ( line = reader.readLine() ) != null ) {
2477 errorStringBuilder.append("\n").append( line );
2480 ErrorResponse errorresponse = mapper.readValue(errorStringBuilder.toString(), ErrorResponse.class);
2481 // ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2482 LOGwriteEndingTrace(responseCode, responseMessage, mapper.writeValueAsString(errorresponse));
2483 throw new AAIServiceException(responseCode, errorresponse);
2486 } catch(AAIServiceException aaiexc) {
2488 } catch (Exception exc) {
2489 LOG.warn(errorStringBuilder.toString(), exc);
2490 throw new AAIServiceException(exc);
2492 if(inputStream != null){
2494 inputStream.close();
2495 } catch(Exception exc) {
2503 private URL appendDepth(URL requestUrl, AAIRequest request) throws MalformedURLException {
2505 String depth = request.requestProperties.getProperty("depth", "1");
2506 String path = requestUrl.toString();
2507 if(path.contains("?depth=") || path.contains("&depth=")) {
2510 if(path.contains("?")) {
2511 path = String.format("%s&depth=%s", path, depth);
2513 path = String.format("%s?depth=%s", path, depth);
2515 return new URL(path);
2520 public String post(AAIRequest request) throws AAIServiceException {
2521 InputStream inputStream = null;
2522 String requestId = UUID.randomUUID().toString();
2525 String resourceVersion = null;
2526 AAIDatum instance = request.getRequestObject();
2528 Method getResourceVersionMethod = instance.getClass().getMethod("getResourceVersion");
2529 if(getResourceVersionMethod != null){
2531 getResourceVersionMethod.setAccessible(true);
2532 Object object = getResourceVersionMethod.invoke(instance);
2534 resourceVersion = object.toString();
2535 } catch (InvocationTargetException x) {
2536 Throwable cause = x.getCause();
2540 URL requestUrl = null;
2541 HttpURLConnection con = getConfiguredConnection(requestUrl = request.getRequestUrl(HttpMethod.PUT, resourceVersion), HttpMethod.PUT);
2542 ObjectMapper mapper = getObjectMapper();
2543 String json_text = request.toJSONString();
2545 LOGwriteDateTrace("data", json_text);
2546 logMetricRequest(requestId, "PUT "+requestUrl.getPath(), json_text, requestUrl.getPath());
2548 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
2549 osw.write(json_text);
2553 String responseMessage = con.getResponseMessage();
2554 int responseCode = con.getResponseCode();
2555 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2556 inputStream = con.getInputStream();
2558 inputStream = con.getErrorStream();
2561 LOG.debug("HttpURLConnection result:" + responseCode + " : " + responseMessage);
2562 logMetricResponse(requestId,responseCode, responseMessage);
2564 // Process the response
2565 BufferedReader reader;
2567 reader = new BufferedReader( new InputStreamReader( inputStream ) );
2568 mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
2570 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2571 StringBuilder stringBuilder = new StringBuilder();
2573 while( ( line = reader.readLine() ) != null ) {
2574 stringBuilder.append( line );
2576 LOGwriteEndingTrace(responseCode, responseMessage, (stringBuilder != null) ? stringBuilder.toString() : "{no-data}");
2577 return stringBuilder.toString();
2579 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2580 LOGwriteEndingTrace(responseCode, responseMessage, mapper.writeValueAsString(errorresponse));
2582 throw new AAIServiceException(responseCode, errorresponse);
2584 } catch(AAIServiceException aaiexc) {
2586 } catch (Exception exc) {
2587 LOG.warn("AAIRequestExecutor.post", exc);
2588 throw new AAIServiceException(exc);
2591 if(inputStream != null)
2592 inputStream.close();
2593 } catch (Exception exc) {
2600 public Boolean delete(AAIRequest request, String resourceVersion) throws AAIServiceException {
2601 Boolean response = null;
2602 InputStream inputStream = null;
2603 String requestId = UUID.randomUUID().toString();
2605 if(resourceVersion == null) {
2606 throw new AAIServiceException("resource-version is required for DELETE request");
2610 URL requestUrl = null;
2611 HttpURLConnection conn = getConfiguredConnection(requestUrl = request.getRequestUrl(HttpMethod.DELETE, resourceVersion), HttpMethod.DELETE);
2612 logMetricRequest(requestId, "DELETE "+requestUrl.getPath(), "", requestUrl.getPath());
2613 conn.setDoOutput(true);
2614 // if(request.isDeleteDataRequired()) {
2615 // String json_text = request.toJSONString();
2617 // LOGwriteDateTrace("data", json_text);
2618 // OutputStream os = con.getOutputStream();
2619 // OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
2620 // osw.write(json_text);
2625 String responseMessage = conn.getResponseMessage();
2626 int responseCode = conn.getResponseCode();
2627 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2628 inputStream = conn.getInputStream();
2630 inputStream = conn.getErrorStream();
2633 // Process the response
2634 LOG.debug("HttpURLConnection result:" + responseCode + " : " + responseMessage);
2635 logMetricResponse(requestId,responseCode, responseMessage);
2637 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
2638 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2641 ObjectMapper mapper = getObjectMapper();
2643 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2644 StringBuilder stringBuilder = new StringBuilder();
2646 while( ( line = reader.readLine() ) != null ) {
2647 stringBuilder.append( line );
2649 LOGwriteEndingTrace(responseCode, responseMessage, stringBuilder.toString());
2651 } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
2652 LOGwriteEndingTrace(responseCode, responseMessage, "Entry does not exist.");
2655 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2656 LOGwriteEndingTrace(responseCode, responseMessage, mapper.writeValueAsString(errorresponse));
2657 throw new AAIServiceException(responseCode, errorresponse);
2659 } catch(AAIServiceException aaiexc) {
2661 } catch (Exception exc) {
2662 LOG.warn("delete", exc);
2663 throw new AAIServiceException(exc);
2665 if(inputStream != null){
2667 inputStream.close();
2668 } catch(Exception exc) {
2677 public Object query(AAIRequest request, Class clas) throws AAIServiceException {
2678 Object response = null;
2679 InputStream inputStream = null;
2680 HttpURLConnection con = null;
2681 URL requestUrl = null;
2682 String requestId = UUID.randomUUID().toString();
2685 con = getConfiguredConnection(requestUrl = request.getRequestQueryUrl(HttpMethod.GET), HttpMethod.GET);
2686 logMetricRequest(requestId, "GET "+requestUrl.getPath(), "", requestUrl.getPath());
2689 String responseMessage = con.getResponseMessage();
2690 int responseCode = con.getResponseCode();
2691 if (responseCode == HttpURLConnection.HTTP_OK) {
2692 inputStream = con.getInputStream();
2694 inputStream = con.getErrorStream();
2697 logMetricResponse(requestId,responseCode, responseMessage);
2698 ObjectMapper mapper = getObjectMapper();
2700 if (responseCode == HttpURLConnection.HTTP_OK) {
2701 // Process the response
2702 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2703 response = mapper.readValue(reader, clas);
2704 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, "SUCCESS", mapper.writeValueAsString(response));
2705 } else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
2706 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
2709 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2710 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2711 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
2712 throw new AAIServiceException(responseCode, errorresponse);
2715 } catch(AAIServiceException aaiexc) {
2717 } catch (Exception exc) {
2718 LOG.warn("GET", exc);
2719 throw new AAIServiceException(exc);
2721 if(inputStream != null){
2723 inputStream.close();
2724 } catch(Exception exc) {
2734 public Boolean patch(AAIRequest request, String resourceVersion) throws AAIServiceException {
2735 InputStream inputStream = null;
2736 String requestId = UUID.randomUUID().toString();
2739 AAIDatum instance = request.getRequestObject();
2740 if(instance instanceof ResourceVersion) {
2741 resourceVersion = ((ResourceVersion)instance).getResourceVersion();
2744 URL requestUrl = null;
2745 HttpURLConnection con = getConfiguredConnection(requestUrl = request.getRequestUrl("PATCH", resourceVersion), "PATCH");
2746 ObjectMapper mapper = getObjectMapper();
2747 String json_text = request.toJSONString();
2749 LOGwriteDateTrace("data", json_text);
2750 logMetricRequest(requestId, "PATCH "+requestUrl.getPath(), json_text, requestUrl.getPath());
2752 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
2753 osw.write(json_text);
2757 String responseMessage = con.getResponseMessage();
2758 int responseCode = con.getResponseCode();
2759 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2760 inputStream = con.getInputStream();
2762 inputStream = con.getErrorStream();
2765 LOG.info("HttpURLConnection result: " + responseCode + " : " + responseMessage);
2766 logMetricResponse(requestId,responseCode, responseMessage);
2768 // Process the response
2769 BufferedReader reader;
2771 reader = new BufferedReader( new InputStreamReader( inputStream ) );
2772 mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
2774 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2775 StringBuilder stringBuilder = new StringBuilder();
2777 while( ( line = reader.readLine() ) != null ) {
2778 stringBuilder.append( line );
2780 LOGwriteEndingTrace(responseCode, responseMessage, (stringBuilder != null) ? stringBuilder.toString() : "{no-data}");
2783 StringBuilder stringBuilder = new StringBuilder();
2785 while( ( line = reader.readLine() ) != null ) {
2786 stringBuilder.append("\n").append( line );
2788 LOG.info(stringBuilder.toString());
2791 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2792 LOGwriteEndingTrace(responseCode, responseMessage, mapper.writeValueAsString(errorresponse));
2794 throw new AAIServiceException(responseCode, errorresponse);
2796 } catch(AAIServiceException aaiexc) {
2798 } catch (Exception exc) {
2799 LOG.warn("AAIRequestExecutor.patch", exc);
2800 throw new AAIServiceException(exc);
2803 if(inputStream != null)
2804 inputStream.close();
2805 } catch (Exception exc) {
2813 public Tenant requestTenantData(String tenant_id, String cloudOwner, String cloudRegionId) throws AAIServiceException {
2814 Tenant response = null;
2817 AAIRequest request = AAIRequest.getRequestFromResource("tenant");
2818 request.addRequestProperty("tenant.tenant-id", tenant_id);
2819 request.addRequestProperty("cloud-region.cloud-owner", cloudOwner);
2820 request.addRequestProperty("cloud-region.cloud-region-id", cloudRegionId);
2822 String rv = executor.get(request);
2824 ObjectMapper mapper = getObjectMapper();
2825 response = mapper.readValue(rv, Tenant.class);
2827 } catch(AAIServiceException aaiexc) {
2829 } catch (Exception exc) {
2830 LOG.warn("requestTenantData", exc);
2831 throw new AAIServiceException(exc);
2838 public Tenant requestTenantDataByName(String tenant_name, String cloudOwner, String cloudRegionId) throws AAIServiceException {
2839 Tenant response = null;
2842 AAIRequest request = AAIRequest.getRequestFromResource("tenant");
2843 request.addRequestProperty("tenant.tenant-name", tenant_name);
2844 request.addRequestProperty("cloud-region.cloud-owner", cloudOwner);
2845 request.addRequestProperty("cloud-region.cloud-region-id", cloudRegionId);
2846 Object rv = executor.query(request, Tenant.class);
2848 return (Tenant)null;
2850 response = (Tenant)rv;
2851 } catch(AAIServiceException aaiexc) {
2853 } catch (Exception exc) {
2854 LOG.warn("requestTenantDataByName", exc);
2855 throw new AAIServiceException(exc);
2863 public boolean postTenantData(String tenant_id, String cloudOwner, String cloudRegionId, Tenant tenannt) throws AAIServiceException {
2865 AAIRequest request = AAIRequest.getRequestFromResource("tenant");
2866 request.addRequestProperty("tenant.tenant-id", tenant_id);
2867 request.addRequestProperty("cloud-region.cloud-owner", cloudOwner);
2868 request.addRequestProperty("cloud-region.cloud-region-id", cloudRegionId);
2869 request.setRequestObject(tenannt);
2870 Object response = executor.post(request);
2872 } catch(AAIServiceException aaiexc) {
2874 } catch (Exception exc) {
2875 LOG.warn("postTenantData", exc);
2876 throw new AAIServiceException(exc);
2882 public String getTenantIdFromVserverUrl(URL url) {
2884 String path = url.getPath();
2886 String[] split = path.split("/tenants/tenant/");
2887 if(split.length > 1) {
2888 split = split[1].split("/");
2896 public String getCloudOwnerFromVserverUrl(URL url) {
2898 String path = url.getPath();
2900 String[] split = path.split("/cloud-regions/cloud-region/");
2901 if(split.length > 1) {
2902 split = split[1].split("/");
2910 public String getCloudRegionFromVserverUrl(URL url) {
2912 String path = url.getPath();
2914 String[] split = path.split("/cloud-regions/cloud-region/");
2915 if(split.length > 1) {
2916 split = split[1].split("/");
2924 public String getVServerIdFromVserverUrl(URL url, String tenantId) {
2925 String pattern = network_vserver_path;
2926 pattern = pattern.replace("{tenant-id}", tenantId);
2928 int end = pattern.indexOf("{vserver-id}");
2929 String prefix = pattern.substring(0, end);
2931 String path = url.getPath();
2933 if(path.startsWith(prefix)) {
2934 path = path.substring(prefix.length());
2940 protected Logger getLogger(){
2946 public AAIRequestExecutor getExecutor() {
2951 * Creates a current time stamp in UTC i.e. 2016-03-08T22:15:13.343Z.
2952 * If there are any parameters the values are appended to the time stamp.
2955 * values to be appended to current time stamp
2957 * used to set an attribute for a DG
2958 * @throws SvcLogicException
2960 public void setStatusMethod(Map<String, String> parameters, SvcLogicContext ctx) throws SvcLogicException {
2962 throw new SvcLogicException("SvcLogicContext is null.");
2965 StringBuilder sb = new StringBuilder();
2966 sb.append(String.format("%tFT%<tTZ", Calendar.getInstance(TimeZone.getTimeZone("Z")))).append(" - ");
2968 for (Entry<String, String> entry : parameters.entrySet()) {
2969 sb.append(entry.getValue()).append(" ");
2972 if (sb.length() > 0) {
2973 sb.setLength(sb.length() - 2);
2976 ctx.setAttribute("aai-summary-status-message", sb.toString());
2977 LOG.info("aai-summary-status-message: " + sb.toString());
2981 * Generic method to GET json data from an A&AI using key structure.
2982 * Then convert that json to an Object.
2983 * If successful the Object is attempted to be cast to the type parameter.
2986 * key identifying the resource to be retrieved from AAI
2988 * the class of object that A&AI will return
2989 * @return the object created from json or null if the response code is not 200
2991 * @throws AAIServiceException
2992 * if empty or null key and or type or there's an error with processing
2995 public <T> T getResource(String key, Class<T> type) throws AAIServiceException {
2996 if (StringUtils.isEmpty(key) || type == null) {
2997 throw new AAIServiceException("Key is empty or null and or type is null");
3002 SvcLogicContext ctx = new SvcLogicContext();
3003 if(!key.contains(" = ")) {
3004 if(isValidURL(key)) {
3005 key = String.format("selflink = '%s'", key);
3006 } else if(isValidURI(key)) {
3007 key = String.format("resource-path = '%s'", key);
3013 HashMap<String, String> nameValues = AAIServiceUtils.keyToHashMap(key, ctx);
3015 AAIRequest request = new SelfLinkRequest(type);
3016 if(nameValues.containsKey(PathRequest.RESOURCE_PATH.replaceAll("-", "_"))) {
3017 request = new PathRequest(type);
3020 request.processRequestPathValues(nameValues);
3021 Object obj = this.getExecutor().query(request, type);
3022 response = type.cast(obj);
3024 return response != null ? type.cast(response) : response;
3027 public boolean isValidURL(String url) {
3033 } catch (MalformedURLException e) {
3039 } catch (URISyntaxException e) {
3047 public boolean isValidURI(String url) {
3053 } catch (URISyntaxException e) {
3062 protected boolean deleteRelationshipList(URL httpReqUrl, String json_text) throws AAIServiceException {
3063 if(httpReqUrl == null) {
3064 throw new NullPointerException();
3067 boolean response = false;
3068 InputStream inputStream = null;
3071 HttpURLConnection con = getConfiguredConnection(httpReqUrl, HttpMethod.DELETE);
3073 // SSLSocketFactory sockFact = CTX.getSocketFactory();
3074 // con.setSSLSocketFactory( sockFact );
3075 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
3076 osw.write(json_text);
3081 LOGwriteFirstTrace("DELETE", httpReqUrl.toString());
3082 LOGwriteDateTrace("data", json_text);
3085 int responseCode = con.getResponseCode();
3086 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
3087 inputStream = con.getInputStream();
3089 inputStream = con.getErrorStream();
3092 // Process the response
3093 LOG.debug("HttpURLConnection result:" + responseCode);
3094 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
3095 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
3098 ObjectMapper mapper = getObjectMapper();
3100 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
3101 StringBuilder stringBuilder = new StringBuilder();
3103 while( ( line = reader.readLine() ) != null ) {
3104 stringBuilder.append( line );
3106 LOGwriteEndingTrace(responseCode, "SUCCESS", stringBuilder.toString());
3108 } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
3109 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
3112 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
3113 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
3114 throw new AAIServiceException(responseCode, errorresponse);
3117 } catch(AAIServiceException aaiexc) {
3119 } catch (Exception exc) {
3120 LOG.warn("deleteRelationshipList", exc);
3121 throw new AAIServiceException(exc);
3123 if(inputStream != null){
3125 inputStream.close();
3126 } catch(Exception exc) {
3134 public static ObjectMapper getObjectMapper() {
3135 ObjectMapper mapper = new ObjectMapper();
3136 AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance());
3137 AnnotationIntrospector secondary = new JacksonAnnotationIntrospector();
3138 mapper.setAnnotationIntrospector(AnnotationIntrospector.pair(introspector, secondary));
3139 mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
3140 mapper.setSerializationInclusion(Include.NON_NULL);
3144 public void logMetricRequest(String requestId, String targetServiceName, String msg, String path){
3145 String svcInstanceId = "";
3146 String svcName = null;
3147 String partnerName = null;
3148 String targetEntity = "A&AI";
3149 String targetVirtualEntity = null;
3151 targetServiceName = "";
3153 ml.logRequest(svcInstanceId, svcName, partnerName, targetEntity, targetServiceName, targetVirtualEntity, msg);
3156 public void logMetricResponse(String requestId, int responseCode, String responseDescription){
3157 ml.logResponse(responseCode < 400 ? "SUCCESS" : "FAILURE", Integer.toString(responseCode), responseDescription);
3160 public void logKeyError(String keys){
3161 LOG.error("Atleast one of the keys [" + keys + "] should have been populated. This will cause a NPE.");
3169 public QueryStatus save(String resource, boolean force, boolean localOnly, String key, Map<String, String> params, String prefix, SvcLogicContext ctx)
3170 throws SvcLogicException {
3171 String normResource = resource.split(":")[0];
3173 switch(normResource){
3174 case "formatted-query":
3175 case "generic-query":
3179 case "l2-bridge-sbg":
3180 case "l2-bridge-bgf":
3186 if(key.contains("selflink =")) {
3189 if(!key.contains(String.format("%s.", normResource))) {
3190 key = rewriteKey(resource, key, ctx);
3193 return super.save(resource, force, localOnly, key, params, prefix, ctx);
3197 public QueryStatus query(String resource, boolean localOnly, String select, String key, String prefix, String orderBy, SvcLogicContext ctx)
3198 throws SvcLogicException {
3199 String normResource = resource.split(":")[0];
3201 switch(normResource){
3202 case "formatted-query":
3203 case "generic-query":
3207 case "l2-bridge-sbg":
3208 case "l2-bridge-bgf":
3214 if(key.contains("selflink =")) {
3217 if(!key.contains(String.format("%s.", normResource))) {
3218 key = rewriteKey(resource, key, ctx);
3222 return super.query(resource, localOnly, select, key, prefix, orderBy, ctx);
3226 public QueryStatus delete(String resource, String key, SvcLogicContext ctx) throws SvcLogicException {
3227 String normResource = resource.split(":")[0];
3229 switch(normResource){
3230 case "formatted-query":
3231 case "generic-query":
3235 case "l2-bridge-sbg":
3236 case "l2-bridge-bgf":
3242 if(key.contains("selflink =")) {
3245 if(!key.contains(String.format("%s.", normResource))) {
3246 key = rewriteKey(resource, key, ctx);
3250 return super.delete(resource, key, ctx);
3254 public QueryStatus update(String resource, String key, Map<String, String> params, String prefix, SvcLogicContext ctx) throws SvcLogicException {
3255 String normResource = resource.split(":")[0];
3257 switch(normResource){
3258 case "formatted-query":
3259 case "generic-query":
3263 case "l2-bridge-sbg":
3264 case "l2-bridge-bgf":
3270 if(key.contains("selflink =")) {
3273 if(!key.contains(String.format("%s.", normResource))) {
3274 key = rewriteKey(resource, key, ctx);
3278 return super.update(resource, key, params, prefix, ctx);
3281 private String rewriteKey(String resource, String key, SvcLogicContext ctx) {
3282 LOG.info("AAI Deprecation - the format of request key is no longer supported. Please rewrite this key : " + key);
3284 String normResource = resource.split(":")[0];
3285 Class<? extends AAIDatum> clazz = null;
3287 clazz = AAIRequest.getClassFromResource(normResource) ;
3288 } catch (ClassNotFoundException e) {
3289 LOG.warn("AAIRequest does not support class: " + e.getMessage());
3295 List<String> fieldAnnotatedNames = new LinkedList<String>();
3297 Field[] fields = clazz.getDeclaredFields();
3298 for(Field field : fields) {
3299 String fieldName = field.getName();
3300 XmlElement annotation = field.getAnnotation(XmlElement.class);
3301 if(annotation == null)
3303 String primaryId = annotation.name();
3304 if("##default".equals(primaryId)) {
3305 primaryId = fieldName;
3307 fieldAnnotatedNames.add(primaryId);
3310 HashMap<String, String> nameValues = AAIServiceUtils.keyToHashMap(key, ctx);
3311 Set<String> keyset = nameValues.keySet();
3312 for(String keyName : keyset) {
3313 if(keyName.contains("."))
3316 String tmpKeyName = keyName.replaceAll("_", "-");
3317 String valueToSubstitute = String.format("%s =", tmpKeyName);
3318 if(fieldAnnotatedNames.contains(tmpKeyName) && key.contains(valueToSubstitute)) {
3319 key = key.replace(valueToSubstitute, String.format("%s.%s =", normResource, tmpKeyName));
3329 public String getPathTemplateForResource(String resoourceName, String keys, SvcLogicContext ctx) throws MalformedURLException {
3330 return AAIServiceUtils.getPathForResource(resoourceName, StringUtils.join(keys, " AND "), ctx);
3334 public boolean isDeprecatedFormat(String resource, HashMap<String, String> nameValues) {
3335 return !AAIServiceUtils.isValidFormat(resource, nameValues);