2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 ONAP Intellectual Property. All rights
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
22 package org.onap.ccsdk.sli.adaptors.aai;
25 import java.io.BufferedReader;
26 import java.io.ByteArrayInputStream;
28 import java.io.FileInputStream;
29 import java.io.InputStream;
30 import java.io.InputStreamReader;
31 import java.io.OutputStreamWriter;
32 import java.io.UnsupportedEncodingException;
33 import java.lang.reflect.Field;
34 import java.lang.reflect.InvocationTargetException;
35 import java.lang.reflect.Method;
36 import java.lang.reflect.Modifier;
37 import java.net.HttpURLConnection;
38 import java.net.MalformedURLException;
39 import java.net.URISyntaxException;
41 import java.net.URLEncoder;
42 import java.nio.charset.StandardCharsets;
43 import java.security.KeyManagementException;
44 import java.security.KeyStore;
45 import java.security.NoSuchAlgorithmException;
46 import java.text.SimpleDateFormat;
47 import java.util.ArrayList;
48 import java.util.Calendar;
49 import java.util.Enumeration;
50 import java.util.HashMap;
51 import java.util.LinkedList;
52 import java.util.List;
54 import java.util.Map.Entry;
55 import java.util.Properties;
57 import java.util.TimeZone;
58 import java.util.UUID;
59 import java.util.regex.Matcher;
60 import java.util.regex.Pattern;
62 import javax.net.ssl.HostnameVerifier;
63 import javax.net.ssl.HttpsURLConnection;
64 import javax.net.ssl.KeyManagerFactory;
65 import javax.net.ssl.SSLContext;
66 import javax.net.ssl.SSLSession;
67 import javax.net.ssl.SSLSocketFactory;
68 import javax.ws.rs.HttpMethod;
69 import javax.xml.bind.annotation.XmlElement;
71 import org.apache.commons.codec.binary.Base64;
72 import org.apache.commons.lang3.StringUtils;
73 import org.onap.ccsdk.sli.core.sli.ConfigurationException;
74 import org.onap.ccsdk.sli.core.sli.MetricLogger;
75 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
76 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
77 import org.onap.ccsdk.sli.core.sli.SvcLogicResource;
78 import org.openecomp.aai.inventory.v10.AvailabilityZone;
79 import org.openecomp.aai.inventory.v10.Complex;
80 import org.openecomp.aai.inventory.v10.CtagPool;
81 import org.openecomp.aai.inventory.v10.DvsSwitch;
82 import org.openecomp.aai.inventory.v10.GenericVnf;
83 import org.openecomp.aai.inventory.v10.L3Network;
84 import org.openecomp.aai.inventory.v10.OamNetwork;
85 import org.openecomp.aai.inventory.v10.PInterface;
86 import org.openecomp.aai.inventory.v10.PhysicalLink;
87 import org.openecomp.aai.inventory.v10.Pserver;
88 import org.openecomp.aai.inventory.v10.ResultData;
89 import org.openecomp.aai.inventory.v10.SearchResults;
90 import org.openecomp.aai.inventory.v10.Service;
91 import org.openecomp.aai.inventory.v10.ServiceInstance;
92 import org.openecomp.aai.inventory.v10.SitePairSet;
93 import org.openecomp.aai.inventory.v10.Tenant;
94 import org.openecomp.aai.inventory.v10.Vce;
95 import org.openecomp.aai.inventory.v10.VnfImage;
96 import org.openecomp.aai.inventory.v10.VnfImages;
97 import org.openecomp.aai.inventory.v10.Vpe;
98 import org.openecomp.aai.inventory.v10.VplsPe;
99 import org.openecomp.aai.inventory.v10.VpnBinding;
100 import org.openecomp.aai.inventory.v10.Vserver;
101 import org.onap.ccsdk.sli.adaptors.aai.data.AAIDatum;
102 import org.onap.ccsdk.sli.adaptors.aai.data.ErrorResponse;
103 import org.onap.ccsdk.sli.adaptors.aai.data.RequestError;
104 import org.onap.ccsdk.sli.adaptors.aai.data.ResourceVersion;
105 import org.onap.ccsdk.sli.adaptors.aai.data.ServiceException;
106 import org.onap.ccsdk.sli.adaptors.aai.data.notify.NotifyEvent;
107 import org.onap.ccsdk.sli.adaptors.aai.data.v1507.VServer;
108 import org.slf4j.Logger;
109 import org.slf4j.LoggerFactory;
111 import com.fasterxml.jackson.annotation.JsonInclude.Include;
112 import com.fasterxml.jackson.databind.AnnotationIntrospector;
113 import com.fasterxml.jackson.databind.DeserializationFeature;
114 import com.fasterxml.jackson.databind.ObjectMapper;
115 import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector;
116 import com.fasterxml.jackson.databind.type.TypeFactory;
117 import com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector;
118 import com.sun.jersey.api.client.config.DefaultClientConfig;
119 import com.sun.jersey.client.urlconnection.HTTPSProperties;
122 public class AAIService extends AAIDeclarations implements AAIClient, SvcLogicResource {
124 public static final String AAICLIENT_PROPERTIES = "/aaiclient.properties";
125 public static final String PATH_PROPERTIES = "/aai-path.properties";
127 private static final Logger LOG = LoggerFactory.getLogger(AAIService.class);
129 private final String truststore_path;
130 private final String truststore_password;
131 private final String keystore_path;
132 private final String keystore_password;
133 private final Boolean ignore_certificate_host_error;
135 private final String target_uri;
136 private final String query_path; // = "sdn-zone-query";
138 private final String network_vserver_path;
140 private final String svc_instance_path;
141 private final String svc_inst_qry_path;
143 private final String vnf_image_query_path;
145 private final String param_service_type; //= "service-type";
147 private final String ubb_notify_path;
148 private final String selflink_avpn;
149 private final String selflink_fqdn;
151 private final String p_interface_path;
153 private final String service_path;
154 private final String site_pair_set_path;
156 private final int connection_timeout;
157 private final int read_timeout;
160 private final String query_nodes_path;
161 private final String update_path;
163 private final String application_id;
165 // authentication credentials
166 private String user_name;
167 private String user_password;
170 private final boolean runtimeOSGI;
172 private SSLContext CTX;
174 private final MetricLogger ml = new MetricLogger();
176 private final AAIRequestExecutor executor;
178 public AAIService(URL propURL) {
179 LOG.info("Entered AAIService.ctor");
181 String runtime = System.getProperty("aaiclient.runtime");
182 if(runtime != null && runtime.equals("OSGI")) {
188 Properties props = null;
190 props = initialize(propURL);
191 AAIRequest.setProperties(props, this);
193 } catch(Exception exc){
194 LOG.error("AicAAIResource.static", exc);
197 executor = new AAIRequestExecutor();
199 user_name = props.getProperty(CLIENT_NAME);
200 user_password = props.getProperty(CLIENT_PWWD);
202 if(user_name == null || user_name.isEmpty()){
203 LOG.debug("Basic user name is not set");
205 if(user_password == null || user_password.isEmpty()) {
206 LOG.debug("Basic password is not set");
209 truststore_path = props.getProperty(TRUSTSTORE_PATH);
210 truststore_password = props.getProperty(TRUSTSTORE_PSSWD);
211 keystore_path = props.getProperty(KEYSTORE_PATH);
212 keystore_password = props.getProperty(KEYSTORE_PSSWD);
214 target_uri = props.getProperty(TARGET_URI);
215 query_path = props.getProperty(QUERY_PATH);
216 update_path = props.getProperty(UPDATE_PATH);
218 String applicationId =props.getProperty(APPLICATION_ID);
219 if(applicationId == null || applicationId.isEmpty()) {
220 applicationId = "SDNC";
222 application_id = applicationId;
224 // connection timeout
225 int tmpConnectionTimeout = 30000;
226 int tmpReadTimeout = 30000;
229 String tmpValue = null;
230 tmpValue = props.getProperty(CONNECTION_TIMEOUT, "30000");
231 tmpConnectionTimeout = Integer.parseInt(tmpValue);
232 tmpValue = props.getProperty(READ_TIMEOUT, "30000");
233 tmpReadTimeout = Integer.parseInt(tmpValue);
234 } catch(Exception exc) {
235 LOG.error("Failed setting connection timeout", exc);
236 tmpConnectionTimeout = 30000;
237 tmpReadTimeout = 30000;
239 connection_timeout = tmpConnectionTimeout;
240 read_timeout = tmpReadTimeout;
242 network_vserver_path =props.getProperty(NETWORK_VSERVER_PATH);
244 svc_instance_path = props.getProperty(SVC_INSTANCE_PATH); // "/aai/v1/business/customers/customer/{customer-id}/service-subscriptions/service-subscription/{service-type}/service-instances");
245 // "/aai/v1/business/customers/customer/ma9181-203-customerid/service-subscriptions/service-subscription/ma9181%20Hosted%20Voice/service-instances";
247 // 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");
248 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");
251 param_service_type = props.getProperty(PARAM_SERVICE_TYPE, "service-type");
254 p_interface_path = props.getProperty(P_INTERFACE_PATH);
256 vnf_image_query_path = props.getProperty(VNF_IMAGE_QUERY_PATH);
258 ubb_notify_path = props.getProperty(UBB_NOTIFY_PATH);
259 selflink_avpn = props.getProperty(SELFLINK_AVPN);
260 selflink_fqdn = props.getProperty(SELFLINK_FQDN);
262 service_path = props.getProperty(SERVICE_PATH);
264 site_pair_set_path = props.getProperty(SITE_PAIR_SET_PATH);
266 query_nodes_path = props.getProperty(QUERY_NODES_PATH);
268 String iche = props.getProperty(CERTIFICATE_HOST_ERROR);
269 boolean host_error = false;
270 if(iche != null && !iche.isEmpty()) {
271 host_error = Boolean.valueOf(iche);
274 ignore_certificate_host_error = host_error;
276 HttpsURLConnection.setDefaultHostnameVerifier( new HostnameVerifier(){
277 public boolean verify(String string,SSLSession ssls) {
278 return ignore_certificate_host_error;
282 if(truststore_path != null && truststore_password != null && (new File(truststore_path)).exists()) {
283 System.setProperty("javax.net.ssl.trustStore", truststore_path);
284 System.setProperty("javax.net.ssl.trustStorePassword", truststore_password);
287 if(keystore_path != null && keystore_password != null && (new File(keystore_path)).exists())
289 DefaultClientConfig config = new DefaultClientConfig();
290 //both jersey and HttpURLConnection can use this
291 SSLContext ctx = null;
293 ctx = SSLContext.getInstance("TLS");
295 KeyManagerFactory kmf = null;
297 String def = "SunX509";
298 String storeType = "PKCS12";
299 def = KeyStore.getDefaultType();
300 kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
301 FileInputStream fin = new FileInputStream(keystore_path);
302 // KeyStore ks = KeyStore.getInstance("PKCS12");
304 String extension = keystore_path.substring(keystore_path.lastIndexOf(".") + 1);
306 if(extension != null && !extension.isEmpty() && extension.equalsIgnoreCase("JKS")) {
309 KeyStore ks = KeyStore.getInstance(storeType);
311 char[] pwd = keystore_password.toCharArray();
314 } catch (Exception ex) {
315 LOG.error("AAIResource", ex);
318 ctx.init(kmf.getKeyManagers(), null, null);
319 config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties( new HostnameVerifier() {
321 public boolean verify( String s, SSLSession sslSession ) {
322 return ignore_certificate_host_error;
327 LOG.debug("SSLContext created");
329 } catch (KeyManagementException | NoSuchAlgorithmException exc) {
330 LOG.error("AAIResource", exc);
334 LOG.info("AAIResource.ctor initialized.");
337 Field methodsField = HttpURLConnection.class.getDeclaredField("methods");
338 methodsField.setAccessible(true);
339 // get the methods field modifiers
340 Field modifiersField = Field.class.getDeclaredField("modifiers");
341 // bypass the "private" modifier
342 modifiersField.setAccessible(true);
344 // remove the "final" modifier
345 modifiersField.setInt(methodsField, methodsField.getModifiers() & ~Modifier.FINAL);
347 /* valid HTTP methods */
349 "GET", "POST", "HEAD", "OPTIONS", "PUT", "DELETE", "TRACE", "PATCH"
351 // set the new methods - including patch
352 methodsField.set(null, methods);
354 } catch (SecurityException | IllegalArgumentException | IllegalAccessException | NoSuchFieldException e) {
360 public void cleanUp() {
366 * @param http_req_url
371 protected HttpURLConnection getConfiguredConnection(URL http_req_url, String method) throws Exception {
372 HttpURLConnection con = (HttpURLConnection) http_req_url.openConnection();
374 // Set up the connection properties
375 con.setRequestProperty( "Connection", "close" );
376 con.setDoInput(true);
377 con.setDoOutput(true);
378 con.setUseCaches(false);
379 con.setConnectTimeout( connection_timeout );
380 con.setReadTimeout( read_timeout );
381 con.setRequestMethod( method );
382 con.setRequestProperty( "Accept", "application/json" );
383 con.setRequestProperty( "Content-Type", "PATCH".equalsIgnoreCase(method) ? "application/merge-patch+json" : "application/json" );
384 con.setRequestProperty("X-FromAppId", application_id);
385 con.setRequestProperty("X-TransactionId",TransactionIdTracker.getNextTransactionId());
386 con.setRequestProperty(MetricLogger.REQUEST_ID, ml.getRequestID());
388 if(user_name != null && !user_name.isEmpty() && user_password != null && !user_password.isEmpty()) {
389 String basicAuth = "Basic " + new String(Base64.encodeBase64((user_name + ":" + user_password).getBytes()));
390 con.setRequestProperty ("Authorization", basicAuth);
393 if(con instanceof HttpsURLConnection && CTX != null) {
394 SSLSocketFactory sockFact = CTX.getSocketFactory();
395 HttpsURLConnection.class.cast(con).setSSLSocketFactory( sockFact );
402 public GenericVnf requestGenericVnfData(String vnf_id) throws AAIServiceException {
403 GenericVnf response = null;
406 AAIRequest request = AAIRequest.getRequestFromResource("generic-vnf");
407 request.addRequestProperty("generic-vnf.vnf-id", vnf_id);
408 String rv = executor.get(request);
410 ObjectMapper mapper = getObjectMapper();
411 response = mapper.readValue(rv, GenericVnf.class);
413 } catch(AAIServiceException aaiexc) {
415 } catch (Exception exc) {
416 LOG.warn(new Object(){}.getClass().getEnclosingMethod().getName(), exc);
417 throw new AAIServiceException(exc);
425 public boolean postGenericVnfData(String vnf_id, GenericVnf data) throws AAIServiceException {
427 AAIRequest request = AAIRequest.getRequestFromResource("generic-vnf");
428 request.addRequestProperty("generic-vnf.vnf-id", vnf_id);
429 request.setRequestObject(data);
430 Object response = executor.post(request);
432 } catch(AAIServiceException aaiexc) {
434 } catch (Exception exc) {
435 LOG.warn("requestGenericVnfData", exc);
436 throw new AAIServiceException(exc);
441 public boolean deleteGenericVnfData(String vnf_id, String resourceVersion) throws AAIServiceException {
442 boolean response = false;
445 AAIRequest request = AAIRequest.getRequestFromResource("generic-vnf");
446 request.addRequestProperty("generic-vnf.vnf-id", vnf_id);
447 response = executor.delete(request, resourceVersion);
448 } catch(AAIServiceException aaiexc) {
450 } catch (Exception exc) {
451 LOG.warn("deleteGenericVnfData", exc);
452 throw new AAIServiceException(exc);
458 * @see org.onap.ccsdk.sli.adaptors.resource.aic.AnAIClient#requestSdnZoneQuery(java.lang.String, java.lang.String, java.lang.String)
461 public Vce requestNetworkVceData(String vnf_id) throws AAIServiceException {
464 AAIRequest request = AAIRequest.getRequestFromResource("vce");
465 request.addRequestProperty("vce.vnf-id", vnf_id);
466 String rv = executor.get(request);
468 ObjectMapper mapper = getObjectMapper();
469 response = mapper.readValue(rv, Vce.class);
471 } catch(AAIServiceException aaiexc) {
473 } catch (Exception exc) {
474 LOG.warn(new Object(){}.getClass().getEnclosingMethod().getName(), exc);
475 throw new AAIServiceException(exc);
483 * @see org.onap.ccsdk.sli.adaptors.resource.aic.AnAIClient#requestSdnZoneQuery(java.lang.String, java.lang.String, java.lang.String)
486 public boolean deleteNetworkVceData(String vnf_id, String resourceVersion) throws AAIServiceException {
487 boolean response = false;
490 AAIRequest request = AAIRequest.getRequestFromResource("vce");
491 request.addRequestProperty("vce.vnf-id", vnf_id);
492 response = executor.delete(request, resourceVersion);
493 } catch(AAIServiceException aaiexc) {
495 } catch (Exception exc) {
496 LOG.warn("deleteNetworkVceData", exc);
497 throw new AAIServiceException(exc);
503 * @see org.onap.ccsdk.sli.adaptors.resource.aic.AnAIClient#postNetworkVceData(java.lang.String, org.onap.ccsdk.sli.adaptors.resource.aic.aai.VCERequest)
506 public boolean postNetworkVceData(String vnf_id, Vce data) throws AAIServiceException {
508 AAIRequest request = AAIRequest.getRequestFromResource("vce");
509 request.addRequestProperty("vce.vnf-id", vnf_id);
510 request.setRequestObject(data);
511 Object response = executor.post(request);
513 } catch(AAIServiceException aaiexc) {
515 } catch (Exception exc) {
516 LOG.warn("requestGenericVnfData", exc);
517 throw new AAIServiceException(exc);
523 public SearchResults requestServiceInstanceURL(String svc_instance_id) throws AAIServiceException {
524 SearchResults response = null;
525 InputStream inputStream = null;
528 String path = svc_inst_qry_path;
529 path = path.replace("{svc-instance-id}", encodeQuery(svc_instance_id));
531 String request_url = target_uri+path;
532 URL http_req_url = new URL(request_url);
534 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.GET);
536 LOGwriteFirstTrace(HttpMethod.GET, http_req_url.toString());
537 LOGwriteDateTrace("svc_instance_id", svc_instance_id);
540 int responseCode = con.getResponseCode();
541 if (responseCode == HttpURLConnection.HTTP_OK) {
542 inputStream = con.getInputStream();
544 inputStream = con.getErrorStream();
547 // Process the response
548 LOG.debug("HttpURLConnection result:" + responseCode);
549 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
550 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
552 ObjectMapper mapper = getObjectMapper();
554 if (responseCode == HttpURLConnection.HTTP_OK) {
555 // StringBuilder stringBuilder = new StringBuilder("\n");
556 // String line = null;
557 // while( ( line = reader.readLine() ) != null ) {
558 // stringBuilder.append("\n").append( line );
560 // LOG.info(stringBuilder.toString());
561 response = mapper.readValue(reader, SearchResults.class);
562 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, "SUCCESS", mapper.writeValueAsString(response));
563 } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
564 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
567 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
568 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
569 throw new AAIServiceException(responseCode, errorresponse);
572 } catch(AAIServiceException aaiexc) {
574 } catch (Exception exc) {
575 LOG.warn("requestServiceInstanceURL", exc);
576 throw new AAIServiceException(exc);
578 if(inputStream != null){
581 } catch(Exception exc) {
590 public ServiceInstance requestServiceInterfaceData(String customer_id, String service_type, String svc_instance_id) throws AAIServiceException {
591 ServiceInstance response = null;
594 AAIRequest request = AAIRequest.getRequestFromResource("service-instance");
595 request.addRequestProperty("customer.global-customer-id", customer_id);
596 request.addRequestProperty("ervice-subscription.service-type", service_type);
597 request.addRequestProperty("service-instance.service-instance-id", svc_instance_id);
599 String rv = executor.get(request);
601 ObjectMapper mapper = getObjectMapper();
602 response = mapper.readValue(rv, ServiceInstance.class);
604 } catch(AAIServiceException aaiexc) {
606 } catch (Exception exc) {
607 LOG.warn("requestServiceInterfaceData", exc);
608 throw new AAIServiceException(exc);
614 public boolean postServiceInterfaceData(String customer_id, String service_type, String svc_instance_id, ServiceInstance data) throws AAIServiceException {
616 AAIRequest request = AAIRequest.getRequestFromResource("service-instance");
617 request.addRequestProperty("customer.customer-id", customer_id);
618 request.addRequestProperty("service-subscription.service-type", service_type);
619 request.addRequestProperty("service-instance.service-instance-id", svc_instance_id);
620 request.setRequestObject(data);
621 Object response = executor.post(request);
623 } catch(AAIServiceException aaiexc) {
625 } catch (Exception exc) {
626 LOG.warn("requestGenericVnfData", exc);
627 throw new AAIServiceException(exc);
632 private static Properties initialize(URL url ) throws ConfigurationException {
635 throw new NullPointerException();
638 InputStream is = null;
639 Properties props = new Properties();
642 if(LOG.isDebugEnabled())
643 LOG.info("Property file is: " + url.toString());
645 is = url.openStream();
648 if(LOG.isDebugEnabled()) {
649 LOG.info("Properties loaded: " + props.size());
650 Enumeration<Object> en = props.keys();
652 while(en.hasMoreElements()) {
653 String key = (String)en.nextElement();
654 String property = props.getProperty(key);
655 LOG.debug(key + " : " + property);
658 } catch (Exception e) {
659 throw new ConfigurationException("Could not load properties file.", e);
664 static class TransactionIdTracker {
665 // protected static AtomicLong tracker = new AtomicLong();
667 public static String getNextTransactionId() {
668 // long id = tracker.getAndIncrement();
669 // String transactionId = String.format("N%016X", id);
670 String transactionId = UUID.randomUUID().toString();
671 return transactionId;
676 protected void LOGwriteFirstTrace(String method, String url) {
677 String time = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").format(System.currentTimeMillis());
678 LOG.info("A&AI transaction :");
679 LOG.info("Request Time : " + time + ", Method : " + method);
680 LOG.info("Request URL : "+ url);
683 protected void LOGwriteDateTrace(String name, String data) {
684 LOG.info("Input - " + name + " : " + data);
687 protected void LOGwriteEndingTrace(int response_code, String comment, String data) {
688 LOG.info("Response code : " + response_code +", " + comment);
689 LOG.info(String.format("Response data : %s", data));
692 protected String encodeQuery(String param) throws UnsupportedEncodingException {
693 return URLEncoder.encode(param, "UTF-8").replace("+", "%20");
696 private String encodeCustomerURL(final String selection)
698 String encrypted_url = selection;
700 "/aai/v10/business/customers/customer/(.+)/service-subscriptions/service-subscription/(.+)/service-instances/service-instance/(.+)/";
701 Pattern pattern = Pattern.compile(apnpattern);
704 URL url = new URL(selection);
705 String path = url.getPath();
707 LOG.info("Trying to match apn to <" + path + ">");
709 Matcher matcher = pattern.matcher(path);
711 while(matcher.find()) {
712 String customer = matcher.group(1);
713 String subscription = matcher.group(2);
714 String service = matcher.group(3);
716 encrypted_url = selection.replace(customer, encodeQuery(customer));
717 encrypted_url = encrypted_url.replace(subscription, encodeQuery(subscription));
718 encrypted_url = encrypted_url.replace(service, encodeQuery(service));
720 } catch (Exception e) {
724 return encrypted_url;
728 public Vpe requestNetworkVpeData(String vnf_id) throws AAIServiceException {
732 AAIRequest request = AAIRequest.getRequestFromResource("vpe");
733 request.addRequestProperty("vpe.vnf-id", vnf_id);
734 String rv = executor.get(request);
736 ObjectMapper mapper = getObjectMapper();
737 response = mapper.readValue(rv, Vpe.class);
739 } catch(AAIServiceException aaiexc) {
741 } catch (Exception exc) {
742 LOG.warn(new Object(){}.getClass().getEnclosingMethod().getName(), exc);
743 throw new AAIServiceException(exc);
749 public boolean postNetworkVpeData(String vnf_id, Vpe data) throws AAIServiceException {
751 AAIRequest request = AAIRequest.getRequestFromResource("vpe");
752 request.addRequestProperty("vpe.vnf-id", vnf_id);
753 request.setRequestObject(data);
754 Object response = executor.post(request);
756 } catch(AAIServiceException aaiexc) {
758 } catch (Exception exc) {
759 LOG.warn(new Object(){}.getClass().getEnclosingMethod().getName(), exc);
760 throw new AAIServiceException(exc);
765 public boolean deleteNetworkVpeData(String vnf_id, String resourceVersion) throws AAIServiceException {
766 boolean response = false;
769 AAIRequest request = AAIRequest.getRequestFromResource("vpe");
770 request.addRequestProperty("vpe.vnf-id", vnf_id);
771 response = executor.delete(request, resourceVersion);
772 } catch(AAIServiceException aaiexc) {
774 } catch (Exception exc) {
775 LOG.warn(new Object(){}.getClass().getEnclosingMethod().getName(), exc);
776 throw new AAIServiceException(exc);
782 public VplsPe requestNetworkVplsPeData(String equipment_name)throws AAIServiceException {
783 VplsPe response = null;
786 AAIRequest request = AAIRequest.getRequestFromResource("vpls-pe");
787 request.addRequestProperty("vpls-pe.equipment-name", equipment_name);
789 String rv = executor.get(request);
791 ObjectMapper mapper = getObjectMapper();
792 response = mapper.readValue(rv, VplsPe.class);
794 } catch(AAIServiceException aaiexc) {
796 } catch (Exception exc) {
797 LOG.warn(new Object(){}.getClass().getEnclosingMethod().getName(), exc);
798 throw new AAIServiceException(exc);
804 public boolean postNetworkVplsPeData(String equipment_name, VplsPe data) throws AAIServiceException {
806 AAIRequest request = AAIRequest.getRequestFromResource("vpls-pe");
807 request.addRequestProperty("vpls-pe.equipment-name", equipment_name);
808 request.setRequestObject(data);
809 Object response = executor.post(request);
811 } catch(AAIServiceException aaiexc) {
813 } catch (Exception exc) {
814 LOG.warn("requestGenericVnfData", exc);
815 throw new AAIServiceException(exc);
820 public boolean deleteNetworkVplsPeData(String vnf_id, String resourceVersion) throws AAIServiceException {
821 boolean response = false;
824 AAIRequest request = AAIRequest.getRequestFromResource("vpls-pe");
825 request.addRequestProperty("vpls-pe.equipment-name", vnf_id);
826 response = executor.delete(request, resourceVersion);
827 } catch(AAIServiceException aaiexc) {
829 } catch (Exception exc) {
830 LOG.warn("deleteNetworkVplsPeData", exc);
831 throw new AAIServiceException(exc);
837 public Complex requestNetworkComplexData(String pLocId) throws AAIServiceException {
838 Complex response = null;
839 InputStream inputStream = null;
842 AAIRequest request = AAIRequest.getRequestFromResource("complex");
843 request.addRequestProperty("complex.physical-location-id", pLocId);
845 String rv = executor.get(request);
847 ObjectMapper mapper = getObjectMapper();
848 response = mapper.readValue(rv, Complex.class);
850 } catch(AAIServiceException aaiexc) {
852 } catch (Exception exc) {
853 LOG.warn("requestNetworkComplexData", exc);
854 throw new AAIServiceException(exc);
856 if(inputStream != null){
859 } catch(Exception exc) {
868 public boolean postNetworkComplexData(String vnf_id, Complex data) throws AAIServiceException {
870 AAIRequest request = AAIRequest.getRequestFromResource("complex");
871 request.addRequestProperty("complex.physical-location-id", vnf_id);
872 request.setRequestObject(data);
873 Object response = executor.post(request);
875 } catch(AAIServiceException aaiexc) {
877 } catch (Exception exc) {
878 LOG.warn("postNetworkComplexData", exc);
879 throw new AAIServiceException(exc);
884 public boolean deleteNetworkComplexData(String pLocId, String resourceVersion) throws AAIServiceException {
885 boolean response = false;
888 AAIRequest request = AAIRequest.getRequestFromResource("complex");
889 request.addRequestProperty("complex.physical-location-id", pLocId);
891 response = executor.delete(request, resourceVersion);
893 } catch(AAIServiceException aaiexc) {
895 } catch (Exception exc) {
896 LOG.warn("deleteNetworkComplexData", exc);
897 throw new AAIServiceException(exc);
904 * @see org.openecomp.sdnct.sli.aai.AAIClient#requestVServersData(java.lang.String, java.lang.String)
907 public Vserver requestVServerData(String tenantId, String vserverId, String cloudOwner, String cloudRegionId) throws AAIServiceException {
908 Vserver response = null;
911 AAIRequest request = AAIRequest.getRequestFromResource("vserver");
912 request.addRequestProperty("cloud-region.cloud-owner", cloudOwner);
913 request.addRequestProperty("cloud-region.cloud-region-id", cloudRegionId);
914 request.addRequestProperty("tenant.tenant-id", tenantId);
915 request.addRequestProperty("vserver.vserver-id", vserverId);
917 String rv = executor.get(request);
919 ObjectMapper mapper = getObjectMapper();
920 response = mapper.readValue(rv, Vserver.class);
922 } catch(AAIServiceException aaiexc) {
924 } catch (Exception exc) {
925 LOG.warn(new Object(){}.getClass().getEnclosingMethod().getName(), exc);
926 throw new AAIServiceException(exc);
933 public boolean postVServerData(String tenantId, String vserverId, String cloudOwner, String cloudRegionId, Vserver data) throws AAIServiceException {
935 AAIRequest request = AAIRequest.getRequestFromResource("vserver");
936 request.addRequestProperty("cloud-region.cloud-owner", cloudOwner);
937 request.addRequestProperty("cloud-region.cloud-region-id", cloudRegionId);
938 request.addRequestProperty("tenant.tenant-id", tenantId);
939 request.addRequestProperty("vserver.vserver-id", vserverId);
940 request.setRequestObject(data);
941 Object response = executor.post(request);
943 } catch(AAIServiceException aaiexc) {
945 } catch (Exception exc) {
946 LOG.warn("postNetworkComplexData", exc);
947 throw new AAIServiceException(exc);
952 public boolean deleteVServerData(String tenant_id, String vserver_id, String cloudOwner, String cloudRegionId, String resourceVersion) throws AAIServiceException {
953 boolean response = false;
954 InputStream inputStream = null;
957 String local_network_complexes_path = network_vserver_path.replace("{tenant-id}", encodeQuery(tenant_id));
958 local_network_complexes_path = local_network_complexes_path.replace("{vserver-id}", encodeQuery(vserver_id));
959 local_network_complexes_path = local_network_complexes_path.replace("{cloud-owner}", encodeQuery(cloudOwner));
960 local_network_complexes_path = local_network_complexes_path.replace("{cloud-region-id}", encodeQuery(cloudRegionId));
962 String request_url = target_uri+local_network_complexes_path;
963 if(resourceVersion!=null) {
964 request_url = request_url +"?resource-version="+resourceVersion;
966 URL http_req_url = new URL(request_url);
968 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.DELETE);
970 LOGwriteFirstTrace(HttpMethod.DELETE, http_req_url.toString());
971 LOGwriteDateTrace("tenant_id", tenant_id);
972 LOGwriteDateTrace("vserver_id", vserver_id);
973 LOGwriteDateTrace("cloud-owner", cloudOwner);
974 LOGwriteDateTrace("cloud-region-id", cloudRegionId);
977 int responseCode = con.getResponseCode();
978 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
979 inputStream = con.getInputStream();
981 inputStream = con.getErrorStream();
984 // Process the response
985 LOG.debug("HttpURLConnection result:" + responseCode);
986 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
987 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
990 ObjectMapper mapper = getObjectMapper();
992 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
993 StringBuilder stringBuilder = new StringBuilder();
995 while( ( line = reader.readLine() ) != null ) {
996 stringBuilder.append( line );
998 LOGwriteEndingTrace(responseCode, "SUCCESS", stringBuilder.toString());
1000 } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
1001 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
1004 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
1005 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
1006 throw new AAIServiceException(responseCode, errorresponse);
1009 } catch(AAIServiceException aaiexc) {
1011 } catch (Exception exc) {
1012 LOG.warn("deleteVServerData", exc);
1013 throw new AAIServiceException(exc);
1015 if(inputStream != null){
1017 inputStream.close();
1018 } catch(Exception exc) {
1029 * @see org.onap.ccsdk.sli.adaptors.aai.AAIClient#requestCtagPoolData(String)
1032 public CtagPool requestCtagPoolData(String physical_location_id, String target_pe, String availability_zone_name) throws AAIServiceException {
1033 CtagPool response = null;
1036 AAIRequest request = AAIRequest.getRequestFromResource("ctag-pool");
1038 request.addRequestProperty("ctag-pool.target-pe", target_pe);
1039 request.addRequestProperty("ctag-pool.availability-zone-name", availability_zone_name);
1040 request.addRequestProperty("complex.physical-location-id", physical_location_id);
1042 String rv = executor.get(request);
1044 ObjectMapper mapper = getObjectMapper();
1045 response = mapper.readValue(rv, CtagPool.class);
1047 } catch(AAIServiceException aaiexc) {
1049 } catch (Exception exc) {
1050 LOG.warn("requestNetworkVceData", exc);
1051 throw new AAIServiceException(exc);
1056 //==================== DvsSwitch ======================
1058 public DvsSwitch requestDvsSwitchData(String vnf_id) throws AAIServiceException {
1059 DvsSwitch response = null;
1060 InputStream inputStream = null;
1063 AAIRequest request = AAIRequest.getRequestFromResource("dvs-switch");
1064 request.addRequestProperty("dvs-switch.switch-name", vnf_id);
1066 String rv = executor.get(request);
1068 ObjectMapper mapper = getObjectMapper();
1069 response = mapper.readValue(rv, DvsSwitch.class);
1071 } catch(AAIServiceException aaiexc) {
1073 } catch (Exception exc) {
1074 LOG.warn("requestDvsSwitchData", exc);
1075 throw new AAIServiceException(exc);
1077 if(inputStream != null){
1079 inputStream.close();
1080 } catch(Exception exc) {
1089 public boolean postDvsSwitchData(String switch_name, DvsSwitch data) throws AAIServiceException {
1091 AAIRequest request = AAIRequest.getRequestFromResource("dvs-switch");
1092 request.addRequestProperty("dvs-switch.switch-name", switch_name);
1093 request.setRequestObject(data);
1094 Object response = executor.post(request);
1096 } catch(AAIServiceException aaiexc) {
1098 } catch (Exception exc) {
1099 LOG.warn(new Object(){}.getClass().getEnclosingMethod().getName(), exc);
1100 throw new AAIServiceException(exc);
1105 public boolean deleteDvsSwitchData(String vnf_id, String resourceVersion) throws AAIServiceException {
1106 boolean response = false;
1107 InputStream inputStream = null;
1110 AAIRequest request = AAIRequest.getRequestFromResource("dvs-switch");
1111 request.addRequestProperty("dvs-switch.switch-name", vnf_id);
1112 response = executor.delete(request, resourceVersion);
1113 } catch(AAIServiceException aaiexc) {
1115 } catch (Exception exc) {
1116 LOG.warn("deleteDvsSwitchData", exc);
1117 throw new AAIServiceException(exc);
1121 //================== End of DvsSwitch =================
1122 //==================== PhysicalLink ======================
1124 public PhysicalLink requestPhysicalLinkData(String linkName) throws AAIServiceException {
1125 PhysicalLink response = null;
1128 AAIRequest request = AAIRequest.getRequestFromResource("physical-link");
1129 request.addRequestProperty("physical-link.link-name", linkName);
1131 String rv = executor.get(request);
1133 ObjectMapper mapper = getObjectMapper();
1134 response = mapper.readValue(rv, PhysicalLink.class);
1136 } catch(AAIServiceException aaiexc) {
1138 } catch (Exception exc) {
1139 LOG.warn("requestPhysicalLinkData", exc);
1140 throw new AAIServiceException(exc);
1146 public boolean postPhysicalLinkData(String linkName, PhysicalLink data) throws AAIServiceException {
1148 AAIRequest request = AAIRequest.getRequestFromResource("physical-link");
1149 request.addRequestProperty("physical-link.link-name", linkName);
1150 request.setRequestObject(data);
1151 Object response = executor.post(request);
1153 } catch(AAIServiceException aaiexc) {
1155 } catch (Exception exc) {
1156 LOG.warn(new Object(){}.getClass().getEnclosingMethod().getName(), exc);
1157 throw new AAIServiceException(exc);
1162 public boolean deletePhysicalLinkData(String linkName, String resourceVersion) throws AAIServiceException {
1163 boolean response = false;
1166 AAIRequest request = AAIRequest.getRequestFromResource("physical-link");
1167 request.addRequestProperty("physical-link.link-name", linkName);
1168 response = executor.delete(request, resourceVersion);
1169 } catch(AAIServiceException aaiexc) {
1171 } catch (Exception exc) {
1172 LOG.warn("deletePhysicalLinkData", exc);
1173 throw new AAIServiceException(exc);
1177 //================== End of PhysicalLink =================
1178 //==================== PInterface ======================
1180 public PInterface requestPInterfaceData(String hostname, String interfaceName) throws AAIServiceException {
1181 PInterface response = null;
1184 AAIRequest request = new PInterfaceRequest();
1185 request.addRequestProperty(PInterfaceRequest.PINTERFACE_INTERFACE_NAME, interfaceName);
1186 request.addRequestProperty(PInterfaceRequest.PSERVER_HOSTNAME, hostname);
1187 String rv = executor.get(request);
1189 ObjectMapper mapper = getObjectMapper();
1190 response = mapper.readValue(rv, PInterface.class);
1192 } catch(AAIServiceException aaiexc) {
1194 } catch (Exception exc) {
1195 LOG.warn(new Object(){}.getClass().getEnclosingMethod().getName(), exc);
1196 throw new AAIServiceException(exc);
1202 public boolean postPInterfaceData(String hostname, String interfaceName, PInterface request) throws AAIServiceException {
1203 InputStream inputStream = null;
1207 ObjectMapper mapper = getObjectMapper();
1208 String json_text = mapper.writeValueAsString(request);
1210 SSLSocketFactory sockFact = CTX.getSocketFactory();
1212 String request_url = target_uri+p_interface_path;
1213 String encoded_vnf = encodeQuery(hostname);
1214 request_url = request_url.replace("{hostname}", encoded_vnf) ;
1215 encoded_vnf = encodeQuery(interfaceName);
1216 request_url = request_url.replace("{interface-name}", encoded_vnf) ;
1217 URL http_req_url = new URL(request_url);
1219 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.PUT);
1221 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
1222 osw.write(json_text);
1227 LOGwriteFirstTrace("PUT", request_url);
1228 LOGwriteDateTrace("hostname", hostname);
1229 LOGwriteDateTrace("interface-name", interfaceName);
1230 LOGwriteDateTrace("PInterface", json_text);
1233 int responseCode = con.getResponseCode();
1234 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1235 inputStream = con.getInputStream();
1237 inputStream = con.getErrorStream();
1240 // Process the response
1241 BufferedReader reader;
1243 reader = new BufferedReader( new InputStreamReader( inputStream ) );
1245 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1246 StringBuilder stringBuilder = new StringBuilder();
1248 while( ( line = reader.readLine() ) != null ) {
1249 stringBuilder.append( line );
1251 LOGwriteEndingTrace(responseCode, "SUCCESS", (stringBuilder != null) ? stringBuilder.toString() : "{no-data}");
1254 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
1255 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
1257 throw new AAIServiceException(responseCode, errorresponse);
1259 } catch(AAIServiceException aaiexc) {
1261 } catch (Exception exc) {
1262 LOG.warn("postPInterfaceData", exc);
1263 throw new AAIServiceException(exc);
1266 if(inputStream != null)
1267 inputStream.close();
1268 } catch (Exception exc) {
1275 public boolean deletePInterfaceData(String hostname, String interfaceName, String resourceVersion) throws AAIServiceException {
1276 boolean response = false;
1279 AAIRequest request = AAIRequest.getRequestFromResource("p-interface");
1280 request.addRequestProperty("p-interface.interface-name", interfaceName);
1281 request.addRequestProperty("pserver.hostname", hostname);
1282 response = executor.delete(request, resourceVersion);
1283 } catch(AAIServiceException aaiexc) {
1285 } catch (Exception exc) {
1286 LOG.warn("deletePInterfaceData", exc);
1287 throw new AAIServiceException(exc);
1291 //================== End of PInterface =================
1292 //==================== SitePairSet ======================
1294 public SitePairSet requestSitePairSetData(String sitePairSetId) throws AAIServiceException {
1295 SitePairSet response = null;
1298 AAIRequest request = AAIRequest.getRequestFromResource("site-pair-set");
1299 request.addRequestProperty("site-pair-set.site-pair-set-id", sitePairSetId);
1300 String rv = executor.get(request);
1302 ObjectMapper mapper = getObjectMapper();
1303 response = mapper.readValue(rv, SitePairSet.class);
1305 } catch(AAIServiceException aaiexc) {
1307 } catch (Exception exc) {
1308 LOG.warn(new Object(){}.getClass().getEnclosingMethod().getName(), exc);
1309 throw new AAIServiceException(exc);
1315 public boolean postSitePairSetData(String linkName, SitePairSet request) throws AAIServiceException {
1316 InputStream inputStream = null;
1320 ObjectMapper mapper = getObjectMapper();
1321 String json_text = mapper.writeValueAsString(request);
1323 SSLSocketFactory sockFact = CTX.getSocketFactory();
1325 String request_url = target_uri+site_pair_set_path;
1326 String encoded_vnf = encodeQuery(linkName);
1327 request_url = request_url.replace("{site-pair-set-id}", encoded_vnf) ;
1328 URL http_req_url = new URL(request_url);
1330 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.PUT);
1332 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
1333 osw.write(json_text);
1338 LOGwriteFirstTrace("PUT", request_url);
1339 LOGwriteDateTrace("link-name", linkName);
1340 LOGwriteDateTrace("SitePairSet", json_text);
1343 int responseCode = con.getResponseCode();
1344 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1345 inputStream = con.getInputStream();
1347 inputStream = con.getErrorStream();
1350 // Process the response
1351 BufferedReader reader;
1353 reader = new BufferedReader( new InputStreamReader( inputStream ) );
1355 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1356 StringBuilder stringBuilder = new StringBuilder();
1358 while( ( line = reader.readLine() ) != null ) {
1359 stringBuilder.append( line );
1361 LOGwriteEndingTrace(responseCode, "SUCCESS", (stringBuilder != null) ? stringBuilder.toString() : "{no-data}");
1364 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
1365 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
1367 throw new AAIServiceException(responseCode, errorresponse);
1369 } catch(AAIServiceException aaiexc) {
1371 } catch (Exception exc) {
1372 LOG.warn("postSitePairSetData", exc);
1373 throw new AAIServiceException(exc);
1376 if(inputStream != null)
1377 inputStream.close();
1378 } catch (Exception exc) {
1385 public boolean deleteSitePairSetData(String linkName, String resourceVersion) throws AAIServiceException {
1386 boolean response = false;
1389 AAIRequest request = AAIRequest.getRequestFromResource("site-pair-set");
1390 request.addRequestProperty("site-pair-set.site-pair-set-id", linkName);
1391 response = executor.delete(request, resourceVersion);
1392 } catch(AAIServiceException aaiexc) {
1394 } catch (Exception exc) {
1395 LOG.warn("deleteSitePairSetData", exc);
1396 throw new AAIServiceException(exc);
1401 //================== End of SitePairSet =================
1402 //==================== Service ======================
1404 public Service requestServiceData(String serviceId) throws AAIServiceException {
1405 Service response = null;
1406 InputStream inputStream = null;
1409 AAIRequest request = AAIRequest.getRequestFromResource("service");
1410 request.addRequestProperty("service.service-id", serviceId);
1413 String rv = executor.get(request);
1415 ObjectMapper mapper = getObjectMapper();
1416 response = mapper.readValue(rv, Service.class);
1418 } catch(AAIServiceException aaiexc) {
1420 } catch (Exception exc) {
1421 LOG.warn("requestServiceData", exc);
1422 throw new AAIServiceException(exc);
1428 public boolean postServiceData(String linkName, Service request) throws AAIServiceException {
1429 InputStream inputStream = null;
1433 ObjectMapper mapper = getObjectMapper();
1434 String json_text = mapper.writeValueAsString(request);
1436 SSLSocketFactory sockFact = CTX.getSocketFactory();
1438 String request_url = target_uri+service_path;
1439 String encoded_vnf = encodeQuery(linkName);
1440 request_url = request_url.replace("{service-id}", encoded_vnf) ;
1441 URL http_req_url = new URL(request_url);
1443 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.PUT);
1445 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
1446 osw.write(json_text);
1451 LOGwriteFirstTrace("PUT", request_url);
1452 LOGwriteDateTrace("service-id", linkName);
1453 LOGwriteDateTrace("Service", json_text);
1456 int responseCode = con.getResponseCode();
1457 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1458 inputStream = con.getInputStream();
1460 inputStream = con.getErrorStream();
1463 // Process the response
1464 BufferedReader reader;
1466 reader = new BufferedReader( new InputStreamReader( inputStream ) );
1468 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1469 StringBuilder stringBuilder = new StringBuilder();
1471 while( ( line = reader.readLine() ) != null ) {
1472 stringBuilder.append( line );
1474 LOGwriteEndingTrace(responseCode, "SUCCESS", (stringBuilder != null) ? stringBuilder.toString() : "{no-data}");
1477 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
1478 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
1480 throw new AAIServiceException(responseCode, errorresponse);
1482 } catch(AAIServiceException aaiexc) {
1484 } catch (Exception exc) {
1485 LOG.warn("postServiceData", exc);
1486 throw new AAIServiceException(exc);
1489 if(inputStream != null)
1490 inputStream.close();
1491 } catch (Exception exc) {
1498 public boolean deleteServiceData(String service_id, String resourceVersion) throws AAIServiceException {
1499 boolean response = false;
1502 AAIRequest request = AAIRequest.getRequestFromResource("service");
1503 request.addRequestProperty("service.service-id", service_id);
1504 response = executor.delete(request, resourceVersion);
1505 } catch(AAIServiceException aaiexc) {
1507 } catch (Exception exc) {
1508 LOG.warn("deleteServiceData", exc);
1509 throw new AAIServiceException(exc);
1514 //================== End of Service =================
1520 public VServer dataChangeRequestVServerData(URL url) throws AAIServiceException {
1523 throw new NullPointerException();
1526 return this.getResource(url.toString(), VServer.class);
1530 public Pserver dataChangeRequestPServerData(URL url) throws AAIServiceException {
1533 throw new NullPointerException();
1536 return this.getResource(url.toString(), Pserver.class);
1540 public CtagPool dataChangeRequestCtagPoolData(URL url) throws AAIServiceException {
1543 throw new NullPointerException();
1546 return this.getResource(url.toString(), CtagPool.class);
1550 public VplsPe dataChangeRequestVplsPeData(URL url) throws AAIServiceException {
1553 throw new NullPointerException();
1556 return this.getResource(url.toString(), VplsPe.class);
1560 public Vpe dataChangeRequestVpeData(URL url) throws AAIServiceException {
1563 throw new NullPointerException();
1566 return this.getResource(url.toString(), Vpe.class);
1570 public DvsSwitch dataChangeRequestDvsSwitchData(URL url) throws AAIServiceException {
1573 throw new NullPointerException();
1576 return this.getResource(url.toString(), DvsSwitch.class);
1580 public OamNetwork dataChangeRequestOAMNetworkData(URL url) throws AAIServiceException {
1583 throw new NullPointerException();
1586 return this.getResource(url.toString(), OamNetwork.class);
1590 public AvailabilityZone dataChangeRequestAvailabilityZoneData(URL url) throws AAIServiceException {
1593 throw new NullPointerException();
1596 return this.getResource(url.toString(), AvailabilityZone.class);
1600 public Complex dataChangeRequestComplexData(URL url) throws AAIServiceException {
1603 throw new NullPointerException();
1606 return this.getResource(url.toString(), Complex.class);
1610 public boolean dataChangeDeleteVServerData(URL url) throws AAIServiceException {
1613 throw new NullPointerException();
1616 return deleteAAIEntity(url, new Object(){}.getClass().getEnclosingMethod().getName());
1619 public boolean dataChangeDeleteCtagPoolData(URL url) throws AAIServiceException {
1622 throw new NullPointerException();
1625 return deleteAAIEntity(url, new Object(){}.getClass().getEnclosingMethod().getName());
1628 public boolean dataChangeDeleteVplsPeData(URL url) throws AAIServiceException {
1631 throw new NullPointerException();
1634 return deleteAAIEntity(url, new Object(){}.getClass().getEnclosingMethod().getName());
1637 public boolean dataChangeDeleteVpeData(URL url) throws AAIServiceException {
1640 throw new NullPointerException();
1643 return deleteAAIEntity(url, new Object(){}.getClass().getEnclosingMethod().getName());
1646 public boolean dataChangeDeleteDvsSwitchData(URL url) throws AAIServiceException {
1649 throw new NullPointerException();
1652 return deleteAAIEntity(url, new Object(){}.getClass().getEnclosingMethod().getName());
1655 public boolean dataChangeDeleteOAMNetworkData(URL url) throws AAIServiceException {
1658 throw new NullPointerException();
1661 return deleteAAIEntity(url, new Object(){}.getClass().getEnclosingMethod().getName());
1663 //Availability-Zone:
1664 public boolean dataChangeDeleteAvailabilityZoneData(URL url) throws AAIServiceException {
1667 throw new NullPointerException();
1670 return deleteAAIEntity(url, new Object(){}.getClass().getEnclosingMethod().getName());
1673 public boolean dataChangeDeleteComplexData(URL url) throws AAIServiceException {
1676 throw new NullPointerException();
1679 return deleteAAIEntity(url, new Object(){}.getClass().getEnclosingMethod().getName());
1682 private boolean deleteAAIEntity(URL url, String caller) throws AAIServiceException {
1685 throw new NullPointerException();
1688 boolean response = false;
1689 InputStream inputStream = null;
1692 URL http_req_url = url;
1694 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.DELETE);
1696 // SSLSocketFactory sockFact = CTX.getSocketFactory();
1697 // con.setSSLSocketFactory( sockFact );
1699 LOGwriteFirstTrace("DELETE", http_req_url.toString());
1703 int responseCode = con.getResponseCode();
1704 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1705 inputStream = con.getInputStream();
1707 inputStream = con.getErrorStream();
1710 // Process the response
1711 LOG.debug("HttpURLConnection result:" + responseCode);
1712 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
1713 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
1716 ObjectMapper mapper = getObjectMapper();
1718 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
1719 StringBuilder stringBuilder = new StringBuilder();
1721 while( ( line = reader.readLine() ) != null ) {
1722 stringBuilder.append( line );
1724 LOGwriteEndingTrace(responseCode, "SUCCESS", stringBuilder.toString());
1726 } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
1727 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
1730 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
1731 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
1732 throw new AAIServiceException(responseCode, errorresponse);
1735 } catch(AAIServiceException aaiexc) {
1737 } catch (Exception exc) {
1738 LOG.warn(caller, exc);
1739 throw new AAIServiceException(exc);
1741 if(inputStream != null){
1743 inputStream.close();
1744 } catch(Exception exc) {
1753 * Generic method to GET json data from an A&AI callback URL.
1754 * Then convert that json to an Object.
1755 * If successful the Object is attempted to be cast to the type parameter.
1758 * callback url for A&AI
1760 * the class of object that A&AI will return
1761 * @return the object created from json or null if the response code is not 200
1763 * @throws AAIServiceException
1764 * if empty or null key and or type or there's an error with processing
1766 public <T> T dataChangeRequestAaiData(String key, Class<T> type) throws AAIServiceException {
1767 if (StringUtils.isEmpty(key) || type == null) {
1768 throw new AAIServiceException("Key is empty or null and or type is null");
1773 SvcLogicContext ctx = new SvcLogicContext();
1774 if(!key.contains(" = ") && isValidURL(key)) {
1775 key = String.format("selflink = '%s'", key);
1777 HashMap<String, String> nameValues = keyToHashMap(key, ctx);
1779 SelfLinkRequest request = new SelfLinkRequest(type);
1780 request.processRequestPathValues(nameValues);
1781 Object obj = this.getExecutor().query(request, type);
1782 response = type.cast(obj);
1784 return response != null ? type.cast(response) : response;
1788 public Pserver requestPServerData(String hostname) throws AAIServiceException {
1789 Pserver response = null;
1790 InputStream inputStream = null;
1793 AAIRequest request = AAIRequest.getRequestFromResource("pserver");
1794 request.addRequestProperty("pserver.hostname", hostname);
1797 String rv = executor.get(request);
1799 ObjectMapper mapper = getObjectMapper();
1800 response = mapper.readValue(rv, Pserver.class);
1802 } catch(AAIServiceException aaiexc) {
1804 } catch (Exception exc) {
1805 LOG.warn("requestPServerData", exc);
1806 throw new AAIServiceException(exc);
1812 public boolean postPServerData(String hostname, Pserver data) throws AAIServiceException {
1814 AAIRequest request = AAIRequest.getRequestFromResource("pserver");
1815 request.addRequestProperty("pserver.hostname", hostname);
1816 request.setRequestObject(data);
1817 Object response = executor.post(request);
1819 } catch(AAIServiceException aaiexc) {
1821 } catch (Exception exc) {
1822 LOG.warn(new Object(){}.getClass().getEnclosingMethod().getName(), exc);
1823 throw new AAIServiceException(exc);
1828 public boolean deletePServerData(String hostname, String resourceVersion) throws AAIServiceException {
1829 boolean response = false;
1832 AAIRequest request = AAIRequest.getRequestFromResource("pserver");
1833 request.addRequestProperty("pserver.hostname", hostname);
1834 response = executor.delete(request, resourceVersion);
1835 } catch(AAIServiceException aaiexc) {
1837 } catch (Exception exc) {
1838 LOG.warn("deletePServerData", exc);
1839 throw new AAIServiceException(exc);
1847 public L3Network requestL3NetworkData(String networkId) throws AAIServiceException {
1848 L3Network response = null;
1849 InputStream inputStream = null;
1852 AAIRequest request = AAIRequest.getRequestFromResource("l3-network");
1853 request.addRequestProperty("l3-network.network-id", networkId);
1855 String rv = executor.get(request);
1857 ObjectMapper mapper = getObjectMapper();
1858 response = mapper.readValue(rv, L3Network.class);
1860 } catch(AAIServiceException aaiexc) {
1862 } catch (Exception exc) {
1863 LOG.warn("requestL3NetworkData", exc);
1864 throw new AAIServiceException(exc);
1870 public L3Network requestL3NetworkQueryByName(String networkName) throws AAIServiceException {
1871 L3Network response = null;
1872 InputStream inputStream = null;
1875 AAIRequest request = AAIRequest.getRequestFromResource("l3-network");
1876 request.addRequestProperty("l3-network.network-name", networkName);
1878 String rv = executor.get(request);
1880 ObjectMapper mapper = getObjectMapper();
1881 response = mapper.readValue(rv, L3Network.class);
1884 } catch(AAIServiceException aaiexc) {
1886 } catch (Exception exc) {
1887 LOG.warn("requestL3NetworkQueryByName", exc);
1888 throw new AAIServiceException(exc);
1890 if(inputStream != null){
1892 inputStream.close();
1893 } catch(Exception exc) {
1902 public boolean postL3NetworkData(String networkId, L3Network data) throws AAIServiceException {
1904 AAIRequest request = AAIRequest.getRequestFromResource("l3-network");
1905 request.addRequestProperty("l3-network.network-id", networkId);
1906 request.setRequestObject(data);
1907 Object response = executor.post(request);
1909 } catch(AAIServiceException aaiexc) {
1911 } catch (Exception exc) {
1912 LOG.warn(new Object(){}.getClass().getEnclosingMethod().getName(), exc);
1913 throw new AAIServiceException(exc);
1918 public boolean deleteL3NetworkData(String networkId, String resourceVersion) throws AAIServiceException {
1919 boolean response = false;
1922 AAIRequest request = AAIRequest.getRequestFromResource("l3-network");
1923 request.addRequestProperty("l3-network.network-id", networkId);
1924 response = executor.delete(request, resourceVersion);
1925 } catch(AAIServiceException aaiexc) {
1927 } catch (Exception exc) {
1928 LOG.warn("deleteL3NetworkData", exc);
1929 throw new AAIServiceException(exc);
1937 public VpnBinding requestVpnBindingData(String vpnId) throws AAIServiceException {
1938 VpnBinding response = null;
1941 AAIRequest request = AAIRequest.getRequestFromResource("vpn-binding");
1942 request.addRequestProperty("vpn-binding.vpn-id", vpnId);
1944 String rv = executor.get(request);
1946 ObjectMapper mapper = getObjectMapper();
1947 response = mapper.readValue(rv, VpnBinding.class);
1949 } catch(AAIServiceException aaiexc) {
1951 } catch (Exception exc) {
1952 LOG.warn("requestVpnBindingData", exc);
1953 throw new AAIServiceException(exc);
1959 public boolean deleteVpnBindingData(String vpnId, String resourceVersion) throws AAIServiceException {
1960 boolean response = false;
1963 AAIRequest request = AAIRequest.getRequestFromResource("vpn-binding");
1964 request.addRequestProperty("vpn-binding.vpn-id", vpnId);
1965 response = executor.delete(request, resourceVersion);
1966 } catch(AAIServiceException aaiexc) {
1968 } catch (Exception exc) {
1969 LOG.warn("deleteVpnBindingData", exc);
1970 throw new AAIServiceException(exc);
1977 public VnfImage requestVnfImageData(String att_uuid) throws AAIServiceException {
1978 VnfImage response = null;
1981 AAIRequest request = AAIRequest.getRequestFromResource("vnf-image");
1982 request.addRequestProperty("vnf-image.att-uuid", att_uuid);
1984 String rv = executor.get(request);
1986 ObjectMapper mapper = getObjectMapper();
1987 response = mapper.readValue(rv, VnfImage.class);
1989 } catch(AAIServiceException aaiexc) {
1991 } catch (Exception exc) {
1992 LOG.warn("requestVnfImageData", exc);
1993 throw new AAIServiceException(exc);
1999 public VnfImage requestVnfImageDataByVendorModel(String vendor, String model) throws AAIServiceException {
2000 return requestVnfImageDataByVendorModelVersion(vendor, model, null);
2004 public VnfImage requestVnfImageDataByVendorModelVersion(String vendor, String model, String version) throws AAIServiceException
2006 List<VnfImage> responseList = new ArrayList<VnfImage>();
2007 VnfImage response = null;
2008 InputStream inputStream = null;
2011 String request_url = target_uri+vnf_image_query_path + (version==null? "": "&application-version={application_version}");
2012 request_url = request_url.replace("{application_vendor}", encodeQuery(vendor)) ;
2013 request_url = request_url.replace("{application_model}", encodeQuery(model)) ;
2014 if(version != null) {
2015 request_url = request_url.replace("{application_version}", encodeQuery(version)) ;
2017 URL http_req_url = new URL(request_url);
2019 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.GET);
2021 LOGwriteFirstTrace(HttpMethod.GET, http_req_url.toString());
2022 LOGwriteDateTrace("application_vendor", vendor);
2023 LOGwriteDateTrace("application_model", model);
2024 if(version != null) {
2025 LOGwriteDateTrace("application_version", version);
2029 int responseCode = con.getResponseCode();
2030 if (responseCode == HttpURLConnection.HTTP_OK) {
2031 inputStream = con.getInputStream();
2033 inputStream = con.getErrorStream();
2036 // Process the response
2037 LOG.debug("HttpURLConnection result:" + responseCode);
2038 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
2039 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2041 ObjectMapper mapper = getObjectMapper();
2043 if (responseCode == HttpURLConnection.HTTP_OK) {
2044 // StringBuilder stringBuilder = new StringBuilder("\n");
2045 // String line = null;
2046 // while( ( line = reader.readLine() ) != null ) {
2047 // stringBuilder.append("\n").append( line );
2049 // LOG.info(stringBuilder.toString());
2050 response = mapper.readValue(reader, VnfImage.class);
2051 String original_buffer = mapper.writeValueAsString(response);
2052 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, "SUCCESS", original_buffer);
2053 if(response.getApplicationVendor() == null /*&& response.getAdditionalProperties() != null && !response.getAdditionalProperties().isEmpty()*/){
2054 LOG.warn("A List of multiple VNF-IMAGE entries has been returned");
2055 VnfImages listOfObjects = mapper.readValue(original_buffer, VnfImages.class);
2056 if(!listOfObjects.getVnfImage().isEmpty()) {
2057 response = listOfObjects.getVnfImage().get(0);
2060 } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
2061 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
2064 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2065 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
2066 throw new AAIServiceException(responseCode, errorresponse);
2069 } catch(AAIServiceException aaiexc) {
2071 } catch (Exception exc) {
2072 LOG.warn("requestVnfImageData", exc);
2073 throw new AAIServiceException(exc);
2075 if(inputStream != null){
2077 inputStream.close();
2078 } catch(Exception exc) {
2087 public boolean sendNotify(NotifyEvent event, String serviceInstanceId, String pathCode) throws AAIServiceException {
2088 InputStream inputStream = null;
2092 String selfLink = selflink_fqdn;
2093 if(SELFLINK_AVPN != null && SELFLINK_AVPN.equals(pathCode)) {
2094 selfLink = selflink_avpn;
2096 selfLink = selfLink.replace("{service-instance-id}", encodeQuery(serviceInstanceId));
2097 event.setSelflink(selfLink);
2099 ObjectMapper mapper = getObjectMapper();
2100 String json_text = mapper.writeValueAsString(event);
2102 SSLSocketFactory sockFact = CTX.getSocketFactory();
2104 String request_url = target_uri+ubb_notify_path;
2105 URL http_req_url = new URL(request_url);
2107 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.PUT);
2109 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
2110 osw.write(json_text);
2115 LOGwriteFirstTrace("PUT", request_url);
2116 LOGwriteDateTrace("NotifyEvent", json_text);
2119 int responseCode = con.getResponseCode();
2120 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2121 inputStream = con.getInputStream();
2123 inputStream = con.getErrorStream();
2126 // Process the response
2127 BufferedReader reader;
2129 reader = new BufferedReader( new InputStreamReader( inputStream ) );
2131 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2132 StringBuilder stringBuilder = new StringBuilder();
2134 while( ( line = reader.readLine() ) != null ) {
2135 stringBuilder.append( line );
2137 LOGwriteEndingTrace(responseCode, "SUCCESS", (stringBuilder != null) ? stringBuilder.toString() : "{no-data}");
2140 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2141 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
2143 throw new AAIServiceException(responseCode, errorresponse);
2145 } catch(AAIServiceException aaiexc) {
2147 } catch (Exception exc) {
2148 LOG.warn("sendNotify", exc);
2149 throw new AAIServiceException(exc);
2152 if(inputStream != null)
2153 inputStream.close();
2154 } catch (Exception exc) {
2161 public SearchResults requestNodeQuery(String node_type, String entityIdentifier, String entityName) throws AAIServiceException {
2162 SearchResults response = null;
2163 InputStream inputStream = null;
2166 String request_url = target_uri+query_nodes_path;
2167 request_url = request_url.replace("{node-type}", encodeQuery(node_type)) ;
2168 request_url = request_url.replace("{entity-identifier}", entityIdentifier) ;
2169 request_url = request_url.replace("{entity-name}", encodeQuery(entityName)) ;
2170 URL http_req_url = new URL(request_url);
2172 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.GET);
2174 LOGwriteFirstTrace(HttpMethod.GET, http_req_url.toString());
2175 LOGwriteDateTrace("node_type", node_type);
2176 LOGwriteDateTrace("vnf_name", entityName);
2179 int responseCode = con.getResponseCode();
2180 if (responseCode == HttpURLConnection.HTTP_OK) {
2181 inputStream = con.getInputStream();
2183 inputStream = con.getErrorStream();
2186 // Process the response
2187 LOG.debug("HttpURLConnection result:" + responseCode);
2188 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
2189 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2191 ObjectMapper mapper = getObjectMapper();
2193 if (responseCode == HttpURLConnection.HTTP_OK) {
2194 response = mapper.readValue(reader, SearchResults.class);
2195 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, "SUCCESS", mapper.writeValueAsString(response));
2196 } else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
2197 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
2200 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2201 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
2202 throw new AAIServiceException(responseCode, errorresponse);
2205 } catch(AAIServiceException aaiexc) {
2207 } catch (Exception exc) {
2208 LOG.warn("requestNodeQuery", exc);
2209 throw new AAIServiceException(exc);
2211 if(inputStream != null){
2213 inputStream.close();
2214 } catch(Exception exc) {
2225 public String requestDataByURL(URL url) throws AAIServiceException {
2228 throw new NullPointerException();
2231 String response = null;
2232 InputStream inputStream = null;
2235 URL http_req_url = url;
2237 HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.GET);
2239 LOGwriteFirstTrace(HttpMethod.GET, http_req_url.toString());
2242 int responseCode = con.getResponseCode();
2243 if (responseCode == HttpURLConnection.HTTP_OK) {
2244 inputStream = con.getInputStream();
2246 inputStream = con.getErrorStream();
2249 // Process the response
2250 LOG.debug("HttpURLConnection result:" + responseCode);
2251 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
2252 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2254 ObjectMapper mapper = getObjectMapper();
2256 if (responseCode == HttpURLConnection.HTTP_OK) {
2257 StringBuilder stringBuilder = new StringBuilder("\n");
2259 while( ( line = reader.readLine() ) != null ) {
2260 stringBuilder.append( line );
2262 LOG.info(stringBuilder.toString());
2263 // response = mapper.readValue(reader, String.class);
2264 response = stringBuilder.toString();
2265 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, "SUCCESS", mapper.writeValueAsString(response));
2266 } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
2267 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
2270 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2271 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
2272 throw new AAIServiceException(responseCode, errorresponse);
2275 } catch(AAIServiceException aaiexc) {
2277 } catch (Exception exc) {
2278 LOG.warn("requestNetworkVceData", exc);
2279 throw new AAIServiceException(exc);
2281 if(inputStream != null){
2283 inputStream.close();
2284 } catch(Exception exc) {
2294 public GenericVnf requestGenericVnfeNodeQuery(String vnf_name) throws AAIServiceException {
2296 if(vnf_name == null) {
2297 throw new NullPointerException();
2300 GenericVnf entity = null;
2301 SearchResults resp = this.requestNodeQuery("generic-vnf", "vnf-name", vnf_name);
2303 List<ResultData> resultDataList = resp.getResultData();
2306 for (ResultData datum : resultDataList) {
2307 String data_type = datum.getResourceType();
2308 URL url = new URL(datum.getResourceLink());
2309 entity = this.getResource(url.toString(), GenericVnf.class);
2314 LOG.error("Caught exception", e);
2320 public Vserver requestVServerDataByURL(URL url) throws AAIServiceException {
2323 throw new NullPointerException();
2326 Vserver entity = null;
2329 entity = this.getResource(url.toString(), Vserver.class);
2330 } catch (AAIServiceException exc) {
2332 } catch (Exception e) {
2333 throw new AAIServiceException(e);
2339 public URL requestVserverURLNodeQuery(String vserver_name) throws AAIServiceException {
2341 if(vserver_name == null) {
2342 throw new NullPointerException();
2346 SearchResults resp = this.requestNodeQuery("vserver", "vserver-name", vserver_name);
2348 List<ResultData> resultDataList = resp.getResultData();
2351 for (ResultData datum : resultDataList) {
2352 String data_type = datum.getResourceType();
2353 entity = new URL(datum.getResourceLink());
2355 } catch (Exception e) {
2356 throw new AAIServiceException(e);
2361 class AAIRequestExecutor implements AAIExecutorInterface {
2364 public String get(AAIRequest request) throws AAIServiceException {
2365 String response = null;
2366 InputStream inputStream = null;
2367 HttpURLConnection con = null;
2368 URL requestUrl = null;
2370 String requestId = UUID.randomUUID().toString();
2374 if(request.getRequestObject() != null) {
2375 requestUrl = request.getRequestUrl(HttpMethod.POST, null);
2376 requestUrl = appendDepth(requestUrl, request);
2377 con = getConfiguredConnection(requestUrl, HttpMethod.POST);
2378 String json_text = request.toJSONString();
2379 LOGwriteDateTrace("data", json_text);
2380 logMetricRequest(requestId, "POST "+requestUrl.getPath(), json_text, requestUrl.getPath());
2381 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
2382 osw.write(json_text);
2385 requestUrl = request.getRequestUrl(HttpMethod.GET, null);
2386 requestUrl = appendDepth(requestUrl, request);
2387 con = getConfiguredConnection(requestUrl, HttpMethod.GET);
2388 logMetricRequest(requestId, "GET "+requestUrl.getPath(), "", requestUrl.getPath());
2392 String responseMessage = con.getResponseMessage();
2393 int responseCode = con.getResponseCode();
2394 if (responseCode == HttpURLConnection.HTTP_OK) {
2395 inputStream = con.getInputStream();
2397 inputStream = con.getErrorStream();
2400 // Process the response
2401 LOG.debug("HttpURLConnection result:" + responseCode + " : " + responseMessage);
2402 logMetricResponse(requestId, responseCode, responseMessage);
2404 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
2405 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2407 ObjectMapper mapper = getObjectMapper();
2409 if (responseCode == HttpURLConnection.HTTP_OK) {
2410 StringBuilder stringBuilder = new StringBuilder();
2412 while( ( line = reader.readLine() ) != null ) {
2413 stringBuilder.append( line );
2415 response = stringBuilder.toString();
2417 Object object = mapper.readValue(response, Object.class);
2418 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, responseMessage, mapper.writeValueAsString(object));
2419 } catch(Exception exc) {
2420 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, responseMessage, mapper.writeValueAsString(response));
2422 } else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
2423 LOGwriteEndingTrace(responseCode, responseMessage, "Entry does not exist.");
2424 ErrorResponse errorresponse = null;
2426 errorresponse = mapper.readValue(reader, ErrorResponse.class);
2427 } catch(Exception exc) {
2428 errorresponse = new ErrorResponse();
2429 RequestError requestError = new RequestError();
2430 ServiceException serviceException = new ServiceException();
2431 serviceException.setText("Entry does not exist.");
2432 requestError.setServiceException(serviceException);
2433 errorresponse.setRequestError(requestError );
2435 throw new AAIServiceException(responseCode, errorresponse);
2436 } else if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
2437 StringBuilder stringBuilder = new StringBuilder();
2439 while( ( line = reader.readLine() ) != null ) {
2440 stringBuilder.append( line );
2442 LOGwriteEndingTrace(responseCode, responseMessage, stringBuilder.toString());
2443 ServiceException serviceException = new ServiceException();
2444 serviceException.setMessageId("HTTP_UNAUTHORIZED");
2445 serviceException.setText(stringBuilder.toString());
2446 RequestError requestError = new RequestError();
2447 requestError.setServiceException(serviceException);
2448 ErrorResponse errorresponse = new ErrorResponse();
2449 errorresponse.setRequestError(requestError);
2450 throw new AAIServiceException(responseCode, errorresponse);
2453 // StringBuilder stringBuilder = new StringBuilder("\n");
2454 // String line = null;
2455 // while( ( line = reader.readLine() ) != null ) {
2456 // stringBuilder.append("\n").append( line );
2458 // LOG.info(stringBuilder.toString());
2460 // ErrorResponse errorresponse = mapper.readValue(stringBuilder.toString(), ErrorResponse.class);
2461 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2462 LOGwriteEndingTrace(responseCode, responseMessage, mapper.writeValueAsString(errorresponse));
2463 throw new AAIServiceException(responseCode, errorresponse);
2466 } catch(AAIServiceException aaiexc) {
2468 } catch (Exception exc) {
2469 LOG.warn("GET", exc);
2470 throw new AAIServiceException(exc);
2472 if(inputStream != null){
2474 inputStream.close();
2475 } catch(Exception exc) {
2483 private URL appendDepth(URL requestUrl, AAIRequest request) throws MalformedURLException {
2485 String depth = request.requestProperties.getProperty("depth", "1");
2486 String path = requestUrl.toString();
2487 if(path.contains("?depth=") || path.contains("&depth=")) {
2490 if(path.contains("?")) {
2491 path = String.format("%s&depth=%s", path, depth);
2493 path = String.format("%s?depth=%s", path, depth);
2495 return new URL(path);
2500 public String post(AAIRequest request) throws AAIServiceException {
2501 InputStream inputStream = null;
2502 String requestId = UUID.randomUUID().toString();
2505 String resourceVersion = null;
2506 AAIDatum instance = request.getRequestObject();
2508 Method getResourceVersionMethod = instance.getClass().getMethod("getResourceVersion");
2509 if(getResourceVersionMethod != null){
2511 getResourceVersionMethod.setAccessible(true);
2512 Object object = getResourceVersionMethod.invoke(instance);
2514 resourceVersion = object.toString();
2515 } catch (InvocationTargetException x) {
2516 Throwable cause = x.getCause();
2520 URL requestUrl = null;
2521 HttpURLConnection con = getConfiguredConnection(requestUrl = request.getRequestUrl(HttpMethod.PUT, resourceVersion), HttpMethod.PUT);
2522 ObjectMapper mapper = getObjectMapper();
2523 String json_text = request.toJSONString();
2525 LOGwriteDateTrace("data", json_text);
2526 logMetricRequest(requestId, "PUT "+requestUrl.getPath(), json_text, requestUrl.getPath());
2528 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
2529 osw.write(json_text);
2533 String responseMessage = con.getResponseMessage();
2534 int responseCode = con.getResponseCode();
2535 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2536 inputStream = con.getInputStream();
2538 inputStream = con.getErrorStream();
2541 LOG.debug("HttpURLConnection result:" + responseCode + " : " + responseMessage);
2542 logMetricResponse(requestId,responseCode, responseMessage);
2544 // Process the response
2545 BufferedReader reader;
2547 reader = new BufferedReader( new InputStreamReader( inputStream ) );
2548 mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
2550 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2551 StringBuilder stringBuilder = new StringBuilder();
2553 while( ( line = reader.readLine() ) != null ) {
2554 stringBuilder.append( line );
2556 LOGwriteEndingTrace(responseCode, responseMessage, (stringBuilder != null) ? stringBuilder.toString() : "{no-data}");
2557 return stringBuilder.toString();
2559 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2560 LOGwriteEndingTrace(responseCode, responseMessage, mapper.writeValueAsString(errorresponse));
2562 throw new AAIServiceException(responseCode, errorresponse);
2564 } catch(AAIServiceException aaiexc) {
2566 } catch (Exception exc) {
2567 LOG.warn("AAIRequestExecutor.post", exc);
2568 throw new AAIServiceException(exc);
2571 if(inputStream != null)
2572 inputStream.close();
2573 } catch (Exception exc) {
2580 public Boolean delete(AAIRequest request, String resourceVersion) throws AAIServiceException {
2581 Boolean response = null;
2582 InputStream inputStream = null;
2583 String requestId = UUID.randomUUID().toString();
2585 if(resourceVersion == null) {
2586 throw new AAIServiceException("resource-version is required for DELETE request");
2590 URL requestUrl = null;
2591 HttpURLConnection conn = getConfiguredConnection(requestUrl = request.getRequestUrl(HttpMethod.DELETE, resourceVersion), HttpMethod.DELETE);
2592 logMetricRequest(requestId, "DELETE "+requestUrl.getPath(), "", requestUrl.getPath());
2593 conn.setDoOutput(true);
2594 // if(request.isDeleteDataRequired()) {
2595 // String json_text = request.toJSONString();
2597 // LOGwriteDateTrace("data", json_text);
2598 // OutputStream os = con.getOutputStream();
2599 // OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
2600 // osw.write(json_text);
2605 String responseMessage = conn.getResponseMessage();
2606 int responseCode = conn.getResponseCode();
2607 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2608 inputStream = conn.getInputStream();
2610 inputStream = conn.getErrorStream();
2613 // Process the response
2614 LOG.debug("HttpURLConnection result:" + responseCode + " : " + responseMessage);
2615 logMetricResponse(requestId,responseCode, responseMessage);
2617 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
2618 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2621 ObjectMapper mapper = getObjectMapper();
2623 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2624 StringBuilder stringBuilder = new StringBuilder();
2626 while( ( line = reader.readLine() ) != null ) {
2627 stringBuilder.append( line );
2629 LOGwriteEndingTrace(responseCode, responseMessage, stringBuilder.toString());
2631 } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
2632 LOGwriteEndingTrace(responseCode, responseMessage, "Entry does not exist.");
2635 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2636 LOGwriteEndingTrace(responseCode, responseMessage, mapper.writeValueAsString(errorresponse));
2637 throw new AAIServiceException(responseCode, errorresponse);
2639 } catch(AAIServiceException aaiexc) {
2641 } catch (Exception exc) {
2642 LOG.warn("delete", exc);
2643 throw new AAIServiceException(exc);
2645 if(inputStream != null){
2647 inputStream.close();
2648 } catch(Exception exc) {
2657 public Object query(AAIRequest request, Class clas) throws AAIServiceException {
2658 Object response = null;
2659 InputStream inputStream = null;
2660 HttpURLConnection con = null;
2661 URL requestUrl = null;
2662 String requestId = UUID.randomUUID().toString();
2665 con = getConfiguredConnection(requestUrl = request.getRequestQueryUrl(HttpMethod.GET), HttpMethod.GET);
2666 logMetricRequest(requestId, "GET "+requestUrl.getPath(), "", requestUrl.getPath());
2669 String responseMessage = con.getResponseMessage();
2670 int responseCode = con.getResponseCode();
2671 if (responseCode == HttpURLConnection.HTTP_OK) {
2672 inputStream = con.getInputStream();
2674 inputStream = con.getErrorStream();
2677 logMetricResponse(requestId,responseCode, responseMessage);
2678 ObjectMapper mapper = getObjectMapper();
2680 if (responseCode == HttpURLConnection.HTTP_OK) {
2681 // Process the response
2682 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2683 response = mapper.readValue(reader, clas);
2684 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, "SUCCESS", mapper.writeValueAsString(response));
2685 } else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
2686 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
2689 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
2690 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2691 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
2692 throw new AAIServiceException(responseCode, errorresponse);
2695 } catch(AAIServiceException aaiexc) {
2697 } catch (Exception exc) {
2698 LOG.warn("GET", exc);
2699 throw new AAIServiceException(exc);
2701 if(inputStream != null){
2703 inputStream.close();
2704 } catch(Exception exc) {
2714 public Boolean patch(AAIRequest request, String resourceVersion) throws AAIServiceException {
2715 InputStream inputStream = null;
2716 String requestId = UUID.randomUUID().toString();
2719 AAIDatum instance = request.getRequestObject();
2720 if(instance instanceof ResourceVersion) {
2721 resourceVersion = ((ResourceVersion)instance).getResourceVersion();
2724 URL requestUrl = null;
2725 HttpURLConnection con = getConfiguredConnection(requestUrl = request.getRequestUrl("PATCH", resourceVersion), "PATCH");
2726 ObjectMapper mapper = getObjectMapper();
2727 String json_text = request.toJSONString();
2729 LOGwriteDateTrace("data", json_text);
2730 logMetricRequest(requestId, "PATCH "+requestUrl.getPath(), json_text, requestUrl.getPath());
2732 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
2733 osw.write(json_text);
2737 String responseMessage = con.getResponseMessage();
2738 int responseCode = con.getResponseCode();
2739 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2740 inputStream = con.getInputStream();
2742 inputStream = con.getErrorStream();
2745 LOG.info("HttpURLConnection result: " + responseCode + " : " + responseMessage);
2746 logMetricResponse(requestId,responseCode, responseMessage);
2748 // Process the response
2749 BufferedReader reader;
2751 reader = new BufferedReader( new InputStreamReader( inputStream ) );
2752 mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
2754 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
2755 StringBuilder stringBuilder = new StringBuilder();
2757 while( ( line = reader.readLine() ) != null ) {
2758 stringBuilder.append( line );
2760 LOGwriteEndingTrace(responseCode, responseMessage, (stringBuilder != null) ? stringBuilder.toString() : "{no-data}");
2763 StringBuilder stringBuilder = new StringBuilder();
2765 while( ( line = reader.readLine() ) != null ) {
2766 stringBuilder.append("\n").append( line );
2768 LOG.info(stringBuilder.toString());
2771 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
2772 LOGwriteEndingTrace(responseCode, responseMessage, mapper.writeValueAsString(errorresponse));
2774 throw new AAIServiceException(responseCode, errorresponse);
2776 } catch(AAIServiceException aaiexc) {
2778 } catch (Exception exc) {
2779 LOG.warn("AAIRequestExecutor.patch", exc);
2780 throw new AAIServiceException(exc);
2783 if(inputStream != null)
2784 inputStream.close();
2785 } catch (Exception exc) {
2793 public Tenant requestTenantData(String tenant_id, String cloudOwner, String cloudRegionId) throws AAIServiceException {
2794 Tenant response = null;
2797 AAIRequest request = AAIRequest.getRequestFromResource("tenant");
2798 request.addRequestProperty("tenant.tenant-id", tenant_id);
2799 request.addRequestProperty("cloud-region.cloud-owner", cloudOwner);
2800 request.addRequestProperty("cloud-region.cloud-region-id", cloudRegionId);
2802 String rv = executor.get(request);
2804 ObjectMapper mapper = getObjectMapper();
2805 response = mapper.readValue(rv, Tenant.class);
2807 } catch(AAIServiceException aaiexc) {
2809 } catch (Exception exc) {
2810 LOG.warn("requestTenantData", exc);
2811 throw new AAIServiceException(exc);
2818 public Tenant requestTenantDataByName(String tenant_name, String cloudOwner, String cloudRegionId) throws AAIServiceException {
2819 Tenant response = null;
2822 AAIRequest request = AAIRequest.getRequestFromResource("tenant");
2823 request.addRequestProperty("tenant.tenant-name", tenant_name);
2824 request.addRequestProperty("cloud-region.cloud-owner", cloudOwner);
2825 request.addRequestProperty("cloud-region.cloud-region-id", cloudRegionId);
2826 Object rv = executor.query(request, Tenant.class);
2828 return (Tenant)null;
2830 response = (Tenant)rv;
2831 } catch(AAIServiceException aaiexc) {
2833 } catch (Exception exc) {
2834 LOG.warn("requestTenantDataByName", exc);
2835 throw new AAIServiceException(exc);
2843 public boolean postTenantData(String tenant_id, String cloudOwner, String cloudRegionId, Tenant tenannt) throws AAIServiceException {
2845 AAIRequest request = AAIRequest.getRequestFromResource("tenant");
2846 request.addRequestProperty("tenant.tenant-id", tenant_id);
2847 request.addRequestProperty("cloud-region.cloud-owner", cloudOwner);
2848 request.addRequestProperty("cloud-region.cloud-region-id", cloudRegionId);
2849 request.setRequestObject(tenannt);
2850 Object response = executor.post(request);
2852 } catch(AAIServiceException aaiexc) {
2854 } catch (Exception exc) {
2855 LOG.warn("postTenantData", exc);
2856 throw new AAIServiceException(exc);
2862 public String getTenantIdFromVserverUrl(URL url) {
2864 String path = url.getPath();
2866 String[] split = path.split("/tenants/tenant/");
2867 if(split.length > 1) {
2868 split = split[1].split("/");
2876 public String getCloudOwnerFromVserverUrl(URL url) {
2878 String path = url.getPath();
2880 String[] split = path.split("/cloud-regions/cloud-region/");
2881 if(split.length > 1) {
2882 split = split[1].split("/");
2890 public String getCloudRegionFromVserverUrl(URL url) {
2892 String path = url.getPath();
2894 String[] split = path.split("/cloud-regions/cloud-region/");
2895 if(split.length > 1) {
2896 split = split[1].split("/");
2904 public String getVServerIdFromVserverUrl(URL url, String tenantId) {
2905 String pattern = network_vserver_path;
2906 pattern = pattern.replace("{tenant-id}", tenantId);
2908 int end = pattern.indexOf("{vserver-id}");
2909 String prefix = pattern.substring(0, end);
2911 String path = url.getPath();
2913 if(path.startsWith(prefix)) {
2914 path = path.substring(prefix.length());
2920 protected Logger getLogger(){
2926 public AAIRequestExecutor getExecutor() {
2931 * Creates a current time stamp in UTC i.e. 2016-03-08T22:15:13.343Z.
2932 * If there are any parameters the values are appended to the time stamp.
2935 * values to be appended to current time stamp
2937 * used to set an attribute for a DG
2938 * @throws SvcLogicException
2940 public void setStatusMethod(Map<String, String> parameters, SvcLogicContext ctx) throws SvcLogicException {
2942 throw new SvcLogicException("SvcLogicContext is null.");
2945 StringBuilder sb = new StringBuilder();
2946 sb.append(String.format("%tFT%<tTZ", Calendar.getInstance(TimeZone.getTimeZone("Z")))).append(" - ");
2948 for (Entry<String, String> entry : parameters.entrySet()) {
2949 sb.append(entry.getValue()).append(" ");
2952 if (sb.length() > 0) {
2953 sb.setLength(sb.length() - 2);
2956 ctx.setAttribute("aai-summary-status-message", sb.toString());
2957 LOG.info("aai-summary-status-message: " + sb.toString());
2961 * Generic method to GET json data from an A&AI using key structure.
2962 * Then convert that json to an Object.
2963 * If successful the Object is attempted to be cast to the type parameter.
2966 * key identifying the resource to be retrieved from AAI
2968 * the class of object that A&AI will return
2969 * @return the object created from json or null if the response code is not 200
2971 * @throws AAIServiceException
2972 * if empty or null key and or type or there's an error with processing
2975 public <T> T getResource(String key, Class<T> type) throws AAIServiceException {
2976 if (StringUtils.isEmpty(key) || type == null) {
2977 throw new AAIServiceException("Key is empty or null and or type is null");
2982 SvcLogicContext ctx = new SvcLogicContext();
2983 if(!key.contains(" = ")) {
2984 if(isValidURL(key)) {
2985 key = String.format("selflink = '%s'", key);
2991 HashMap<String, String> nameValues = keyToHashMap(key, ctx);
2993 AAIRequest request = new SelfLinkRequest(type);
2994 if(nameValues.containsKey(PathRequest.RESOURCE_PATH.replaceAll("-", "_"))) {
2995 request = new PathRequest(type);
2998 request.processRequestPathValues(nameValues);
2999 Object obj = this.getExecutor().query(request, type);
3000 response = type.cast(obj);
3002 return response != null ? type.cast(response) : response;
3005 public boolean isValidURL(String url) {
3011 } catch (MalformedURLException e) {
3017 } catch (URISyntaxException e) {
3025 protected boolean deleteRelationshipList(URL httpReqUrl, String json_text) throws AAIServiceException {
3026 if(httpReqUrl == null) {
3027 throw new NullPointerException();
3030 boolean response = false;
3031 InputStream inputStream = null;
3034 HttpURLConnection con = getConfiguredConnection(httpReqUrl, HttpMethod.DELETE);
3036 // SSLSocketFactory sockFact = CTX.getSocketFactory();
3037 // con.setSSLSocketFactory( sockFact );
3038 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
3039 osw.write(json_text);
3044 LOGwriteFirstTrace("DELETE", httpReqUrl.toString());
3045 LOGwriteDateTrace("data", json_text);
3048 int responseCode = con.getResponseCode();
3049 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
3050 inputStream = con.getInputStream();
3052 inputStream = con.getErrorStream();
3055 // Process the response
3056 LOG.debug("HttpURLConnection result:" + responseCode);
3057 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
3058 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
3061 ObjectMapper mapper = getObjectMapper();
3063 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
3064 StringBuilder stringBuilder = new StringBuilder();
3066 while( ( line = reader.readLine() ) != null ) {
3067 stringBuilder.append( line );
3069 LOGwriteEndingTrace(responseCode, "SUCCESS", stringBuilder.toString());
3071 } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
3072 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
3075 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
3076 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
3077 throw new AAIServiceException(responseCode, errorresponse);
3080 } catch(AAIServiceException aaiexc) {
3082 } catch (Exception exc) {
3083 LOG.warn("deleteRelationshipList", exc);
3084 throw new AAIServiceException(exc);
3086 if(inputStream != null){
3088 inputStream.close();
3089 } catch(Exception exc) {
3097 public static ObjectMapper getObjectMapper() {
3098 ObjectMapper mapper = new ObjectMapper();
3099 AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance());
3100 AnnotationIntrospector secondary = new JacksonAnnotationIntrospector();
3101 mapper.setAnnotationIntrospector(AnnotationIntrospector.pair(introspector, secondary));
3102 mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
3103 mapper.setSerializationInclusion(Include.NON_NULL);
3107 public void logMetricRequest(String requestId, String targetServiceName, String msg, String path){
3108 String svcInstanceId = "";
3109 String svcName = null;
3110 String partnerName = null;
3111 String targetEntity = "A&AI";
3112 String targetVirtualEntity = null;
3114 targetServiceName = "";
3116 ml.logRequest(svcInstanceId, svcName, partnerName, targetEntity, targetServiceName, targetVirtualEntity, msg);
3119 public void logMetricResponse(String requestId, int responseCode, String responseDescription){
3120 ml.logResponse(responseCode < 400 ? "SUCCESS" : "FAILURE", Integer.toString(responseCode), responseDescription);
3123 public void logKeyError(String keys){
3124 LOG.error("Atleast one of the keys [" + keys + "] should have been populated. This will cause a NPE.");
3132 public QueryStatus save(String resource, boolean force, boolean localOnly, String key, Map<String, String> params, String prefix, SvcLogicContext ctx)
3133 throws SvcLogicException {
3134 String normResource = resource.split(":")[0];
3136 switch(normResource){
3137 case "formatted-query":
3138 case "generic-query":
3142 case "l2-bridge-sbg":
3143 case "l2-bridge-bgf":
3149 if(!key.contains(String.format("%s.", normResource))) {
3150 key = rewriteKey(resource, key, ctx);
3153 return super.save(resource, force, localOnly, key, params, prefix, ctx);
3157 public QueryStatus query(String resource, boolean localOnly, String select, String key, String prefix, String orderBy, SvcLogicContext ctx)
3158 throws SvcLogicException {
3159 String normResource = resource.split(":")[0];
3161 switch(normResource){
3162 case "formatted-query":
3163 case "generic-query":
3167 case "l2-bridge-sbg":
3168 case "l2-bridge-bgf":
3174 if(!key.contains(String.format("%s.", normResource))) {
3175 key = rewriteKey(resource, key, ctx);
3179 return super.query(resource, localOnly, select, key, prefix, orderBy, ctx);
3183 public QueryStatus delete(String resource, String key, SvcLogicContext ctx) throws SvcLogicException {
3184 String normResource = resource.split(":")[0];
3186 switch(normResource){
3187 case "formatted-query":
3188 case "generic-query":
3192 case "l2-bridge-sbg":
3193 case "l2-bridge-bgf":
3199 if(!key.contains(String.format("%s.", normResource))) {
3200 key = rewriteKey(resource, key, ctx);
3204 return super.delete(resource, key, ctx);
3208 public QueryStatus update(String resource, String key, Map<String, String> params, String prefix, SvcLogicContext ctx) throws SvcLogicException {
3209 String normResource = resource.split(":")[0];
3211 switch(normResource){
3212 case "formatted-query":
3213 case "generic-query":
3217 case "l2-bridge-sbg":
3218 case "l2-bridge-bgf":
3224 if(!key.contains(String.format("%s.", normResource))) {
3225 key = rewriteKey(resource, key, ctx);
3229 return super.update(resource, key, params, prefix, ctx);
3232 private String rewriteKey(String resource, String key, SvcLogicContext ctx) {
3233 LOG.info("AAI Deprecation - the format of request key is no longer supported. Please rewrite this key : " + key);
3235 String normResource = resource.split(":")[0];
3236 Class<? extends AAIDatum> clazz = null;
3238 clazz = AAIRequest.getClassFromResource(normResource) ;
3239 } catch (ClassNotFoundException e) {
3240 LOG.warn("AAIRequest does not support class: " + e.getMessage());
3246 List<String> fieldAnnotatedNames = new LinkedList<String>();
3248 Field[] fields = clazz.getDeclaredFields();
3249 for(Field field : fields) {
3250 String fieldName = field.getName();
3251 XmlElement annotation = field.getAnnotation(XmlElement.class);
3252 if(annotation == null)
3254 String primaryId = annotation.name();
3255 if("##default".equals(primaryId)) {
3256 primaryId = fieldName;
3258 fieldAnnotatedNames.add(primaryId);
3261 HashMap<String, String> nameValues = keyToHashMap(key, ctx);
3262 Set<String> keyset = nameValues.keySet();
3263 for(String keyName : keyset) {
3264 if(keyName.contains("."))
3267 String tmpKeyName = keyName.replaceAll("_", "-");
3268 if(fieldAnnotatedNames.contains(tmpKeyName)) {
3269 key = key.replace(tmpKeyName, String.format("%s.%s", normResource, tmpKeyName));