diff options
author | Singal, Kapil (ks220y) <ks220y@att.com> | 2021-04-26 13:41:57 -0400 |
---|---|---|
committer | KAPIL SINGAL <ks220y@att.com> | 2021-04-27 14:30:34 +0000 |
commit | 7b25afd7fbb945686f5444e05e5e15716052b027 (patch) | |
tree | 98be595154b40b9cd07776800f6ea8a5020e1e86 /adaptors/netconf-adaptor/netconf-adaptor-bundle/src | |
parent | 70ac2b906e4e80f817185542a649f188fc9178b0 (diff) |
Moving Netconf-adaptor from APPC to CCSDK SLI
Issue-ID: CCSDK-3198
Signed-off-by: Singal, Kapil (ks220y) <ks220y@att.com>
Change-Id: I638d57729d100211325f4e3121970d6737b9a50c
Diffstat (limited to 'adaptors/netconf-adaptor/netconf-adaptor-bundle/src')
45 files changed, 4106 insertions, 0 deletions
diff --git a/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/ConnectionDetails.java b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/ConnectionDetails.java new file mode 100644 index 000000000..d9a593d8f --- /dev/null +++ b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/ConnectionDetails.java @@ -0,0 +1,66 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 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. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.netconf; + + +public class ConnectionDetails { + + private String host; + private int port; + private String username; + private String password; + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } + + public int getPort() { + return port; + } + + public void setPort(int port) { + this.port = port; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + +} diff --git a/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/HttpClient.java b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/HttpClient.java new file mode 100644 index 000000000..e665db62f --- /dev/null +++ b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/HttpClient.java @@ -0,0 +1,204 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 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. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.netconf; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.MalformedURLException; +import java.net.URL; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.auth.AuthScope; +import org.apache.http.auth.UsernamePasswordCredentials; +import org.apache.http.client.CredentialsProvider; +import org.apache.http.client.methods.HttpDelete; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.BasicCredentialsProvider; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.utils.configuration.Configuration; +import org.onap.ccsdk.sli.core.utils.configuration.ConfigurationFactory; + +public class HttpClient { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(HttpClient.class); + + private static final Configuration configuration = ConfigurationFactory.getConfiguration(); + + @SuppressWarnings("deprecation") + public static int postMethod(String protocol, String ip, int port, String path, String payload, + String contentType) throws SvcLogicException { + + logger.info("Sending POST request to " + path); + + HttpPost post; + try { + + URL serviceUrl = new URL(protocol, ip, port, path); + post = new HttpPost(serviceUrl.toExternalForm()); + post.setHeader("Content-Type", contentType); + + StringEntity entity = new StringEntity(payload); + entity.setContentType(contentType); + post.setEntity(new StringEntity(payload)); + } catch (UnsupportedEncodingException | MalformedURLException e) { + throw new SvcLogicException(e.toString(), e); + } + + logger.debug("Sending request " + post); + + CredentialsProvider credsProvider = new BasicCredentialsProvider(); + credsProvider.setCredentials(new AuthScope(ip, port), new UsernamePasswordCredentials( + configuration.getProperty("username"), configuration.getProperty("password"))); + CloseableHttpClient client = + HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); + + int httpCode; + try { + HttpResponse response = client.execute(post); + httpCode = response.getStatusLine().getStatusCode(); + } catch (IOException e) { + throw new SvcLogicException(e.toString()); + } + return httpCode; + } + + @SuppressWarnings("deprecation") + public static int putMethod(String protocol, String ip, int port, String path, String payload, + String contentType) throws SvcLogicException { + + logger.info("Sending PUT request to " + path); + + HttpPut put; + try { + + URL serviceUrl = new URL(protocol, ip, port, path); + put = new HttpPut(serviceUrl.toExternalForm()); + put.setHeader("Content-Type", contentType); + + StringEntity entity = new StringEntity(payload); + entity.setContentType(contentType); + put.setEntity(new StringEntity(payload)); + } catch (UnsupportedEncodingException | MalformedURLException e) { + throw new SvcLogicException(e.toString()); + } + + logger.debug("Sending request " + put); + + CredentialsProvider credsProvider = new BasicCredentialsProvider(); + credsProvider.setCredentials(new AuthScope(ip, port), new UsernamePasswordCredentials( + configuration.getProperty("username"), configuration.getProperty("password"))); + CloseableHttpClient client = + HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); + + int httpCode; + try { + HttpResponse response = client.execute(put); + httpCode = response.getStatusLine().getStatusCode(); + } catch (IOException e) { + throw new SvcLogicException(e.toString()); + } + return httpCode; + } + + @SuppressWarnings("deprecation") + public static String getMethod(String protocol, String ip, int port, String path, + String contentType) throws SvcLogicException { + + logger.info("Sending GET request to " + path); + + HttpGet get; + try { + + URL serviceUrl = new URL(protocol, ip, port, path); + get = new HttpGet(serviceUrl.toExternalForm()); + get.setHeader("Content-Type", contentType); + } catch (MalformedURLException e) { + throw new SvcLogicException(e.toString()); + } + + logger.debug("Sending request " + get); + + CredentialsProvider credsProvider = new BasicCredentialsProvider(); + credsProvider.setCredentials(new AuthScope(ip, port), new UsernamePasswordCredentials( + configuration.getProperty("username"), configuration.getProperty("password"))); + CloseableHttpClient client = + HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); + + int httpCode; + String result; + + try { + HttpResponse response = client.execute(get); + httpCode = response.getStatusLine().getStatusCode(); + result = (httpCode == HttpStatus.SC_OK) ? response.getEntity().toString() : null; + } catch (IOException e) { + throw new SvcLogicException(e.toString()); + } + + return result; + } + + @SuppressWarnings("deprecation") + public static int deleteMethod(String protocol, String ip, int port, String path, + String contentType) throws SvcLogicException { + + logger.info("Sending DELETE request to " + path); + + HttpDelete delete; + try { + + URL serviceUrl = new URL(protocol, ip, port, path); + delete = new HttpDelete(serviceUrl.toExternalForm()); + delete.setHeader("Content-Type", contentType); + } catch (MalformedURLException e) { + throw new SvcLogicException(e.toString()); + } + + logger.debug("Sending request " + delete); + + CredentialsProvider credsProvider = new BasicCredentialsProvider(); + credsProvider.setCredentials(new AuthScope(ip, port), new UsernamePasswordCredentials( + configuration.getProperty("username"), configuration.getProperty("password"))); + CloseableHttpClient client = + HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); + + int httpCode; + + try { + HttpResponse response = client.execute(delete); + httpCode = response.getStatusLine().getStatusCode(); + } catch (IOException e) { + throw new SvcLogicException(e.toString()); + } + + return httpCode; + } +} diff --git a/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/MockOperationalStateValidatorImpl.java b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/MockOperationalStateValidatorImpl.java new file mode 100644 index 000000000..fceb4c3ce --- /dev/null +++ b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/MockOperationalStateValidatorImpl.java @@ -0,0 +1,47 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 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. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.netconf; + +import org.onap.ccsdk.sli.core.sli.SvcLogicException; + +public class MockOperationalStateValidatorImpl implements OperationalStateValidator { + + @Override + public VnfType getVnfType() { + return VnfType.MOCK; + } + + @Override + public String getConfigurationFileName() { + return OperationalStateValidatorFactory.configuration + .getProperty(this.getClass().getCanonicalName() + CONFIG_FILE_PROPERTY_SUFFIX); + } + + @Override + public void validateResponse(String response) throws SvcLogicException { + if(response != null && response.toUpperCase().contains("INVALID")){ + throw new SvcLogicException("INVALID"); + } + } +} diff --git a/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/NetconfAdaptorConstants.java b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/NetconfAdaptorConstants.java new file mode 100644 index 000000000..1b41cada3 --- /dev/null +++ b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/NetconfAdaptorConstants.java @@ -0,0 +1,69 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 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. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.netconf; + +public class NetconfAdaptorConstants { + + public static final String CONFIGURE_PATH = "/restconf/config/opendaylight-inventory:nodes/node/"; + public static final String CONNECT_PATH = "/restconf/config/opendaylight-inventory:nodes/node/controller-config/yang-ext:mount/config:modules"; + public static final String CHECK_CONNECTION_PATH = "/restconf/operational/opendaylight-inventory:nodes/node/"; + public static final String DISCONNECT_PATH = "/restconf/config/opendaylight-inventory:nodes/node/controller-config/yang-ext:mount/config:modules/module/odl-sal-netconf-connector-cfg:sal-netconf-connector/"; + + public static final String CONTROLLER_IP = "127.0.0.1"; + public static final int CONTROLLER_PORT = 8181; + public static final String PROTOCOL = "http"; + + // tables and fields + public static final String NETCONF_SCHEMA = "sdnctl"; + public static final String DEVICE_AUTHENTICATION_TABLE_NAME = "DEVICE_AUTHENTICATION"; + public static final String CONFIGFILES_TABLE_NAME = "CONFIGFILES"; + public static final String DEVICE_INTERFACE_LOG_TABLE_NAME = "DEVICE_INTERFACE_LOG"; + public static final String FILE_CONTENT_TABLE_FIELD_NAME = "FILE_CONTENT"; + public static final String FILE_NAME_TABLE_FIELD_NAME = "FILE_NAME"; + public static final String USER_NAME_TABLE_FIELD_NAME = "USER_NAME"; + public static final String PASSWORD_TABLE_FIELD_NAME = "PASSWORD"; + public static final String VM_HOST_TABLE_FIELD_NAME = "VM_HOST"; + public static final String VM_NAME_TABLE_FIELD_NAME = "VM_NAME"; + public static final String PORT_NUMBER_TABLE_FIELD_NAME = "PORT_NUMBER"; + public static final String VNF_TYPE_TABLE_FIELD_NAME = "VNF_TYPE"; + public static final String SERVICE_INSTANCE_ID_FIELD_NAME = "SERVICE_INSTANCE_ID"; + public static final String REQUEST_ID_FIELD_NAME = "REQUEST_ID"; + public static final String CREATION_DATE_FIELD_NAME = "CREATION_DATE"; + public static final String LOG_FIELD_NAME = "LOG"; + + // input fields names + public static final String VNF_TYPE_FIELD_NAME = "org.onap.appc.vftype"; + public static final String TARGET_VNF_TYPE = "target-vnf-type"; + public static final String FILE_CONTENT_FIELD_NAME = "file-content"; + public static final String CONNECTION_DETAILS_FIELD_NAME = "connection-details"; + public static final String CONFIGURATION_FILE_FIELD_NAME = "configuration-file-name"; + public static final String VNF_HOST_IP_ADDRESS_FIELD_NAME = "vnf-host-ip-address"; + public static final String DG_ERROR_FIELD_NAME = "org.onap.appc.dg.error"; + public static final String RESOURCEKEY = "resourceKey"; + public static final String ATTRIBUTE_ERROR_MESSAGE = "error-message"; + public static final String DG_OUTPUT_STATUS_MESSAGE = "output.status.message"; + + private NetconfAdaptorConstants() { + } +} diff --git a/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/NetconfClient.java b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/NetconfClient.java new file mode 100644 index 000000000..f9707e1fa --- /dev/null +++ b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/NetconfClient.java @@ -0,0 +1,63 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 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. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.netconf; + +import org.onap.ccsdk.sli.core.sli.SvcLogicException; + + + +public interface NetconfClient { + + /** + * Open connection to netconf device. + * + * @param connectionDetails object providing details required for netconf connection + */ + void connect(NetconfConnectionDetails connectionDetails) throws SvcLogicException; + + /** + * Send Netconf message to device and receive response. + * + * @param message input netconf xml message + * @return output netconf xml message + */ + String exchangeMessage(String message) throws SvcLogicException; + + /** + * send configuration to Netconf server + * + * @param configuration - xml configuration payload + */ + void configure(String configuration) throws SvcLogicException; + + /** + * returns running configuration of Netconf server + */ + String getConfiguration() throws SvcLogicException; + + /** + * Disconnect from netconf device. + */ + void disconnect() throws SvcLogicException; +} diff --git a/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/NetconfClientFactory.java b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/NetconfClientFactory.java new file mode 100644 index 000000000..d1e78a4cc --- /dev/null +++ b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/NetconfClientFactory.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 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. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.netconf; + +import org.onap.ccsdk.sli.adaptors.netconf.jsch.NetconfClientJsch; +import org.onap.ccsdk.sli.adaptors.netconf.odlconnector.NetconfClientRestconfImpl; + +public class NetconfClientFactory { + + public NetconfClient getNetconfClient(NetconfClientType type){ + + if(type==NetconfClientType.RESTCONF) { + return new NetconfClientRestconfImpl(); + }else if(type == NetconfClientType.SSH){ + return new NetconfClientJsch(); + } + + return null; + } +} diff --git a/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/NetconfClientRestconf.java b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/NetconfClientRestconf.java new file mode 100644 index 000000000..668d965e5 --- /dev/null +++ b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/NetconfClientRestconf.java @@ -0,0 +1,67 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 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. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.netconf; + +import org.onap.ccsdk.sli.core.sli.SvcLogicException; + + + +public interface NetconfClientRestconf { + + /* + mount device to controller + @param deviceMountPointName - the name of the mounting point in controller + @param payload - json data describing device info + */ + void connect(String deviceMountPointName, String payload) throws SvcLogicException; + + /* + check connection to device + @param deviceMountPointName - the name of the mounting point in controller + */ + boolean checkConnection(String deviceMountPointName) throws SvcLogicException; + + /* + send configuration to Netconf server + @param configuration - xml configuration payload + @param deviceMountPointName - the name of the mounting point in controller + @param moduleName - name of the yang model + @param nodeName - name of the node created in server + */ + void configure(String configuration, String deviceMountPointName, String moduleName, String nodeName) throws SvcLogicException; + + /* + returns configuration of Netconf server + @param deviceMountPointName - the name of the mounting point in controller + @param moduleName - name of the yang model + @param nodeName - name of the node created in server + */ + String getConfiguration(String deviceName, String moduleName, String nodeName) throws SvcLogicException; + + /* + unmount device + @param deviceMountPointName - the name of the mounting point in controller + */ + void disconnect(String deviceMountPointName) throws SvcLogicException; +} diff --git a/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/NetconfClientType.java b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/NetconfClientType.java new file mode 100644 index 000000000..88d9f2cae --- /dev/null +++ b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/NetconfClientType.java @@ -0,0 +1,30 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 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. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.netconf; + + +public enum NetconfClientType { + RESTCONF, + SSH +} diff --git a/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/NetconfConnectionDetails.java b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/NetconfConnectionDetails.java new file mode 100644 index 000000000..54b733b4d --- /dev/null +++ b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/NetconfConnectionDetails.java @@ -0,0 +1,94 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 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. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.netconf; + +import java.util.List; +import java.util.Properties; + +/** + * Provides details required for connecting to netconf device. + */ +public class NetconfConnectionDetails { + + private String host; + private int port; + private String username; + private String password; + + public static final int DEFAULT_PORT = 830; + private List<String> capabilities; + private Properties additionalProperties; + + public NetconfConnectionDetails() { + super(); + setPort(DEFAULT_PORT); + } + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } + + public int getPort() { + return port; + } + + public void setPort(int port) { + this.port = port; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public List<String> getCapabilities() { + return capabilities; + } + + public void setCapabilities(List<String> capabilities) { + this.capabilities = capabilities; + } + + public Properties getAdditionalProperties() { + return additionalProperties; + } + + public void setAdditionalProperties(Properties additionalProperties) { + this.additionalProperties = additionalProperties; + } +} diff --git a/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/NetconfDataAccessService.java b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/NetconfDataAccessService.java new file mode 100644 index 000000000..a5178c008 --- /dev/null +++ b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/NetconfDataAccessService.java @@ -0,0 +1,82 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 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. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.netconf; + +import org.onap.ccsdk.sli.adaptors.netconf.exception.DataAccessException; +import org.onap.ccsdk.sli.core.dblib.DbLibService; + + +@SuppressWarnings("JavaDoc") +public interface NetconfDataAccessService { + + /** + * + * @param schema + */ + void setSchema(String schema); + + /** + * + * @param dbLibService + */ + void setDbLibService(DbLibService dbLibService); + + /** + * + * @param xmlID + * @return + * @throws DataAccessException + */ + String retrieveConfigFileName(String xmlID); + + /** + * + * @param vnfType + * @param connectionDetails + * @return + * @throws DataAccessException + */ + boolean retrieveConnectionDetails(String vnfType, ConnectionDetails connectionDetails); + + /** + * + * @param vnfType + * @param connectionDetails + * @return + * @throws DataAccessException + */ + boolean retrieveNetconfConnectionDetails(String vnfType, NetconfConnectionDetails connectionDetails); + + /** + * + * @param instanceId + * @param requestId + * @param creationDate + * @param logText + * @return + * @throws DataAccessException + */ + boolean logDeviceInteraction(String instanceId, String requestId, String creationDate, String logText); + +} diff --git a/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/OperationalStateValidator.java b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/OperationalStateValidator.java new file mode 100644 index 000000000..3ffa20748 --- /dev/null +++ b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/OperationalStateValidator.java @@ -0,0 +1,35 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 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. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.netconf; + +import org.onap.ccsdk.sli.core.sli.SvcLogicException; + + +public interface OperationalStateValidator { + public static final String CONFIG_FILE_PROPERTY_SUFFIX = "-CONFIG_FILE"; + public VnfType getVnfType(); + public String getConfigurationFileName(); + public void validateResponse(String response) throws SvcLogicException; + +} diff --git a/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/OperationalStateValidatorFactory.java b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/OperationalStateValidatorFactory.java new file mode 100644 index 000000000..52838252b --- /dev/null +++ b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/OperationalStateValidatorFactory.java @@ -0,0 +1,56 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 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. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.netconf; + +import org.apache.commons.lang3.NotImplementedException; +import org.onap.ccsdk.sli.core.utils.configuration.Configuration; +import org.onap.ccsdk.sli.core.utils.configuration.ConfigurationFactory; + +public class OperationalStateValidatorFactory { + protected static final Configuration configuration = ConfigurationFactory.getConfiguration(); + + protected OperationalStateValidatorFactory() {} + + public static OperationalStateValidator getOperationalStateValidator(String vnfType) { + VnfType vnfTypeEnum; + try { + vnfTypeEnum = VnfType.getVnfType(vnfType); + } catch (IllegalArgumentException e) { + throw new IllegalArgumentException("Illegal value in vnfType. vnfType="+vnfType,e); + } + return getOperationalStateValidator(vnfTypeEnum); + } + + public static OperationalStateValidator getOperationalStateValidator(VnfType vnfType) { + switch (vnfType) { + case VNF: + case VNF_MOCK: + return new VNFOperationalStateValidatorImpl(); + case MOCK: + return new MockOperationalStateValidatorImpl(); + default: + throw new NotImplementedException("missing implementaion for the given vnfType:" + vnfType.name()); + } + } +} diff --git a/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/VNFOperationalStateValidatorImpl.java b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/VNFOperationalStateValidatorImpl.java new file mode 100644 index 000000000..3a6b1428a --- /dev/null +++ b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/VNFOperationalStateValidatorImpl.java @@ -0,0 +1,129 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 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. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.netconf; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.AbstractMap; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import org.apache.commons.lang3.StringUtils; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.SAXException; + +public class VNFOperationalStateValidatorImpl implements OperationalStateValidator { + private static final String OPERATIONAL_STATE_ELEMENT_NAME = "operationalState"; + + @Override + public VnfType getVnfType() { + return VnfType.VNF; + } + + @Override + public String getConfigurationFileName() { + String configFileName = OperationalStateValidatorFactory.configuration + .getProperty(this.getClass().getCanonicalName() + CONFIG_FILE_PROPERTY_SUFFIX); + configFileName = configFileName == null ? "VnfGetOperationalStates" : configFileName; + return configFileName; + } + + @Override + public void validateResponse(String response) throws SvcLogicException { + if(StringUtils.isEmpty(response)) { + throw new SvcLogicException("empty response"); + } + try { + List<Map.Entry> operationalStateList = getOperationalStateList(response).orElseThrow(() -> + new SvcLogicException("response without any "+OPERATIONAL_STATE_ELEMENT_NAME+" element")); + + if(operationalStateList.stream().anyMatch(this::isNotEnabled)) { + throw new SvcLogicException("at least one "+OPERATIONAL_STATE_ELEMENT_NAME+" is not in valid state. " + +operationalStateList.toString()); + } + + } catch (Exception e) { + throw new SvcLogicException(e.toString()); + } + } + + private boolean isNotEnabled(Map.Entry stateEntry) { + return !("ENABLED").equalsIgnoreCase((String)stateEntry.getValue()); + } + + private static Optional<List<Map.Entry>> getOperationalStateList(String xmlText) throws IOException, ParserConfigurationException, SAXException { + List<Map.Entry> entryList = null; + + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + Document document = builder.parse(new ByteArrayInputStream(xmlText.getBytes(StandardCharsets.UTF_8))); + + if(document != null) { + Element rootElement = document.getDocumentElement(); + NodeList nodeList = rootElement.getElementsByTagName(OPERATIONAL_STATE_ELEMENT_NAME); + if (nodeList != null && nodeList.getLength() > 0) { + entryList = new ArrayList<>(); + for (int i = 0; i < nodeList.getLength(); i++) { + Node node = nodeList.item(i); + String text = node.getTextContent(); + String id = getElementID(node); + Map.Entry entry = new AbstractMap.SimpleEntry<>(id, text); + entryList.add(entry); + } + } + } + return Optional.ofNullable(entryList); + } + + private static String getElementID(Node node) { + String id = null; + Node parentNode = node.getParentNode(); + if (parentNode != null) { + if (node.getNodeType() == Node.ELEMENT_NODE) { + NodeList nodeList = ((Element) parentNode).getElementsByTagName("id"); + if (nodeList != null && nodeList.getLength() > 0) { + Node idNode = nodeList.item(0); + id = idNode != null ? idNode.getTextContent() : null; + } + }else { + id = parentNode.getNodeValue()+"|"+parentNode.getTextContent(); + } + } + + id = StringUtils.isEmpty(id) ? null : StringUtils.normalizeSpace(id); + id = StringUtils.isBlank(id) ? null : id; + id = id != null ? id : "unknown-id"; + return id; + } + +} diff --git a/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/VnfType.java b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/VnfType.java new file mode 100644 index 000000000..7151899b3 --- /dev/null +++ b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/VnfType.java @@ -0,0 +1,57 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 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. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.netconf; + +public enum VnfType { + VNF("VNF"), + MOCK("MOCK"), + VNF_MOCK("MOCK"), + ; + + String familyType; + String upperCaseName; + VnfType(String familyType) { + this.familyType = familyType; + this.upperCaseName = name().toUpperCase(); + } + + public VnfType getFamilyType() { + return VnfType.valueOf(familyType); + } + + public String getUpperCaseName() { + return upperCaseName; + } + + public static VnfType getVnfType(String inSensitiveCaseName){ + String localUpperCaseName = inSensitiveCaseName.toUpperCase(); + for(VnfType vnfType : VnfType.values()){ + if(vnfType.getUpperCaseName().equals(localUpperCaseName)){ + return vnfType; + } + } + throw new IllegalArgumentException( + "No enum with upperCaseName for this input value:" + inSensitiveCaseName ); + } +} diff --git a/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/exception/DataAccessException.java b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/exception/DataAccessException.java new file mode 100644 index 000000000..37a129134 --- /dev/null +++ b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/exception/DataAccessException.java @@ -0,0 +1,47 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 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. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.netconf.exception; + + +public class DataAccessException extends RuntimeException { + + private static final long serialVersionUID = -155423437162622414L; + + public DataAccessException(){ + // DataAccessException + } + + public DataAccessException(String message){ + super(message); + } + + public DataAccessException(Throwable cause){ + super(cause); + } + + public DataAccessException(String message , Throwable cause){ + super(message , cause); + } + +} diff --git a/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/exception/NetconfDAOException.java b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/exception/NetconfDAOException.java new file mode 100644 index 000000000..35fbb29ae --- /dev/null +++ b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/exception/NetconfDAOException.java @@ -0,0 +1,47 @@ +/* + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 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. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.netconf.exception; + +public class NetconfDAOException extends RuntimeException { + + private static final long serialVersionUID = -155423437162622414L; + + public NetconfDAOException(){ + // for NetconfDAOException + } + + public NetconfDAOException(String message){ + super(message); + } + + public NetconfDAOException(Throwable cause){ + super(cause); + } + + public NetconfDAOException(String message , Throwable cause){ + super(message , cause); + } + + +} diff --git a/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/internal/NetconfAdaptor.java b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/internal/NetconfAdaptor.java new file mode 100644 index 000000000..57903f6ad --- /dev/null +++ b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/internal/NetconfAdaptor.java @@ -0,0 +1,128 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 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. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.netconf.internal; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import org.onap.ccsdk.sli.core.utils.configuration.ConfigurationFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Provides basic methods for exchanging netconf messages. + */ +public class NetconfAdaptor { + + private static final Logger LOG = LoggerFactory.getLogger(NetconfAdaptor.class); + private static final long MAX_WAITING_TIME = 1800000; + private static final ExecutorService executor = Executors.newFixedThreadPool(5); + + // device input stream + private final InputStream in; + // device output stream + private final OutputStream out; + private final long maxWaitingTime = ConfigurationFactory.getConfiguration().getLongProperty("org.onap.appc.netconf.recv.timeout", MAX_WAITING_TIME); + + /** + * Constructor. + * + * @param in InputStream this instance will read netconf messages from + * @param out OutputStream this instance will write netconf messages to + * + * @throws IOException the io exception + */ + public NetconfAdaptor(InputStream in, OutputStream out) throws IOException { + this.in = in; + this.out = out; + } + + /** + * Receives netconf message from InputStream and return it's text (without netconf frame characters). + * + * @return text of message received from netconf device + * + * @throws IOException the io exception + */ + public String receiveMessage() throws IOException { + + final NetconfMessage message = new NetconfMessage(); + final byte[] buf = new byte[1024]; + + // Read data with timeout + Callable<Boolean> readTask = () -> { + int c; + while ((c = in.read(buf)) > 0) { + message.append(buf, 0, c); + if (message.isCompleted()) { + break; + } + } + + return c >= 0; + }; + + Future<Boolean> future = executor.submit(readTask); + Boolean status; + try { + status = future.get(maxWaitingTime, TimeUnit.MILLISECONDS); + } catch (Exception e) { + throw new IOException(e); + } + + if (!status) { + throw new IOException("Failed to read netconf message"); + } + + String text = message.getText(); + if (text != null) { + text = text.trim(); + } + if (LOG.isDebugEnabled()) { + LOG.debug("Received message from netconf device:\n" + text); + } + return text; + } + + /** + * Sends netconf message with provided text (adds netconf frame characters and sends the message). + * + * @param text text of message to be sent to netconf device + * + * @throws IOException the io exception + */ + public void sendMessage(final String text) throws IOException { + if (LOG.isDebugEnabled()) { + LOG.debug("Sending message to netconf device:\n" + text); + } + out.write(new NetconfMessage(text).getFrame()); + out.flush(); + } + +} diff --git a/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/internal/NetconfAdaptor2.java b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/internal/NetconfAdaptor2.java new file mode 100644 index 000000000..54ea65fdb --- /dev/null +++ b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/internal/NetconfAdaptor2.java @@ -0,0 +1,127 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 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. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.netconf.internal; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PipedInputStream; +import java.io.PipedOutputStream; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Provides basic methods for exchanging netconf messages. + */ +public class NetconfAdaptor2 { + + private static final Logger LOG = LoggerFactory.getLogger(NetconfAdaptor2.class); + + // device input pipe + private final PipedOutputStream pipedOutIn = new PipedOutputStream(); + private final PipedInputStream in; + // device output pipe + private final PipedInputStream pipedInOut = new PipedInputStream(); + private final PipedOutputStream out; + + /** + * Constructor. + * + * @throws IOException the io exception + */ + public NetconfAdaptor2() throws IOException { + in = new PipedInputStream(pipedOutIn); + out = new PipedOutputStream(pipedInOut); + } + + /** + * Constructor. + * + * @param in InputStream this instance will read netconf messages from + * @param out OutputStream this instance will write netconf messages to + * + * @throws IOException the io exception + */ + public NetconfAdaptor2(PipedInputStream in, PipedOutputStream out) throws IOException { + this.in = in; + this.out = out; + + } + + /** + * Gets in. + * + * @return InputStream this instance will read netconf messages from. + */ + public InputStream getIn() { + return in; + } + + /** + * Gets out. + * + * @return OutputStream this instance will write netconf messages to. + */ + public OutputStream getOut() { + return out; + } + + /** + * Receives netconf message from InputStream and return it's text (without netconf frame characters). + * + * @return text of message received from netconf device + * + * @throws IOException the io exception + */ + public String receiveMessage() throws IOException { + NetconfMessage message = new NetconfMessage(); + byte[] buf = new byte[1024]; + int c; + while((c = pipedInOut.read(buf)) > 0) { + message.append(buf, 0, c); + if (message.isCompleted()) { + break; + } + } + String text = message.getText(); + if(LOG.isDebugEnabled()) { + LOG.debug("Received message from netconf device:\n" + text); + } + return text; + } + + /** + * Sends netconf message with provided text (adds netconf frame characters and sends the message). + * + * @param text text of message to be sent to netconf device + * + * @throws IOException the io exception + */ + public void sendMessage(final String text) throws IOException { + if(LOG.isDebugEnabled()) { + LOG.debug("Sending message to netconf device:\n" + text); + } + pipedOutIn.write(new NetconfMessage(text).getFrame()); + } +} diff --git a/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/internal/NetconfConstMessages.java b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/internal/NetconfConstMessages.java new file mode 100644 index 000000000..fa1384f3e --- /dev/null +++ b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/internal/NetconfConstMessages.java @@ -0,0 +1,59 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 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. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.netconf.internal; + +public class NetconfConstMessages { + + private static final String XML_HEADER = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; + + public static final String CAPABILITIES_START = + XML_HEADER + + "<hello xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" + + " <capabilities>\n"; + + public static final String CAPABILITIES_BASE = + " <capability>urn:ietf:params:netconf:base:1.0</capability>\n"; + + public static final String CAPABILITIES_END = + " </capabilities>\n" + + "</hello>"; + + public static final String GET_RUNNING_CONFIG = + XML_HEADER + + "<rpc message-id=\"1\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" + + " <get-config>\n" + + " <source>\n" + + " <running/>\n" + + " </source>\n" + + " </get-config>\n" + + "</rpc>"; + + public static final String CLOSE_SESSION = + XML_HEADER + + "<rpc message-id=\"terminateConnection\" xmlns:netconf=\"urn:ietf:params:xml:ns:netconf:base:1.0\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" + + " <close-session/>\n" + + "</rpc>"; + + private NetconfConstMessages() {} +} diff --git a/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/internal/NetconfDataAccessServiceImpl.java b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/internal/NetconfDataAccessServiceImpl.java new file mode 100644 index 000000000..a56565d74 --- /dev/null +++ b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/internal/NetconfDataAccessServiceImpl.java @@ -0,0 +1,146 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ================================================================================ + * Modifications Copyright (C) 2019 Ericsson + * ============================================================================= + * 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. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.netconf.internal; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import java.sql.SQLException; +import java.util.ArrayList; +import javax.sql.rowset.CachedRowSet; +import org.onap.ccsdk.sli.adaptors.netconf.ConnectionDetails; +import org.onap.ccsdk.sli.adaptors.netconf.NetconfAdaptorConstants; +import org.onap.ccsdk.sli.adaptors.netconf.NetconfConnectionDetails; +import org.onap.ccsdk.sli.adaptors.netconf.NetconfDataAccessService; +import org.onap.ccsdk.sli.adaptors.netconf.exception.DataAccessException; +import org.onap.ccsdk.sli.core.dblib.DbLibService; + +public class NetconfDataAccessServiceImpl implements NetconfDataAccessService { + + private final EELFLogger logger = EELFManager.getInstance().getLogger(NetconfDataAccessServiceImpl.class); + + private String schema; + + private DbLibService dbLibService; + + @Override + public void setSchema(String schema) { + this.schema = schema; + } + + @Override + public void setDbLibService(DbLibService service) {dbLibService = service;} + + @Override + public String retrieveConfigFileName(String xmlID) { + String fileContent = ""; + + String queryString = "select " + NetconfAdaptorConstants.FILE_CONTENT_TABLE_FIELD_NAME + " " + + "from " + NetconfAdaptorConstants.CONFIGFILES_TABLE_NAME + " " + + "where " + NetconfAdaptorConstants.FILE_NAME_TABLE_FIELD_NAME + " = ?"; + + ArrayList<String> argList = new ArrayList<>(); + argList.add(xmlID); + + try { + final CachedRowSet data = dbLibService.getData(queryString, argList, schema); + if (data.first()) { + fileContent = data.getString(NetconfAdaptorConstants.FILE_CONTENT_TABLE_FIELD_NAME); + } + } catch (Exception e) { + logger.error("Error Accessing Database " + e); + throw new DataAccessException(e); + } + + return fileContent; + } + + @Override + public boolean retrieveConnectionDetails(String vnfType, ConnectionDetails connectionDetails) { + boolean recordFound = false; + + String queryString = "select " + NetconfAdaptorConstants.USER_NAME_TABLE_FIELD_NAME + "," + + NetconfAdaptorConstants.PASSWORD_TABLE_FIELD_NAME + "," + NetconfAdaptorConstants.PORT_NUMBER_TABLE_FIELD_NAME + " " + + "from " + NetconfAdaptorConstants.DEVICE_AUTHENTICATION_TABLE_NAME + " " + + "where " + NetconfAdaptorConstants.VNF_TYPE_TABLE_FIELD_NAME + " = ?"; + + ArrayList<String> argList = new ArrayList<>(); + argList.add(vnfType); + + try { + final CachedRowSet data = dbLibService.getData(queryString, argList, schema); + if (data.first()) { + connectionDetails.setUsername(data.getString(NetconfAdaptorConstants.USER_NAME_TABLE_FIELD_NAME)); + connectionDetails.setPassword(data.getString(NetconfAdaptorConstants.PASSWORD_TABLE_FIELD_NAME)); + connectionDetails.setPort(data.getInt(NetconfAdaptorConstants.PORT_NUMBER_TABLE_FIELD_NAME)); + recordFound = true; + } + } catch (SQLException e) { + logger.error("Error Accessing Database " + e); + throw new DataAccessException(e); + } + + return recordFound; + } + + @Override + public boolean retrieveNetconfConnectionDetails(String vnfType, NetconfConnectionDetails connectionDetails) { + ConnectionDetails connDetails = new ConnectionDetails(); + if(this.retrieveConnectionDetails(vnfType, connDetails)) + { + connectionDetails.setHost(connDetails.getHost()); + connectionDetails.setPort(connDetails.getPort()); + connectionDetails.setUsername(connDetails.getUsername()); + connectionDetails.setPassword(connDetails.getPassword()); + } + return true; + } + + @Override + public boolean logDeviceInteraction(String instanceId, String requestId, String creationDate, String logText) { + String queryString = "INSERT INTO " + NetconfAdaptorConstants.DEVICE_INTERFACE_LOG_TABLE_NAME + "(" + + NetconfAdaptorConstants.SERVICE_INSTANCE_ID_FIELD_NAME + "," + + NetconfAdaptorConstants.REQUEST_ID_FIELD_NAME + "," + + NetconfAdaptorConstants.CREATION_DATE_FIELD_NAME + "," + + NetconfAdaptorConstants.LOG_FIELD_NAME + ") "; + queryString += "values(?,?,?,?)"; + + ArrayList<String> argList = new ArrayList<>(); + argList.add(instanceId); + argList.add(requestId); + argList.add(creationDate); + argList.add(logText); + + try { + dbLibService.writeData(queryString, argList, schema); + } catch (SQLException e) { + logger.error("Logging Device interaction failed - " + queryString); + throw new DataAccessException(e); + } + + return true; + } + +} diff --git a/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/internal/NetconfMessage.java b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/internal/NetconfMessage.java new file mode 100644 index 000000000..800126a26 --- /dev/null +++ b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/internal/NetconfMessage.java @@ -0,0 +1,97 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 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. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.netconf.internal; + +import java.io.ByteArrayOutputStream; + +class NetconfMessage { + + private static final String EOM = "]]>]]>"; + + private String text; + private MessageBuffer buffer = new MessageBuffer(); + private int eomNotch; + + NetconfMessage() { + } + + NetconfMessage(String text) { + if(text == null) { + throw new NullPointerException("Netconf message payload is null"); + } + append(text.getBytes(), 0, text.length()); + if(this.text == null) { + this.text = text; + } + } + + void append(byte[] bytes, int start, int finish) { + boolean eomFound = false; + int end = finish; + for(int i = start; i < end; i++) { + if(bytes[i] == EOM.charAt(eomNotch)) { + // advance notch + eomNotch++; + } else { + // reset notch + eomNotch = 0; + } + if(eomNotch == EOM.length()) { + // end of message found + eomFound = true; + end = i + 1; + break; + } + } + buffer.write(bytes, start, end); + if(eomFound) { + text = new String(buffer.getBytes(), 0, buffer.size() - EOM.length()); + buffer.reset(); + } + } + + String getText() { + return text; + } + + boolean isCompleted() { + return text != null; + } + + byte[] getFrame() { + StringBuilder sb = new StringBuilder(); + if(text != null) { + sb.append(text).append("\n"); + } + sb.append(EOM); + return sb.toString().getBytes(); + } + + private class MessageBuffer extends ByteArrayOutputStream { + + byte[] getBytes() { + return buf; + } + } +} diff --git a/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/jsch/JSchLogger.java b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/jsch/JSchLogger.java new file mode 100644 index 000000000..0084a1fb0 --- /dev/null +++ b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/jsch/JSchLogger.java @@ -0,0 +1,64 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 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. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.netconf.jsch; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * JSch logger implementation delegating to logback. + */ +public class JSchLogger implements com.jcraft.jsch.Logger { + + private static final Logger LOG = LoggerFactory.getLogger(JSchLogger.class); + + @Override + public boolean isEnabled(int level) { + return true; + } + + @Override + public void log(int level, String message) { + switch(level) { + case com.jcraft.jsch.Logger.DEBUG: + LOG.debug(message); + break; + + case com.jcraft.jsch.Logger.INFO: + LOG.info(message); + break; + + case com.jcraft.jsch.Logger.WARN: + LOG.warn(message); + break; + + case com.jcraft.jsch.Logger.ERROR: + case com.jcraft.jsch.Logger.FATAL: + LOG.error(message); + break; + default: + break; + } + } +} diff --git a/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/jsch/NetconfClientJsch.java b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/jsch/NetconfClientJsch.java new file mode 100644 index 000000000..210fb5835 --- /dev/null +++ b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/jsch/NetconfClientJsch.java @@ -0,0 +1,184 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ================================================================================ + * Modifications Copyright (C) 2018 Ericsson + * ============================================================================= + * 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. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.netconf.jsch; + +import com.att.eelf.i18n.EELFResourceManager; +import com.jcraft.jsch.Channel; +import com.jcraft.jsch.ChannelSubsystem; +import com.jcraft.jsch.JSch; +import com.jcraft.jsch.Session; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Properties; +import org.onap.ccsdk.sli.adaptors.netconf.NetconfClient; +import org.onap.ccsdk.sli.adaptors.netconf.NetconfConnectionDetails; +import org.onap.ccsdk.sli.adaptors.netconf.internal.NetconfAdaptor; +import org.onap.ccsdk.sli.adaptors.netconf.internal.NetconfConstMessages; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.utils.encryption.EncryptionTool; +import org.onap.ccsdk.sli.core.utils.logging.Msg; + +/** + * Implementation of NetconfClient interface based on JCraft jsch library. + */ +public class NetconfClientJsch implements NetconfClient { + + private static final int SESSION_CONNECT_TIMEOUT = 30000; + private static final int CHANNEL_CONNECT_TIMEOUT = 10000; + + private Session session; + private Channel channel; + private NetconfAdaptor netconfAdaptor; + + + @Override + public void connect(NetconfConnectionDetails connectionDetails) throws SvcLogicException { + String host = connectionDetails.getHost(); + int port = connectionDetails.getPort(); + String username = connectionDetails.getUsername(); + String password = connectionDetails.getPassword(); + try { + JSch.setLogger(new JSchLogger()); + JSch jsch = getJSch(); + session = jsch.getSession(EncryptionTool.getInstance().decrypt(username), host, port); + session.setPassword(EncryptionTool.getInstance().decrypt(password)); + session.setConfig("StrictHostKeyChecking", "no"); + + Properties additionalProps = connectionDetails.getAdditionalProperties(); + if((additionalProps != null) && !additionalProps.isEmpty()) { + session.setConfig(additionalProps); + } + + session.connect(SESSION_CONNECT_TIMEOUT); + session.setTimeout(10000); + + createConnection(connectionDetails); + + } catch(Exception e) { + String message = EELFResourceManager.format(Msg.CANNOT_ESTABLISH_CONNECTION, host, String.valueOf(port), username); + throw new SvcLogicException(message, e); + } + } + + @Override + public String exchangeMessage(String message) throws SvcLogicException { + try { + netconfAdaptor.sendMessage(message); + return netconfAdaptor.receiveMessage(); + } catch(IOException e) { + throw new SvcLogicException(e.toString()); + } + } + + @Override + public void configure(String configuration) throws SvcLogicException { + try { + isOk(exchangeMessage(configuration)); + } catch(IOException e) { + throw new SvcLogicException(e.toString()); + } + } + + @Override + public String getConfiguration() throws SvcLogicException { + return exchangeMessage(NetconfConstMessages.GET_RUNNING_CONFIG); + } + + @Override + public void disconnect() { + try { + if((channel != null) && !channel.isClosed()) { + netconfAdaptor.sendMessage(NetconfConstMessages.CLOSE_SESSION); + isOk(netconfAdaptor.receiveMessage()); + } + } catch(IOException e) { + throw new RuntimeException("Error closing netconf device", e); + } finally { + netconfAdaptor = null; + if(channel != null) { + channel.disconnect(); + channel = null; + } + if(session != null) { + session.disconnect(); + session = null; + } + } + } + + private void createConnection(NetconfConnectionDetails connectionDetails) throws SvcLogicException { + try { + channel = session.openChannel("subsystem"); + ((ChannelSubsystem)channel).setSubsystem("netconf"); + netconfAdaptor = getNetconfAdaptor(channel.getInputStream(), channel.getOutputStream()); + channel.connect(CHANNEL_CONNECT_TIMEOUT); + hello(connectionDetails.getCapabilities()); + } catch(Exception e) { + disconnect(); + throw new SvcLogicException(e.toString()); + } + } + + private void hello(List<String> capabilities) throws IOException { + String helloIn = netconfAdaptor.receiveMessage(); + if(helloIn == null) { + throw new IOException("Expected hello message, but nothing received from netconf device"); + } + if(helloIn.contains("<rpc-error>")) { + throw new IOException("Expected hello message, but received error from netconf device:\n" + helloIn); + } + StringBuilder sb = new StringBuilder(); + sb.append(NetconfConstMessages.CAPABILITIES_START); + sb.append(NetconfConstMessages.CAPABILITIES_BASE); + if(capabilities != null) { + for(String capability: capabilities) { + sb.append(" ").append(capability).append("\n"); + } + } + sb.append(NetconfConstMessages.CAPABILITIES_END); + String helloOut = sb.toString(); + netconfAdaptor.sendMessage(helloOut); + } + + private void isOk(String response) throws IOException { + if(response == null) { + throw new IOException("No response from netconf device"); + } + if(!response.contains("<ok/>")) { + throw new IOException("Error response from netconf device: \n" + response); + } + } + + protected JSch getJSch() { + return new JSch(); + } + + protected NetconfAdaptor getNetconfAdaptor(InputStream inputStream, OutputStream outputStream) throws IOException { + return new NetconfAdaptor(inputStream, outputStream); + } +} diff --git a/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/odlconnector/NetconfClientRestconfImpl.java b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/odlconnector/NetconfClientRestconfImpl.java new file mode 100644 index 000000000..41590edce --- /dev/null +++ b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/netconf/odlconnector/NetconfClientRestconfImpl.java @@ -0,0 +1,246 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ================================================================================ + * Modifications Copyright (C) 2019 Ericsson + * ============================================================================= + * 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. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.netconf.odlconnector; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import java.util.Properties; +import org.apache.http.HttpStatus; +import org.onap.ccsdk.sli.adaptors.netconf.HttpClient; +import org.onap.ccsdk.sli.adaptors.netconf.NetconfAdaptorConstants; +import org.onap.ccsdk.sli.adaptors.netconf.NetconfClient; +import org.onap.ccsdk.sli.adaptors.netconf.NetconfClientRestconf; +import org.onap.ccsdk.sli.adaptors.netconf.NetconfConnectionDetails; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; + +public class NetconfClientRestconfImpl implements NetconfClient, NetconfClientRestconf { + + private final EELFLogger logger = EELFManager.getInstance().getLogger(NetconfClientRestconfImpl.class); + + private NetconfConnectionDetails connectionDetails; + private final String appFormat = "application/json"; + + public NetconfClientRestconfImpl(){ + //constructor + } + + //restconf client impl + + @SuppressWarnings("deprecation") + @Override + public void configure(String configuration, String deviceMountPointName, String moduleName, String nodeName) throws SvcLogicException { + + logger.info("Configuring device " + deviceMountPointName + " with configuration " + configuration); + + int httpCode = HttpClient.putMethod(NetconfAdaptorConstants.PROTOCOL, NetconfAdaptorConstants.CONTROLLER_IP, NetconfAdaptorConstants.CONTROLLER_PORT, + getModuleConfigurePath(deviceMountPointName, moduleName, nodeName), configuration, appFormat); + + if (httpCode != HttpStatus.SC_OK) { + logger.error("Configuration request failed. throwing Exception !"); + throw new SvcLogicException("Error configuring node :" + nodeName + ", of Module :" + moduleName + + ", in device :" + deviceMountPointName); + } + } + + @Override + public void connect(String deviceMountPointName, String payload) throws SvcLogicException{ + + logger.info("Connecting device " + deviceMountPointName); + + int httpCode = HttpClient.postMethod(NetconfAdaptorConstants.PROTOCOL, NetconfAdaptorConstants.CONTROLLER_IP, NetconfAdaptorConstants.CONTROLLER_PORT, + getConnectPath(), payload, appFormat); + + if(httpCode != HttpStatus.SC_NO_CONTENT){ + logger.error("Connect request failed with code " + httpCode + ". throwing Exception !"); + throw new SvcLogicException("Error connecting device :" + deviceMountPointName); + } + } + + @Override + public boolean checkConnection(String deviceMountPointName) throws SvcLogicException { + logger.info("Checking device " + deviceMountPointName + " connectivity"); + + String result = HttpClient.getMethod(NetconfAdaptorConstants.PROTOCOL, NetconfAdaptorConstants.CONTROLLER_IP, + NetconfAdaptorConstants.CONTROLLER_PORT, getCheckConnectivityPath(deviceMountPointName), appFormat); + + return result != null; + } + + @Override + public void disconnect(String deviceMountPointName) throws SvcLogicException { + logger.info("Disconnecting " + deviceMountPointName); + + int httpCode = HttpClient.deleteMethod(NetconfAdaptorConstants.PROTOCOL, NetconfAdaptorConstants.CONTROLLER_IP, NetconfAdaptorConstants.CONTROLLER_PORT, + getDisconnectPath(deviceMountPointName), appFormat); + + if(httpCode != HttpStatus.SC_OK){ + logger.error("Disconnection of device " + deviceMountPointName + " failed!"); + throw new SvcLogicException("Disconnection of device " + deviceMountPointName + " failed!"); + } + } + + @Override + public String getConfiguration(String deviceMountPointName, String moduleName, String nodeName) throws SvcLogicException{ + logger.info("Getting configuration of device " + deviceMountPointName); + + String result = HttpClient.getMethod(NetconfAdaptorConstants.PROTOCOL, NetconfAdaptorConstants.CONTROLLER_IP, NetconfAdaptorConstants.CONTROLLER_PORT, + getModuleConfigurePath(deviceMountPointName, moduleName, nodeName), appFormat); + + if (result == null) { + logger.error("Configuration request failed. throwing Exception !"); + throw new SvcLogicException("Error getting configuration of node :" + nodeName + ", of Module :" + moduleName + + ", in device :" + deviceMountPointName); + } + + return result; + } + + //netconf client impl + + @Override + public void connect(NetconfConnectionDetails connectionDetails) throws SvcLogicException { + if(connectionDetails == null){ + throw new SvcLogicException("Invalid connection details - null value"); + } + this.connectionDetails = connectionDetails; + this.connect(connectionDetails.getHost(), getPayload()); + } + + @Override + public String exchangeMessage(String message) throws SvcLogicException { + // TODO implement + return null; + } + + @Override + public void configure(String configuration) throws SvcLogicException { + if(connectionDetails == null){ + throw new SvcLogicException("Invalid connection details - null value"); + } + + Properties props = connectionDetails.getAdditionalProperties(); + if(props == null || !props.containsKey("module.name") || !props.containsKey("node.name")) { + throw new SvcLogicException("Invalid properties!"); + } + + String moduleName = props.getProperty("module.name"); + String nodeName = props.getProperty("node.name"); + String deviceMountPointName = connectionDetails.getHost(); + + int httpCode = HttpClient.putMethod(NetconfAdaptorConstants.PROTOCOL, NetconfAdaptorConstants.CONTROLLER_IP, NetconfAdaptorConstants.CONTROLLER_PORT, + getModuleConfigurePath(deviceMountPointName, moduleName, nodeName), configuration, "application/xml"); + + if (httpCode != HttpStatus.SC_OK) { + logger.error("Configuration request failed. throwing Exception !"); + throw new SvcLogicException("Error configuring node :" + nodeName + ", of Module :" + moduleName + + ", in device :" + deviceMountPointName); + } + } + + @Override + public String getConfiguration() throws SvcLogicException { + if(connectionDetails == null){ + throw new SvcLogicException("Invalid connection details - null value"); + } + + Properties props = connectionDetails.getAdditionalProperties(); + if(props == null || !props.containsKey("module.name") || !props.containsKey("node.name")) { + throw new SvcLogicException("Invalid properties!"); + } + + return this.getConfiguration(connectionDetails.getHost(), props.getProperty("module.name"), + props.getProperty("node.name")); + } + + @Override + public void disconnect() throws SvcLogicException { + if(connectionDetails == null){ + throw new SvcLogicException("Invalid connection details - null value"); + } + this.disconnect(connectionDetails.getHost()); + } + + //private methods + private String getModuleConfigurePath(String deviceMountPointName, String moduleName, String nodeName){ + + String deviceSpecificPath = deviceMountPointName + "/yang-ext:mount/" + moduleName + ":" + nodeName; + + return NetconfAdaptorConstants.CONFIGURE_PATH + deviceSpecificPath; + } + + private String getConnectPath(){ + + return NetconfAdaptorConstants.CONNECT_PATH; + } + + private String getCheckConnectivityPath(String deviceMountPointName) { + return NetconfAdaptorConstants.CHECK_CONNECTION_PATH + deviceMountPointName; + } + + private String getDisconnectPath(String deviceMountPointName) { + return NetconfAdaptorConstants.DISCONNECT_PATH + deviceMountPointName; + } + + private String getPayload() { + return "{\n" + + " \"config:module\":\n" + + " {\n" + + " \"type\":\"odl-sal-netconf-connector-cfg:sal-netconf-connector\",\n" + + " \"netconf-northbound-ssh\\odl-sal-netconf-connector-cfg:name\":"+connectionDetails.getHost()+",\n" + + " \"odl-sal-netconf-connector-cfg:address\":"+connectionDetails.getHost()+",\n" + + " \"odl-sal-netconf-connector-cfg:port\":"+connectionDetails.getPort()+",\n" + + " \"odl-sal-netconf-connector-cfg:username\":"+connectionDetails.getUsername()+",\n" + + " \"odl-sal-netconf-connector-cfg:password\":"+connectionDetails.getPassword()+",\n" + + " \"tcp-only\":\"false\",\n" + + " \"odl-sal-netconf-connector-cfg:event-executor\":\n" + + " {\n" + + " \"type\":\"netty:netty-event-executor\",\n" + + " \"name\":\"global-event-executor\"\n" + + " },\n" + + " \"odl-sal-netconf-connector-cfg:binding-registry\":\n" + + " {\n" + + " \"type\":\"opendaylight-md-sal-binding:binding-broker-osgi-registry\",\n" + + " \"name\":\"binding-osgi-broker\"\n" + + " },\n" + + " \"odl-sal-netconf-connector-cfg:dom-registry\":\n" + + " {\n" + + " \"type\":\"opendaylight-md-sal-dom:dom-broker-osgi-registry\",\n" + + " \"name\":\"dom-broker\"\n" + + " },\n" + + " \"odl-sal-netconf-connector-cfg:client-dispatcher\":\n" + + " {\n" + + " \"type\":\"odl-netconf-cfg:netconf-client-dispatcher\",\n" + + " \"name\":\"global-netconf-dispatcher\"\n" + + " },\n" + + " \"odl-sal-netconf-connector-cfg:processing-executor\":\n" + + " {\n" + + " \"type\":\"threadpool:threadpool\",\n" + + " \"name\":\"global-netconf-processing-executor\"\n" + + " }\n" + + " }\n" + + "}"; + } +} diff --git a/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/resources/netconf-adaptor.properties b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/resources/netconf-adaptor.properties new file mode 100644 index 000000000..7d0eb7cca --- /dev/null +++ b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/main/resources/netconf-adaptor.properties @@ -0,0 +1,43 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017-2018 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. +# +# ============LICENSE_END========================================================= +### + +org.onap.appc.bootstrap.file=appc.properties +org.onap.appc.bootstrap.path=/opt/onap/appc/data/properties,${user.home},. + +org.onap.appc.netconf.db.jdbc.driver=netconfctl +org.onap.appc.netconf.db.url.netconfctl=jdbc:mysql://127.0.0.1:3306/test +org.onap.appc.netconf.db.user.netconfctl=test +org.onap.appc.netconf.db.pass.netconfctl=123456 +org.onap.appc.netconf.recv.timeout=1800000 + +### ### +### Properties commented out below provided in appc.properties ### +### ### +#event.pool.members=<DMAAP_IP>:3904 +event.topic.write=APPC-TEST1 +event.client.key=VIlbtVl6YLhNUrtU +event.client.secret=64AG2hF4pYeG2pq7CT6XwUOT +#restconf.user=<RESTCONF_USER> +#restconf.pass=<RESTCONF_PASSWORD> + +VNFOperationalStateValidatorImpl-CONFIG_FILE=VnfGetOperationalStates diff --git a/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/NetconfClientFactoryTest.java b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/NetconfClientFactoryTest.java new file mode 100644 index 000000000..b3a1d8edb --- /dev/null +++ b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/NetconfClientFactoryTest.java @@ -0,0 +1,50 @@ +/* + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2018 Nokia. All rights reserved. + * ================================================================================ + * Modifications Copyright (C) 2019 Ericsson + * ============================================================================= + * 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. + * ============LICENSE_END========================================================= + */ +package org.onap.ccsdk.sli.adaptors.netconf; + +import org.junit.Test; +import org.onap.ccsdk.sli.adaptors.netconf.jsch.NetconfClientJsch; +import org.onap.ccsdk.sli.adaptors.netconf.odlconnector.NetconfClientRestconfImpl; + +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +public class NetconfClientFactoryTest { + + @Test + public void getNetconfClient_shouldCreateRestClient_forRestClientType() { + NetconfClient netconfClient = new NetconfClientFactory().getNetconfClient(NetconfClientType.RESTCONF); + assertTrue(netconfClient instanceof NetconfClientRestconfImpl); + } + + @Test + public void getNetconfClient_shouldCreateJschClient_forSshClientType() { + NetconfClient netconfClient = new NetconfClientFactory().getNetconfClient(NetconfClientType.SSH); + assertTrue(netconfClient instanceof NetconfClientJsch); + } + + @Test + public void getNetconfClient_shouldReturnNullForInvalidClientType() { + NetconfClient netconfClient = new NetconfClientFactory().getNetconfClient(null); + assertNull(netconfClient); + } +}
\ No newline at end of file diff --git a/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/NetconfClientTypeTest.java b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/NetconfClientTypeTest.java new file mode 100644 index 000000000..cd862f9d9 --- /dev/null +++ b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/NetconfClientTypeTest.java @@ -0,0 +1,41 @@ +/* +* ============LICENSE_START======================================================= +* ONAP : APPC +* ================================================================================ +* Copyright 2018 TechMahindra +* ================================================================================ +* Modifications Copyright (C) 2019 Ericsson +*================================================================================= +* 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. +* ============LICENSE_END========================================================= +*/ +package org.onap.ccsdk.sli.adaptors.netconf; + +import org.junit.Assert; +import org.junit.Test; + +public class NetconfClientTypeTest { + private NetconfClientType netconfClientType = NetconfClientType.RESTCONF; + + @Test + public void testName() { + Assert.assertEquals("RESTCONF", netconfClientType.name()); + } + + @Test + public void testEquals() { + Assert.assertTrue(netconfClientType.equals(NetconfClientType.RESTCONF)); + Assert.assertFalse(netconfClientType.equals(null)); + } + +} diff --git a/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/NetconfConnectionDetailsTest.java b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/NetconfConnectionDetailsTest.java new file mode 100644 index 000000000..2d0bea92c --- /dev/null +++ b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/NetconfConnectionDetailsTest.java @@ -0,0 +1,118 @@ +/* +* ============LICENSE_START======================================================= +* ONAP : APPC +* ================================================================================ +* Copyright 2018 TechMahindra +* ================================================================================ +* Modifications Copyright (C) 2019 Ericsson +*================================================================================= +* 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. +* ============LICENSE_END========================================================= +*/ +package org.onap.ccsdk.sli.adaptors.netconf; + +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +public class NetconfConnectionDetailsTest { + private NetconfConnectionDetails netconfConnectionDetails; + private List<String> capabilities; + private Properties additionalProperties; + + @Before + public void SetUp() { + netconfConnectionDetails = new NetconfConnectionDetails(); + } + + @Test + public void testGetHost() { + netconfConnectionDetails.setHost("host1"); + Assert.assertNotNull(netconfConnectionDetails.getHost()); + Assert.assertEquals("host1", netconfConnectionDetails.getHost()); + } + + @Test + public void testGetPort() { + netconfConnectionDetails.setPort(123); + Assert.assertNotNull(netconfConnectionDetails.getPort()); + Assert.assertEquals(123, netconfConnectionDetails.getPort()); + } + + @Test + public void testGetUsername() { + netconfConnectionDetails.setUsername("ABC"); + Assert.assertNotNull(netconfConnectionDetails.getUsername()); + Assert.assertEquals("ABC", netconfConnectionDetails.getUsername()); + } + + @Test + public void testGetPassword() { + netconfConnectionDetails.setPassword("pass1"); + Assert.assertNotNull(netconfConnectionDetails.getPassword()); + Assert.assertEquals("pass1", netconfConnectionDetails.getPassword()); + } + + @Test + public void testNullCapabilities() { + capabilities = new ArrayList<String>(); + Assert.assertNull(netconfConnectionDetails.getCapabilities()); + } + + @Test + public void testCapabilitiesWithValues() { + capabilities = new ArrayList<String>(); + capabilities.add("capabilities1"); + capabilities.add("capabilities2"); + netconfConnectionDetails.setCapabilities(capabilities); + Assert.assertTrue(capabilities.contains("capabilities2")); + } + + @Test + public void testCapabilities_Size() { + capabilities = new ArrayList<String>(); + capabilities.add("capabilities1"); + capabilities.add("capabilities2"); + netconfConnectionDetails.setCapabilities(capabilities); + Assert.assertEquals(2, capabilities.size()); + } + + @Test + public void testAdditionalProperties() { + additionalProperties = new Properties(); + Assert.assertNull(netconfConnectionDetails.getAdditionalProperties()); + } + + @Test + public void testAdditionalPropertiesWithValues() { + additionalProperties = new Properties(); + additionalProperties.put("A", "a"); + additionalProperties.put("B", "b"); + netconfConnectionDetails.setAdditionalProperties(additionalProperties); + Assert.assertEquals("a", netconfConnectionDetails.getAdditionalProperties().get("A")); + } + + @Test + public void testAdditionalProperties_Size() { + additionalProperties = new Properties(); + additionalProperties.put("A", "a"); + additionalProperties.put("B", "b"); + additionalProperties.put("C", "c"); + netconfConnectionDetails.setAdditionalProperties(additionalProperties); + Assert.assertNotNull(netconfConnectionDetails.getAdditionalProperties()); + Assert.assertEquals(3, additionalProperties.size()); + } +} diff --git a/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/OperationalStateValidatorTest.java b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/OperationalStateValidatorTest.java new file mode 100644 index 000000000..8b60373b1 --- /dev/null +++ b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/OperationalStateValidatorTest.java @@ -0,0 +1,200 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ================================================================================ + * Modifications Copyright (C) 2019 Ericsson + * ============================================================================= + * 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. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.netconf; + +import org.junit.Test; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; + + +public class OperationalStateValidatorTest { + + @Test + public void testVNFValidResponse() { + String validResponse = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + + "<rpc-reply xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\" message-id=\"101\">\n" + + " <data>\n" + + " <ManagedElement xmlns=\"urn:org:onap:appc:Test\">\n" + + " <managedElementId>1</managedElementId>\n" + + " <VnfFunction xmlns=\"urn:org:onap:appc:Test\">\n" + + " <id>1</id>\n" + + " <ProcessorManagement>\n" + + " <id>1</id>\n" + + " <MatedPair>\n" + + " <id>1</id>\n" + + " <operationalState>ENABLED</operationalState>\n" + + " <PayloadProcessor>\n" + + " <id>processor_0_5</id>\n" + + " <operationalState>ENABLED</operationalState>\n" + + " </PayloadProcessor>\n" + + " <PayloadProcessor>\n" + + " <id>processor_0_7</id>\n" + + " <operationalState>ENABLED</operationalState>\n" + + " </PayloadProcessor>\n" + + " </MatedPair>\n" + + " <SystemController>\n" + + " <id>SC-1</id>\n" + + " <operationalState>ENABLED</operationalState>\n" + + " </SystemController>\n" + + " <SystemController>\n" + + " <id>SC-2</id>\n" + + " <operationalState>ENABLED</operationalState>\n" + + " </SystemController>\n" + + " </ProcessorManagement>\n" + + " </VnfFunction>\n" + + " </ManagedElement>\n" + + " </data>\n" + + "</rpc-reply>"; + OperationalStateValidator operationalStateValidator = OperationalStateValidatorFactory.getOperationalStateValidator(VnfType.VNF); + assertValidResponse(validResponse, operationalStateValidator); + } + + void assertInvalidResponse(String response, OperationalStateValidator operationalStateValidator) { + try { + operationalStateValidator.validateResponse(response); + fail("invalid response passed without exception!!!"); + } catch (SvcLogicException e) { + assertNotNull(e.getMessage()); + } + } + + @Test + public void testVNFInvalidResponses() { + + OperationalStateValidator operationalStateValidator = OperationalStateValidatorFactory.getOperationalStateValidator(VnfType.VNF); + assertInvalidResponse(null, operationalStateValidator); + + assertInvalidResponse("", operationalStateValidator); + + String response = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; + assertInvalidResponse(response, operationalStateValidator); + + response = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + + "<rpc-reply xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\" message-id=\"101\">\n" + + "</rpc-reply>"; + assertInvalidResponse(response, operationalStateValidator); + + response = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + + "<rpc-reply xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\" message-id=\"101\">\n" + + " <data>\n" + + " <ManagedElement xmlns=\"urn:org:onap:appc:Test\">\n" + + " <managedElementId>1</managedElementId>\n" + + " <VnfFunction xmlns=\"urn:org:onap:appc:Test\">\n" + + " <id>1</id>\n" + + " <ProcessorManagement>\n" + + " <id>1</id>\n" + + " <MatedPair>\n" + + " <id>1</id>\n" + + " <operationalState>ENABLED</operationalState>\n" + + " <PayloadProcessor>\n" + + " <id>processor_0_5</id>\n" + + " <operationalState>ENABLED</operationalState>\n" + + " </PayloadProcessor>\n" + + " <PayloadProcessor>\n" + + " <id>processor_0_7</id>\n" + + " <operationalState>ENABLED</operationalState>\n" + + " </PayloadProcessor>\n" + + " </MatedPair>\n" + + " <SystemController>\n" + + " <id>SC-1</id>\n" + + " <operationalState>ENABLED</operationalState>\n" + + " </SystemController>\n" + + " <SystemController>\n" + + " <id>SC-2</id>\n" + + " <operationalState></operationalState>\n" + + " </SystemController>\n" + + " </ProcessorManagement>\n" + + " </VnfFunction>\n" + + " </ManagedElement>\n" + + " </data>\n" + + "</rpc-reply>"; + assertInvalidResponse(response, operationalStateValidator); + } + + void assertValidResponse(String response, OperationalStateValidator operationalStateValidator) { + try { + operationalStateValidator.validateResponse(response); + } catch (SvcLogicException e) { + fail("Got unexpected exception. Validation failed. " + e.getMessage()); + } + } + + @Test + public void testMockValidResponse() { + String response = "valid"; + OperationalStateValidator operationalStateValidator = OperationalStateValidatorFactory.getOperationalStateValidator("mock"); + assertValidResponse(response, operationalStateValidator); + + response = ""; + assertValidResponse(response, operationalStateValidator); + + response = null; + assertValidResponse(response, operationalStateValidator); + } + + @Test + public void testMockInValidResponse() { + String response = "anything InValid anything.. "; + OperationalStateValidator operationalStateValidator = OperationalStateValidatorFactory.getOperationalStateValidator(VnfType.MOCK); + assertInvalidResponse(response, operationalStateValidator); + } + + @Test + public void testGetOperationalStateValidatorForInValidVnfType() { + try{ + OperationalStateValidatorFactory.getOperationalStateValidator("wrongVnfType"); + fail("invalid vnfType without exception!!!"); + } catch (Exception e) { + assertNotNull(e.getMessage()); + } + } + + @Test + public void testGetOperationalStateValidatorForValidVnfType() { + String vnfType = VnfType.VNF.name().toLowerCase(); + assertGettingValidatorForValidVnf(vnfType); + + vnfType = VnfType.VNF.name().toUpperCase(); + assertGettingValidatorForValidVnf(vnfType); + + vnfType = VnfType.MOCK.name().toLowerCase(); + assertGettingValidatorForValidVnf(vnfType); + + vnfType = VnfType.MOCK.name().toUpperCase(); + assertGettingValidatorForValidVnf(vnfType); + } + + void assertGettingValidatorForValidVnf(String vnfType) { + try{ + OperationalStateValidator operationalStateValidator = OperationalStateValidatorFactory.getOperationalStateValidator(vnfType); + assertNotNull(operationalStateValidator); + } catch (Exception e) { + fail("valid vnfType throw exception!!!"); + } + } +} diff --git a/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/TestConnectionDetails.java b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/TestConnectionDetails.java new file mode 100644 index 000000000..9720732bf --- /dev/null +++ b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/TestConnectionDetails.java @@ -0,0 +1,46 @@ +/*-
+ * ============LICENSE_START=======================================================
+ * ONAP : APPC
+ * ================================================================================
+ * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * 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.
+ *
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.ccsdk.sli.adaptors.netconf;
+
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+
+public class TestConnectionDetails {
+
+ @Test
+ public void testGetSetMethods() {
+ ConnectionDetails connectionDetails = new ConnectionDetails();
+ connectionDetails.setHost("host1");
+ assertEquals("host1", connectionDetails.getHost());
+
+ connectionDetails.setPort(123);
+ assertEquals(123, connectionDetails.getPort());
+
+ connectionDetails.setUsername("myname");
+ assertEquals("myname", connectionDetails.getUsername());
+
+ connectionDetails.setPassword("mypassword");
+ assertEquals("mypassword", connectionDetails.getPassword());
+ }
+
+}
diff --git a/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/TestVnfType.java b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/TestVnfType.java new file mode 100644 index 000000000..7c6373046 --- /dev/null +++ b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/TestVnfType.java @@ -0,0 +1,42 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2019 IBM. + * ================================================================================ + * 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. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.netconf; + +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class TestVnfType { + private VnfType vnfType; + + @Before + public void setUp() { + vnfType = VnfType.VNF; + } + + @Test + public void testGetFamilyType() { + assertEquals(VnfType.VNF, vnfType.getFamilyType()); + } + +} diff --git a/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/VNFOperationalStateValidatorImplTest.java b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/VNFOperationalStateValidatorImplTest.java new file mode 100644 index 000000000..098118252 --- /dev/null +++ b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/VNFOperationalStateValidatorImplTest.java @@ -0,0 +1,51 @@ +/* + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2019 IBM. + * ================================================================================ + * 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. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.netconf; + +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class VNFOperationalStateValidatorImplTest { + + private VNFOperationalStateValidatorImpl vnfOperationalStateValidatorImpl; + + @Before + public void setUp() + { + vnfOperationalStateValidatorImpl= new VNFOperationalStateValidatorImpl(); + } + + @Test + public void testGetVnfType() + { + assertEquals(VnfType.VNF, vnfOperationalStateValidatorImpl.getVnfType()); + } + + @Test + public void testgetConfigurationFileName() + { + assertEquals("VnfGetOperationalStates", vnfOperationalStateValidatorImpl.getConfigurationFileName()); + } + +} diff --git a/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/exception/DataAccessExceptionTest.java b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/exception/DataAccessExceptionTest.java new file mode 100644 index 000000000..45fecf4f7 --- /dev/null +++ b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/exception/DataAccessExceptionTest.java @@ -0,0 +1,64 @@ +/* +* ============LICENSE_START======================================================= +* ONAP : APPC +* ================================================================================ +* Copyright 2018 TechMahindra +*================================================================================= +* 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. +* ============LICENSE_END========================================================= +*/ +package org.onap.ccsdk.sli.adaptors.netconf.exception; + +import org.junit.Assert; +import org.junit.Test; + +public class DataAccessExceptionTest { + + @Test + public void testConstructorNoArgument() throws Exception { + DataAccessException dataAccessException = new DataAccessException(); + Assert.assertTrue(dataAccessException.getCause() == null); + Assert.assertTrue(dataAccessException.getLocalizedMessage() == null); + Assert.assertTrue(dataAccessException.getMessage() == null); + } + + @Test + public void testConstructorWithMessage() throws Exception { + String message = "testing message"; + DataAccessException dataAccessException = new DataAccessException(message); + Assert.assertTrue(dataAccessException.getCause() == null); + Assert.assertEquals(message, dataAccessException.getLocalizedMessage()); + Assert.assertEquals(message, dataAccessException.getMessage()); + } + + @Test + public void testConstructorWithThrowable() throws Exception { + String message = "testing message"; + Throwable throwable = new Throwable(message); + DataAccessException dataAccessException = new DataAccessException(throwable); + Assert.assertEquals(throwable, dataAccessException.getCause()); + Assert.assertTrue(dataAccessException.getLocalizedMessage().contains(message)); + Assert.assertTrue(dataAccessException.getMessage().contains(message)); + } + + @Test + public void testConstructorWithMessageAndThrowable() throws Exception { + String message = "testing message"; + String tMessage = "throwable message"; + Throwable throwable = new Throwable(tMessage); + DataAccessException dataAccessException = new DataAccessException(message, throwable); + Assert.assertEquals(throwable, dataAccessException.getCause()); + Assert.assertTrue(dataAccessException.getLocalizedMessage().contains(message)); + Assert.assertTrue(dataAccessException.getMessage().contains(message)); + } +} diff --git a/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/exception/NetconfDAOExceptionTest.java b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/exception/NetconfDAOExceptionTest.java new file mode 100644 index 000000000..70fb2eeb5 --- /dev/null +++ b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/exception/NetconfDAOExceptionTest.java @@ -0,0 +1,64 @@ +/* +* ============LICENSE_START======================================================= +* ONAP : APPC +* ================================================================================ +* Copyright 2018 TechMahindra +*================================================================================= +* 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. +* ============LICENSE_END========================================================= +*/ +package org.onap.ccsdk.sli.adaptors.netconf.exception; + +import org.junit.Assert; +import org.junit.Test; + +public class NetconfDAOExceptionTest { + + @Test + public void testConstructorNoArgument() throws Exception { + NetconfDAOException netconfDAOException = new NetconfDAOException(); + Assert.assertTrue(netconfDAOException.getCause() == null); + Assert.assertTrue(netconfDAOException.getLocalizedMessage() == null); + Assert.assertTrue(netconfDAOException.getMessage() == null); + } + + @Test + public void testConstructorWithMessage() throws Exception { + String message = "testing message"; + NetconfDAOException netconfDAOException = new NetconfDAOException(message); + Assert.assertTrue(netconfDAOException.getCause() == null); + Assert.assertEquals(message, netconfDAOException.getLocalizedMessage()); + Assert.assertEquals(message, netconfDAOException.getMessage()); + } + + @Test + public void testConstructorWithThrowable() throws Exception { + String message = "testing message"; + Throwable throwable = new Throwable(message); + NetconfDAOException netconfDAOException = new NetconfDAOException(throwable); + Assert.assertEquals(throwable, netconfDAOException.getCause()); + Assert.assertTrue(netconfDAOException.getLocalizedMessage().contains(message)); + Assert.assertTrue(netconfDAOException.getMessage().contains(message)); + } + + @Test + public void testConstructorWithMessageAndThrowable() throws Exception { + String message = "testing message"; + String tMessage = "throwable message"; + Throwable throwable = new Throwable(tMessage); + NetconfDAOException netconfDAOException = new NetconfDAOException(message, throwable); + Assert.assertEquals(throwable, netconfDAOException.getCause()); + Assert.assertTrue(netconfDAOException.getLocalizedMessage().contains(message)); + Assert.assertTrue(netconfDAOException.getMessage().contains(message)); + } +} diff --git a/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/internal/TestNetconfAdaptor.java b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/internal/TestNetconfAdaptor.java new file mode 100644 index 000000000..757d767dd --- /dev/null +++ b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/internal/TestNetconfAdaptor.java @@ -0,0 +1,88 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 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. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.netconf.internal; + +import java.io.IOException; +import java.io.PipedInputStream; +import java.io.PipedOutputStream; +import org.junit.Assert; +import org.junit.Test; + +public class TestNetconfAdaptor { + + private static final String EOM = "]]>]]>"; + + @Test + public void testReceiveMessage() throws IOException { + PipedOutputStream pos = new PipedOutputStream(); + PipedInputStream is = new PipedInputStream(pos); + + PipedInputStream pis = new PipedInputStream(); + PipedOutputStream os = new PipedOutputStream(pis); + + NetconfAdaptor netconfAdaptor = new NetconfAdaptor(is, os); + + String request = "Hello, netconf!"; + pos.write(request.getBytes()); + pos.write(EOM.getBytes()); + String response = netconfAdaptor.receiveMessage(); + Assert.assertNotNull(response); + Assert.assertEquals(request, response.trim()); + } + + @Test + public void testSendMessage() throws IOException { + PipedOutputStream pos = new PipedOutputStream(); + PipedInputStream is = new PipedInputStream(pos); + + PipedInputStream pis = new PipedInputStream(); + PipedOutputStream os = new PipedOutputStream(pis); + + NetconfAdaptor netconfAdaptor = new NetconfAdaptor(is, os); + + String request = "Hello, netconf!"; + netconfAdaptor.sendMessage(request); + byte[] bytes = new byte[request.length()+EOM.length()+2]; + int count = pis.read(bytes); + String response = new String(bytes, 0, count); + Assert.assertNotNull(response); + Assert.assertTrue(response.endsWith(EOM)); + response = response.substring(0, response.length() - EOM.length()).trim(); + Assert.assertEquals(request, response); + } + + @Test + public void testSendReceive() throws IOException { + PipedOutputStream os = new PipedOutputStream(); + PipedInputStream is = new PipedInputStream(os); + + NetconfAdaptor netconfAdaptor = new NetconfAdaptor(is, os); + + String request = "Hello, netconf!"; + netconfAdaptor.sendMessage(request); + String response = netconfAdaptor.receiveMessage(); + Assert.assertNotNull(response); + Assert.assertEquals(request, response.trim()); + } +} diff --git a/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/internal/TestNetconfAdaptor2.java b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/internal/TestNetconfAdaptor2.java new file mode 100644 index 000000000..b276a0875 --- /dev/null +++ b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/internal/TestNetconfAdaptor2.java @@ -0,0 +1,103 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2018 Samsung + * ================================================================================ + * 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. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.netconf.internal; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PipedInputStream; +import java.io.PipedOutputStream; +import org.junit.Assert; +import org.junit.Test; + +public class TestNetconfAdaptor2 { + + private static final String EOM = "]]>]]>"; + + @Test (expected = IOException.class) + public void testReceiveMessage() throws IOException { + PipedOutputStream pos = new PipedOutputStream(); + PipedInputStream is = new PipedInputStream(pos); + + PipedInputStream pis = new PipedInputStream(); + PipedOutputStream os = new PipedOutputStream(pis); + + NetconfAdaptor2 netconfAdaptor = new NetconfAdaptor2(is, os); + + String request = "Hello, netconf!"; + pos.write(request.getBytes()); + pos.write(EOM.getBytes()); + String response = netconfAdaptor.receiveMessage(); + Assert.assertNotNull(response); + Assert.assertEquals(request, response.trim()); + } + + @Test (expected = IOException.class) + public void testSendMessage() throws IOException { + PipedOutputStream pos = new PipedOutputStream(); + PipedInputStream is = new PipedInputStream(pos); + + PipedInputStream pis = new PipedInputStream(); + PipedOutputStream os = new PipedOutputStream(pis); + + NetconfAdaptor2 netconfAdaptor = new NetconfAdaptor2(is, os); + + String request = "Hello, netconf!"; + netconfAdaptor.sendMessage(request); + byte[] bytes = new byte[request.length()+EOM.length()+2]; + int count = pis.read(bytes); + String response = new String(bytes, 0, count); + Assert.assertNotNull(response); + Assert.assertTrue(response.endsWith(EOM)); + response = response.substring(0, response.length() - EOM.length()).trim(); + Assert.assertEquals(request, response); + } + + @Test (expected = IOException.class) + public void testSendReceive() throws IOException { + PipedOutputStream os = new PipedOutputStream(); + PipedInputStream is = new PipedInputStream(os); + + NetconfAdaptor2 netconfAdaptor = new NetconfAdaptor2(is, os); + + String request = "Hello, netconf!"; + netconfAdaptor.sendMessage(request); + String response = netconfAdaptor.receiveMessage(); + Assert.assertNotNull(response); + Assert.assertEquals(request, response.trim()); + } + + @Test + public void testDefaultSendReceive() throws IOException { + + NetconfAdaptor2 netconfAdaptor = new NetconfAdaptor2(); + + String request = "Hello, netconf!"; + netconfAdaptor.sendMessage(request); + + InputStream in = netconfAdaptor.getIn(); + OutputStream out = netconfAdaptor.getOut(); + + Assert.assertNotNull(in); + Assert.assertNotNull(out); + } +}
\ No newline at end of file diff --git a/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/internal/TestNetconfDataAccessServiceImpl.java b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/internal/TestNetconfDataAccessServiceImpl.java new file mode 100644 index 000000000..0c5d49d2f --- /dev/null +++ b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/internal/TestNetconfDataAccessServiceImpl.java @@ -0,0 +1,139 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2018 Samsung + * ================================================================================ + * Modifications Copyright (C) 2019 Ericsson + * ================================================================================ + * 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. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.netconf.internal; + +import java.io.IOException; +import java.io.PrintWriter; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.SQLFeatureNotSupportedException; +import java.util.ArrayList; +import java.util.logging.Logger; +import javax.sql.rowset.CachedRowSet; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.onap.ccsdk.sli.adaptors.netconf.NetconfAdaptorConstants; +import org.onap.ccsdk.sli.adaptors.netconf.NetconfConnectionDetails; +import org.onap.ccsdk.sli.core.dblib.DbLibService; + +public class TestNetconfDataAccessServiceImpl { + NetconfDataAccessServiceImpl netconfDataAccessService; + private String schema; + private DbLibService dbLibServiceMocked; + + @Before + public void SetUp() { + schema = "test-netconf-adaptor"; + dbLibServiceMocked = new DbLibService() { + @Override + public CachedRowSet getData(String s, ArrayList<String> arrayList, String s1) throws SQLException { + CachedRowSet cachedRowSetMocked = Mockito.mock(CachedRowSet.class); + Mockito.when(cachedRowSetMocked.first()).thenReturn(true); + Mockito.when(cachedRowSetMocked.getString(NetconfAdaptorConstants.FILE_CONTENT_TABLE_FIELD_NAME)).thenReturn("File_Content"); + return cachedRowSetMocked; + } + + @Override + public boolean writeData(String s, ArrayList<String> arrayList, String s1) throws SQLException { + return false; + } + + @Override + public boolean isActive() { + return false; + } + + @Override + public Connection getConnection() throws SQLException { + return null; + } + + @Override + public Connection getConnection(String username, String password) throws SQLException { + return null; + } + + @Override + public <T> T unwrap(Class<T> iface) throws SQLException { + return null; + } + + @Override + public boolean isWrapperFor(Class<?> iface) throws SQLException { + return false; + } + + @Override + public PrintWriter getLogWriter() throws SQLException { + return null; + } + + @Override + public void setLogWriter(PrintWriter out) throws SQLException { + + } + + @Override + public int getLoginTimeout() throws SQLException { + return 0; + } + + @Override + public void setLoginTimeout(int seconds) throws SQLException { + + } + + @Override + public Logger getParentLogger() throws SQLFeatureNotSupportedException { + return null; + } + }; + + netconfDataAccessService = new NetconfDataAccessServiceImpl(); + netconfDataAccessService.setSchema(schema); + netconfDataAccessService.setDbLibService(dbLibServiceMocked); + } + + @Test + public void testRetrieveConfigFileName() throws IOException { + String response = netconfDataAccessService.retrieveConfigFileName("test"); + Assert.assertEquals("File_Content", response); + } + + @Test + public void testRetrieveNetconfConnectionDetails() throws IOException { + NetconfConnectionDetails netconfConnectionDetails = new NetconfConnectionDetails(); + boolean response = netconfDataAccessService.retrieveNetconfConnectionDetails("test", netconfConnectionDetails); + Assert.assertEquals(true, response); + } + + @Test + public void testLogDeviceInteraction() throws IOException { + boolean response = netconfDataAccessService.logDeviceInteraction("test", "", + "", ""); + Assert.assertEquals(true, response); + } +} diff --git a/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/jsch/TestGetRunningConfig.java b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/jsch/TestGetRunningConfig.java new file mode 100644 index 000000000..2ad873f54 --- /dev/null +++ b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/jsch/TestGetRunningConfig.java @@ -0,0 +1,59 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 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. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.netconf.jsch; + +import java.util.Collections; +import java.util.List; +import org.onap.ccsdk.sli.adaptors.netconf.NetconfConnectionDetails; + +public class TestGetRunningConfig { + + private static final String HOST = "192.168.1.2"; + private static final String USER = "test"; + private static final String PSWD = "test123"; + private static final int PORT = 830; + private static final List<String> CAPABILITIES = Collections.singletonList("<capability>urn:org:onap:appc:capability:1.1.0</capability>"); + + public static void main(String[] args) { + try { + NetconfConnectionDetails connectionDetails = new NetconfConnectionDetails(); + connectionDetails.setHost(HOST); + connectionDetails.setPort(PORT); + connectionDetails.setUsername(USER); + connectionDetails.setPassword(PSWD); + connectionDetails.setCapabilities(CAPABILITIES); + NetconfClientJsch netconfClientJsch = new NetconfClientJsch(); + netconfClientJsch.connect(connectionDetails); + try { + System.out.println("=> Running get configuration..."); + String configuration = netconfClientJsch.getConfiguration(); + System.out.println("=> Configuration:\n" + configuration); + } finally { + netconfClientJsch.disconnect(); + } + } catch(Exception e) { + e.printStackTrace(); + } + } +} diff --git a/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/jsch/TestJSchLogger.java b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/jsch/TestJSchLogger.java new file mode 100644 index 000000000..0a7bd5203 --- /dev/null +++ b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/jsch/TestJSchLogger.java @@ -0,0 +1,55 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2018 Samsung + * ================================================================================ + * 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. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.netconf.jsch; + +import java.io.IOException; +import org.junit.Assert; +import org.junit.Test; + +import static org.junit.Assert.assertNotNull; + +public class TestJSchLogger { + + + @Test + public void testIsEnabled() throws IOException { + JSchLogger jSchLogger = new JSchLogger(); + + boolean response = jSchLogger.isEnabled(2); + + Assert.assertEquals(true, response); + } + + @Test + public void testLog() throws IOException { + JSchLogger jSchLogger = new JSchLogger(); + + jSchLogger.log(0, "test-debug"); + jSchLogger.log(1, "test-info"); + jSchLogger.log(2, "test-warn"); + jSchLogger.log(3, "test-error"); + jSchLogger.log(4, "test-fatal"); + jSchLogger.log(5, "test-other"); + assertNotNull(jSchLogger); + + } +} diff --git a/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/jsch/TestModifyConfig.java b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/jsch/TestModifyConfig.java new file mode 100644 index 000000000..aaa74f5c9 --- /dev/null +++ b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/jsch/TestModifyConfig.java @@ -0,0 +1,92 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 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. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.netconf.jsch; + +import java.util.Collections; +import java.util.List; +import org.onap.ccsdk.sli.adaptors.netconf.NetconfConnectionDetails; + +public class TestModifyConfig { + + private static final String HOST = "192.168.1.2"; + private static final String USER = "test"; + private static final String PSWD = "test123"; + private static final int PORT = 830; + private static final List<String> CAPABILITIES = Collections.singletonList("<capability>urn:org:onap:appc:capability:1.1.0</capability>"); + private static final String CONFIG = + "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + + "<rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\" message-id=\"1\">\n" + + " <edit-config>\n" + + " <target>\n" + + " <running />\n" + + " </target>\n" + + " <default-operation>merge</default-operation>\n" + + " <config xmlns:xc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" + + " <ManagedElement xmlns=\"urn:org.onap.appc:Test\">\n" + + " <managedElementId>1</managedElementId>\n" + + " <VnfFunction xmlns=\"urn:org:onap:appc:VnfFunction\">\n" + + " <id>1</id>\n" + + " <Interfaces>\n" + + " <id>1</id>\n" + + " <DiaRealmRf>\n" + + " <realm>example.com</realm>\n" + + " <reconnectTimer>60</reconnectTimer>\n" + + " </DiaRealmRf>\n" + + " </Interfaces>\n" + + " </VnfFunction>\n" + + " </ManagedElement>\n" + + " </config>\n" + + " </edit-config>\n" + + "</rpc>"; + + public static void main(String[] args) { + try { + NetconfConnectionDetails connectionDetails = new NetconfConnectionDetails(); + connectionDetails.setHost(HOST); + connectionDetails.setPort(PORT); + connectionDetails.setUsername(USER); + connectionDetails.setPassword(PSWD); + connectionDetails.setCapabilities(CAPABILITIES); + NetconfClientJsch netconfClientJsch = new NetconfClientJsch(); + netconfClientJsch.connect(connectionDetails); + try { + System.out.println("=> Running get configuration..."); + String configuration = netconfClientJsch.getConfiguration(); + System.out.println("=> Configuration:\n" + configuration); + + System.out.println("=> Reconfiguring device..."); + String outMessage = netconfClientJsch.exchangeMessage(CONFIG); + System.out.println("=> Reconfiguration response:\n" + outMessage); + + System.out.println("=> Running get configuration..."); + configuration = netconfClientJsch.getConfiguration(); + System.out.println("=> Configuration:\n" + configuration); + } finally { + netconfClientJsch.disconnect(); + } + } catch(Exception e) { + e.printStackTrace(); + } + } +} diff --git a/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/jsch/TestModifyConfigMock.java b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/jsch/TestModifyConfigMock.java new file mode 100644 index 000000000..eb6473854 --- /dev/null +++ b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/jsch/TestModifyConfigMock.java @@ -0,0 +1,92 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 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. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.netconf.jsch; + +import java.util.Collections; +import java.util.List; +import org.onap.ccsdk.sli.adaptors.netconf.NetconfConnectionDetails; + +public class TestModifyConfigMock { + + private static final String HOST = "192.168.1.2"; + private static final String USER = "test"; + private static final String PSWD = "test123"; + private static final int PORT = 830; + private static final List<String> CAPABILITIES = Collections.singletonList("<capability>urn:org:onap:appc:capability:1.1.0</capability>"); + private static final String CONFIG = + "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + + "<rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\" message-id=\"1\">\n" + + " <edit-config>\n" + + " <target>\n" + + " <running />\n" + + " </target>\n" + + " <default-operation>merge</default-operation>\n" + + " <config xmlns:xc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" + + " <ManagedElement xmlns=\"urn:org.onap.appc:Test\">\n" + + " <managedElementId>1</managedElementId>\n" + + " <VnfFunction xmlns=\"urn:org:onap:appc:VnfFunction\">\n" + + " <id>1</id>\n" + + " <Interfaces>\n" + + " <id>1</id>\n" + + " <DiaRealmRf>\n" + + " <realm>example.com</realm>\n" + + " <reconnectTimer>60</reconnectTimer>\n" + + " </DiaRealmRf>\n" + + " </Interfaces>\n" + + " </VnfFunction>\n" + + " </ManagedElement>\n" + + " </config>\n" + + " </edit-config>\n" + + "</rpc>"; + + public static void main(String[] args) { + try { + NetconfConnectionDetails connectionDetails = new NetconfConnectionDetails(); + connectionDetails.setHost(HOST); + connectionDetails.setPort(PORT); + connectionDetails.setUsername(USER); + connectionDetails.setPassword(PSWD); + connectionDetails.setCapabilities(CAPABILITIES); + NetconfClientJsch netconfClientJsch = new NetconfClientJsch(); + netconfClientJsch.connect(connectionDetails); + try { + System.out.println("=> Running get configuration..."); + String configuration = netconfClientJsch.getConfiguration(); + System.out.println("=> Configuration:\n" + configuration); + + System.out.println("=> Reconfiguring device..."); + String outMessage = netconfClientJsch.exchangeMessage(CONFIG); + System.out.println("=> Reconfiguration response:\n" + outMessage); + + System.out.println("=> Running get configuration..."); + configuration = netconfClientJsch.getConfiguration(); + System.out.println("=> Configuration:\n" + configuration); + } finally { + netconfClientJsch.disconnect(); + } + } catch(Exception e) { + e.printStackTrace(); + } + } +} diff --git a/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/jsch/TestModifyConfigRouterMock.java b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/jsch/TestModifyConfigRouterMock.java new file mode 100644 index 000000000..7c209b9c2 --- /dev/null +++ b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/jsch/TestModifyConfigRouterMock.java @@ -0,0 +1,90 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 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. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.netconf.jsch; + +import java.util.Collections; +import java.util.List; +import org.onap.ccsdk.sli.adaptors.netconf.NetconfConnectionDetails; + +public class TestModifyConfigRouterMock { + + private static final String HOST = "10.147.27.50"; // yuma netconf simulator + private static final int PORT = 830; + private static final String USER = "admin"; + private static final String PSWD = "admin"; + private static final List<String> CAPABILITIES = Collections.emptyList(); + private static final String CONFIG = + "<rpc message-id=\"101\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" + + " <edit-config>\n" + + " <target>\n" + + " <candidate/>\n" + + " </target>\n" + + " <config xmlns:xc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" + + " <router xmlns=\"urn:sdnhub:odl:tutorial:router\">\n" + + " <ospf>\n" + + " <process-id>1</process-id>\n" + + " <networks>\n" + + " <subnet-ip>100.100.100.0/24</subnet-ip>\n" + + " <area-id>10</area-id>\n" + + " </networks>\n" + + " </ospf>\n" + + " <bgp>\n" + + " <as-number>1000</as-number>\n" + + " <router-id>10.10.1.1</router-id>\n" + + " <neighbors>\n" + + " <as-number>2000</as-number>\n" + + " <peer-ip>10.10.1.2</peer-ip>\n" + + " </neighbors>\n" + + " </bgp>\n" + + " </router>\n" + + " </config>\n" + + " </edit-config>\n" + + "</rpc>\n"; + + public static void main(String[] args) { + try { + NetconfConnectionDetails connectionDetails = new NetconfConnectionDetails(); + connectionDetails.setHost(HOST); + connectionDetails.setPort(PORT); + connectionDetails.setUsername(USER); + connectionDetails.setPassword(PSWD); + connectionDetails.setCapabilities(CAPABILITIES); + NetconfClientJsch netconfClientJsch = new NetconfClientJsch(); + netconfClientJsch.connect(connectionDetails); + try { + System.out.println("=> Running get configuration..."); + String configuration = netconfClientJsch.getConfiguration(); + System.out.println("=> Configuration:\n" + configuration); + + System.out.println("=> Reconfiguring device..."); + String outMessage = netconfClientJsch.exchangeMessage(CONFIG); + System.out.println("=> Reconfiguration response:\n" + outMessage); + } finally { + netconfClientJsch.disconnect(); + } + } catch(Exception e) { + e.printStackTrace(); + } + } +} diff --git a/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/jsch/TestNetconfClientJsch.java b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/jsch/TestNetconfClientJsch.java new file mode 100644 index 000000000..22d3ec482 --- /dev/null +++ b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/jsch/TestNetconfClientJsch.java @@ -0,0 +1,191 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2018 Samsung + * ================================================================================ + * Modifications Copyright (C) 2018 Ericsson + * ================================================================================ + * 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. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.netconf.jsch; + +import com.jcraft.jsch.ChannelSubsystem; +import com.jcraft.jsch.JSch; +import com.jcraft.jsch.JSchException; +import com.jcraft.jsch.Session; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.Collections; +import java.util.List; +import java.util.Properties; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.mockito.Mockito; +import org.onap.ccsdk.sli.adaptors.netconf.NetconfConnectionDetails; +import org.onap.ccsdk.sli.adaptors.netconf.internal.NetconfAdaptor; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.powermock.reflect.Whitebox; + +import static org.hamcrest.CoreMatchers.allOf; +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.isA; +import static org.hamcrest.beans.HasPropertyWithValue.hasProperty; +import static org.junit.Assert.assertEquals; + +public class TestNetconfClientJsch { + + NetconfClientJsch netconfClientJsch; + private ChannelSubsystem mockChannel; + private NetconfAdaptor mockNetconfAdaptor; + + @Rule + public ExpectedException expectedEx = ExpectedException.none(); + + @Before + public void SetUp() { + netconfClientJsch = Mockito.spy(new NetconfClientJsch()); + } + + private void setupForConnectTests() throws JSchException, IOException { + Session mockSession = Mockito.mock(Session.class); + JSch mockJSch = Mockito.mock(JSch.class); + mockChannel = Mockito.mock(ChannelSubsystem.class); + InputStream mockInputStream = Mockito.mock(InputStream.class); + OutputStream mockOutputStream = Mockito.mock(OutputStream.class); + mockNetconfAdaptor = Mockito.mock(NetconfAdaptor.class); + Mockito.doReturn(mockJSch).when(netconfClientJsch).getJSch(); + Mockito.doReturn(mockSession).when(mockJSch).getSession(Mockito.anyString(), + Mockito.anyString(), Mockito.anyInt()); + Mockito.doReturn(mockChannel).when(mockSession).openChannel("subsystem"); + Mockito.doReturn(mockInputStream).when(mockChannel).getInputStream(); + Mockito.doReturn(mockOutputStream).when(mockChannel).getOutputStream(); + Mockito.doReturn(mockNetconfAdaptor).when(netconfClientJsch) + .getNetconfAdaptor(Mockito.any(InputStream.class), Mockito.any(OutputStream.class)); + } + + @Test + public void testConnect() throws SvcLogicException, IOException, JSchException { + setupForConnectTests(); + Mockito.doReturn("<hello>").when(mockNetconfAdaptor).receiveMessage(); + NetconfConnectionDetails connectionDetails = new NetconfConnectionDetails(); + connectionDetails.setHost("test"); + connectionDetails.setPort(8080); + connectionDetails.setUsername("test"); + connectionDetails.setPassword("test"); + List<String> capabilities = Collections.singletonList( + "<capability>urn:ietf:params:netconf:base:1.1</capability>\r\n"); + connectionDetails.setCapabilities(capabilities); + Properties additionalProperties = new Properties(); + additionalProperties.setProperty("testKey1", "testParam1"); + connectionDetails.setAdditionalProperties(additionalProperties); + netconfClientJsch.connect(connectionDetails); + Mockito.verify(mockNetconfAdaptor).sendMessage( + Mockito.contains("<capability>urn:ietf:params:netconf:base:1.1</capability>")); + } + + @Test + public void testConnectNullMessage() throws JSchException, IOException, SvcLogicException { + setupForConnectTests(); + NetconfConnectionDetails connectionDetails = new NetconfConnectionDetails(); + expectedEx.expect(SvcLogicException.class); + //expectedEx.expectMessage("Cannot establish connection to server"); + netconfClientJsch.connect(connectionDetails); + } + + @Test + public void testConnectNullMessageNonNullResponse() + throws JSchException, IOException, SvcLogicException { + setupForConnectTests(); + Mockito.doReturn("NOT NULL RESPONSE").when(mockNetconfAdaptor).receiveMessage(); + Mockito.doThrow(new JSchException()).when(mockChannel).connect(10000); + NetconfConnectionDetails connectionDetails = new NetconfConnectionDetails(); + expectedEx.expect(SvcLogicException.class); + expectedEx.expectCause(allOf(isA(RuntimeException.class), + hasProperty("message", is("Error closing netconf device")))); + netconfClientJsch.connect(connectionDetails); + } + + @Test + public void testConnectErrorMessage() throws JSchException, IOException, SvcLogicException { + setupForConnectTests(); + Mockito.doReturn("<rpc-error>").when(mockNetconfAdaptor).receiveMessage(); + NetconfConnectionDetails connectionDetails = new NetconfConnectionDetails(); + expectedEx.expect(SvcLogicException.class); + expectedEx + .expectCause(allOf(isA(RuntimeException.class), + hasProperty("cause", allOf(isA(IOException.class), + hasProperty("message", + containsString("Error response from netconf device:")), + hasProperty("message", containsString("<rpc-error>")) + )))); + netconfClientJsch.connect(connectionDetails); + } + + @Test + public void testConnectWithSuccessfulDisconnect() + throws JSchException, IOException, SvcLogicException { + setupForConnectTests(); + Mockito.doThrow(new JSchException()).when(mockChannel).connect(10000); + Mockito.doReturn("<ok/>").when(mockNetconfAdaptor).receiveMessage(); + NetconfConnectionDetails connectionDetails = new NetconfConnectionDetails(); + expectedEx.expect(SvcLogicException.class); + expectedEx.expectCause(allOf(isA(SvcLogicException.class), + hasProperty("message", is(JSchException.class.getName())))); + netconfClientJsch.connect(connectionDetails); + } + + @Test + public void testGetConfiguration() throws IOException, SvcLogicException { + mockNetconfAdaptor = Mockito.mock(NetconfAdaptor.class); + Whitebox.setInternalState(netconfClientJsch, "netconfAdaptor", mockNetconfAdaptor); + Mockito.doReturn("TEST RETURN VALUE").when(mockNetconfAdaptor).receiveMessage(); + assertEquals("TEST RETURN VALUE", netconfClientJsch.getConfiguration()); + } + + @Test + public void testGetConfigurationExceptionFlow() throws IOException, SvcLogicException { + mockNetconfAdaptor = Mockito.mock(NetconfAdaptor.class); + Whitebox.setInternalState(netconfClientJsch, "netconfAdaptor", mockNetconfAdaptor); + Mockito.doThrow(new IOException()).when(mockNetconfAdaptor).receiveMessage(); + expectedEx.expect(SvcLogicException.class); + expectedEx.expectMessage(IOException.class.getName()); + netconfClientJsch.getConfiguration(); + } + + @Test + public void testConfigure() throws IOException, SvcLogicException { + mockNetconfAdaptor = Mockito.mock(NetconfAdaptor.class); + Whitebox.setInternalState(netconfClientJsch, "netconfAdaptor", mockNetconfAdaptor); + Mockito.doReturn("<ok/>").when(mockNetconfAdaptor).receiveMessage(); + netconfClientJsch.configure(null); + Mockito.verify(netconfClientJsch).exchangeMessage(null); + } + + @Test + public void testConfigureExceptionFlow() throws IOException, SvcLogicException { + mockNetconfAdaptor = Mockito.mock(NetconfAdaptor.class); + Whitebox.setInternalState(netconfClientJsch, "netconfAdaptor", mockNetconfAdaptor); + Mockito.doThrow(new IOException()).when(mockNetconfAdaptor).receiveMessage(); + expectedEx.expect(SvcLogicException.class); + expectedEx.expectMessage(IOException.class.getName()); + netconfClientJsch.configure(null); + } +} diff --git a/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/jsch/TestOperationalStates.java b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/jsch/TestOperationalStates.java new file mode 100644 index 000000000..128d68347 --- /dev/null +++ b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/jsch/TestOperationalStates.java @@ -0,0 +1,86 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 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. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.netconf.jsch; + +import java.util.Collections; +import java.util.List; +import org.onap.ccsdk.sli.adaptors.netconf.NetconfConnectionDetails; + +public class TestOperationalStates { + + private static final String HOST = "192.168.1.2"; + private static final String USER = "test"; + private static final String PSWD = "test123"; + private static final int PORT = 830; + private static final List<String> CAPABILITIES = Collections.singletonList("<capability>urn:org:onap:appc:capability:1.1.0</capability>"); + private static final String GET_OPERATIONAL_STATES = + "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + + "<rpc message-id=\"101\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" + + " <get>\n" + + " <filter>\n" + + " <ManagedElement xmlns=\"urn:org:onap:appc:Test\">\n" + + " <VnfFunction xmlns=\"urn:org:onap:appc:Test\">\n" + + " <ProcessorManagement>\n" + + " <MatedPair>\n" + + " <operationalState/>\n" + + " <PayloadProcessor>\n" + + " <operationalState/>\n" + + " </PayloadProcessor>\n" + + " </MatedPair>\n" + + " <SystemController>\n" + + " <operationalState/>\n" + + " </SystemController>\n" + + " </ProcessorManagement>\n" + + " </VnfFunction>\n" + + " </ManagedElement>\n" + + " </filter>\n" + + " </get>\n" + + "</rpc>"; + + public static void main(String[] args) { + try { + NetconfConnectionDetails connectionDetails = new NetconfConnectionDetails(); + connectionDetails.setHost(HOST); + connectionDetails.setPort(PORT); + connectionDetails.setUsername(USER); + connectionDetails.setPassword(PSWD); + connectionDetails.setCapabilities(CAPABILITIES); + NetconfClientJsch netconfClientJsch = new NetconfClientJsch(); + netconfClientJsch.connect(connectionDetails); + try { + System.out.println("=> Running get configuration..."); + String configuration = netconfClientJsch.getConfiguration(); + System.out.println("=> Configuration:\n" + configuration); + + System.out.println("=> Running get operational states..."); + String outMessage = netconfClientJsch.exchangeMessage(GET_OPERATIONAL_STATES); + System.out.println("=> Operational states:\n" + outMessage); + } finally { + netconfClientJsch.disconnect(); + } + } catch(Exception e) { + e.printStackTrace(); + } + } +} diff --git a/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/odlconnector/NetconfClientRestconfImplTest.java b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/odlconnector/NetconfClientRestconfImplTest.java new file mode 100644 index 000000000..4b59c6d2a --- /dev/null +++ b/adaptors/netconf-adaptor/netconf-adaptor-bundle/src/test/java/org/onap/ccsdk/sli/adaptors/netconf/odlconnector/NetconfClientRestconfImplTest.java @@ -0,0 +1,207 @@ +/* + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2019 Ericsson + * ================================================================================ + * 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. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.netconf.odlconnector; + +import java.util.Properties; +import org.apache.http.HttpStatus; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.onap.ccsdk.sli.adaptors.netconf.HttpClient; +import org.onap.ccsdk.sli.adaptors.netconf.NetconfAdaptorConstants; +import org.onap.ccsdk.sli.adaptors.netconf.NetconfConnectionDetails; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.reflect.Whitebox; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +@Ignore +@RunWith(PowerMockRunner.class) +@PrepareForTest(HttpClient.class) +public class NetconfClientRestconfImplTest { + + @Rule + public ExpectedException expectedEx = ExpectedException.none(); + + @Before + public void setup() { + PowerMockito.mockStatic(HttpClient.class); + } + @Test + public void testConfigureNullDetails() throws SvcLogicException { + NetconfClientRestconfImpl client = new NetconfClientRestconfImpl(); + expectedEx.expect(SvcLogicException.class); + expectedEx.expectMessage("Invalid connection details - null value"); + client.configure(null); + } + + @Test + public void testConfigureNullProperties() throws SvcLogicException { + NetconfClientRestconfImpl client = Mockito.spy(new NetconfClientRestconfImpl()); + expectedEx.expect(SvcLogicException.class); + expectedEx.expectMessage("Invalid properties!"); + Whitebox.setInternalState(client, "connectionDetails", Mockito.mock(NetconfConnectionDetails.class)); + client.configure(null); + } + + @Test + public void testConfigureWithError() throws SvcLogicException { + PowerMockito.when(HttpClient.putMethod(NetconfAdaptorConstants.PROTOCOL, NetconfAdaptorConstants.CONTROLLER_IP, NetconfAdaptorConstants.CONTROLLER_PORT, + NetconfAdaptorConstants.CONFIGURE_PATH + "null/yang-ext:mount/MODULE_NAME:NODE_NAME", null, "application/xml")) + .thenReturn(HttpStatus.SC_ACCEPTED); + NetconfClientRestconfImpl client = Mockito.spy(new NetconfClientRestconfImpl()); + NetconfConnectionDetails details = new NetconfConnectionDetails(); + Properties properties = new Properties(); + properties.setProperty("module.name", "MODULE_NAME"); + properties.setProperty("node.name", "NODE_NAME"); + details.setAdditionalProperties(properties); + Whitebox.setInternalState(client, "connectionDetails", details); + expectedEx.expect(SvcLogicException.class); + expectedEx.expectMessage("Error configuring node :NODE_NAME, of Module :MODULE_NAME, in device :null"); + client.configure(null); + } + + @Test + public void testConfigure4ArgWithError() throws SvcLogicException { + PowerMockito.when(HttpClient.putMethod(NetconfAdaptorConstants.PROTOCOL, NetconfAdaptorConstants.CONTROLLER_IP, NetconfAdaptorConstants.CONTROLLER_PORT, + NetconfAdaptorConstants.CONFIGURE_PATH + "null/yang-ext:mount/MODULE_NAME:NODE_NAME", null, "application/xml")) + .thenReturn(HttpStatus.SC_ACCEPTED); + NetconfClientRestconfImpl client = Mockito.spy(new NetconfClientRestconfImpl()); + expectedEx.expect(SvcLogicException.class); + expectedEx.expectMessage("Error configuring node :NODE_NAME, of Module :MODULE_NAME, in device :null"); + client.configure(null, null, "MODULE_NAME", "NODE_NAME"); + } + + @Test + public void testConnect() throws SvcLogicException { + PowerMockito.when(HttpClient.putMethod(NetconfAdaptorConstants.PROTOCOL, NetconfAdaptorConstants.CONTROLLER_IP, NetconfAdaptorConstants.CONTROLLER_PORT, + NetconfAdaptorConstants.CONFIGURE_PATH + "null/yang-ext:mount/MODULE_NAME:NODE_NAME", null, "application/xml")) + .thenReturn(HttpStatus.SC_ACCEPTED); + NetconfClientRestconfImpl client = Mockito.spy(new NetconfClientRestconfImpl()); + NetconfConnectionDetails details = new NetconfConnectionDetails(); + Properties properties = new Properties(); + properties.setProperty("module.name", "MODULE_NAME"); + properties.setProperty("node.name", "NODE_NAME"); + details.setAdditionalProperties(properties); + Whitebox.setInternalState(client, "connectionDetails", details); + expectedEx.expect(SvcLogicException.class); + expectedEx.expectMessage("Error connecting device :null"); + client.connect(details); + } + + @Test + public void testConnectWithNullDetails() throws SvcLogicException { + PowerMockito.when(HttpClient.putMethod(NetconfAdaptorConstants.PROTOCOL, NetconfAdaptorConstants.CONTROLLER_IP, NetconfAdaptorConstants.CONTROLLER_PORT, + NetconfAdaptorConstants.CONFIGURE_PATH + "null/yang-ext:mount/MODULE_NAME:NODE_NAME", null, "application/xml")) + .thenReturn(HttpStatus.SC_ACCEPTED); + NetconfClientRestconfImpl client = Mockito.spy(new NetconfClientRestconfImpl()); + expectedEx.expect(SvcLogicException.class); + expectedEx.expectMessage("Invalid connection details - null value"); + client.connect(null); + } + + @Test + public void testDisconnectNullDetails() throws SvcLogicException { + NetconfClientRestconfImpl client = Mockito.spy(new NetconfClientRestconfImpl()); + expectedEx.expect(SvcLogicException.class); + expectedEx.expectMessage("Invalid connection details - null value"); + client.disconnect(); + } + + @Test + public void testDisconnect() throws SvcLogicException { + NetconfClientRestconfImpl client = Mockito.spy(new NetconfClientRestconfImpl()); + NetconfConnectionDetails details = new NetconfConnectionDetails(); + Properties properties = new Properties(); + properties.setProperty("module.name", "MODULE_NAME"); + properties.setProperty("node.name", "NODE_NAME"); + details.setAdditionalProperties(properties); + Whitebox.setInternalState(client, "connectionDetails", details); + expectedEx.expect(SvcLogicException.class); + expectedEx.expectMessage("Disconnection of device null failed!"); + client.disconnect(); + } + + @Test + public void testGetConfigurationNullDetails() throws SvcLogicException { + NetconfClientRestconfImpl client = Mockito.spy(new NetconfClientRestconfImpl()); + expectedEx.expect(SvcLogicException.class); + expectedEx.expectMessage("Invalid connection details - null value"); + client.getConfiguration(); + } + + @Test + public void testGetConfigurationNullProperties() throws SvcLogicException { + NetconfClientRestconfImpl client = Mockito.spy(new NetconfClientRestconfImpl()); + expectedEx.expect(SvcLogicException.class); + expectedEx.expectMessage("Invalid properties!"); + Whitebox.setInternalState(client, "connectionDetails", Mockito.mock(NetconfConnectionDetails.class)); + client.getConfiguration(); + } + + @Test + public void testGetConfigurationWithError() throws SvcLogicException { + PowerMockito.when(HttpClient.putMethod(NetconfAdaptorConstants.PROTOCOL, NetconfAdaptorConstants.CONTROLLER_IP, NetconfAdaptorConstants.CONTROLLER_PORT, + NetconfAdaptorConstants.CONFIGURE_PATH + "null/yang-ext:mount/MODULE_NAME:NODE_NAME", null, "application/xml")) + .thenReturn(HttpStatus.SC_ACCEPTED); + NetconfClientRestconfImpl client = Mockito.spy(new NetconfClientRestconfImpl()); + NetconfConnectionDetails details = new NetconfConnectionDetails(); + Properties properties = new Properties(); + properties.setProperty("module.name", "MODULE_NAME"); + properties.setProperty("node.name", "NODE_NAME"); + details.setAdditionalProperties(properties); + Whitebox.setInternalState(client, "connectionDetails", details); + expectedEx.expect(SvcLogicException.class); + expectedEx.expectMessage("Error getting configuration of node :NODE_NAME, of Module :MODULE_NAME, in device :null"); + client.getConfiguration(); + } + + @Test + public void testGetConfigurationSuccess() throws SvcLogicException { + PowerMockito.when(HttpClient.getMethod(NetconfAdaptorConstants.PROTOCOL, NetconfAdaptorConstants.CONTROLLER_IP, NetconfAdaptorConstants.CONTROLLER_PORT, + NetconfAdaptorConstants.CONFIGURE_PATH + "null/yang-ext:mount/MODULE_NAME:NODE_NAME", "application/json")) + .thenReturn("TEST"); + NetconfClientRestconfImpl client = Mockito.spy(new NetconfClientRestconfImpl()); + NetconfConnectionDetails details = new NetconfConnectionDetails(); + Properties properties = new Properties(); + properties.setProperty("module.name", "MODULE_NAME"); + properties.setProperty("node.name", "NODE_NAME"); + details.setAdditionalProperties(properties); + Whitebox.setInternalState(client, "connectionDetails", details); + assertEquals("TEST", client.getConfiguration()); + } + + @Test + public void testCheckConnection() throws SvcLogicException { + NetconfClientRestconfImpl client = new NetconfClientRestconfImpl(); + assertFalse(client.checkConnection(null)); + + } +} |