From e4037ffc232e37758db669402523bf4e24321e4d Mon Sep 17 00:00:00 2001 From: Rich Tabedzki Date: Wed, 4 Oct 2017 16:53:04 +0000 Subject: Improve CCSDK adaptors Sonar coverage Changes made: 1. Cleaned up blocker issues Change-Id: Ie0424ce7aeaf07ed8a521dc2bff21b66a28e051f Issue-ID: CCSDK-108 Signed-off-by: Rich Tabedzki --- .../onap/ccsdk/sli/adaptors/aai/AAIService.java | 116 ++---- .../sli/adaptors/aai/AAIServiceActivator.java | 396 ++++++++++----------- 2 files changed, 230 insertions(+), 282 deletions(-) (limited to 'aai-service/provider/src/main') diff --git a/aai-service/provider/src/main/java/org/onap/ccsdk/sli/adaptors/aai/AAIService.java b/aai-service/provider/src/main/java/org/onap/ccsdk/sli/adaptors/aai/AAIService.java index 1ec222c9..4781f2e2 100755 --- a/aai-service/provider/src/main/java/org/onap/ccsdk/sli/adaptors/aai/AAIService.java +++ b/aai-service/provider/src/main/java/org/onap/ccsdk/sli/adaptors/aai/AAIService.java @@ -126,18 +126,18 @@ public class AAIService extends AAIDeclarations implements AAIClient, SvcLogicRe private static final Logger LOG = LoggerFactory.getLogger(AAIService.class); - private final String truststore_path; - private final String truststore_password; - private final String keystore_path; - private final String keystore_password; - private final Boolean ignore_certificate_host_error; + private final String truststorePath; + private final String truststorePassword; + private final String keystorePath; + private final String keystorePassword; + private final Boolean ignoreCertificateHostError; private final String target_uri; - private final String query_path; + private final String queryPath; - private final String network_vserver_path; + private final String networkVserverPath; - private final String svc_instance_path; + private final String svcInstancePath; private final String svc_inst_qry_path; private final String vnf_image_query_path; @@ -206,13 +206,13 @@ public class AAIService extends AAIDeclarations implements AAIClient, SvcLogicRe LOG.debug("Basic password is not set"); } - truststore_path = props.getProperty(TRUSTSTORE_PATH); - truststore_password = props.getProperty(TRUSTSTORE_PSSWD); - keystore_path = props.getProperty(KEYSTORE_PATH); - keystore_password = props.getProperty(KEYSTORE_PSSWD); + truststorePath = props.getProperty(TRUSTSTORE_PATH); + truststorePassword = props.getProperty(TRUSTSTORE_PSSWD); + keystorePath = props.getProperty(KEYSTORE_PATH); + keystorePassword = props.getProperty(KEYSTORE_PSSWD); target_uri = props.getProperty(TARGET_URI); - query_path = props.getProperty(QUERY_PATH); + queryPath = props.getProperty(QUERY_PATH); update_path = props.getProperty(UPDATE_PATH); String applicationId =props.getProperty(APPLICATION_ID); @@ -239,9 +239,9 @@ public class AAIService extends AAIDeclarations implements AAIClient, SvcLogicRe connection_timeout = tmpConnectionTimeout; read_timeout = tmpReadTimeout; - network_vserver_path =props.getProperty(NETWORK_VSERVER_PATH); + networkVserverPath =props.getProperty(NETWORK_VSERVER_PATH); - svc_instance_path = props.getProperty(SVC_INSTANCE_PATH); + svcInstancePath = props.getProperty(SVC_INSTANCE_PATH); svc_inst_qry_path = props.getProperty(SVC_INST_QRY_PATH); param_service_type = props.getProperty(PARAM_SERVICE_TYPE, "service-type"); @@ -266,20 +266,20 @@ public class AAIService extends AAIDeclarations implements AAIClient, SvcLogicRe host_error = Boolean.valueOf(iche); } - ignore_certificate_host_error = host_error; + ignoreCertificateHostError = host_error; HttpsURLConnection.setDefaultHostnameVerifier( new HostnameVerifier(){ public boolean verify(String string,SSLSession ssls) { - return ignore_certificate_host_error; + return ignoreCertificateHostError; } }); - if(truststore_path != null && truststore_password != null && (new File(truststore_path)).exists()) { - System.setProperty("javax.net.ssl.trustStore", truststore_path); - System.setProperty("javax.net.ssl.trustStorePassword", truststore_password); + if(truststorePath != null && truststorePassword != null && (new File(truststorePath)).exists()) { + System.setProperty("javax.net.ssl.trustStore", truststorePath); + System.setProperty("javax.net.ssl.trustStorePassword", truststorePassword); } - if(keystore_path != null && keystore_password != null && (new File(keystore_path)).exists()) { + if(keystorePath != null && keystorePassword != null && (new File(keystorePath)).exists()) { DefaultClientConfig config = new DefaultClientConfig(); //both jersey and HttpURLConnection can use this SSLContext ctx = null; @@ -287,19 +287,19 @@ public class AAIService extends AAIDeclarations implements AAIClient, SvcLogicRe ctx = SSLContext.getInstance("TLS"); KeyManagerFactory kmf = null; - try (FileInputStream fin = new FileInputStream(keystore_path)){ + try (FileInputStream fin = new FileInputStream(keystorePath)){ String def = "SunX509"; String storeType = "PKCS12"; def = KeyStore.getDefaultType(); kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); - String extension = keystore_path.substring(keystore_path.lastIndexOf(".") + 1); + String extension = keystorePath.substring(keystorePath.lastIndexOf(".") + 1); if("JKS".equalsIgnoreCase(extension)) { storeType = "JKS"; } KeyStore ks = KeyStore.getInstance(storeType); - char[] pwd = keystore_password.toCharArray(); + char[] pwd = keystorePassword.toCharArray(); ks.load(fin, pwd); kmf.init(ks, pwd); } catch (Exception ex) { @@ -310,7 +310,7 @@ public class AAIService extends AAIDeclarations implements AAIClient, SvcLogicRe config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties( new HostnameVerifier() { @Override public boolean verify( String s, SSLSession sslSession ) { - return ignore_certificate_host_error; + return ignoreCertificateHostError; } }, ctx)); @@ -883,74 +883,22 @@ public class AAIService extends AAIDeclarations implements AAIClient, SvcLogicRe @Override public boolean deleteVServerData(String tenant_id, String vserver_id, String cloudOwner, String cloudRegionId, String resourceVersion) throws AAIServiceException { boolean response = false; - InputStream inputStream = null; try { - String local_network_complexes_path = network_vserver_path.replace("{tenant-id}", encodeQuery(tenant_id)); - local_network_complexes_path = local_network_complexes_path.replace("{vserver-id}", encodeQuery(vserver_id)); - local_network_complexes_path = local_network_complexes_path.replace("{cloud-owner}", encodeQuery(cloudOwner)); - local_network_complexes_path = local_network_complexes_path.replace("{cloud-region-id}", encodeQuery(cloudRegionId)); - - String request_url = target_uri+local_network_complexes_path; - if(resourceVersion!=null) { - request_url = request_url +"?resource-version="+resourceVersion; - } - URL http_req_url = new URL(request_url); - - HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.DELETE); - - LOGwriteFirstTrace(HttpMethod.DELETE, http_req_url.toString()); - LOGwriteDateTrace("tenant_id", tenant_id); - LOGwriteDateTrace("vserver_id", vserver_id); - LOGwriteDateTrace("cloud-owner", cloudOwner); - LOGwriteDateTrace("cloud-region-id", cloudRegionId); - - // Check for errors - int responseCode = con.getResponseCode(); - if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) { - inputStream = con.getInputStream(); - } else { - inputStream = con.getErrorStream(); - } - - // Process the response - LOG.debug("HttpURLConnection result:" + responseCode); - if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8)); - BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) ); - String line = null; - - ObjectMapper mapper = getObjectMapper(); + AAIRequest request = AAIRequest.getRequestFromResource("vserver"); - if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) { - StringBuilder stringBuilder = new StringBuilder(); + request.addRequestProperty("vserver.vserver-id", vserver_id); + request.addRequestProperty("tenant.tenant-id", tenant_id); + request.addRequestProperty("cloud-region.cloud-owner", cloudOwner); + request.addRequestProperty("cloud-region.cloud-region-id",cloudRegionId); - while( ( line = reader.readLine() ) != null ) { - stringBuilder.append( line ); - } - LOGwriteEndingTrace(responseCode, "SUCCESS", stringBuilder.toString()); - response = true; - } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) { - LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist."); - response = false; - } else { - ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class); - LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse)); - throw new AAIServiceException(responseCode, errorresponse); - } + response = executor.delete(request, resourceVersion); } catch(AAIServiceException aaiexc) { throw aaiexc; } catch (Exception exc) { LOG.warn("deleteVServerData", exc); throw new AAIServiceException(exc); - } finally { - if(inputStream != null){ - try { - inputStream.close(); - } catch(Exception exc) { - - } - } } return response; } @@ -2808,7 +2756,7 @@ public class AAIService extends AAIDeclarations implements AAIClient, SvcLogicRe @Override public String getVServerIdFromVserverUrl(URL url, String tenantId) { - String pattern = network_vserver_path; + String pattern = networkVserverPath; pattern = pattern.replace("{tenant-id}", tenantId); int end = pattern.indexOf("{vserver-id}"); diff --git a/aai-service/provider/src/main/java/org/onap/ccsdk/sli/adaptors/aai/AAIServiceActivator.java b/aai-service/provider/src/main/java/org/onap/ccsdk/sli/adaptors/aai/AAIServiceActivator.java index 37a207fb..09877ee6 100755 --- a/aai-service/provider/src/main/java/org/onap/ccsdk/sli/adaptors/aai/AAIServiceActivator.java +++ b/aai-service/provider/src/main/java/org/onap/ccsdk/sli/adaptors/aai/AAIServiceActivator.java @@ -3,7 +3,7 @@ * openECOMP : SDN-C * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. + * reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,201 +39,201 @@ import org.slf4j.LoggerFactory; public class AAIServiceActivator implements BundleActivator { - private static final String DEFAULT_CONFIG_FILE_NAME = "aaiclient.config"; - private static final String DEFAULT_PROPERTY_FILE_NAME = "aaiclient.properties"; - private static final String DEFAULT_KEYWORD = "default"; - - private static final String SDNC_CONFIG_DIR = "SDNC_CONFIG_DIR"; - - private static final String BVC_PROPERTY_FILE = "/opt/bvc/controller/configuration/aaiclient.properties"; - private static final String DEFAULT_SDNC_PROPERTY_FILE = "/opt/sdnc/data/properties/aaiclient.properties"; - - private Set registrationSet = new HashSet(); - - private static final Logger LOG = LoggerFactory.getLogger(AAIServiceActivator.class); - - @Override - public void start(BundleContext ctx) throws Exception { - - System.setProperty("aaiclient.runtime", "OSGI"); - - String sdnConfigDirectory = System.getenv(SDNC_CONFIG_DIR); - - // check SDNC CONFIG DIR system property - if(sdnConfigDirectory == null ) { - LOG.error("System property SDNC_CONFIG_DIR is not defined."); - LOG.info("Defaulting SDNC_CONFIG_DIR to '/opt/sdnc/data/properties/'"); - sdnConfigDirectory = "/opt/sdnc/data/properties/"; - } - - LOG.debug("Configuration directory used : " + sdnConfigDirectory); - - // check existance of properties directory - File configDirectory = new File(sdnConfigDirectory); - if(!configDirectory.exists() || !configDirectory.isDirectory()){ - LOG.error("System property SDNC_CONFIG_DIR = '" + sdnConfigDirectory + "' does not point to a valid directory. AAIService will not be initialized."); - return; - } - - Properties properties = new Properties(); - InputStream input = null; - - // find aaiclient config file - File[] files = findFiles(configDirectory, DEFAULT_CONFIG_FILE_NAME); - - // read the aai config data - if(files != null && files.length > 0) { - LOG.debug("AAIService config file exists and it is named :" + files[0].getAbsolutePath() ); - try { - input = new FileInputStream(files[0]); - properties.load(input); - LOG.debug("Loaded AAI Client properties from " + files[0].getAbsolutePath()); - } catch (IOException exc) { - LOG.warn("Problem loading AAI Client properties from " + files[0].getAbsolutePath(), exc); - } finally { - if(input != null ) { - try { - input.close(); - } catch(Exception exc) { - // ignore - } - } - int size = properties.keySet().size() ; - if(size == 0) { - LOG.debug(files[0].getAbsolutePath() + " contained no entries. Adding the default entry"); - properties.put(DEFAULT_KEYWORD, DEFAULT_PROPERTY_FILE_NAME); - } - } - } else { - LOG.debug("No configuration entries were found. Adding the default entry"); - properties.put(DEFAULT_KEYWORD, DEFAULT_PROPERTY_FILE_NAME); - } - - Set entrySet = properties. stringPropertyNames(); - String value = null; - - // initialize AAI Service for each aai client property files - for(String entry : entrySet) { - value = properties.getProperty(entry); - if(value != null && !value.isEmpty()) { - - final String fileName = value; - - File[] propertyFileList = findFiles(configDirectory, fileName); - - for(File propertiesFile : propertyFileList) { - LOG.info(propertiesFile.getName()); - // Advertise AAI resource adaptor - AAIClient impl = null; - switch(entry) { - case DEFAULT_KEYWORD: - impl = new AAIService(propertiesFile.toURI().toURL()); - break; - case "trinity": - impl = new AAITrinityService(propertiesFile.toURI().toURL()); - break; - default: - LOG.error("Invalid configuration keyword '"+entry+"' detected in aaiclient.config. Aborting initialization"); - continue; - } - String regName = impl.getClass().getName(); - - LOG.debug("Registering AAIService service "+regName); - ServiceRegistration registration = ctx.registerService(regName, impl, null); - registrationSet.add(registration); - - } - } - } - } - -// @Override - @Deprecated - public void start1(BundleContext ctx) throws Exception { - - String sdnConfigDirectory = System.getenv(SDNC_CONFIG_DIR); - String propertiesPath = null; - - if (sdnConfigDirectory == null || sdnConfigDirectory.isEmpty()) { - String filename = DEFAULT_SDNC_PROPERTY_FILE; - File file = new File(filename); - if(file != null && file.exists()) { - propertiesPath = filename; - LOG.info("Using property file (1): " + propertiesPath); - } else { - filename = BVC_PROPERTY_FILE; - file = new File(filename); - if(file != null && file.exists()) { - propertiesPath = filename; - LOG.info("Using property file (1): " + propertiesPath); - } else { - throw new ConfigurationException("Cannot find config file - "+filename+" and "+SDNC_CONFIG_DIR+" is unset"); - } - } - } else { - propertiesPath = sdnConfigDirectory + "/aaiclient.properties"; - LOG.info("Environment variable " + SDNC_CONFIG_DIR + " set, - calculated path " + propertiesPath); - } - - File propFile = new File(propertiesPath); - if(!propFile.exists()) { - String filename = DEFAULT_SDNC_PROPERTY_FILE; - File file = new File(filename); - if(file != null && file.exists()) { - propertiesPath = filename; - LOG.info("Using property file (1): " + propertiesPath); - } else { - filename = BVC_PROPERTY_FILE; - file = new File(filename); - if(file != null && file.exists()) { - propertiesPath = filename; - LOG.info("Using property file (1): " + propertiesPath); - } else { - LOG.error("AnAI Service Property file " + propertiesPath + "does not exist."); - throw new ConfigurationException("Cannot find config file - "+propertiesPath+" and " + SDNC_CONFIG_DIR + " is unset."); - } - } - } - - // Advertise AAI resource adaptor - AAIClient impl = new AAIService(propFile.toURI().toURL()); - String regName = impl.getClass().getName(); - - LOG.debug("Registering AAIService service "+regName); - ServiceRegistration registration = ctx.registerService(regName, impl, null); - registrationSet.add(registration); - } - - @Override - public void stop(BundleContext ctx) throws Exception { - - Set localRegistrationSet = new HashSet(); - localRegistrationSet.addAll(registrationSet); - - for(ServiceRegistration registration : localRegistrationSet) { - if (registration != null) { - try { - AAIService aaiService = (AAIService)ctx.getService(registration.getReference()); - registration.unregister(); - registrationSet.remove(registration); - if(aaiService != null) { - aaiService.cleanUp(); - } - } catch(Exception exc) { - if(LOG.isDebugEnabled()) - LOG.debug(exc.getMessage()); - } - } - } - } - - private File[] findFiles(File configDirectory, final String filter) { - File[] files = configDirectory.listFiles(new FilenameFilter() { - public boolean accept(File dir, String name) { - return name.equalsIgnoreCase(filter); - } - }); - - return files; - } + private static final String DEFAULT_CONFIG_FILE_NAME = "aaiclient.config"; + private static final String DEFAULT_PROPERTY_FILE_NAME = "aaiclient.properties"; + private static final String DEFAULT_KEYWORD = "default"; + + private static final String SDNC_CONFIG_DIR = "SDNC_CONFIG_DIR"; + + private static final String BVC_PROPERTY_FILE = "/opt/bvc/controller/configuration/aaiclient.properties"; + private static final String DEFAULT_SDNC_PROPERTY_FILE = "/opt/sdnc/data/properties/aaiclient.properties"; + + private Set registrationSet = new HashSet(); + + private static final Logger LOG = LoggerFactory.getLogger(AAIServiceActivator.class); + + @Override + public void start(BundleContext ctx) throws Exception { + + System.setProperty("aaiclient.runtime", "OSGI"); + + String sdnConfigDirectory = System.getenv(SDNC_CONFIG_DIR); + + // check SDNC CONFIG DIR system property + if(sdnConfigDirectory == null ) { + LOG.error("System property SDNC_CONFIG_DIR is not defined."); + LOG.info("Defaulting SDNC_CONFIG_DIR to '/opt/sdnc/data/properties/'"); + sdnConfigDirectory = "/opt/sdnc/data/properties/"; + } + + LOG.debug("Configuration directory used : " + sdnConfigDirectory); + + // check existance of properties directory + File configDirectory = new File(sdnConfigDirectory); + if(!configDirectory.exists() || !configDirectory.isDirectory()){ + LOG.error("System property SDNC_CONFIG_DIR = '" + sdnConfigDirectory + "' does not point to a valid directory. AAIService will not be initialized."); + return; + } + + Properties properties = new Properties(); + InputStream input = null; + + // find aaiclient config file + File[] files = findFiles(configDirectory, DEFAULT_CONFIG_FILE_NAME); + + // read the aai config data + if(files != null && files.length > 0) { + LOG.debug("AAIService config file exists and it is named :" + files[0].getAbsolutePath() ); + try { + input = new FileInputStream(files[0]); + properties.load(input); + LOG.debug("Loaded AAI Client properties from " + files[0].getAbsolutePath()); + } catch (IOException exc) { + LOG.warn("Problem loading AAI Client properties from " + files[0].getAbsolutePath(), exc); + } finally { + if(input != null ) { + try { + input.close(); + } catch(Exception exc) { + LOG.debug(exc.getMessage()); + } + } + int size = properties.keySet().size() ; + if(size == 0) { + LOG.debug(files[0].getAbsolutePath() + " contained no entries. Adding the default entry"); + properties.put(DEFAULT_KEYWORD, DEFAULT_PROPERTY_FILE_NAME); + } + } + } else { + LOG.debug("No configuration entries were found. Adding the default entry"); + properties.put(DEFAULT_KEYWORD, DEFAULT_PROPERTY_FILE_NAME); + } + + Set entrySet = properties. stringPropertyNames(); + String value = null; + + // initialize AAI Service for each aai client property files + for(String entry : entrySet) { + value = properties.getProperty(entry); + if(value != null && !value.isEmpty()) { + + final String fileName = value; + + File[] propertyFileList = findFiles(configDirectory, fileName); + + for(File propertiesFile : propertyFileList) { + LOG.info(propertiesFile.getName()); + // Advertise AAI resource adaptor + AAIClient impl = null; + switch(entry) { + case DEFAULT_KEYWORD: + impl = new AAIService(propertiesFile.toURI().toURL()); + break; + case "trinity": + impl = new AAITrinityService(propertiesFile.toURI().toURL()); + break; + default: + LOG.error("Invalid configuration keyword '"+entry+"' detected in aaiclient.config. Aborting initialization"); + continue; + } + String regName = impl.getClass().getName(); + + LOG.debug("Registering AAIService service "+regName); + ServiceRegistration registration = ctx.registerService(regName, impl, null); + registrationSet.add(registration); + + } + } + } + } + +// @Override + @Deprecated + public void start1(BundleContext ctx) throws Exception { + + String sdnConfigDirectory = System.getenv(SDNC_CONFIG_DIR); + String propertiesPath = null; + + if (sdnConfigDirectory == null || sdnConfigDirectory.isEmpty()) { + String filename = DEFAULT_SDNC_PROPERTY_FILE; + File file = new File(filename); + if(file.exists()) { + propertiesPath = filename; + LOG.info("Using property file (1): " + propertiesPath); + } else { + filename = BVC_PROPERTY_FILE; + file = new File(filename); + if(file.exists()) { + propertiesPath = filename; + LOG.info("Using property file (1): " + propertiesPath); + } else { + throw new ConfigurationException("Cannot find config file - "+filename+" and "+SDNC_CONFIG_DIR+" is unset"); + } + } + } else { + propertiesPath = sdnConfigDirectory + "/aaiclient.properties"; + LOG.info("Environment variable " + SDNC_CONFIG_DIR + " set, - calculated path " + propertiesPath); + } + + File propFile = new File(propertiesPath); + if(!propFile.exists()) { + String filename = DEFAULT_SDNC_PROPERTY_FILE; + File file = new File(filename); + if(file.exists()) { + propertiesPath = filename; + LOG.info("Using property file (1): " + propertiesPath); + } else { + filename = BVC_PROPERTY_FILE; + file = new File(filename); + if(file.exists()) { + propertiesPath = filename; + LOG.info("Using property file (1): " + propertiesPath); + } else { + LOG.error("AnAI Service Property file " + propertiesPath + "does not exist."); + throw new ConfigurationException("Cannot find config file - "+propertiesPath+" and " + SDNC_CONFIG_DIR + " is unset."); + } + } + } + + // Advertise AAI resource adaptor + AAIClient impl = new AAIService(propFile.toURI().toURL()); + String regName = impl.getClass().getName(); + + LOG.debug("Registering AAIService service "+regName); + ServiceRegistration registration = ctx.registerService(regName, impl, null); + registrationSet.add(registration); + } + + @Override + public void stop(BundleContext ctx) throws Exception { + + Set localRegistrationSet = new HashSet(); + localRegistrationSet.addAll(registrationSet); + + for(ServiceRegistration registration : localRegistrationSet) { + if (registration != null) { + try { + AAIService aaiService = (AAIService)ctx.getService(registration.getReference()); + registration.unregister(); + registrationSet.remove(registration); + if(aaiService != null) { + aaiService.cleanUp(); + } + } catch(Exception exc) { + if(LOG.isDebugEnabled()) + LOG.debug(exc.getMessage()); + } + } + } + } + + private File[] findFiles(File configDirectory, final String filter) { + File[] files = configDirectory.listFiles(new FilenameFilter() { + public boolean accept(File dir, String name) { + return name.equalsIgnoreCase(filter); + } + }); + + return files; + } } -- cgit 1.2.3-korg