From 38713207b817ed4700f630748c681116338d32f0 Mon Sep 17 00:00:00 2001 From: Patrick Brady Date: Fri, 28 Jul 2017 11:29:23 -0700 Subject: Merging in bug fixes Change-Id: I85da90b9ba0d03149f42035a820c76ef0285e413 Signed-off-by: Patrick Brady Issue: APPC-100 --- .../openecomp/appc/dg/aai/impl/AAIPluginImpl.java | 4 +- .../org/openecomp/appc/dg/aai/impl/Constants.java | 5 + appc-dg/appc-dg-shared/appc-dg-common/pom.xml | 28 +- .../appc-dg-dependency-model/pom.xml | 23 +- .../helper/DependencyModelParser.java | 25 +- .../appc/dg/objects/VnfcDependencyModel.java | 2 +- .../org/openecomp/appc/mdsal/impl/Constants.java | 15 + .../openecomp/appc/mdsal/impl/MDSALStoreImpl.java | 18 +- .../mdsal/operation/ConfigOperation.java~ccmerge | 295 +++++++++ .../operation/ConfigOperationRequestFormatter.java | 2 +- appc-dg/appc-dg-shared/appc-dg-netconf/pom.xml | 2 - .../netconf/impl/NetconfClientPluginImplTest.java | 681 +++++++++++++++++++++ appc-dg/appc-dg-shared/pom.xml | 5 + 13 files changed, 1080 insertions(+), 25 deletions(-) create mode 100644 appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/operation/ConfigOperation.java~ccmerge create mode 100644 appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/NetconfClientPluginImplTest.java (limited to 'appc-dg/appc-dg-shared') diff --git a/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/impl/AAIPluginImpl.java b/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/impl/AAIPluginImpl.java index 308261cfc..93ad6a5e7 100644 --- a/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/impl/AAIPluginImpl.java +++ b/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/impl/AAIPluginImpl.java @@ -147,7 +147,7 @@ public class AAIPluginImpl implements AAIPlugin { vnfQueryResult = readVnf(vnfId); vnfType = vnfQueryResult.getAdditionProperties().get("vnf-type"); - vnfVersion = vnfQueryResult.getAdditionProperties().get("persona-model-version"); + vnfVersion = vnfQueryResult.getAdditionProperties().get(Constants.AAI_VNF_MODEL_VERSION_ID); for(Relationship vnfRelationship:vnfQueryResult.getRelationshipList()){ if("vserver".equalsIgnoreCase(vnfRelationship.getRelatedTo())){ @@ -258,7 +258,7 @@ public class AAIPluginImpl implements AAIPlugin { String[] additionalProperties = new String[]{"vnf-type","vnf-name", "in-maint","prov-status","heat-stack-id", - "is-closed-loop-disabled","orchestration-status","resource-version","persona-model-version"}; + "is-closed-loop-disabled","orchestration-status","resource-version",Constants.AAI_VNF_MODEL_VERSION_ID}; AAIQueryResult result = readRelationDataAndProperties(prefix, vnfContext,additionalProperties); diff --git a/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/impl/Constants.java b/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/impl/Constants.java index 0a9fe2176..1ccd6c47d 100644 --- a/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/impl/Constants.java +++ b/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/impl/Constants.java @@ -93,6 +93,11 @@ public class Constants { public static final String IS_ACQUIRE_ENTITLEMENT_REQUIRE ="is.acquire-entitlement.require"; public static final String IS_RELEASE_ENTITLEMENT_REQUIRE ="is.release-entitlement.require"; + /** + * AAI property names + */ + public static final String AAI_VNF_MODEL_VERSION_ID ="model-version-id"; + public enum ASDC_ARTIFACTS_FIELDS { SERVICE_UUID, DISTRIBUTION_ID, diff --git a/appc-dg/appc-dg-shared/appc-dg-common/pom.xml b/appc-dg/appc-dg-shared/appc-dg-common/pom.xml index ae59b07dc..1d92f1385 100644 --- a/appc-dg/appc-dg-shared/appc-dg-common/pom.xml +++ b/appc-dg/appc-dg-shared/appc-dg-common/pom.xml @@ -87,7 +87,31 @@ appc-dg-mdsal-store ${project.version} - + + com.fasterxml.jackson.dataformat + jackson-dataformat-yaml + ${jackson-yaml-version} + + + com.fasterxml.jackson.core + jackson-annotations + ${jackson-yaml-version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson-yaml-version} + + + com.fasterxml.jackson.core + jackson-core + ${jackson-yaml-version} + + + org.yaml + snakeyaml + ${snakeyaml.version} + @@ -102,7 +126,7 @@ org.openecomp.appc.dg.common.impl.* org.openecomp.appc.adapter.message.*,org.openecomp.appc.adapter.factory.*,org.openecomp.appc.adapter.messaging.*, *;resolution:=optional - appc-dg-mdsal-store,appc-dg-domain-model-lib,appc-dg-dependency-model,jackson-dataformat-yaml,jackson-databind;scope=compile|runtime;inline=false;artifactId=!org.eclipse.osgi + appc-dg-mdsal-store,appc-dg-domain-model-lib,appc-dg-dependency-model,jackson-dataformat-yaml,jackson-databind,jackson-core;scope=compile|runtime;inline=false;artifactId=!org.eclipse.osgi true diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/pom.xml b/appc-dg/appc-dg-shared/appc-dg-dependency-model/pom.xml index 20dbc6b46..52a3d5fcf 100644 --- a/appc-dg/appc-dg-shared/appc-dg-dependency-model/pom.xml +++ b/appc-dg/appc-dg-shared/appc-dg-dependency-model/pom.xml @@ -17,11 +17,6 @@ - - junit - junit - test - org.openecomp.appc appc-common @@ -35,12 +30,28 @@ com.fasterxml.jackson.dataformat jackson-dataformat-yaml - 2.3.2 + ${jackson-yaml-version} + + + com.fasterxml.jackson.core + jackson-annotations + ${jackson-yaml-version} com.fasterxml.jackson.core jackson-databind + ${jackson-yaml-version} + + + com.fasterxml.jackson.core + jackson-core + ${jackson-yaml-version} + + org.yaml + snakeyaml + ${snakeyaml.version} + commons-io commons-io diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/helper/DependencyModelParser.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/helper/DependencyModelParser.java index 222e3a02a..c06841251 100644 --- a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/helper/DependencyModelParser.java +++ b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/helper/DependencyModelParser.java @@ -68,7 +68,6 @@ public class DependencyModelParser { String prefix = "org.openecomp.resource.vfc."+vnfType+".abstract.nodes."; try { ObjectNode root = (ObjectNode) mapper.readTree(vnfModel); - logger.debug("VNF Model after parsing: " + root); if(root.get(TOPOLOGY_TEMPLATE) == null || root.get(TOPOLOGY_TEMPLATE).get("node_templates") == null) { throw new InvalidDependencyModel("Dependency model is missing 'topology_template' or 'node_templates' elements"); @@ -79,7 +78,8 @@ public class DependencyModelParser { Iterator> itretor = nodeTemplateNode.fields(); for (JsonNode yamlNode : nodeTemplateNode) { logger.debug("Processing node: " + yamlNode); - String vnfcType = itretor.next().getKey(); + String fullvnfcType = itretor.next().getValue().get("type").textValue(); + String vnfcType= getQualifiedVnfcType(fullvnfcType); String type = yamlNode.get("type").textValue(); type = type.substring(0,type.lastIndexOf(".")+1); if(type.concat(vnfcType).toLowerCase().startsWith(prefix.concat(vnfcType).toLowerCase())) { @@ -95,7 +95,7 @@ public class DependencyModelParser { }else { mandatory = yamlNode.get(PROPERTIES).findValue(MANDATORY).booleanValue(); } - String[] parentList = getDependencyArray(yamlNode); + String[] parentList = getDependencyArray(yamlNode,nodeTemplateNode); Node vnfcNode = getNode(dependencies, vnfcType); if (vnfcNode != null) { logger.debug("Dependency node already exists for vnfc Type: " + vnfcType); @@ -126,6 +126,10 @@ public class DependencyModelParser { return new VnfcDependencyModel(dependencies); } + private String getQualifiedVnfcType(String fullvnfcType) { + return fullvnfcType.substring(fullvnfcType.lastIndexOf(".")+1,fullvnfcType.length()); + } + private void addDependencies(Set> nodes, Node node, String[] parentList) { for (String type : parentList) { String parentType = getVnfcType(type); @@ -143,15 +147,18 @@ public class DependencyModelParser { } } - private String[] getDependencyArray(JsonNode node) { + private String[] getDependencyArray(JsonNode node, JsonNode nodeTemplateNode) { JsonNode requirementsNode = node.get("requirements"); List dependencyList = new ArrayList(); if(requirementsNode!=null) { for (JsonNode internalNode : requirementsNode) { - if (nodeNullCheck(internalNode) &&"tosca.capabilities.Node".equalsIgnoreCase(internalNode.get("capability").asText()) - && "tosca.relationships.DependsOn".equalsIgnoreCase(internalNode.get("relationship").asText())) { - if(internalNode.get("node") != null) { - dependencyList.add(internalNode.get("node").asText()); + //TODO : In this release we are supporting both relationship = tosca.capabilities.Node and relationship =tosca.relationships.DependsOn we need to remove one of them in next release post confirming with SDC team + if (nodeNullCheck(internalNode) &&"tosca.capabilities.Node".equalsIgnoreCase(internalNode.findValue("capability").asText()) + && ("tosca.relationships.DependsOn".equalsIgnoreCase(internalNode.findValue("relationship").asText()) || "tosca.capabilities.Node".equalsIgnoreCase(internalNode.findValue("relationship").asText()))) { + if(internalNode.findValue("node") != null) { + String nodeName = internalNode.findValue("node").asText(); + String fullVnfcName = nodeTemplateNode.get(nodeName).get("type").asText(); + dependencyList.add(getQualifiedVnfcType(fullVnfcName)); }else{ throw new InvalidDependencyModel("Error parsing dependency model. " + "Dependent Node not found for "+ node.get("type")); } @@ -164,7 +171,7 @@ public class DependencyModelParser { } private boolean nodeNullCheck(JsonNode internalNode) { - return internalNode.get("dependency") != null && internalNode.get("capability") != null && internalNode.get("relationship") != null; + return internalNode.get("dependency") != null && internalNode.findValue("capability") != null && internalNode.findValue("relationship") != null; } private Node getNode(Set> nodes, String vnfcType) { diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/VnfcDependencyModel.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/VnfcDependencyModel.java index 0eb11bf20..f8b0d0381 100644 --- a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/VnfcDependencyModel.java +++ b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/VnfcDependencyModel.java @@ -46,6 +46,6 @@ public class VnfcDependencyModel { for(Node node:dependencies){ stringBuilder.append(node.toString()).append(", "); } - return super.toString(); + return stringBuilder.toString(); } } diff --git a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/impl/Constants.java b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/impl/Constants.java index a367bdc89..711ec1d4e 100644 --- a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/impl/Constants.java +++ b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/impl/Constants.java @@ -80,6 +80,21 @@ public class Constants { */ public static final String CONFIG_URL = "https://localhost:8443/restconf/config"; + public static final String CONFIG_URL_DEFAULT = "https://localhost:8443/restconf/config"; + + public static final String CONFIG_URL_PROPERTY = "appc.LCM.provider.url"; + + public static final String CONFIG_PATH = "/restconf/config"; + + /** + * Restconf authentication user property name + */ + public static final String CONFIG_USER_PROPERTY = "appc.LCM.provider.user"; + + /** + * Restconf authentication password property name + */ + public static final String CONFIG_PASS_PROPERTY = "appc.LCM.provider.pass"; /** * Content for blueprint.xml used while creation of OSGI bundle. diff --git a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/impl/MDSALStoreImpl.java b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/impl/MDSALStoreImpl.java index 091c770fd..b90d9c0e5 100644 --- a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/impl/MDSALStoreImpl.java +++ b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/impl/MDSALStoreImpl.java @@ -24,6 +24,8 @@ package org.openecomp.appc.mdsal.impl; +import org.openecomp.appc.configuration.Configuration; +import org.openecomp.appc.configuration.ConfigurationFactory; import org.openecomp.appc.exceptions.APPCException; import org.openecomp.appc.mdsal.MDSALStore; import org.openecomp.appc.mdsal.exception.MDSALStoreException; @@ -38,6 +40,7 @@ import org.osgi.framework.FrameworkUtil; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.Date; +import java.util.Properties; import java.util.jar.Attributes; import java.util.jar.JarEntry; import java.util.jar.JarOutputStream; @@ -50,9 +53,20 @@ public class MDSALStoreImpl implements MDSALStore{ private static final EELFLogger logger = EELFManager.getInstance().getLogger(MDSALStoreImpl.class); + private static final Configuration configuration = ConfigurationFactory.getConfiguration(); + MDSALStoreImpl(){ - ConfigOperation.setUrl(Constants.CONFIG_URL); - ConfigOperation.setAuthentication(null,null); + String configUrl = null; + String user =null; + String password = null; + Properties properties = configuration.getProperties(); + if (properties != null) { + configUrl= properties.getProperty( Constants.CONFIG_URL_PROPERTY , Constants.CONFIG_URL_DEFAULT); + user = properties.getProperty(Constants.CONFIG_USER_PROPERTY); + password = properties.getProperty(Constants.CONFIG_PASS_PROPERTY); + } + ConfigOperation.setUrl(configUrl); + ConfigOperation.setAuthentication(user,password); } diff --git a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/operation/ConfigOperation.java~ccmerge b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/operation/ConfigOperation.java~ccmerge new file mode 100644 index 000000000..c1695d467 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/operation/ConfigOperation.java~ccmerge @@ -0,0 +1,295 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.appc.mdsal.operation; + +import org.openecomp.appc.exceptions.APPCException; +import org.openecomp.appc.mdsal.impl.Constants; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.commons.codec.binary.Base64; +import org.apache.http.HttpHeaders; +import org.apache.http.HttpResponse; +import org.apache.http.HttpVersion; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.conn.ClientConnectionManager; +import org.apache.http.conn.scheme.PlainSocketFactory; +import org.apache.http.conn.scheme.Scheme; +import org.apache.http.conn.scheme.SchemeRegistry; +import org.apache.http.conn.ssl.SSLSocketFactory; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; +import org.apache.http.params.BasicHttpParams; +import org.apache.http.params.HttpParams; +import org.apache.http.params.HttpProtocolParams; +import org.apache.http.protocol.HTTP; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.MalformedURLException; +import java.net.Socket; +import java.net.URL; +import java.security.*; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Iterator; + +import org.apache.commons.io.IOUtils; + +/** + * Provides method to store configuration to MD-SAL store. It also exposes doPut operation which can be used to invoke REST Put operation. +*/ +public class ConfigOperation { + private static final EELFLogger LOG = EELFManager.getInstance().getLogger(ConfigOperation.class); + + private static URL url; + private static String basicAuth; + + ConfigOperation(){} + + private static ConfigOperationRequestFormatter requestFormatter = new ConfigOperationRequestFormatter(); + + private static ObjectMapper mapper = new ObjectMapper(); + + /** + * This method stores configuration JSON to MD-SAL store. Following input parameters are expected as input + * @param configJson - configuration JSON as String. This value will be stored in MD-SAL store + * @param module - Module name that contains yang Schema + * @param containerName - yang container name which will be used as base container. + * @param subModules - Sub modules list if any. Order of sub module is top to bottom. + * @throws APPCException + */ + public static void storeConfig(String configJson , String module, String containerName, String... subModules ) throws APPCException { + if (configJson == null) { + throw new APPCException("Provided message was null"); + } + LOG.debug("Config JSON: " + configJson +"\n" + +"module" + module +"\n" + +"containerName" + containerName +"\n" + +"subModules length : " + subModules.length ); + + int httpCode; + String respBody ; + try { + String path = requestFormatter.buildPath(url, module, containerName, subModules); + LOG.debug("Configuration Path : " + path); + URL serviceUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), path); + HttpResponse response = doPut(serviceUrl , configJson); + httpCode = response.getStatusLine().getStatusCode(); + respBody = IOUtils.toString(response.getEntity().getContent()); + } catch (IOException e) { + LOG.error("Error while storing configuration json "+e.getMessage(), e); + throw new APPCException(e); + } + + if (httpCode < 200 || httpCode >= 300 ) { + try { + LOG.debug("Config operation Error response code: " + httpCode); + ArrayList errorMessage = new ArrayList<>(); + JsonNode responseJson = toJsonNodeFromJsonString(respBody); + if(responseJson!=null && responseJson.get("errors")!=null) { + JsonNode errors = responseJson.get("errors").get("error"); + for (Iterator i = errors.elements();i.hasNext();){ + JsonNode error = i.next(); + errorMessage.add(error.get("error-message").textValue()); + } + } + throw new APPCException("Failed to load config JSON to MD SAL store. Error code:" + httpCode +" Error Message:" + errorMessage.toString()); + } catch (Exception e) { + LOG.error("Error while loading config JSON to MD SAL store. Error code:" + httpCode +" Error Message:" + e.getMessage(), e); + throw new APPCException("Error while loading config JSON to MD SAL store. Error code:" + httpCode +" Error Message:" + e.getMessage(),e); + } + }else{ + LOG.debug("Config operation successful. Response code: " + httpCode); + } + } + + /** + * This is Generic method that can be used to perform REST Put operation + * @param url - Destination URL for put + * @param body - payload for put action which will be sent as request body. + * @return - HttpResponse object which is returned from put REST call. + * @throws APPCException + */ + public static HttpResponse doPut (URL url, String body) throws APPCException { + HttpPut put; + try { + put = new HttpPut(url.toExternalForm()); + put.setHeader(HttpHeaders.CONTENT_TYPE, Constants.OPERATION_APPLICATION_JSON); + put.setHeader(HttpHeaders.ACCEPT, Constants.OPERATION_APPLICATION_JSON); + + if (basicAuth != null) { + put.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + basicAuth); + } + + StringEntity entity = new StringEntity(body); + entity.setContentType(Constants.OPERATION_APPLICATION_JSON); + put.setEntity(new StringEntity(body)); + } catch (UnsupportedEncodingException e) { + throw new APPCException(e); + } + + HttpClient client = getHttpClient(); + + try { + return client.execute(put); + } catch (IOException e) { + throw new APPCException(e); + } + + } + + /** + * Updates the static var URL and returns the value; + * + * @return The new value of URL + */ + public static String getUrl() { + return url.toExternalForm(); + } + + public static void setUrl(String newUrl) { + try { + url = new URL(newUrl); + } catch (MalformedURLException e) { + LOG.error("Malformed URL " +newUrl + e.getMessage(), e); + } + } + + /** + * Sets the basic authentication header for the given user and password. If either entry is null then set basic auth + * to null + * + * @param user The user with optional domain name (for AAF) + * @param password The password for the user + * @return The new value of the basic auth string that will be used in the request headers + */ + public static String setAuthentication(String user, String password) { + if (user != null && password != null) { + String authStr = user + ":" + password; + basicAuth = new String(Base64.encodeBase64(authStr.getBytes())); + } else { + basicAuth = null; + } + return basicAuth; + } + + @SuppressWarnings("deprecation") + private static HttpClient getHttpClient() throws APPCException { + HttpClient client; + if (url.getProtocol().equals(Constants.OPERATION_HTTPS)) { + try { + KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); + trustStore.load(null, null); + MySSLSocketFactory sf = new MySSLSocketFactory(trustStore); + sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); + + HttpParams params = new BasicHttpParams(); + HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); + HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); + + SchemeRegistry registry = new SchemeRegistry(); + registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); + registry.register(new Scheme(Constants.OPERATION_HTTPS, sf, 443)); + registry.register(new Scheme(Constants.OPERATION_HTTPS, sf, 8443)); + registry.register(new Scheme("http", sf, 8181)); + + ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); + client = new DefaultHttpClient(ccm, params); + } catch (Exception e) { + LOG.error("Error creating HTTP Client. Creating default client." , e); + client = new DefaultHttpClient(); + } + } else if ("http".equals(url.getProtocol())) { + client = new DefaultHttpClient(); + } else { + throw new APPCException( + "The provider.topology.url property is invalid. The url did not start with http[s]"); + } + return client; + } + + @SuppressWarnings("deprecation") + private static class MySSLSocketFactory extends SSLSocketFactory { + private SSLContext sslContext = SSLContext.getInstance("TLS"); + + private MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, + KeyStoreException, UnrecoverableKeyException { + super(truststore); + + TrustManager tm = new X509TrustManager() { + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { + LOG.debug("Inside checkClientTrusted"); + } + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { + LOG.debug("Inside checkServerTrusted"); + } + + @Override + public X509Certificate[] getAcceptedIssuers() { + return new X509Certificate[1]; + } + }; + + sslContext.init(null, new TrustManager[]{ + tm + }, null); + } + + @Override + public Socket createSocket(Socket socket, String host, int port, boolean autoClose) + throws IOException { + return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose); + } + + @Override + public Socket createSocket() throws IOException { + return sslContext.getSocketFactory().createSocket(); + } + } + + private static JsonNode toJsonNodeFromJsonString(String jsonStr) { + JsonNode jsonNode = null; + if(jsonStr != null) { + try { + jsonNode = mapper.readTree(jsonStr); + } catch (IOException e) { + LOG.warn(String.format("Could not map %s to jsonNode.", jsonStr), e); + } + } + return jsonNode; + } + +} diff --git a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/operation/ConfigOperationRequestFormatter.java b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/operation/ConfigOperationRequestFormatter.java index d5d6a0cb5..94e120faf 100644 --- a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/operation/ConfigOperationRequestFormatter.java +++ b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/operation/ConfigOperationRequestFormatter.java @@ -42,7 +42,7 @@ public class ConfigOperationRequestFormatter { */ public String buildPath(URL url,String module, String containerName , String... subModules ) { - StringBuilder path = new StringBuilder( url.getPath()+ Constants.URL_BACKSLASH + module + ":"+containerName + Constants.URL_BACKSLASH); + StringBuilder path = new StringBuilder( Constants.CONFIG_PATH + Constants.URL_BACKSLASH + module + ":"+containerName + Constants.URL_BACKSLASH); if(subModules.length >0){ for(String subModule : subModules){ path.append(subModule); diff --git a/appc-dg/appc-dg-shared/appc-dg-netconf/pom.xml b/appc-dg/appc-dg-shared/appc-dg-netconf/pom.xml index 8ccb980e8..0aac26212 100644 --- a/appc-dg/appc-dg-shared/appc-dg-netconf/pom.xml +++ b/appc-dg/appc-dg-shared/appc-dg-netconf/pom.xml @@ -52,14 +52,12 @@ org.powermock powermock-api-mockito - 1.6.2 test org.powermock powermock-module-junit4 - 1.6.2 test diff --git a/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/NetconfClientPluginImplTest.java b/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/NetconfClientPluginImplTest.java new file mode 100644 index 000000000..66b3b15c3 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/NetconfClientPluginImplTest.java @@ -0,0 +1,681 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.appc.dg.netconf.impl; + +import org.openecomp.appc.exceptions.APPCException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Matchers; +import org.mockito.Mockito; +import org.openecomp.appc.adapter.netconf.*; +import org.openecomp.appc.adapter.netconf.util.Constants; +import org.openecomp.appc.dg.netconf.impl.NetconfClientPluginImpl; +import org.openecomp.sdnc.sli.SvcLogicContext; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import java.lang.reflect.Field; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +import static org.powermock.api.mockito.PowerMockito.when; + + + +@RunWith(PowerMockRunner.class) +@PrepareForTest({OperationalStateValidatorFactory.class, NetconfClientPluginImpl.class, FrameworkUtil.class, ObjectMapper.class}) + +public class NetconfClientPluginImplTest { + private NetconfClientPluginImpl netconfClientPlugin; + private NetconfDataAccessService dao; + private NetconfClientFactory clientFactory; + private Map params; + + private final BundleContext bundleContext = Mockito.mock(BundleContext.class); + private final Bundle bundleService = Mockito.mock(Bundle.class); + private final ServiceReference sref1 = Mockito.mock(ServiceReference.class); + private final ServiceReference sref2 = Mockito.mock(ServiceReference.class); + private final ServiceReference sref3 = Mockito.mock(ServiceReference.class); + private static final String DG_OUTPUT_STATUS_MESSAGE = "output.status.message"; + + + String host = "http://www.test.com"; + String host1 = "http://www.test1.com"; + String vnfType = "VNF"; + int port = 8080; + String username = "test"; + String password = "test"; + String connectionDetails = "{\"host\":\"" + host + "\",\"port\":" + port + ",\"username\":\"" + username + "\",\"password\":\"" + password + "\",\"capabilities\":null,\"additionalProperties\":null}"; + String fileContent = "\n" + + "\n" + + "\t\n" + + "\t\t\n" + + "\t\t\t\n" + + "\t\t \n" + + "\t\n" + + "'"; + String operationalState = "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "\n"; + + + @Before + public void setUp() throws NoSuchFieldException, IllegalAccessException { + clientFactory = new NetconfClientFactoryMock(); + + } + + + @Test + public void testConfigure() throws Exception { + + shortInit(); + SvcLogicContext ctx = new SvcLogicContext(); + + params = new HashMap<>(); + params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, connectionDetails); + params.put(Constants.FILE_CONTENT_FIELD_NAME, fileContent); + + netconfClientPlugin.configure(params, ctx); + + NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); + + try { + Assert.assertEquals("wrong configuration", fileContent, client.getConf()); + Assert.assertEquals("wrong host", host, client.getLastConnectionDetails().getHost()); + Assert.assertEquals("wrong port", port, client.getLastConnectionDetails().getPort()); + Assert.assertEquals("wrong username", username, client.getLastConnectionDetails().getUsername()); + Assert.assertEquals("wrong password", password, client.getLastConnectionDetails().getPassword()); + Assert.assertFalse(client.isConnection()); + } catch (Exception e) { + Assert.fail("failed with because of " + e.getCause()); + } + + + } + + + @Test + public void testConfigureNegativeIOException() throws Exception { + shortInit(); + SvcLogicContext ctx = new SvcLogicContext(); + + params = new HashMap<>(); + params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, "{" + connectionDetails); + params.put(Constants.FILE_CONTENT_FIELD_NAME, fileContent); + NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); + + + try { + netconfClientPlugin.configure(params, ctx); + Assert.assertTrue(false); + } catch (APPCException e) { + Assert.assertNull(client.getLastConnectionDetails()); + Assert.assertNull(client.getConf()); + } + + } + + @Test + public void testOperationStateValidation() throws Exception { + shortInit(); + SvcLogicContext ctx = new SvcLogicContext(); + DAOServiceMock daoServiceMock = (DAOServiceMock) dao; + daoServiceMock.setConfigFile(fileContent); + + NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); + client.setAnswer(operationalState); + + + params = new HashMap<>(); + params.put(Constants.VNF_TYPE_FIELD_NAME, vnfType); + params.put(Constants.VNF_HOST_IP_ADDRESS_FIELD_NAME, host1); + params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, connectionDetails); + MockOperationalStateValidatorImpl validatorMock = new MockOperationalStateValidatorImpl(); + validatorMock.setConfigurationFileName("VnfGetRunningConfig"); + + PowerMockito.mockStatic(OperationalStateValidatorFactory.class); + when(OperationalStateValidatorFactory.getOperationalStateValidator(Matchers.any(VnfType.class))).thenReturn(validatorMock); + + netconfClientPlugin.operationStateValidation(params, ctx); + + Assert.assertTrue("validation process failed", validatorMock.isValidated()); + Assert.assertEquals(fileContent, client.getLastMessage()); + } + + + @Test + public void testOperationStateValidationNegativeJsonProcessingNullIllegalStateException() throws Exception { + shortInit(); + SvcLogicContext ctx = new SvcLogicContext(); + DAOServiceMock daoServiceMock = (DAOServiceMock) dao; + daoServiceMock.setConfigFile(fileContent); + + NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); + client.setAnswer(operationalState); + + params = new HashMap<>(); + params.put(Constants.VNF_TYPE_FIELD_NAME, vnfType); + params.put(Constants.VNF_HOST_IP_ADDRESS_FIELD_NAME, host1); + params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, connectionDetails); + MockOperationalStateValidatorImpl validatorMock = new MockOperationalStateValidatorImpl(); + validatorMock.setConfigurationFileName("VnfGetRunningConfig"); + + PowerMockito.mockStatic(OperationalStateValidatorFactory.class); + when(OperationalStateValidatorFactory.getOperationalStateValidator(Matchers.any(VnfType.class))).thenReturn(validatorMock); + substituteMapper(true); + + try { + netconfClientPlugin.operationStateValidation(params, ctx); + substituteMapper(false); + } catch (APPCException e) { + substituteMapper(false); + Assert.assertNotNull(ctx.getAttribute(DG_OUTPUT_STATUS_MESSAGE)); + Assert.assertFalse(validatorMock.isValidated()); + Assert.assertNull(client.getLastMessage()); + } + } + + @Test + public void testOperationStateValidationNegativeConnectionDetailsAreNullNullPointerException() throws Exception { + shortInit(); + SvcLogicContext ctx = new SvcLogicContext(); + DAOServiceMock daoServiceMock = (DAOServiceMock) dao; + daoServiceMock.setConfigFile(fileContent); + + NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); + client.setAnswer(operationalState); + + + params = new HashMap<>(); + params.put(Constants.VNF_TYPE_FIELD_NAME, vnfType); + params.put(Constants.VNF_HOST_IP_ADDRESS_FIELD_NAME, host1); + params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, null); + MockOperationalStateValidatorImpl validatorMock = new MockOperationalStateValidatorImpl(); + validatorMock.setConfigurationFileName("VnfGetRunningConfig"); + + PowerMockito.mockStatic(OperationalStateValidatorFactory.class); + when(OperationalStateValidatorFactory.getOperationalStateValidator(Matchers.any(VnfType.class))).thenReturn(validatorMock); + ObjectMapper mapper = PowerMockito.mock(ObjectMapper.class); + final NetconfConnectionDetails netconfConnectionDetails = null; + when(mapper.readValue(Matchers.anyString(), Matchers.any(Class.class))).thenReturn(netconfConnectionDetails); + + + try { + netconfClientPlugin.operationStateValidation(params, ctx); + Assert.assertTrue(false); + } catch (APPCException e) { + Assert.assertNotNull(ctx.getAttribute(DG_OUTPUT_STATUS_MESSAGE)); + Assert.assertFalse("validation process failed", validatorMock.isValidated()); + + } + } + + + @Test + public void testOperationStateValidationNegativeAppcException() throws Exception { + shortInit(); + SvcLogicContext ctx = new SvcLogicContext(); + DAOServiceMock daoServiceMock = (DAOServiceMock) dao; + daoServiceMock.setConfigFile(fileContent); + + NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); + client.setAnswer("wrong"); + + + params = new HashMap<>(); + params.put(Constants.VNF_TYPE_FIELD_NAME, vnfType); + params.put(Constants.VNF_HOST_IP_ADDRESS_FIELD_NAME, host1); + params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, connectionDetails); + MockOperationalStateValidatorImpl validatorMock = new MockOperationalStateValidatorImpl(); + validatorMock.setConfigurationFileName("VnfGetRunningConfig"); + + PowerMockito.mockStatic(OperationalStateValidatorFactory.class); + when(OperationalStateValidatorFactory.getOperationalStateValidator(Matchers.any(VnfType.class))).thenReturn(validatorMock); + + + try { + netconfClientPlugin.operationStateValidation(params, ctx); + Assert.assertTrue(false); + } catch (APPCException e) { + Assert.assertNotNull(ctx.getAttribute(DG_OUTPUT_STATUS_MESSAGE)); + Assert.assertFalse("validation process failed", validatorMock.isValidated()); + + } + } + + + @Test + public void testOperationStateValidatioConnectionDetailsInParamsAreEmpty() throws Exception { + shortInit(); + SvcLogicContext ctx = new SvcLogicContext(); + DAOServiceMock daoServiceMock = (DAOServiceMock) dao; + daoServiceMock.setConfigFile(fileContent); + + NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); + client.setAnswer(operationalState); + ((DAOServiceMock) dao).setConnection(getConnectionDetails()); + + + params = new HashMap<>(); + params.put(Constants.VNF_TYPE_FIELD_NAME, vnfType); + params.put(Constants.VNF_HOST_IP_ADDRESS_FIELD_NAME, host1); + params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, ""); + MockOperationalStateValidatorImpl validatorMock = new MockOperationalStateValidatorImpl(); + validatorMock.setConfigurationFileName("VnfGetRunningConfig"); + + PowerMockito.mockStatic(OperationalStateValidatorFactory.class); + when(OperationalStateValidatorFactory.getOperationalStateValidator(Matchers.any(VnfType.class))).thenReturn(validatorMock); + + netconfClientPlugin.operationStateValidation(params, ctx); + + Assert.assertTrue("validation process failed", validatorMock.isValidated()); + Assert.assertEquals(fileContent, client.getLastMessage()); + } + + @Test + public void testOperationStateValidatioConnectionDetailsInParamsAreNull() throws Exception { + shortInit(); + SvcLogicContext ctx = new SvcLogicContext(); + DAOServiceMock daoServiceMock = (DAOServiceMock) dao; + daoServiceMock.setConfigFile(fileContent); + + NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); + client.setAnswer(operationalState); + ((DAOServiceMock) dao).setConnection(getConnectionDetails()); + + + params = new HashMap<>(); + params.put(Constants.VNF_TYPE_FIELD_NAME, vnfType); + params.put(Constants.VNF_HOST_IP_ADDRESS_FIELD_NAME, host1); + params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, null); + MockOperationalStateValidatorImpl validatorMock = new MockOperationalStateValidatorImpl(); + validatorMock.setConfigurationFileName("VnfGetRunningConfig"); + + PowerMockito.mockStatic(OperationalStateValidatorFactory.class); + when(OperationalStateValidatorFactory.getOperationalStateValidator(Matchers.any(VnfType.class))).thenReturn(validatorMock); + + netconfClientPlugin.operationStateValidation(params, ctx); + + Assert.assertTrue("validation process failed", validatorMock.isValidated()); + Assert.assertEquals(fileContent, client.getLastMessage()); + } + + + @Test + public void testBackupConfiguration() throws Exception { + shortInit(); + SvcLogicContext ctx = new SvcLogicContext(); + params = new HashMap<>(); + params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, connectionDetails); + NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); + client.setConf(fileContent); + netconfClientPlugin.backupConfiguration(params, ctx); + + DAOServiceMock mockdao = (DAOServiceMock) dao; + DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd"); + Date date = new Date(); + String creationDateExpected = dateFormat.format(date); + String creationDateActual = mockdao.getBackupConf().get("creationDate").substring(0, 10); + + + Assert.assertEquals("wrong configuration in db", fileContent, mockdao.getBackupConf().get("logText")); + Assert.assertEquals(creationDateExpected, creationDateActual); + + + } + + + @Test + public void testBackupConfigurationNegativeDgErrorFieldName() throws Exception { + shortInit(); + SvcLogicContext ctx = new SvcLogicContext(); + params = new HashMap<>(); + params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, "{" + connectionDetails); + NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); + client.setConf(fileContent); + try { + netconfClientPlugin.backupConfiguration(params, ctx); + Assert.assertTrue(false); + } catch (APPCException e) { + Assert.assertNotNull(ctx.getAttribute(DG_OUTPUT_STATUS_MESSAGE)); + + DAOServiceMock mockdao = (DAOServiceMock) dao; + Assert.assertNull(mockdao.getBackupConf()); + } + + } + + @Test + public void testGetConfig() throws Exception { + fullInit(); + String entity = "123"; + + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("entity", entity); + + params = new HashMap<>(); + params.put("conf-id", "current"); + params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, connectionDetails); + NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); + client.setConf(fileContent); + + + netconfClientPlugin.getConfig(params, ctx); + + Assert.assertEquals("Success", ctx.getAttribute("getConfig_Result")); + Assert.assertEquals(fileContent, ctx.getAttribute("fullConfig")); + Assert.assertNotNull(ctx.getAttribute(entity + ".Configuration")); + Assert.assertEquals(fileContent, ctx.getAttribute(entity + ".Configuration")); + } + + + @Test + public void testGetConfigNegativeConfigurationNull() throws Exception { + fullInit(); + String entity = "123"; + + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("entity", entity); + + params = new HashMap<>(); + params.put("conf-id", "current"); + params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, connectionDetails); + + + netconfClientPlugin.getConfig(params, ctx); + + Assert.assertEquals("failure", ctx.getAttribute("getConfig_Result")); + Assert.assertNull(ctx.getAttribute("fullConfig")); + Assert.assertNull(ctx.getAttribute(entity + ".Configuration")); + Assert.assertNull(ctx.getAttribute(entity + ".Configuration")); + } + + + @Test + public void testGetConfigNegativeNotSupportedConfId() throws Exception { + fullInit(); + String entity = "123"; + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("entity", entity); + + params = new HashMap<>(); + params.put("conf-id", "current1"); + params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, connectionDetails); + + + netconfClientPlugin.getConfig(params, ctx); + + Assert.assertNull(ctx.getAttribute("getConfig_Result")); + Assert.assertNull(ctx.getAttribute("fullConfig")); + Assert.assertNull(ctx.getAttribute(entity + ".Configuration")); + Assert.assertNull(ctx.getAttribute(entity + ".Configuration")); + } + + @Test + public void testGetConfigNegativeWronjJsonConnectionDetailsException() throws Exception { + fullInit(); + String entity = "123"; + + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("entity", entity); + + params = new HashMap<>(); + params.put("conf-id", "current"); + params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, "{" + connectionDetails); + + + try { + netconfClientPlugin.getConfig(params, ctx); + Assert.assertTrue(false); + } catch (APPCException e) { + Assert.assertEquals("failure", ctx.getAttribute("getConfig_Result")); + Assert.assertNull(ctx.getAttribute("fullConfig")); + Assert.assertNull(ctx.getAttribute(entity + ".Configuration")); + Assert.assertNull(ctx.getAttribute(entity + ".Configuration")); + Assert.assertNotNull(ctx.getAttribute(DG_OUTPUT_STATUS_MESSAGE)); + } + + + } + + @Test + public void testGetRunningConfig() throws Exception { + fullInit(); + SvcLogicContext ctx = new SvcLogicContext(); + params = new HashMap<>(); + params.put("host-ip-address", host); + params.put("user-name", username); + params.put("password", password); + params.put("port-number", String.valueOf(port)); + + NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); + client.setConf(fileContent); + + netconfClientPlugin.getRunningConfig(params, ctx); + + Assert.assertEquals("Success", ctx.getAttribute("getRunningConfig_Result")); + Assert.assertEquals(fileContent, ctx.getAttribute("running-config")); + Assert.assertEquals("success", ctx.getStatus()); + } + + @Test + public void testGetRunningConfigWithoutPortNumberDgErrorFieldNameException() throws Exception { + fullInit(); + SvcLogicContext ctx = new SvcLogicContext(); + params = new HashMap<>(); + params.put("host-ip-address", host); + params.put("user-name", username); + params.put("password", password); + + NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); + client.setConf(fileContent); + + try { + netconfClientPlugin.getRunningConfig(params, ctx); + Assert.assertTrue(false); + } catch (APPCException e) { + Assert.assertEquals("failure", ctx.getAttribute("getRunningConfig_Result")); + Assert.assertNull(ctx.getAttribute("running-config")); + Assert.assertNotNull(ctx.getAttribute(DG_OUTPUT_STATUS_MESSAGE)); + } + + + } + + @Test + public void testGetRunningConfigNegativeConfigurationNull() throws Exception { + fullInit(); + SvcLogicContext ctx = new SvcLogicContext(); + params = new HashMap<>(); + params.put("host-ip-address", host); + params.put("user-name", username); + params.put("password", password); + params.put("port-number", String.valueOf(port)); + + netconfClientPlugin.getRunningConfig(params, ctx); + + Assert.assertEquals("failure", ctx.getAttribute("getRunningConfig_Result")); + Assert.assertNull(ctx.getAttribute("running-config")); + } + + @Test + public void testValidateMandatoryParamNegativeEmptyParamValue() throws Exception { + shortInit(); + String paramName = "test"; + String paramValue = ""; + + try { + netconfClientPlugin.validateMandatoryParam(paramName, paramValue); + Assert.assertTrue(false); + } catch (Exception e) { + Assert.assertTrue(true); + } + } + + @Test + public void testRetrieveConnectionDetails() throws Exception { + shortInit(); + DAOServiceMock daoServiceMock = (DAOServiceMock) dao; + daoServiceMock.setConfigFile(fileContent); + ConnectionDetails connectionDetails1 = getConnectionDetails(); + daoServiceMock.setConnection(connectionDetails1); + + NetconfConnectionDetails connectionDetailsActual = netconfClientPlugin.retrieveConnectionDetails(VnfType.VNF); + + + Assert.assertEquals("wrong host", connectionDetails1.getHost(), connectionDetailsActual.getHost()); + Assert.assertEquals("wrong password", connectionDetails1.getPassword(), connectionDetailsActual.getPassword()); + Assert.assertEquals("wrong port", connectionDetails1.getPort(), connectionDetailsActual.getPort()); + Assert.assertEquals("wrong usename", connectionDetails1.getUsername(), connectionDetailsActual.getUsername()); + } + + + @Test + public void testRetrieveConnectionDetailsNegativeMissingConfiguration() throws Exception { + shortInit(); + DAOServiceMock daoServiceMock = (DAOServiceMock) dao; + daoServiceMock.setConfigFile(fileContent); + ConnectionDetails connectionDetails1 = getConnectionDetails(); + daoServiceMock.setConnection(connectionDetails1); + + NetconfConnectionDetails connectionDetailsActual = null; + try { + connectionDetailsActual = netconfClientPlugin.retrieveConnectionDetails(VnfType.MOCK); + Assert.assertTrue(false); + } catch (APPCException e) { + Assert.assertNull(connectionDetailsActual); + } + + + } + + @Test + public void testRetrieveConfigurationFileContent() throws Exception { + shortInit(); + + DAOServiceMock daoServiceMock = (DAOServiceMock) dao; + daoServiceMock.setConfigFile(fileContent); + + Assert.assertEquals("wrong config in a database", fileContent, netconfClientPlugin.retrieveConfigurationFileContent("VnfGetRunningConfig")); + } + + private ConnectionDetails getConnectionDetails() { + + ConnectionDetails connectionDetails = new ConnectionDetails(); + connectionDetails.setPassword(password); + connectionDetails.setPort(port); + connectionDetails.setUsername(username); + connectionDetails.setHost(host); + return connectionDetails; + } + + + private void initDao() throws NoSuchFieldException, IllegalAccessException { + dao = new DAOServiceMock(); + PowerMockito.mockStatic(FrameworkUtil.class); + when(FrameworkUtil.getBundle(Matchers.any(Class.class))).thenReturn(bundleService); + when(bundleService.getBundleContext()).thenReturn(bundleContext); + when(bundleContext.getServiceReference(NetconfDataAccessService.class)).thenReturn(sref1); + when(bundleContext.getService(sref1)).thenReturn(dao); + + + } + + private void fullInit() throws NoSuchFieldException, IllegalAccessException { + initClientFactory(); + initClientFactory2(); + initDao(); + netconfClientPlugin = new NetconfClientPluginImpl(); + netconfClientPlugin.setDao(this.dao); + } + + private void shortInit() throws NoSuchFieldException, IllegalAccessException { + initClientFactory(); + initDao(); + netconfClientPlugin = new NetconfClientPluginImpl(); + netconfClientPlugin.setDao(this.dao); + } + + private void initClientFactory() throws NoSuchFieldException, IllegalAccessException { + + PowerMockito.mockStatic(FrameworkUtil.class); + when(FrameworkUtil.getBundle(Matchers.any(Class.class))).thenReturn(bundleService); + when(bundleService.getBundleContext()).thenReturn(bundleContext); + when(bundleContext.getServiceReference(NetconfClientFactory.class)).thenReturn(sref2); + when(bundleContext.getService(sref2)).thenReturn(clientFactory); + + } + + private void initClientFactory2() { + PowerMockito.mockStatic(FrameworkUtil.class); + when(FrameworkUtil.getBundle(Matchers.any(Class.class))).thenReturn(bundleService); + when(bundleService.getBundleContext()).thenReturn(bundleContext); + when(bundleContext.getServiceReference(Matchers.anyString())).thenReturn(sref3); + when(bundleContext.getService(sref3)).thenReturn(clientFactory); + } + + private void substituteMapper(boolean command) throws NoSuchFieldException, IllegalAccessException { + ObjectMapper mapper = new ObjectMapperMock(); + ObjectMapper mapper2 = new ObjectMapper(); + Field field = NetconfClientPluginImpl.class.getDeclaredField("mapper"); + field.setAccessible(true); + if (command) { + field.set(netconfClientPlugin, mapper); + } else { + field.set(netconfClientPlugin, mapper2); + } + } + +} diff --git a/appc-dg/appc-dg-shared/pom.xml b/appc-dg/appc-dg-shared/pom.xml index 9082e0d0e..43396d0a4 100644 --- a/appc-dg/appc-dg-shared/pom.xml +++ b/appc-dg/appc-dg-shared/pom.xml @@ -9,6 +9,11 @@ appc-dg-shared pom + + 2.8.1 + 1.15 + + appc-dg-common appc-dg-dependency-model -- cgit 1.2.3-korg