From ea5bf0a1c8a4e525d2cee03841b8e8f9b3563ed0 Mon Sep 17 00:00:00 2001 From: Dan Timoney Date: Tue, 18 Jul 2017 20:32:15 -0400 Subject: [CCSDK-6] Populate seed code Add seed code for sli/northbound repository Update groupId to org.onap.ccsdk.sli.northbound Update to use CCSDK version of sli core Change-Id: Id3a154a53150a74f4b65060544e76f3e0cad932e Signed-off-by: Dan Timoney --- dmaap-listener/src/assembly/assemble_zip.xml | 61 +++++++ .../openecomp/sdnc/dmaapclient/DmaapListener.java | 165 +++++++++++++++++ .../sdnc/dmaapclient/DummyDmaapConsumer.java | 37 ++++ .../sdnc/dmaapclient/InvalidMessageException.java | 37 ++++ .../sdnc/dmaapclient/SdncDmaapConsumer.java | 146 +++++++++++++++ .../dmaapclient/SdncFlatJsonDmaapConsumer.java | 196 +++++++++++++++++++++ .../sdnc/dmaapclient/SdncOdlConnection.java | 159 +++++++++++++++++ .../src/main/resources/edgeRouterStatusChange.map | 23 +++ dmaap-listener/src/main/resources/log4j.properties | 37 ++++ .../src/main/resources/preferredRoute.txt | 1 + .../src/main/scripts/start-dmaap-listener.sh | 69 ++++++++ .../src/main/scripts/stop-dmaap-listener.sh | 52 ++++++ dmaap-listener/src/site/apt/index.apt | 46 +++++ dmaap-listener/src/site/site.xml | 31 ++++ 14 files changed, 1060 insertions(+) create mode 100644 dmaap-listener/src/assembly/assemble_zip.xml create mode 100644 dmaap-listener/src/main/java/org/openecomp/sdnc/dmaapclient/DmaapListener.java create mode 100644 dmaap-listener/src/main/java/org/openecomp/sdnc/dmaapclient/DummyDmaapConsumer.java create mode 100644 dmaap-listener/src/main/java/org/openecomp/sdnc/dmaapclient/InvalidMessageException.java create mode 100644 dmaap-listener/src/main/java/org/openecomp/sdnc/dmaapclient/SdncDmaapConsumer.java create mode 100644 dmaap-listener/src/main/java/org/openecomp/sdnc/dmaapclient/SdncFlatJsonDmaapConsumer.java create mode 100644 dmaap-listener/src/main/java/org/openecomp/sdnc/dmaapclient/SdncOdlConnection.java create mode 100644 dmaap-listener/src/main/resources/edgeRouterStatusChange.map create mode 100644 dmaap-listener/src/main/resources/log4j.properties create mode 100644 dmaap-listener/src/main/resources/preferredRoute.txt create mode 100644 dmaap-listener/src/main/scripts/start-dmaap-listener.sh create mode 100644 dmaap-listener/src/main/scripts/stop-dmaap-listener.sh create mode 100644 dmaap-listener/src/site/apt/index.apt create mode 100644 dmaap-listener/src/site/site.xml (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/src/assembly/assemble_zip.xml b/dmaap-listener/src/assembly/assemble_zip.xml new file mode 100644 index 000000000..15f6bf4d2 --- /dev/null +++ b/dmaap-listener/src/assembly/assemble_zip.xml @@ -0,0 +1,61 @@ + + + + + + assemble_zip + + zip + + + false + + + + src/main/scripts + bin + + + target + lib + + *.jar + + + + src/main/resources + lib + + *.properties + *.map + + + + + + lib + true + runtime + + + diff --git a/dmaap-listener/src/main/java/org/openecomp/sdnc/dmaapclient/DmaapListener.java b/dmaap-listener/src/main/java/org/openecomp/sdnc/dmaapclient/DmaapListener.java new file mode 100644 index 000000000..7096d83bf --- /dev/null +++ b/dmaap-listener/src/main/java/org/openecomp/sdnc/dmaapclient/DmaapListener.java @@ -0,0 +1,165 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 ONAP 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.openecomp.sdnc.dmaapclient; + +import java.io.File; +import java.io.FileInputStream; +import java.util.LinkedList; +import java.util.List; +import java.util.Properties; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class DmaapListener { + + private static final String DMAAP_LISTENER_PROPERTIES = "dmaap-listener.properties"; + private static final String SDNC_CONFIG_DIR = "SDNC_CONFIG_DIR"; + private static final Logger LOG = LoggerFactory + .getLogger(DmaapListener.class); + + public static void main(String[] args) { + + Properties properties = new Properties(); + + + String propFileName = DMAAP_LISTENER_PROPERTIES; + + if (args.length > 0) { + propFileName = args[0]; + } + + String propPath = null; + String propDir = System.getenv(SDNC_CONFIG_DIR); + + List consumers = new LinkedList(); + + if (propDir == null) { + + propDir = "/opt/sdnc/data/properties"; + } + + if (!propFileName.startsWith("/")) { + propPath = propDir + "/" + propFileName; + } + + File propFile = new File(propPath); + + if (!propFile.canRead()) { + LOG.error("Cannot read properties file "+propPath); + System.exit(1); + } + + try { + properties.load(new FileInputStream(propFile)); + } catch (Exception e) { + LOG.error("Caught exception loading properties from "+propPath, e); + System.exit(1); + } + + String subscriptionStr = properties.getProperty("subscriptions"); + + boolean threadsRunning = false; + + LOG.debug("Dmaap subscriptions : "+subscriptionStr); + + if (subscriptionStr != null) { + String[] subscriptions = subscriptionStr.split(";"); + + for (int i = 0; i < subscriptions.length; i++) { + String[] subscription = subscriptions[i].split(":"); + String consumerClassName = subscription[0]; + String propertyPath = subscription[1]; + + LOG.debug("Handling subscription [" + consumerClassName + "," + propertyPath + "]"); + + if (propertyPath == null) { + LOG.error("Invalid subscription (" + subscriptions[i] + ") property file missing"); + continue; + } + + if (!propertyPath.startsWith("/")) { + propertyPath = propDir + "/" + propertyPath; + } + + Class consumerClass = null; + + try { + consumerClass = Class.forName(consumerClassName); + } catch (Exception e) { + LOG.error("Could not find DMaap consumer class " + consumerClassName); + } + + if (consumerClass != null) { + + SdncDmaapConsumer consumer = null; + + try { + consumer = (SdncDmaapConsumer) consumerClass.newInstance(); + } catch (Exception e) { + LOG.error("Could not create consumer from class " + consumerClassName, e); + } + + if (consumer != null) { + LOG.debug("Initializing consumer " + consumerClassName + "(" + propertyPath + ")"); + consumer.init(properties, propertyPath); + + if (consumer.isReady()) { + Thread consumerThread = new Thread(consumer); + consumerThread.start(); + consumers.add(consumer); + threadsRunning = true; + LOG.info("Started consumer thread (" + consumerClassName + " : " + propertyPath + ")"); + } else { + LOG.debug("Consumer " + consumerClassName + " is not ready"); + } + } + + } + + } + } + + while (threadsRunning) { + + threadsRunning = false; + for (SdncDmaapConsumer consumer : consumers) { + if (consumer.isRunning()) { + threadsRunning = true; + } + } + + if (!threadsRunning) { + break; + } + + try { + Thread.sleep(10000); + } catch (InterruptedException e) { + + } + } + + LOG.info("No listener threads running - exitting"); + + } +} diff --git a/dmaap-listener/src/main/java/org/openecomp/sdnc/dmaapclient/DummyDmaapConsumer.java b/dmaap-listener/src/main/java/org/openecomp/sdnc/dmaapclient/DummyDmaapConsumer.java new file mode 100644 index 000000000..5edc1c908 --- /dev/null +++ b/dmaap-listener/src/main/java/org/openecomp/sdnc/dmaapclient/DummyDmaapConsumer.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 ONAP 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.openecomp.sdnc.dmaapclient; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class DummyDmaapConsumer extends SdncDmaapConsumer { + + private static final Logger LOG = LoggerFactory + .getLogger(DummyDmaapConsumer.class); + + @Override + public void processMsg(String msg) { + LOG.info("Consumed message: \n"+msg); + } + +} diff --git a/dmaap-listener/src/main/java/org/openecomp/sdnc/dmaapclient/InvalidMessageException.java b/dmaap-listener/src/main/java/org/openecomp/sdnc/dmaapclient/InvalidMessageException.java new file mode 100644 index 000000000..3de5df6c2 --- /dev/null +++ b/dmaap-listener/src/main/java/org/openecomp/sdnc/dmaapclient/InvalidMessageException.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 ONAP 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.openecomp.sdnc.dmaapclient; + +public class InvalidMessageException extends Exception { + + public InvalidMessageException() { + super(); + } + + public InvalidMessageException(String msg) { + super(msg); + } + + public InvalidMessageException(String msg, Throwable t) { + super(msg, t); + } +} diff --git a/dmaap-listener/src/main/java/org/openecomp/sdnc/dmaapclient/SdncDmaapConsumer.java b/dmaap-listener/src/main/java/org/openecomp/sdnc/dmaapclient/SdncDmaapConsumer.java new file mode 100644 index 000000000..5b55bda5b --- /dev/null +++ b/dmaap-listener/src/main/java/org/openecomp/sdnc/dmaapclient/SdncDmaapConsumer.java @@ -0,0 +1,146 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 ONAP 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.openecomp.sdnc.dmaapclient; + +import java.io.File; +import java.io.FileInputStream; +import java.util.Properties; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.att.nsa.mr.client.MRClientFactory; +import com.att.nsa.mr.client.MRConsumer; +import com.att.nsa.mr.client.response.MRConsumerResponse; + +public abstract class SdncDmaapConsumer implements Runnable { + + private static final Logger LOG = LoggerFactory + .getLogger(SdncDmaapConsumer.class); + + private String propertiesPath = ""; + private Properties properties = null; + MRConsumer consumer = null; + MRConsumerResponse consumerResponse = null; + boolean running = false; + boolean ready = false; + int fetchPause = 5000; // Default pause between fetchs - 5 seconds + + public boolean isReady() { + return ready; + } + + int timeout = 15000; // Default timeout - 15 seconds + + public boolean isRunning() { + return running; + } + + public SdncDmaapConsumer() { + + } + + public SdncDmaapConsumer(Properties properties, String propertiesPath) { + init(properties, propertiesPath); + } + + public String getProperty(String name) { + return(properties.getProperty(name, "")); + } + + public void init(Properties properties, String propertiesPath) { + + this.propertiesPath = propertiesPath; + + try { + + this.properties = (Properties) properties.clone(); + + this.properties.load(new FileInputStream(new File(propertiesPath))); + + String timeoutStr = properties.getProperty("timeout"); + + if ((timeoutStr != null) && (timeoutStr.length() > 0)) { + try { + timeout = Integer.parseInt(timeoutStr); + } catch (NumberFormatException e) { + LOG.error("Non-numeric value specified for timeout ("+timeoutStr+")"); + } + } + + String fetchPauseStr = properties.getProperty("fetchPause"); + if ((fetchPauseStr != null) && (fetchPauseStr.length() > 0)) { + try { + fetchPause = Integer.parseInt(fetchPauseStr); + } catch (NumberFormatException e) { + LOG.error("Non-numeric valud specified for fetchPause ("+fetchPauseStr+")"); + } + } + + this.consumer = MRClientFactory.createConsumer(propertiesPath); + ready = true; + } catch (Exception e) { + LOG.error("Error initializing DMaaP consumer from file "+propertiesPath, e); + } + } + + + @Override + public void run() { + if (ready) { + + running = true; + + while (running) { + + try { + boolean noData = true; + consumerResponse = consumer.fetchWithReturnConsumerResponse(timeout, -1); + for (String msg : consumerResponse.getActualMessages()) { + noData = false; + LOG.info("Received message from DMaaP:\n"+msg); + processMsg(msg); + } + + if (noData) { + if (fetchPause > 0) { + + LOG.info("No data received from fetch. Pausing "+fetchPause+" ms before retry"); + Thread.sleep(fetchPause); + } else { + + LOG.info("No data received from fetch. No fetch pause specified - retrying immediately"); + } + } + } catch (Exception e) { + LOG.error("Caught exception reading from DMaaP", e); + running = false; + } + + + } + } + + } + + abstract public void processMsg(String msg) throws InvalidMessageException; +} diff --git a/dmaap-listener/src/main/java/org/openecomp/sdnc/dmaapclient/SdncFlatJsonDmaapConsumer.java b/dmaap-listener/src/main/java/org/openecomp/sdnc/dmaapclient/SdncFlatJsonDmaapConsumer.java new file mode 100644 index 000000000..7e9c069ac --- /dev/null +++ b/dmaap-listener/src/main/java/org/openecomp/sdnc/dmaapclient/SdncFlatJsonDmaapConsumer.java @@ -0,0 +1,196 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 ONAP 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.openecomp.sdnc.dmaapclient; + +import java.io.BufferedReader; +import java.io.DataOutputStream; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.Authenticator; +import java.net.HttpURLConnection; +import java.net.PasswordAuthentication; +import java.net.URL; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLSession; + +import org.apache.commons.codec.binary.Base64; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; + + +public class SdncFlatJsonDmaapConsumer extends SdncDmaapConsumer { + + private static final Logger LOG = LoggerFactory + .getLogger(SdncFlatJsonDmaapConsumer.class); + + private static final String DMAAPLISTENERROOT = "DMAAPLISTENERROOT"; + private static final String SDNC_ENDPOINT = "SDNC.endpoint"; + + + + @Override + public void processMsg(String msg) throws InvalidMessageException { + + processMsg(msg, null); + } + + public void processMsg(String msg, String mapDirName) throws InvalidMessageException { + + if (msg == null) { + throw new InvalidMessageException("Null message"); + } + + ObjectMapper oMapper = new ObjectMapper(); + JsonNode instarRootNode = null; + ObjectNode sdncRootNode = null; + + String instarMsgName = null; + + try { + instarRootNode = oMapper.readTree(msg); + } catch (Exception e) { + throw new InvalidMessageException("Cannot parse json object", e); + } + + Iterator> instarFields = instarRootNode.fields(); + + while (instarFields.hasNext()) { + Map.Entry entry = instarFields.next(); + + instarMsgName = entry.getKey(); + instarRootNode = entry.getValue(); + break; + } + + Map fieldMap = loadMap(instarMsgName, mapDirName); + + if (fieldMap == null) { + throw new InvalidMessageException("Unable to process message - cannot load field mappings"); + } + + if (!fieldMap.containsKey(SDNC_ENDPOINT)) { + throw new InvalidMessageException("No SDNC endpoint known for message "+instarMsgName); + } + + String sdncEndpoint = fieldMap.get(SDNC_ENDPOINT); + + sdncRootNode = oMapper.createObjectNode(); + ObjectNode inputNode = oMapper.createObjectNode(); + + + for (String fromField : fieldMap.keySet()) { + + if (!SDNC_ENDPOINT.equals(fromField)) { + JsonNode curNode = instarRootNode.get(fromField); + if (curNode != null) { + String fromValue = curNode.textValue(); + + inputNode.put(fieldMap.get(fromField), fromValue); + } + } + } + sdncRootNode.put("input", inputNode); + + try { + String rpcMsgbody = oMapper.writeValueAsString(sdncRootNode); + String odlUrlBase = getProperty("sdnc.odl.url-base"); + String odlUser = getProperty("sdnc.odl.user"); + String odlPassword = getProperty("sdnc.odl.password"); + + if ((odlUrlBase != null) && (odlUrlBase.length() > 0)) { + SdncOdlConnection conn = SdncOdlConnection.newInstance(odlUrlBase + sdncEndpoint, odlUser, odlPassword); + + conn.send("POST", "application/json", rpcMsgbody); + } else { + LOG.info("POST message body would be:\n"+rpcMsgbody); + } + } catch (Exception e) { + + } + + } + + private Map loadMap(String msgType, String mapDirName) { + Map results = new HashMap(); + + + if (mapDirName == null) { + String rootdir = System.getenv(DMAAPLISTENERROOT); + + if ((rootdir == null) || (rootdir.length() == 0)) { + rootdir = "/opt/app/dmaap-listener"; + } + + mapDirName = rootdir + "/lib"; + + } + + String mapFilename = mapDirName + "/" + msgType + ".map"; + + File mapFile = new File(mapFilename); + + if (!mapFile.canRead()) { + LOG.error("Cannot read map file ("+mapFilename+")"); + return(null); + } + + try { + BufferedReader mapReader = new BufferedReader(new FileReader(mapFile)); + + String curLine = null; + + while ((curLine = mapReader.readLine()) != null) { + curLine = curLine.trim(); + + if ((curLine.length() > 0) && (!curLine.startsWith("#"))) { + + if (curLine.contains("=>")) { + String[] entry = curLine.split("=>"); + if (entry.length == 2) { + results.put(entry[0].trim(), entry[1].trim()); + } + } + } + } + mapReader.close(); + } catch (Exception e) { + LOG.error("Caught exception reading map "+mapFilename, e); + return(null); + } + + return(results); + } + + + +} diff --git a/dmaap-listener/src/main/java/org/openecomp/sdnc/dmaapclient/SdncOdlConnection.java b/dmaap-listener/src/main/java/org/openecomp/sdnc/dmaapclient/SdncOdlConnection.java new file mode 100644 index 000000000..6c6f308fb --- /dev/null +++ b/dmaap-listener/src/main/java/org/openecomp/sdnc/dmaapclient/SdncOdlConnection.java @@ -0,0 +1,159 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 ONAP 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.openecomp.sdnc.dmaapclient; + +import java.io.BufferedReader; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.Authenticator; +import java.net.HttpURLConnection; +import java.net.PasswordAuthentication; +import java.net.ProtocolException; +import java.net.URL; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLSession; + +import org.apache.commons.codec.binary.Base64; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +public class SdncOdlConnection { + + private static final Logger LOG = LoggerFactory + .getLogger(SdncOdlConnection.class); + + private HttpURLConnection httpConn = null; + + private String url = null; + private String user = null; + private String password = null; + + private class SdncAuthenticator extends Authenticator { + + private String user; + private String passwd; + + SdncAuthenticator(String user, String passwd) { + this.user = user; + this.passwd = passwd; + } + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(user, passwd.toCharArray()); + } + + } + + private SdncOdlConnection() { + + } + + private SdncOdlConnection(String url, String user, String password) { + this.url = url; + this.user = user; + this.password = password; + + try { + URL sdncUrl = new URL(url); + Authenticator.setDefault(new SdncAuthenticator(user, password)); + + this.httpConn = (HttpURLConnection) sdncUrl.openConnection(); + } catch (Exception e) { + LOG.error("Unable to create http connection", e); + } + } + + public static SdncOdlConnection newInstance(String url, String user, String password) throws IOException + { + return (new SdncOdlConnection(url, user, password)); + } + + + + public String send(String method, String contentType, String msg) throws IOException { + + LOG.info("Sending REST " + method + " to " + url); + LOG.info("Message body:\n" + msg); + String authStr = user + ":" + password; + String encodedAuthStr = new String(Base64.encodeBase64(authStr.getBytes())); + + httpConn.addRequestProperty("Authentication", "Basic " + encodedAuthStr); + + httpConn.setRequestMethod(method); + httpConn.setRequestProperty("Content-Type", contentType); + httpConn.setRequestProperty("Accept", contentType); + + httpConn.setDoInput(true); + httpConn.setDoOutput(true); + httpConn.setUseCaches(false); + + if (httpConn instanceof HttpsURLConnection) { + HostnameVerifier hostnameVerifier = new HostnameVerifier() { + @Override + public boolean verify(String hostname, SSLSession session) { + return true; + } + }; + ((HttpsURLConnection) httpConn).setHostnameVerifier(hostnameVerifier); + } + + // Write message + httpConn.setRequestProperty("Content-Length", "" + msg.length()); + DataOutputStream outStr = new DataOutputStream(httpConn.getOutputStream()); + outStr.write(msg.getBytes()); + outStr.close(); + + // Read response + BufferedReader respRdr; + + LOG.info("Response: " + httpConn.getResponseCode() + " " + httpConn.getResponseMessage()); + + if (httpConn.getResponseCode() < 300) { + + respRdr = new BufferedReader(new InputStreamReader(httpConn.getInputStream())); + } else { + respRdr = new BufferedReader(new InputStreamReader(httpConn.getErrorStream())); + } + + StringBuffer respBuff = new StringBuffer(); + + String respLn; + + while ((respLn = respRdr.readLine()) != null) { + respBuff.append(respLn + "\n"); + } + respRdr.close(); + + String respString = respBuff.toString(); + + LOG.info("Response body :\n" + respString); + + return (respString); + + } + + +} diff --git a/dmaap-listener/src/main/resources/edgeRouterStatusChange.map b/dmaap-listener/src/main/resources/edgeRouterStatusChange.map new file mode 100644 index 000000000..57644bbd5 --- /dev/null +++ b/dmaap-listener/src/main/resources/edgeRouterStatusChange.map @@ -0,0 +1,23 @@ +# SDN-C URL +SDNC.endpoint => FLOWRED-API:process-edge-router-status-change + +# Field mapping +equip_id => equip_id +ptnii_equip_name => equip-name +equip_type.equip_type => equip-type +ip_addr => loopback0 +router_prov_status => prov-status +country.region => region +country_abbr => country +equip_name_code => equip-name-code +as_number => as-number +loopback1 => loopback1 +loopback2 => loopback2 +loopback3 => loopback3 +loopback40 => loopback40 +loopback65535 => loopback65535 +inms_list => inms-list +encrypted_access_flag => encrypted-access-flag +sw_name => sw-name +nmipaddr => nm-addr +function_code => function-code \ No newline at end of file diff --git a/dmaap-listener/src/main/resources/log4j.properties b/dmaap-listener/src/main/resources/log4j.properties new file mode 100644 index 000000000..ba815871b --- /dev/null +++ b/dmaap-listener/src/main/resources/log4j.properties @@ -0,0 +1,37 @@ +### +# ============LICENSE_START======================================================= +# openECOMP : SDN-C +# ================================================================================ +# Copyright (C) 2017 ONAP 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========================================================= +### + +log4j.rootLogger=DEBUG,CONSOLE,LOGFILE + +# CONSOLE is set to be a ConsoleAppender using a PatternLayout. +log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender +log4j.appender.CONSOLE.Threshold=ERROR +log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout +log4j.appender.CONSOLE.layout.ConversionPattern=%p %d{yyyy-MM-dd HH:mm:ss.SSS Z} %c{1} - %m%n + +# LOGFILE is set to be a File appender using a PatternLayout. +log4j.appender.LOGFILE=org.apache.log4j.RollingFileAppender +log4j.appender.LOGFILE.File=/opt/app/dmaap-listener/logs/dmaap-listener.log +log4j.appender.LOGFILE.Append=true +log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout +log4j.appender.LOGFILE.layout.ConversionPattern=%p %d{yyyy-MM-dd HH:mm:ss.SSS Z} %c{1} - %m%n +log4j.appender.LOGFILE.MaxFileSize=10MB +log4j.appender.LOGFILE.MaxBackupIndex=10 diff --git a/dmaap-listener/src/main/resources/preferredRoute.txt b/dmaap-listener/src/main/resources/preferredRoute.txt new file mode 100644 index 000000000..662b0aa7d --- /dev/null +++ b/dmaap-listener/src/main/resources/preferredRoute.txt @@ -0,0 +1 @@ +preferredRouteKey=MR1 \ No newline at end of file diff --git a/dmaap-listener/src/main/scripts/start-dmaap-listener.sh b/dmaap-listener/src/main/scripts/start-dmaap-listener.sh new file mode 100644 index 000000000..5eeb62bbf --- /dev/null +++ b/dmaap-listener/src/main/scripts/start-dmaap-listener.sh @@ -0,0 +1,69 @@ +#!/bin/bash + +### +# ============LICENSE_START======================================================= +# openECOMP : SDN-C +# ================================================================================ +# Copyright (C) 2017 ONAP 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========================================================= +### + +PROPERTY_DIR=${PROPERTY_DIR:-/opt/sdnc/data/properties} + +LISTENER=dmaap-listener + + + +PIDFILE=/tmp/.${LISTENER}-pid +UEBLISTENERROOT=${UEBLISTENERROOT:-/opt/app/dmaap-listener} +JAVA_HOME=${JAVA_HOME:-/usr/lib/jvm/java-7-oracle} +JAVA_OPTS=${JAVA_OPTS:--Dhttps.protocols=TLSv1.1,TLSv1.2} +JAVA=${JAVA:-${JAVA_HOME}/bin/java} + +# Redirect output from script to $LISTENER.out +exec >> ${UEBLISTENERROOT}/logs/$LISTENER.out +exec 2>&1 + +if [ -f $PIDFILE ] +then + pid=$(cat $PIDFILE) + if [ "$pid" != "" ] + then + if kill -0 $pid + then + echo "$LISTENER already running" + exit 0 + fi + fi +fi + +if [ ! -d ${UEBLISTENERROOT}/logs ] +then + mkdir ${UEBLISTENERROOT}/logs +fi + +for file in ${UEBLISTENERROOT}/lib/*.jar +do + LISTENERCLASSPATH=$LISTENERCLASSPATH:$file +done + +${JAVA} ${JAVA_OPTS} -Dlog4j.configuration=file:${UEBLISTENERROOT}/lib/log4j.properties -cp ${LISTENERCLASSPATH} com.att.sdnctl.dmaapclient.DmaapListener & + + +echo $! > $PIDFILE + +echo "$LISTENER started!" +exit 0 diff --git a/dmaap-listener/src/main/scripts/stop-dmaap-listener.sh b/dmaap-listener/src/main/scripts/stop-dmaap-listener.sh new file mode 100644 index 000000000..42de474fb --- /dev/null +++ b/dmaap-listener/src/main/scripts/stop-dmaap-listener.sh @@ -0,0 +1,52 @@ +#!/bin/bash + +### +# ============LICENSE_START======================================================= +# openECOMP : SDN-C +# ================================================================================ +# Copyright (C) 2017 ONAP 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========================================================= +### + +PROPERTY_DIR=${PROPERTY_DIR:-/opt/sdnc/data/properties} + +LISTENER=dmaap-listener + + +PIDFILE=/tmp/.${LISTENER}-pid +UEBLISTENERROOT=${UEBLISTENERROOT:-/opt/app/dmaap-listener} + +if [ -f $PIDFILE ] +then + pid=$(cat $PIDFILE) + if [ "$pid" != "" ] + then + if kill -0 $pid + then + echo "Stopping $LISTENER" + kill $pid && rm $PIDFILE + exit 0 + else + echo "$LISTENER not running" + exit 1 + fi + else + echo "$LISTENER not running" + exit 1 + fi +fi + + diff --git a/dmaap-listener/src/site/apt/index.apt b/dmaap-listener/src/site/apt/index.apt new file mode 100644 index 000000000..dd9d3ec39 --- /dev/null +++ b/dmaap-listener/src/site/apt/index.apt @@ -0,0 +1,46 @@ +~~~ +~~ ============LICENSE_START======================================================= +~~ openECOMP : SDN-C +~~ ================================================================================ +~~ Copyright (C) 2017 ONAP 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========================================================= +~~~ + + --- + UEB Listener + --- + + +UEB Listener + + The UEB Listener is a daemon that listens for notifications from SDC, posted to UEB (Universal Event Bus). + On receipt of an event, the UEB listener downloads any artifacts posted and examines them to determine if + the format (the outer XML tag) matches a supported format. If so, it posts the file to the ASDC-API REST + API in order to update the SDN-C database. + +File Locations + + * Root directory : /opt/app/ueb-listener + + * Log files : /opt/app/ueb-listener/logs + + * Incoming files to be processed : /opt/app/ueb-listener/spool/asdc/incoming + + * Files already processed : /opt/app/ueb-listener/spool/asdc/archive + + + + diff --git a/dmaap-listener/src/site/site.xml b/dmaap-listener/src/site/site.xml new file mode 100644 index 000000000..356c9c959 --- /dev/null +++ b/dmaap-listener/src/site/site.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + -- cgit 1.2.3-korg From 41df62392ed3d1775c29b7cc1feb161108026c39 Mon Sep 17 00:00:00 2001 From: Dan Timoney Date: Tue, 15 Aug 2017 14:10:37 -0400 Subject: Refactor rest of sli/northbound Update remainder of sli/northbound to replace references to openECOMP with references to ONAP Change-Id: I2c321c9ec3f3138f3b7377ce1e0a8ff7e8f29bcc Issue-ID: CCSDK-25 Signed-off-by: Dan Timoney --- .../sli/northbound/dmaapclient/DmaapListener.java | 165 +++ .../northbound/dmaapclient/DummyDmaapConsumer.java | 37 + .../dmaapclient/InvalidMessageException.java | 37 + .../northbound/dmaapclient/SdncDmaapConsumer.java | 146 +++ .../dmaapclient/SdncFlatJsonDmaapConsumer.java | 196 ++++ .../northbound/dmaapclient/SdncOdlConnection.java | 159 +++ .../openecomp/sdnc/dmaapclient/DmaapListener.java | 165 --- .../sdnc/dmaapclient/DummyDmaapConsumer.java | 37 - .../sdnc/dmaapclient/InvalidMessageException.java | 37 - .../sdnc/dmaapclient/SdncDmaapConsumer.java | 146 --- .../dmaapclient/SdncFlatJsonDmaapConsumer.java | 196 ---- .../sdnc/dmaapclient/SdncOdlConnection.java | 159 --- example-settings.xml | 163 --- jenkins-settings.xml | 168 --- .../sli/northbound/uebclient/SdncARModel.java | 53 + .../sli/northbound/uebclient/SdncArtifactMap.java | 134 +++ .../sli/northbound/uebclient/SdncBaseModel.java | 297 ++++++ .../sli/northbound/uebclient/SdncNodeModel.java | 145 +++ .../northbound/uebclient/SdncOdlConnection.java | 158 +++ .../sli/northbound/uebclient/SdncServiceModel.java | 98 ++ .../sli/northbound/uebclient/SdncUebCallback.java | 1125 ++++++++++++++++++++ .../sli/northbound/uebclient/SdncUebClient.java | 65 ++ .../northbound/uebclient/SdncUebConfiguration.java | 280 +++++ .../sli/northbound/uebclient/SdncVFCModel.java | 69 ++ .../sli/northbound/uebclient/SdncVFModel.java | 56 + .../northbound/uebclient/SdncVFModuleModel.java | 45 + .../org/openecomp/sdnc/uebclient/SdncARModel.java | 53 - .../openecomp/sdnc/uebclient/SdncArtifactMap.java | 134 --- .../openecomp/sdnc/uebclient/SdncBaseModel.java | 297 ------ .../openecomp/sdnc/uebclient/SdncNodeModel.java | 145 --- .../sdnc/uebclient/SdncOdlConnection.java | 158 --- .../openecomp/sdnc/uebclient/SdncServiceModel.java | 98 -- .../openecomp/sdnc/uebclient/SdncUebCallback.java | 1125 -------------------- .../openecomp/sdnc/uebclient/SdncUebClient.java | 65 -- .../sdnc/uebclient/SdncUebConfiguration.java | 280 ----- .../org/openecomp/sdnc/uebclient/SdncVFCModel.java | 69 -- .../org/openecomp/sdnc/uebclient/SdncVFModel.java | 56 - .../sdnc/uebclient/SdncVFModuleModel.java | 45 - 38 files changed, 3265 insertions(+), 3596 deletions(-) create mode 100644 dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/DmaapListener.java create mode 100644 dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/DummyDmaapConsumer.java create mode 100644 dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/InvalidMessageException.java create mode 100644 dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncDmaapConsumer.java create mode 100644 dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncFlatJsonDmaapConsumer.java create mode 100644 dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncOdlConnection.java delete mode 100644 dmaap-listener/src/main/java/org/openecomp/sdnc/dmaapclient/DmaapListener.java delete mode 100644 dmaap-listener/src/main/java/org/openecomp/sdnc/dmaapclient/DummyDmaapConsumer.java delete mode 100644 dmaap-listener/src/main/java/org/openecomp/sdnc/dmaapclient/InvalidMessageException.java delete mode 100644 dmaap-listener/src/main/java/org/openecomp/sdnc/dmaapclient/SdncDmaapConsumer.java delete mode 100644 dmaap-listener/src/main/java/org/openecomp/sdnc/dmaapclient/SdncFlatJsonDmaapConsumer.java delete mode 100644 dmaap-listener/src/main/java/org/openecomp/sdnc/dmaapclient/SdncOdlConnection.java delete mode 100644 example-settings.xml delete mode 100644 jenkins-settings.xml create mode 100644 ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncARModel.java create mode 100644 ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncArtifactMap.java create mode 100644 ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncBaseModel.java create mode 100644 ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncNodeModel.java create mode 100644 ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncOdlConnection.java create mode 100644 ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncServiceModel.java create mode 100644 ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncUebCallback.java create mode 100644 ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncUebClient.java create mode 100644 ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncUebConfiguration.java create mode 100644 ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncVFCModel.java create mode 100644 ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncVFModel.java create mode 100644 ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncVFModuleModel.java delete mode 100644 ueb-listener/src/main/java/org/openecomp/sdnc/uebclient/SdncARModel.java delete mode 100644 ueb-listener/src/main/java/org/openecomp/sdnc/uebclient/SdncArtifactMap.java delete mode 100644 ueb-listener/src/main/java/org/openecomp/sdnc/uebclient/SdncBaseModel.java delete mode 100644 ueb-listener/src/main/java/org/openecomp/sdnc/uebclient/SdncNodeModel.java delete mode 100644 ueb-listener/src/main/java/org/openecomp/sdnc/uebclient/SdncOdlConnection.java delete mode 100644 ueb-listener/src/main/java/org/openecomp/sdnc/uebclient/SdncServiceModel.java delete mode 100644 ueb-listener/src/main/java/org/openecomp/sdnc/uebclient/SdncUebCallback.java delete mode 100644 ueb-listener/src/main/java/org/openecomp/sdnc/uebclient/SdncUebClient.java delete mode 100644 ueb-listener/src/main/java/org/openecomp/sdnc/uebclient/SdncUebConfiguration.java delete mode 100644 ueb-listener/src/main/java/org/openecomp/sdnc/uebclient/SdncVFCModel.java delete mode 100644 ueb-listener/src/main/java/org/openecomp/sdnc/uebclient/SdncVFModel.java delete mode 100644 ueb-listener/src/main/java/org/openecomp/sdnc/uebclient/SdncVFModuleModel.java (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/DmaapListener.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/DmaapListener.java new file mode 100644 index 000000000..b2976294b --- /dev/null +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/DmaapListener.java @@ -0,0 +1,165 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 ONAP 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.northbound.dmaapclient; + +import java.io.File; +import java.io.FileInputStream; +import java.util.LinkedList; +import java.util.List; +import java.util.Properties; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class DmaapListener { + + private static final String DMAAP_LISTENER_PROPERTIES = "dmaap-listener.properties"; + private static final String SDNC_CONFIG_DIR = "SDNC_CONFIG_DIR"; + private static final Logger LOG = LoggerFactory + .getLogger(DmaapListener.class); + + public static void main(String[] args) { + + Properties properties = new Properties(); + + + String propFileName = DMAAP_LISTENER_PROPERTIES; + + if (args.length > 0) { + propFileName = args[0]; + } + + String propPath = null; + String propDir = System.getenv(SDNC_CONFIG_DIR); + + List consumers = new LinkedList(); + + if (propDir == null) { + + propDir = "/opt/sdnc/data/properties"; + } + + if (!propFileName.startsWith("/")) { + propPath = propDir + "/" + propFileName; + } + + File propFile = new File(propPath); + + if (!propFile.canRead()) { + LOG.error("Cannot read properties file "+propPath); + System.exit(1); + } + + try { + properties.load(new FileInputStream(propFile)); + } catch (Exception e) { + LOG.error("Caught exception loading properties from "+propPath, e); + System.exit(1); + } + + String subscriptionStr = properties.getProperty("subscriptions"); + + boolean threadsRunning = false; + + LOG.debug("Dmaap subscriptions : "+subscriptionStr); + + if (subscriptionStr != null) { + String[] subscriptions = subscriptionStr.split(";"); + + for (int i = 0; i < subscriptions.length; i++) { + String[] subscription = subscriptions[i].split(":"); + String consumerClassName = subscription[0]; + String propertyPath = subscription[1]; + + LOG.debug("Handling subscription [" + consumerClassName + "," + propertyPath + "]"); + + if (propertyPath == null) { + LOG.error("Invalid subscription (" + subscriptions[i] + ") property file missing"); + continue; + } + + if (!propertyPath.startsWith("/")) { + propertyPath = propDir + "/" + propertyPath; + } + + Class consumerClass = null; + + try { + consumerClass = Class.forName(consumerClassName); + } catch (Exception e) { + LOG.error("Could not find DMaap consumer class " + consumerClassName); + } + + if (consumerClass != null) { + + SdncDmaapConsumer consumer = null; + + try { + consumer = (SdncDmaapConsumer) consumerClass.newInstance(); + } catch (Exception e) { + LOG.error("Could not create consumer from class " + consumerClassName, e); + } + + if (consumer != null) { + LOG.debug("Initializing consumer " + consumerClassName + "(" + propertyPath + ")"); + consumer.init(properties, propertyPath); + + if (consumer.isReady()) { + Thread consumerThread = new Thread(consumer); + consumerThread.start(); + consumers.add(consumer); + threadsRunning = true; + LOG.info("Started consumer thread (" + consumerClassName + " : " + propertyPath + ")"); + } else { + LOG.debug("Consumer " + consumerClassName + " is not ready"); + } + } + + } + + } + } + + while (threadsRunning) { + + threadsRunning = false; + for (SdncDmaapConsumer consumer : consumers) { + if (consumer.isRunning()) { + threadsRunning = true; + } + } + + if (!threadsRunning) { + break; + } + + try { + Thread.sleep(10000); + } catch (InterruptedException e) { + + } + } + + LOG.info("No listener threads running - exitting"); + + } +} diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/DummyDmaapConsumer.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/DummyDmaapConsumer.java new file mode 100644 index 000000000..a3bc46153 --- /dev/null +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/DummyDmaapConsumer.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 ONAP 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.northbound.dmaapclient; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class DummyDmaapConsumer extends SdncDmaapConsumer { + + private static final Logger LOG = LoggerFactory + .getLogger(DummyDmaapConsumer.class); + + @Override + public void processMsg(String msg) { + LOG.info("Consumed message: \n"+msg); + } + +} diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/InvalidMessageException.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/InvalidMessageException.java new file mode 100644 index 000000000..b54adaf06 --- /dev/null +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/InvalidMessageException.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 ONAP 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.northbound.dmaapclient; + +public class InvalidMessageException extends Exception { + + public InvalidMessageException() { + super(); + } + + public InvalidMessageException(String msg) { + super(msg); + } + + public InvalidMessageException(String msg, Throwable t) { + super(msg, t); + } +} diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncDmaapConsumer.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncDmaapConsumer.java new file mode 100644 index 000000000..f6d8ff862 --- /dev/null +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncDmaapConsumer.java @@ -0,0 +1,146 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 ONAP 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.northbound.dmaapclient; + +import java.io.File; +import java.io.FileInputStream; +import java.util.Properties; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.att.nsa.mr.client.MRClientFactory; +import com.att.nsa.mr.client.MRConsumer; +import com.att.nsa.mr.client.response.MRConsumerResponse; + +public abstract class SdncDmaapConsumer implements Runnable { + + private static final Logger LOG = LoggerFactory + .getLogger(SdncDmaapConsumer.class); + + private String propertiesPath = ""; + private Properties properties = null; + MRConsumer consumer = null; + MRConsumerResponse consumerResponse = null; + boolean running = false; + boolean ready = false; + int fetchPause = 5000; // Default pause between fetchs - 5 seconds + + public boolean isReady() { + return ready; + } + + int timeout = 15000; // Default timeout - 15 seconds + + public boolean isRunning() { + return running; + } + + public SdncDmaapConsumer() { + + } + + public SdncDmaapConsumer(Properties properties, String propertiesPath) { + init(properties, propertiesPath); + } + + public String getProperty(String name) { + return(properties.getProperty(name, "")); + } + + public void init(Properties properties, String propertiesPath) { + + this.propertiesPath = propertiesPath; + + try { + + this.properties = (Properties) properties.clone(); + + this.properties.load(new FileInputStream(new File(propertiesPath))); + + String timeoutStr = properties.getProperty("timeout"); + + if ((timeoutStr != null) && (timeoutStr.length() > 0)) { + try { + timeout = Integer.parseInt(timeoutStr); + } catch (NumberFormatException e) { + LOG.error("Non-numeric value specified for timeout ("+timeoutStr+")"); + } + } + + String fetchPauseStr = properties.getProperty("fetchPause"); + if ((fetchPauseStr != null) && (fetchPauseStr.length() > 0)) { + try { + fetchPause = Integer.parseInt(fetchPauseStr); + } catch (NumberFormatException e) { + LOG.error("Non-numeric valud specified for fetchPause ("+fetchPauseStr+")"); + } + } + + this.consumer = MRClientFactory.createConsumer(propertiesPath); + ready = true; + } catch (Exception e) { + LOG.error("Error initializing DMaaP consumer from file "+propertiesPath, e); + } + } + + + @Override + public void run() { + if (ready) { + + running = true; + + while (running) { + + try { + boolean noData = true; + consumerResponse = consumer.fetchWithReturnConsumerResponse(timeout, -1); + for (String msg : consumerResponse.getActualMessages()) { + noData = false; + LOG.info("Received message from DMaaP:\n"+msg); + processMsg(msg); + } + + if (noData) { + if (fetchPause > 0) { + + LOG.info("No data received from fetch. Pausing "+fetchPause+" ms before retry"); + Thread.sleep(fetchPause); + } else { + + LOG.info("No data received from fetch. No fetch pause specified - retrying immediately"); + } + } + } catch (Exception e) { + LOG.error("Caught exception reading from DMaaP", e); + running = false; + } + + + } + } + + } + + abstract public void processMsg(String msg) throws InvalidMessageException; +} diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncFlatJsonDmaapConsumer.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncFlatJsonDmaapConsumer.java new file mode 100644 index 000000000..0e2a32646 --- /dev/null +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncFlatJsonDmaapConsumer.java @@ -0,0 +1,196 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 ONAP 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.northbound.dmaapclient; + +import java.io.BufferedReader; +import java.io.DataOutputStream; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.Authenticator; +import java.net.HttpURLConnection; +import java.net.PasswordAuthentication; +import java.net.URL; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLSession; + +import org.apache.commons.codec.binary.Base64; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; + + +public class SdncFlatJsonDmaapConsumer extends SdncDmaapConsumer { + + private static final Logger LOG = LoggerFactory + .getLogger(SdncFlatJsonDmaapConsumer.class); + + private static final String DMAAPLISTENERROOT = "DMAAPLISTENERROOT"; + private static final String SDNC_ENDPOINT = "SDNC.endpoint"; + + + + @Override + public void processMsg(String msg) throws InvalidMessageException { + + processMsg(msg, null); + } + + public void processMsg(String msg, String mapDirName) throws InvalidMessageException { + + if (msg == null) { + throw new InvalidMessageException("Null message"); + } + + ObjectMapper oMapper = new ObjectMapper(); + JsonNode instarRootNode = null; + ObjectNode sdncRootNode = null; + + String instarMsgName = null; + + try { + instarRootNode = oMapper.readTree(msg); + } catch (Exception e) { + throw new InvalidMessageException("Cannot parse json object", e); + } + + Iterator> instarFields = instarRootNode.fields(); + + while (instarFields.hasNext()) { + Map.Entry entry = instarFields.next(); + + instarMsgName = entry.getKey(); + instarRootNode = entry.getValue(); + break; + } + + Map fieldMap = loadMap(instarMsgName, mapDirName); + + if (fieldMap == null) { + throw new InvalidMessageException("Unable to process message - cannot load field mappings"); + } + + if (!fieldMap.containsKey(SDNC_ENDPOINT)) { + throw new InvalidMessageException("No SDNC endpoint known for message "+instarMsgName); + } + + String sdncEndpoint = fieldMap.get(SDNC_ENDPOINT); + + sdncRootNode = oMapper.createObjectNode(); + ObjectNode inputNode = oMapper.createObjectNode(); + + + for (String fromField : fieldMap.keySet()) { + + if (!SDNC_ENDPOINT.equals(fromField)) { + JsonNode curNode = instarRootNode.get(fromField); + if (curNode != null) { + String fromValue = curNode.textValue(); + + inputNode.put(fieldMap.get(fromField), fromValue); + } + } + } + sdncRootNode.put("input", inputNode); + + try { + String rpcMsgbody = oMapper.writeValueAsString(sdncRootNode); + String odlUrlBase = getProperty("sdnc.odl.url-base"); + String odlUser = getProperty("sdnc.odl.user"); + String odlPassword = getProperty("sdnc.odl.password"); + + if ((odlUrlBase != null) && (odlUrlBase.length() > 0)) { + SdncOdlConnection conn = SdncOdlConnection.newInstance(odlUrlBase + sdncEndpoint, odlUser, odlPassword); + + conn.send("POST", "application/json", rpcMsgbody); + } else { + LOG.info("POST message body would be:\n"+rpcMsgbody); + } + } catch (Exception e) { + + } + + } + + private Map loadMap(String msgType, String mapDirName) { + Map results = new HashMap(); + + + if (mapDirName == null) { + String rootdir = System.getenv(DMAAPLISTENERROOT); + + if ((rootdir == null) || (rootdir.length() == 0)) { + rootdir = "/opt/app/dmaap-listener"; + } + + mapDirName = rootdir + "/lib"; + + } + + String mapFilename = mapDirName + "/" + msgType + ".map"; + + File mapFile = new File(mapFilename); + + if (!mapFile.canRead()) { + LOG.error("Cannot read map file ("+mapFilename+")"); + return(null); + } + + try { + BufferedReader mapReader = new BufferedReader(new FileReader(mapFile)); + + String curLine = null; + + while ((curLine = mapReader.readLine()) != null) { + curLine = curLine.trim(); + + if ((curLine.length() > 0) && (!curLine.startsWith("#"))) { + + if (curLine.contains("=>")) { + String[] entry = curLine.split("=>"); + if (entry.length == 2) { + results.put(entry[0].trim(), entry[1].trim()); + } + } + } + } + mapReader.close(); + } catch (Exception e) { + LOG.error("Caught exception reading map "+mapFilename, e); + return(null); + } + + return(results); + } + + + +} diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncOdlConnection.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncOdlConnection.java new file mode 100644 index 000000000..4d16dd2a0 --- /dev/null +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncOdlConnection.java @@ -0,0 +1,159 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 ONAP 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.northbound.dmaapclient; + +import java.io.BufferedReader; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.Authenticator; +import java.net.HttpURLConnection; +import java.net.PasswordAuthentication; +import java.net.ProtocolException; +import java.net.URL; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLSession; + +import org.apache.commons.codec.binary.Base64; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +public class SdncOdlConnection { + + private static final Logger LOG = LoggerFactory + .getLogger(SdncOdlConnection.class); + + private HttpURLConnection httpConn = null; + + private String url = null; + private String user = null; + private String password = null; + + private class SdncAuthenticator extends Authenticator { + + private String user; + private String passwd; + + SdncAuthenticator(String user, String passwd) { + this.user = user; + this.passwd = passwd; + } + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(user, passwd.toCharArray()); + } + + } + + private SdncOdlConnection() { + + } + + private SdncOdlConnection(String url, String user, String password) { + this.url = url; + this.user = user; + this.password = password; + + try { + URL sdncUrl = new URL(url); + Authenticator.setDefault(new SdncAuthenticator(user, password)); + + this.httpConn = (HttpURLConnection) sdncUrl.openConnection(); + } catch (Exception e) { + LOG.error("Unable to create http connection", e); + } + } + + public static SdncOdlConnection newInstance(String url, String user, String password) throws IOException + { + return (new SdncOdlConnection(url, user, password)); + } + + + + public String send(String method, String contentType, String msg) throws IOException { + + LOG.info("Sending REST " + method + " to " + url); + LOG.info("Message body:\n" + msg); + String authStr = user + ":" + password; + String encodedAuthStr = new String(Base64.encodeBase64(authStr.getBytes())); + + httpConn.addRequestProperty("Authentication", "Basic " + encodedAuthStr); + + httpConn.setRequestMethod(method); + httpConn.setRequestProperty("Content-Type", contentType); + httpConn.setRequestProperty("Accept", contentType); + + httpConn.setDoInput(true); + httpConn.setDoOutput(true); + httpConn.setUseCaches(false); + + if (httpConn instanceof HttpsURLConnection) { + HostnameVerifier hostnameVerifier = new HostnameVerifier() { + @Override + public boolean verify(String hostname, SSLSession session) { + return true; + } + }; + ((HttpsURLConnection) httpConn).setHostnameVerifier(hostnameVerifier); + } + + // Write message + httpConn.setRequestProperty("Content-Length", "" + msg.length()); + DataOutputStream outStr = new DataOutputStream(httpConn.getOutputStream()); + outStr.write(msg.getBytes()); + outStr.close(); + + // Read response + BufferedReader respRdr; + + LOG.info("Response: " + httpConn.getResponseCode() + " " + httpConn.getResponseMessage()); + + if (httpConn.getResponseCode() < 300) { + + respRdr = new BufferedReader(new InputStreamReader(httpConn.getInputStream())); + } else { + respRdr = new BufferedReader(new InputStreamReader(httpConn.getErrorStream())); + } + + StringBuffer respBuff = new StringBuffer(); + + String respLn; + + while ((respLn = respRdr.readLine()) != null) { + respBuff.append(respLn + "\n"); + } + respRdr.close(); + + String respString = respBuff.toString(); + + LOG.info("Response body :\n" + respString); + + return (respString); + + } + + +} diff --git a/dmaap-listener/src/main/java/org/openecomp/sdnc/dmaapclient/DmaapListener.java b/dmaap-listener/src/main/java/org/openecomp/sdnc/dmaapclient/DmaapListener.java deleted file mode 100644 index 7096d83bf..000000000 --- a/dmaap-listener/src/main/java/org/openecomp/sdnc/dmaapclient/DmaapListener.java +++ /dev/null @@ -1,165 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 ONAP 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.openecomp.sdnc.dmaapclient; - -import java.io.File; -import java.io.FileInputStream; -import java.util.LinkedList; -import java.util.List; -import java.util.Properties; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class DmaapListener { - - private static final String DMAAP_LISTENER_PROPERTIES = "dmaap-listener.properties"; - private static final String SDNC_CONFIG_DIR = "SDNC_CONFIG_DIR"; - private static final Logger LOG = LoggerFactory - .getLogger(DmaapListener.class); - - public static void main(String[] args) { - - Properties properties = new Properties(); - - - String propFileName = DMAAP_LISTENER_PROPERTIES; - - if (args.length > 0) { - propFileName = args[0]; - } - - String propPath = null; - String propDir = System.getenv(SDNC_CONFIG_DIR); - - List consumers = new LinkedList(); - - if (propDir == null) { - - propDir = "/opt/sdnc/data/properties"; - } - - if (!propFileName.startsWith("/")) { - propPath = propDir + "/" + propFileName; - } - - File propFile = new File(propPath); - - if (!propFile.canRead()) { - LOG.error("Cannot read properties file "+propPath); - System.exit(1); - } - - try { - properties.load(new FileInputStream(propFile)); - } catch (Exception e) { - LOG.error("Caught exception loading properties from "+propPath, e); - System.exit(1); - } - - String subscriptionStr = properties.getProperty("subscriptions"); - - boolean threadsRunning = false; - - LOG.debug("Dmaap subscriptions : "+subscriptionStr); - - if (subscriptionStr != null) { - String[] subscriptions = subscriptionStr.split(";"); - - for (int i = 0; i < subscriptions.length; i++) { - String[] subscription = subscriptions[i].split(":"); - String consumerClassName = subscription[0]; - String propertyPath = subscription[1]; - - LOG.debug("Handling subscription [" + consumerClassName + "," + propertyPath + "]"); - - if (propertyPath == null) { - LOG.error("Invalid subscription (" + subscriptions[i] + ") property file missing"); - continue; - } - - if (!propertyPath.startsWith("/")) { - propertyPath = propDir + "/" + propertyPath; - } - - Class consumerClass = null; - - try { - consumerClass = Class.forName(consumerClassName); - } catch (Exception e) { - LOG.error("Could not find DMaap consumer class " + consumerClassName); - } - - if (consumerClass != null) { - - SdncDmaapConsumer consumer = null; - - try { - consumer = (SdncDmaapConsumer) consumerClass.newInstance(); - } catch (Exception e) { - LOG.error("Could not create consumer from class " + consumerClassName, e); - } - - if (consumer != null) { - LOG.debug("Initializing consumer " + consumerClassName + "(" + propertyPath + ")"); - consumer.init(properties, propertyPath); - - if (consumer.isReady()) { - Thread consumerThread = new Thread(consumer); - consumerThread.start(); - consumers.add(consumer); - threadsRunning = true; - LOG.info("Started consumer thread (" + consumerClassName + " : " + propertyPath + ")"); - } else { - LOG.debug("Consumer " + consumerClassName + " is not ready"); - } - } - - } - - } - } - - while (threadsRunning) { - - threadsRunning = false; - for (SdncDmaapConsumer consumer : consumers) { - if (consumer.isRunning()) { - threadsRunning = true; - } - } - - if (!threadsRunning) { - break; - } - - try { - Thread.sleep(10000); - } catch (InterruptedException e) { - - } - } - - LOG.info("No listener threads running - exitting"); - - } -} diff --git a/dmaap-listener/src/main/java/org/openecomp/sdnc/dmaapclient/DummyDmaapConsumer.java b/dmaap-listener/src/main/java/org/openecomp/sdnc/dmaapclient/DummyDmaapConsumer.java deleted file mode 100644 index 5edc1c908..000000000 --- a/dmaap-listener/src/main/java/org/openecomp/sdnc/dmaapclient/DummyDmaapConsumer.java +++ /dev/null @@ -1,37 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 ONAP 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.openecomp.sdnc.dmaapclient; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class DummyDmaapConsumer extends SdncDmaapConsumer { - - private static final Logger LOG = LoggerFactory - .getLogger(DummyDmaapConsumer.class); - - @Override - public void processMsg(String msg) { - LOG.info("Consumed message: \n"+msg); - } - -} diff --git a/dmaap-listener/src/main/java/org/openecomp/sdnc/dmaapclient/InvalidMessageException.java b/dmaap-listener/src/main/java/org/openecomp/sdnc/dmaapclient/InvalidMessageException.java deleted file mode 100644 index 3de5df6c2..000000000 --- a/dmaap-listener/src/main/java/org/openecomp/sdnc/dmaapclient/InvalidMessageException.java +++ /dev/null @@ -1,37 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 ONAP 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.openecomp.sdnc.dmaapclient; - -public class InvalidMessageException extends Exception { - - public InvalidMessageException() { - super(); - } - - public InvalidMessageException(String msg) { - super(msg); - } - - public InvalidMessageException(String msg, Throwable t) { - super(msg, t); - } -} diff --git a/dmaap-listener/src/main/java/org/openecomp/sdnc/dmaapclient/SdncDmaapConsumer.java b/dmaap-listener/src/main/java/org/openecomp/sdnc/dmaapclient/SdncDmaapConsumer.java deleted file mode 100644 index 5b55bda5b..000000000 --- a/dmaap-listener/src/main/java/org/openecomp/sdnc/dmaapclient/SdncDmaapConsumer.java +++ /dev/null @@ -1,146 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 ONAP 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.openecomp.sdnc.dmaapclient; - -import java.io.File; -import java.io.FileInputStream; -import java.util.Properties; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.att.nsa.mr.client.MRClientFactory; -import com.att.nsa.mr.client.MRConsumer; -import com.att.nsa.mr.client.response.MRConsumerResponse; - -public abstract class SdncDmaapConsumer implements Runnable { - - private static final Logger LOG = LoggerFactory - .getLogger(SdncDmaapConsumer.class); - - private String propertiesPath = ""; - private Properties properties = null; - MRConsumer consumer = null; - MRConsumerResponse consumerResponse = null; - boolean running = false; - boolean ready = false; - int fetchPause = 5000; // Default pause between fetchs - 5 seconds - - public boolean isReady() { - return ready; - } - - int timeout = 15000; // Default timeout - 15 seconds - - public boolean isRunning() { - return running; - } - - public SdncDmaapConsumer() { - - } - - public SdncDmaapConsumer(Properties properties, String propertiesPath) { - init(properties, propertiesPath); - } - - public String getProperty(String name) { - return(properties.getProperty(name, "")); - } - - public void init(Properties properties, String propertiesPath) { - - this.propertiesPath = propertiesPath; - - try { - - this.properties = (Properties) properties.clone(); - - this.properties.load(new FileInputStream(new File(propertiesPath))); - - String timeoutStr = properties.getProperty("timeout"); - - if ((timeoutStr != null) && (timeoutStr.length() > 0)) { - try { - timeout = Integer.parseInt(timeoutStr); - } catch (NumberFormatException e) { - LOG.error("Non-numeric value specified for timeout ("+timeoutStr+")"); - } - } - - String fetchPauseStr = properties.getProperty("fetchPause"); - if ((fetchPauseStr != null) && (fetchPauseStr.length() > 0)) { - try { - fetchPause = Integer.parseInt(fetchPauseStr); - } catch (NumberFormatException e) { - LOG.error("Non-numeric valud specified for fetchPause ("+fetchPauseStr+")"); - } - } - - this.consumer = MRClientFactory.createConsumer(propertiesPath); - ready = true; - } catch (Exception e) { - LOG.error("Error initializing DMaaP consumer from file "+propertiesPath, e); - } - } - - - @Override - public void run() { - if (ready) { - - running = true; - - while (running) { - - try { - boolean noData = true; - consumerResponse = consumer.fetchWithReturnConsumerResponse(timeout, -1); - for (String msg : consumerResponse.getActualMessages()) { - noData = false; - LOG.info("Received message from DMaaP:\n"+msg); - processMsg(msg); - } - - if (noData) { - if (fetchPause > 0) { - - LOG.info("No data received from fetch. Pausing "+fetchPause+" ms before retry"); - Thread.sleep(fetchPause); - } else { - - LOG.info("No data received from fetch. No fetch pause specified - retrying immediately"); - } - } - } catch (Exception e) { - LOG.error("Caught exception reading from DMaaP", e); - running = false; - } - - - } - } - - } - - abstract public void processMsg(String msg) throws InvalidMessageException; -} diff --git a/dmaap-listener/src/main/java/org/openecomp/sdnc/dmaapclient/SdncFlatJsonDmaapConsumer.java b/dmaap-listener/src/main/java/org/openecomp/sdnc/dmaapclient/SdncFlatJsonDmaapConsumer.java deleted file mode 100644 index 7e9c069ac..000000000 --- a/dmaap-listener/src/main/java/org/openecomp/sdnc/dmaapclient/SdncFlatJsonDmaapConsumer.java +++ /dev/null @@ -1,196 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 ONAP 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.openecomp.sdnc.dmaapclient; - -import java.io.BufferedReader; -import java.io.DataOutputStream; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.net.Authenticator; -import java.net.HttpURLConnection; -import java.net.PasswordAuthentication; -import java.net.URL; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.HttpsURLConnection; -import javax.net.ssl.SSLSession; - -import org.apache.commons.codec.binary.Base64; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ObjectNode; - - -public class SdncFlatJsonDmaapConsumer extends SdncDmaapConsumer { - - private static final Logger LOG = LoggerFactory - .getLogger(SdncFlatJsonDmaapConsumer.class); - - private static final String DMAAPLISTENERROOT = "DMAAPLISTENERROOT"; - private static final String SDNC_ENDPOINT = "SDNC.endpoint"; - - - - @Override - public void processMsg(String msg) throws InvalidMessageException { - - processMsg(msg, null); - } - - public void processMsg(String msg, String mapDirName) throws InvalidMessageException { - - if (msg == null) { - throw new InvalidMessageException("Null message"); - } - - ObjectMapper oMapper = new ObjectMapper(); - JsonNode instarRootNode = null; - ObjectNode sdncRootNode = null; - - String instarMsgName = null; - - try { - instarRootNode = oMapper.readTree(msg); - } catch (Exception e) { - throw new InvalidMessageException("Cannot parse json object", e); - } - - Iterator> instarFields = instarRootNode.fields(); - - while (instarFields.hasNext()) { - Map.Entry entry = instarFields.next(); - - instarMsgName = entry.getKey(); - instarRootNode = entry.getValue(); - break; - } - - Map fieldMap = loadMap(instarMsgName, mapDirName); - - if (fieldMap == null) { - throw new InvalidMessageException("Unable to process message - cannot load field mappings"); - } - - if (!fieldMap.containsKey(SDNC_ENDPOINT)) { - throw new InvalidMessageException("No SDNC endpoint known for message "+instarMsgName); - } - - String sdncEndpoint = fieldMap.get(SDNC_ENDPOINT); - - sdncRootNode = oMapper.createObjectNode(); - ObjectNode inputNode = oMapper.createObjectNode(); - - - for (String fromField : fieldMap.keySet()) { - - if (!SDNC_ENDPOINT.equals(fromField)) { - JsonNode curNode = instarRootNode.get(fromField); - if (curNode != null) { - String fromValue = curNode.textValue(); - - inputNode.put(fieldMap.get(fromField), fromValue); - } - } - } - sdncRootNode.put("input", inputNode); - - try { - String rpcMsgbody = oMapper.writeValueAsString(sdncRootNode); - String odlUrlBase = getProperty("sdnc.odl.url-base"); - String odlUser = getProperty("sdnc.odl.user"); - String odlPassword = getProperty("sdnc.odl.password"); - - if ((odlUrlBase != null) && (odlUrlBase.length() > 0)) { - SdncOdlConnection conn = SdncOdlConnection.newInstance(odlUrlBase + sdncEndpoint, odlUser, odlPassword); - - conn.send("POST", "application/json", rpcMsgbody); - } else { - LOG.info("POST message body would be:\n"+rpcMsgbody); - } - } catch (Exception e) { - - } - - } - - private Map loadMap(String msgType, String mapDirName) { - Map results = new HashMap(); - - - if (mapDirName == null) { - String rootdir = System.getenv(DMAAPLISTENERROOT); - - if ((rootdir == null) || (rootdir.length() == 0)) { - rootdir = "/opt/app/dmaap-listener"; - } - - mapDirName = rootdir + "/lib"; - - } - - String mapFilename = mapDirName + "/" + msgType + ".map"; - - File mapFile = new File(mapFilename); - - if (!mapFile.canRead()) { - LOG.error("Cannot read map file ("+mapFilename+")"); - return(null); - } - - try { - BufferedReader mapReader = new BufferedReader(new FileReader(mapFile)); - - String curLine = null; - - while ((curLine = mapReader.readLine()) != null) { - curLine = curLine.trim(); - - if ((curLine.length() > 0) && (!curLine.startsWith("#"))) { - - if (curLine.contains("=>")) { - String[] entry = curLine.split("=>"); - if (entry.length == 2) { - results.put(entry[0].trim(), entry[1].trim()); - } - } - } - } - mapReader.close(); - } catch (Exception e) { - LOG.error("Caught exception reading map "+mapFilename, e); - return(null); - } - - return(results); - } - - - -} diff --git a/dmaap-listener/src/main/java/org/openecomp/sdnc/dmaapclient/SdncOdlConnection.java b/dmaap-listener/src/main/java/org/openecomp/sdnc/dmaapclient/SdncOdlConnection.java deleted file mode 100644 index 6c6f308fb..000000000 --- a/dmaap-listener/src/main/java/org/openecomp/sdnc/dmaapclient/SdncOdlConnection.java +++ /dev/null @@ -1,159 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 ONAP 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.openecomp.sdnc.dmaapclient; - -import java.io.BufferedReader; -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.net.Authenticator; -import java.net.HttpURLConnection; -import java.net.PasswordAuthentication; -import java.net.ProtocolException; -import java.net.URL; - -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.HttpsURLConnection; -import javax.net.ssl.SSLSession; - -import org.apache.commons.codec.binary.Base64; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - - -public class SdncOdlConnection { - - private static final Logger LOG = LoggerFactory - .getLogger(SdncOdlConnection.class); - - private HttpURLConnection httpConn = null; - - private String url = null; - private String user = null; - private String password = null; - - private class SdncAuthenticator extends Authenticator { - - private String user; - private String passwd; - - SdncAuthenticator(String user, String passwd) { - this.user = user; - this.passwd = passwd; - } - @Override - protected PasswordAuthentication getPasswordAuthentication() { - return new PasswordAuthentication(user, passwd.toCharArray()); - } - - } - - private SdncOdlConnection() { - - } - - private SdncOdlConnection(String url, String user, String password) { - this.url = url; - this.user = user; - this.password = password; - - try { - URL sdncUrl = new URL(url); - Authenticator.setDefault(new SdncAuthenticator(user, password)); - - this.httpConn = (HttpURLConnection) sdncUrl.openConnection(); - } catch (Exception e) { - LOG.error("Unable to create http connection", e); - } - } - - public static SdncOdlConnection newInstance(String url, String user, String password) throws IOException - { - return (new SdncOdlConnection(url, user, password)); - } - - - - public String send(String method, String contentType, String msg) throws IOException { - - LOG.info("Sending REST " + method + " to " + url); - LOG.info("Message body:\n" + msg); - String authStr = user + ":" + password; - String encodedAuthStr = new String(Base64.encodeBase64(authStr.getBytes())); - - httpConn.addRequestProperty("Authentication", "Basic " + encodedAuthStr); - - httpConn.setRequestMethod(method); - httpConn.setRequestProperty("Content-Type", contentType); - httpConn.setRequestProperty("Accept", contentType); - - httpConn.setDoInput(true); - httpConn.setDoOutput(true); - httpConn.setUseCaches(false); - - if (httpConn instanceof HttpsURLConnection) { - HostnameVerifier hostnameVerifier = new HostnameVerifier() { - @Override - public boolean verify(String hostname, SSLSession session) { - return true; - } - }; - ((HttpsURLConnection) httpConn).setHostnameVerifier(hostnameVerifier); - } - - // Write message - httpConn.setRequestProperty("Content-Length", "" + msg.length()); - DataOutputStream outStr = new DataOutputStream(httpConn.getOutputStream()); - outStr.write(msg.getBytes()); - outStr.close(); - - // Read response - BufferedReader respRdr; - - LOG.info("Response: " + httpConn.getResponseCode() + " " + httpConn.getResponseMessage()); - - if (httpConn.getResponseCode() < 300) { - - respRdr = new BufferedReader(new InputStreamReader(httpConn.getInputStream())); - } else { - respRdr = new BufferedReader(new InputStreamReader(httpConn.getErrorStream())); - } - - StringBuffer respBuff = new StringBuffer(); - - String respLn; - - while ((respLn = respRdr.readLine()) != null) { - respBuff.append(respLn + "\n"); - } - respRdr.close(); - - String respString = respBuff.toString(); - - LOG.info("Response body :\n" + respString); - - return (respString); - - } - - -} diff --git a/example-settings.xml b/example-settings.xml deleted file mode 100644 index 2e7ce6445..000000000 --- a/example-settings.xml +++ /dev/null @@ -1,163 +0,0 @@ - - - - - - - - openecomp-release - - - openecomp-release - openecomp-release - https://ecomp-nexus:8443/repository/maven-releases/ - - true - never - - - false - - - - - - openecomp-release - openecomp-release - https://ecomp-nexus:8443/repository/maven-releases/ - - true - never - - - false - - - - - - - openecomp-snapshots - - - openecomp-snapshot - openecomp-snapshot - https://ecomp-nexus:8443/repository/maven-snapshots/ - - false - - - true - - - - - - openecomp-snapshot - openecomp-snapshot - https://ecomp-nexus:8443/repository/maven-snapshots/ - - false - - - true - - - - - - opendaylight-release - - - opendaylight-mirror - opendaylight-mirror - https://nexus.opendaylight.org/content/repositories/public/ - - true - never - - - false - - - - - - opendaylight-mirror - opendaylight-mirror - https://nexus.opendaylight.org/content/repositories/public/ - - true - never - - - false - - - - - - - opendaylight-snapshots - - - opendaylight-snapshot - opendaylight-snapshot - https://nexus.opendaylight.org/content/repositories/opendaylight.snapshot/ - - false - - - true - - - - - - opendaylight-snapshot - opendaylight-snapshot - https://nexus.opendaylight.org/content/repositories/opendaylight.snapshot/ - - false - - - true - - - - - - - - openecomp-release - openecomp-snapshots - opendaylight-release - opendaylight-snapshots - - - - - nexus - USERNAME - PASSWORD - - - openecomp-release - USERNAME - PASSWORD - - - openecomp-snapshot - USERNAME - PASSWORD - - - diff --git a/jenkins-settings.xml b/jenkins-settings.xml deleted file mode 100644 index 344994f85..000000000 --- a/jenkins-settings.xml +++ /dev/null @@ -1,168 +0,0 @@ - - - - - - - - openecomp-release - - - openecomp-release - openecomp-release - https://ecomp-nexus:8443/repository/maven-releases/ - - true - never - - - false - - - - - - openecomp-release - openecomp-release - https://ecomp-nexus:8443/repository/maven-releases/ - - true - never - - - false - - - - - - - openecomp-snapshots - - - openecomp-snapshot - openecomp-snapshot - https://ecomp-nexus:8443/repository/maven-snapshots/ - - false - - - true - - - - - - openecomp-snapshot - openecomp-snapshot - https://ecomp-nexus:8443/repository/maven-snapshots/ - - false - - - true - - - - - - opendaylight-release - - - opendaylight-mirror - opendaylight-mirror - https://nexus.opendaylight.org/content/repositories/public/ - - true - never - - - false - - - - - - opendaylight-mirror - opendaylight-mirror - https://nexus.opendaylight.org/content/repositories/public/ - - true - never - - - false - - - - - - - opendaylight-snapshots - - - opendaylight-snapshot - opendaylight-snapshot - https://nexus.opendaylight.org/content/repositories/opendaylight.snapshot/ - - false - - - true - - - - - - opendaylight-snapshot - opendaylight-snapshot - https://nexus.opendaylight.org/content/repositories/opendaylight.snapshot/ - - false - - - true - - - - - - - - openecomp-release - openecomp-snapshots - opendaylight-release - opendaylight-snapshots - - - - - nexus - ${ecomp.nexus.user} - ${ecomp.nexus.password} - - - openecomp-release - ${ecomp.nexus.user} - ${ecomp.nexus.password} - - - openecomp-snapshot - ${ecomp.nexus.user} - ${ecomp.nexus.password} - - - sdnc-javadoc - ${ecomp.nexus.user} - ${ecomp.nexus.password} - - - diff --git a/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncARModel.java b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncARModel.java new file mode 100644 index 000000000..3be906181 --- /dev/null +++ b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncARModel.java @@ -0,0 +1,53 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 ONAP 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.northbound.uebclient; + +import org.openecomp.sdc.tosca.parser.api.ISdcCsarHelper; +import org.openecomp.sdc.tosca.parser.impl.SdcPropertyNames; +import org.openecomp.sdc.toscaparser.api.Metadata; +import org.openecomp.sdc.toscaparser.api.NodeTemplate; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SdncARModel extends SdncBaseModel { + + private static final Logger LOG = LoggerFactory + .getLogger(SdncARModel.class); + + public SdncARModel(ISdcCsarHelper sdcCsarHelper, NodeTemplate nodeTemplate) { + + super(sdcCsarHelper, nodeTemplate); + + // extract metadata + Metadata metadata = nodeTemplate.getMetadata(); + addParameter("type", extractValue (metadata, SdcPropertyNames.PROPERTY_NAME_TYPE)); + + // extract properties + //addParameter("role", extractValue (sdcCsarHelper, nodeTemplate, SdcPropertyNames.PROPERTY_NAME_ROLE)); + //addParameter("type", extractValue (nodeTemplate, SdcPropertyNames.PROPERTY_NAME_TYPE)); - wrong location, get from metadata + addParameter("ecomp_generated_naming", extractBooleanValue (nodeTemplate, SdcPropertyNames.PROPERTY_NAME_VFCNAMING_ECOMPGENERATEDNAMING)); + addParameter("naming_policy", extractValue (nodeTemplate, SdcPropertyNames.PROPERTY_NAME_VFCNAMING_NAMINGPOLICY)); + //addParameter("depending_service", extractValue (sdcCsarHelper, nodeTemplate, SdcPropertyNames.PROPERTY_NAME_DEPENDINGSERVICE)); + //addParameter("service_dependency", extractValue (sdcCsarHelper, nodeTemplate, SdcPropertyNames.PROPERTY_NAME_SERVICEDEPENDENCY)); + } + +} diff --git a/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncArtifactMap.java b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncArtifactMap.java new file mode 100644 index 000000000..d979a3206 --- /dev/null +++ b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncArtifactMap.java @@ -0,0 +1,134 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 ONAP 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.northbound.uebclient; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SdncArtifactMap { + + private static final Logger LOG = LoggerFactory + .getLogger(SdncArtifactMap.class); + + public class SdncArtifactType { + private String tag; + private String artifactType; + private String rpc; + private int pass; + + public String getTag() { + return tag; + } + public String getArtifactType() { + return artifactType; + } + public String getRpc() { + return rpc; + } + + public int getPass() { + return pass; + } + + public String getRpcUrl(String base) { + return(base+rpc); + } + + private SdncArtifactType(String tag, String rpc, String pass) { + this.tag = tag; + this.rpc = rpc; + try { + this.pass = Integer.parseInt(pass); + } catch (Exception e) { + LOG.error("Invalid pass value for artifact map entry ("+tag+","+rpc+","+pass+")"); + } + } + } + + + + private Map mapItems = new HashMap(); + + private int NumPasses = 1; + + public int getNumPasses() { + return NumPasses; + } + + public void load(String fileName) { + + File mapFile = new File(fileName); + + if (mapFile.exists() && mapFile.canRead()) { + + BufferedReader rdr = null; + try { + + rdr = new BufferedReader(new FileReader(mapFile)); + + for (String ln ; (ln = rdr.readLine()) != null ; ) { + String[] lnFields = ln.split(","); + if (lnFields.length == 3) { + SdncArtifactType entry = new SdncArtifactType(lnFields[0], lnFields[1], lnFields[2]); + mapItems.put(entry.getTag(), entry); + if (entry.getPass() + 1 > NumPasses ) { + NumPasses = entry.getPass() + 1; + } + } + } + + + } catch (Exception e) { + LOG.error("Caught exception reading artifact map", e); + return; + } finally { + if (rdr != null) { + try { + rdr.close(); + } catch (IOException e) { + + } + } + } + } + } + + public SdncArtifactType getMapping(String tag) { + if (mapItems.containsKey(tag)) { + return(mapItems.get(tag)); + } else { + return(null); + } + } + + public static SdncArtifactMap getInstance() { + return new SdncArtifactMap(); + } + +} diff --git a/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncBaseModel.java b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncBaseModel.java new file mode 100644 index 000000000..707eee7e4 --- /dev/null +++ b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncBaseModel.java @@ -0,0 +1,297 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 ONAP 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.northbound.uebclient; + +import java.util.HashMap; +import java.util.Map; + +import org.openecomp.sdc.tosca.parser.api.ISdcCsarHelper; +import org.openecomp.sdc.tosca.parser.impl.SdcPropertyNames; +import org.openecomp.sdc.toscaparser.api.Group; +import org.openecomp.sdc.toscaparser.api.Metadata; +import org.openecomp.sdc.toscaparser.api.NodeTemplate; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SdncBaseModel { + + private static final Logger LOG = LoggerFactory + .getLogger(SdncBaseModel.class); + + protected String customizationUUID = null; + protected String invariantUUID = null; + protected String model_yaml = null; + protected String version = null; + + protected Map params = null; + protected ISdcCsarHelper sdcCsarHelper = null; + + public SdncBaseModel() { + + } + + public SdncBaseModel(ISdcCsarHelper sdcCsarHelper, Metadata metadata) { + + params = new HashMap(); + this.sdcCsarHelper = sdcCsarHelper; + + // extract service metadata + invariantUUID = extractValue(metadata, SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID); + addParameter("invariant_uuid",invariantUUID); + addParameter("version",extractValue(metadata, SdcPropertyNames.PROPERTY_NAME_VERSION)); + addParameter("name",extractValue(metadata, SdcPropertyNames.PROPERTY_NAME_NAME)); + addParameter("description",extractValue(metadata, SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)); + addParameter("type",extractValue(metadata, SdcPropertyNames.PROPERTY_NAME_TYPE)); + addParameter("category",extractValue(metadata, SdcPropertyNames.PROPERTY_NAME_CATEGORY)); + } + + public SdncBaseModel(ISdcCsarHelper sdcCsarHelper, NodeTemplate nodeTemplate) { + + params = new HashMap(); + this.sdcCsarHelper = sdcCsarHelper; + + // extract nodeTemplate metadata + Metadata metadata = nodeTemplate.getMetadata(); + customizationUUID = extractValue (metadata, SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID); + addParameter("invariant_uuid", extractValue (metadata, SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)); + addParameter("uuid", extractValue (metadata, SdcPropertyNames.PROPERTY_NAME_UUID)); + addParameter("version", extractValue (metadata, SdcPropertyNames.PROPERTY_NAME_VERSION)); + } + + public SdncBaseModel(ISdcCsarHelper sdcCsarHelper, Group group) { + + params = new HashMap(); + this.sdcCsarHelper = sdcCsarHelper; + + // extract group metadata + Metadata metadata = group.getMetadata(); + //customizationUUID = extractValue (metadata, SdcPropertyNames.PROPERTY_NAME_VFMODULECUSTOMIZATIONUUID); - returning null + customizationUUID = extractValue (metadata, "vfModuleModelCustomizationUUID"); + addParameter("invariant_uuid", extractValue (metadata, SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELINVARIANTUUID)); + addParameter("uuid", extractValue (metadata, SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELUUID)); + addParameter("version", extractValue (metadata, SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELVERSION)); + } + + protected void addParameter (String name, String value) { + if (value != null && !value.isEmpty()) { + params.put(name, "\"" + value + "\""); + } + } + + protected void addIntParameter (String name, String value) { + if (value != null && !value.isEmpty()) { + params.put(name, value); + } + } + + public static void addIntParameter (String name, String value, Map params) { + if (value != null && !value.isEmpty()) { + params.put(name, value); + } + } + + public static void addParameter (String name, String value, Map params) { + if (value != null && !value.isEmpty()) { + params.put(name, "\"" + value + "\""); + } + } + + protected String extractValue (Metadata metadata, String name) { + String value = sdcCsarHelper.getMetadataPropertyValue(metadata, name); + if (value != null) { + return value; + } else { + return ""; + } + } + + public static String extractValue (ISdcCsarHelper sdcCsarHelper, Metadata metadata, String name) { + String value = sdcCsarHelper.getMetadataPropertyValue(metadata, name); + if (value != null) { + return value; + } else { + return ""; + } + } + + protected String extractValue (NodeTemplate nodeTemplate, String name) { + String value = sdcCsarHelper.getNodeTemplatePropertyLeafValue(nodeTemplate, name); + if (value != null) { + return value; + } else { + return ""; + } + } + + public static String extractValue (ISdcCsarHelper sdcCsarHelper, NodeTemplate nodeTemplate, String name) { + String value = sdcCsarHelper.getNodeTemplatePropertyLeafValue(nodeTemplate, name); + if (value != null) { + return value; + } else { + return ""; + } + } + + protected String extractBooleanValue (NodeTemplate nodeTemplate, String name) { + String value = sdcCsarHelper.getNodeTemplatePropertyLeafValue(nodeTemplate, name); + if (value != null && !value.isEmpty()) { + return value.contains("true") ? "Y" : "N"; + } else { + return ""; + } + } + + public static String extractBooleanValue (ISdcCsarHelper sdcCsarHelper, NodeTemplate nodeTemplate, String name) { + String value = sdcCsarHelper.getNodeTemplatePropertyLeafValue(nodeTemplate, name); + if (value != null && !value.isEmpty()) { + return value.contains("true") ? "Y" : "N"; + } else { + return ""; + } + } + + protected String extractValue (Group group, String name) { + String value = sdcCsarHelper.getGroupPropertyLeafValue(group, name); + if (value != null) { + return value; + } else { + return ""; + } + } + + protected String extractBooleanValue (Group group, String name) { + String value = sdcCsarHelper.getGroupPropertyLeafValue(group, name); + if (value != null && !value.isEmpty()) { + return value.contains("true") ? "Y" : "N"; + } else { + return ""; + } + } + + protected String extractInputDefaultValue (String name) { + String value = sdcCsarHelper.getServiceInputLeafValueOfDefault(name); + if (value != null) { + return value; + } else { + return ""; + } + } + + protected String extractBooleanInputDefaultValue (String name) { + String value = sdcCsarHelper.getServiceInputLeafValueOfDefault(name); + if (value != null && !value.isEmpty()) { + return value.contains("true") ? "Y" : "N"; + } else { + return ""; + } + } + + public static String extractInputDefaultValue (ISdcCsarHelper sdcCsarHelper, String name) { + String value = sdcCsarHelper.getServiceInputLeafValueOfDefault(name); + if (value != null) { + return value; + } else { + return ""; + } + } + + public static String extractBooleanInputDefaultValue (ISdcCsarHelper sdcCsarHelper, String name) { + String value = sdcCsarHelper.getServiceInputLeafValueOfDefault(name); + if (value != null && !value.isEmpty()) { + return value.contains("true") ? "Y" : "N"; + } else { + return ""; + } + } + + public static String extractSubstitutionMappingTypeName (ISdcCsarHelper sdcCsarHelper) { + String value = sdcCsarHelper.getServiceSubstitutionMappingsTypeName(); + if (value != null) { + return value; + } else { + return ""; + } + } + + public String getCustomizationUUID() { + return ("\"" + customizationUUID + "\""); + } + public String getCustomizationUUIDNoQuotes() { + return (customizationUUID); + } + public void setCustomizationUUID(String customizationUUID) { + this.customizationUUID = customizationUUID; + } + + public String getSql(String tableName, String model_yaml) { + + StringBuilder sb = new StringBuilder(); + sb.append("INSERT into " + tableName + " (customization_uuid, model_yaml, "); + + int paramCount = 0; + for (String paramKey : params.keySet()) { + paramCount++; + sb.append(paramKey); + if (paramCount < params.size()) sb.append(", "); + } + + sb.append(") values (" + getCustomizationUUID() + ", \"" + model_yaml + "\", "); + + paramCount = 0; + for (String paramKey : params.keySet()) { + paramCount++; + String paramValue = params.get(paramKey); + sb.append(paramValue); + if (paramCount < params.size()) sb.append(", "); + } + + sb.append(");"); + return sb.toString(); + } + + public static String getSql(String tableName, String keyName, String keyValue, String model_yaml, Map params) { + + StringBuilder sb = new StringBuilder(); + sb.append("INSERT into " + tableName + " (" + keyName + ", "); + + int paramCount = 0; + for (String paramKey : params.keySet()) { + paramCount++; + sb.append(paramKey); + if (paramCount < params.size()) sb.append(", "); + } + + sb.append(") values (" + keyValue + ", "); + + paramCount = 0; + for (String paramKey : params.keySet()) { + paramCount++; + String paramValue = params.get(paramKey); + sb.append(paramValue); + if (paramCount < params.size()) sb.append(", "); + } + + sb.append(");"); + return sb.toString(); + } + +} diff --git a/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncNodeModel.java b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncNodeModel.java new file mode 100644 index 000000000..dcf668ed8 --- /dev/null +++ b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncNodeModel.java @@ -0,0 +1,145 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 ONAP 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.northbound.uebclient; + +import org.openecomp.sdc.tosca.parser.api.ISdcCsarHelper; +import org.openecomp.sdc.tosca.parser.impl.SdcPropertyNames; +import org.openecomp.sdc.toscaparser.api.NodeTemplate; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SdncNodeModel extends SdncBaseModel { + + private static final Logger LOG = LoggerFactory + .getLogger(SdncNodeModel.class); + + private String serviceUUID = null; + private String ecompGeneratedNaming = null; + private String [] bindingUuids = null; + + // Using ASDC TOSCA Parser 17.07 + public SdncNodeModel(ISdcCsarHelper sdcCsarHelper, NodeTemplate nodeTemplate) { + + super(sdcCsarHelper, nodeTemplate); + + // extract inputs + String ecompGeneratedNaming = extractBooleanInputDefaultValue(SdcPropertyNames.PROPERTY_NAME_SERVICENAMING_DEFAULT_ECOMPGENERATEDNAMING); + addParameter("ecomp_generated_naming",ecompGeneratedNaming); + addParameter("naming_policy", extractInputDefaultValue(SdcPropertyNames.PROPERTY_NAME_SERVICENAMING_DEFAULT_NAMINGPOLICY)); + + // extract properties + addParameter("network_type", extractValue (nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKTYPE)); + addParameter("network_role", extractValue (nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKROLE)); + addParameter("network_scope", extractValue (nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKSCOPE)); + addParameter("network_technology", extractValue (nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKTECHNOLOGY)); + + // extract properties - network_assignments + addParameter("is_shared_network", extractBooleanValue (nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKASSIGNMENTS_ISSHAREDNETWORK)); + addParameter("is_external_network", extractBooleanValue (nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKASSIGNMENTS_ISEXTERNALNETWORK)); + + // extract properties - network_assignments - ipv4_subnet_default_assignment + String useIpv4 = extractBooleanValue(nodeTemplate, "network_assignments#ipv4_subnet_default_assignment#use_ipv4"); + addParameter("use_ipv4", useIpv4); + addParameter("ipv4_dhcp_enabled", extractBooleanValue(nodeTemplate, "network_assignments#ipv4_subnet_default_assignment#dhcp_enabled")); + if (useIpv4.contains("Y")) { + addParameter("ipv4_ip_version", "ipv4"); + } + addParameter("ipv4_cidr_mask", extractValue(nodeTemplate, "network_assignments#ipv4_subnet_default_assignment#cidr_mask")); + addParameter("eipam_v4_address_plan", extractValue(nodeTemplate, "network_assignments#ipv4_subnet_default_assignment#ip_network_address_plan")); + + // extract properties - network_assignments - ipv6_subnet_default_assignment + String useIpv6 = extractBooleanValue(nodeTemplate, "network_assignments#ipv6_subnet_default_assignment#use_ipv6"); + addParameter("use_ipv6", useIpv6); + addParameter("ipv6_dhcp_enabled", extractBooleanValue(nodeTemplate, "network_assignments#ipv6_subnet_default_assignment#dhcp_enabled")); + if (useIpv6.contains("Y")) { + addParameter("ipv6_ip_version", "ipv6"); + } + addParameter("ipv6_cidr_mask", extractValue(nodeTemplate, "network_assignments#ipv6_subnet_default_assignment#cidr_mask")); + addParameter("eipam_v6_address_plan", extractValue(nodeTemplate, "network_assignments#ipv6_subnet_default_assignment#ip_network_address_plan")); + + // extract properties - provider_network + addParameter("is_provider_network", extractBooleanValue (nodeTemplate, SdcPropertyNames.PROPERTY_NAME_PROVIDERNETWORK_ISPROVIDERNETWORK)); + addParameter("physical_network_name", extractValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_PROVIDERNETWORK_PHYSICALNETWORKNAME)); + + // extract properties - network_flows + addParameter("is_bound_to_vpn", extractBooleanValue (nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKFLOWS_ISBOUNDTOVPN)); + + // extract properties - network_flows - vpn_bindings + String vpnBindingString = extractValue (nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKFLOWS_VPNBINDING); + bindingUuids = vpnBindingString.split(","); + +} + + public String getServiceUUID() { + return serviceUUID; + } + public void setServiceUUID(String serviceUUID) { + this.serviceUUID = serviceUUID; + } + + public String getEcompGeneratedNaming() { + return ecompGeneratedNaming; + } + public void setEcompGeneratedNaming(String ecompGeneratedNaming) { + this.ecompGeneratedNaming = ecompGeneratedNaming; + if (ecompGeneratedNaming != null && !ecompGeneratedNaming.isEmpty()) { + params.put("ecomp_generated_naming", "\"" + ecompGeneratedNaming + "\""); + } + } + + public String getSql(String model_yaml) { + + StringBuilder sb = new StringBuilder(); + sb.append("INSERT into NETWORK_MODEL (service_uuid, customization_uuid, model_yaml, "); + + int paramCount = 0; + for (String paramKey : params.keySet()) { + paramCount++; + sb.append(paramKey); + if (paramCount < params.size()) sb.append(", "); + } + + sb.append(") values (" + serviceUUID + ", " + getCustomizationUUID() + ", \"" + model_yaml + "\", "); + + paramCount = 0; + for (String paramKey : params.keySet()) { + paramCount++; + String paramValue = params.get(paramKey); + sb.append(paramValue); + if (paramCount < params.size()) sb.append(", "); + } + + sb.append(");"); + return sb.toString(); + } + + public String getVpnBindingsSql() { + + StringBuilder sb = new StringBuilder(); + for (int i=0; i < bindingUuids.length; i++) { + sb.append("INSERT into VPN_BINDINGS (network_customization_uuid, binding_uuid) values (" + getCustomizationUUID() + ", \"" + bindingUuids[i] + "\"); "); + } + + return sb.toString(); + } + +} diff --git a/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncOdlConnection.java b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncOdlConnection.java new file mode 100644 index 000000000..7bee801d2 --- /dev/null +++ b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncOdlConnection.java @@ -0,0 +1,158 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 ONAP 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.northbound.uebclient; + +import java.io.BufferedReader; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.Authenticator; +import java.net.HttpURLConnection; +import java.net.PasswordAuthentication; +import java.net.URL; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLSession; + +import org.apache.commons.codec.binary.Base64; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +public class SdncOdlConnection { + + private static final Logger LOG = LoggerFactory + .getLogger(SdncOdlConnection.class); + + private HttpURLConnection httpConn = null; + + private String url = null; + private String user = null; + private String password = null; + + private class SdncAuthenticator extends Authenticator { + + private String user; + private String passwd; + + SdncAuthenticator(String user, String passwd) { + this.user = user; + this.passwd = passwd; + } + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(user, passwd.toCharArray()); + } + + } + + private SdncOdlConnection() { + + } + + private SdncOdlConnection(String url, String user, String password) { + this.url = url; + this.user = user; + this.password = password; + + try { + URL sdncUrl = new URL(url); + Authenticator.setDefault(new SdncAuthenticator(user, password)); + + this.httpConn = (HttpURLConnection) sdncUrl.openConnection(); + } catch (Exception e) { + LOG.error("Unable to create http connection", e); + } + } + + public static SdncOdlConnection newInstance(String url, String user, String password) throws IOException + { + return (new SdncOdlConnection(url, user, password)); + } + + + + public String send(String method, String contentType, String msg) throws IOException { + + LOG.info("Sending REST " + method + " to " + url); + LOG.info("Message body:\n" + msg); + String authStr = user + ":" + password; + String encodedAuthStr = new String(Base64.encodeBase64(authStr.getBytes())); + + httpConn.addRequestProperty("Authentication", "Basic " + encodedAuthStr); + + httpConn.setRequestMethod(method); + httpConn.setRequestProperty("Content-Type", contentType); + httpConn.setRequestProperty("Accept", contentType); + + httpConn.setDoInput(true); + httpConn.setDoOutput(true); + httpConn.setUseCaches(false); + + if (httpConn instanceof HttpsURLConnection) { + HostnameVerifier hostnameVerifier = new HostnameVerifier() { + @Override + public boolean verify(String hostname, SSLSession session) { + return true; + } + }; + ((HttpsURLConnection) httpConn).setHostnameVerifier(hostnameVerifier); + } + + // Write message + httpConn.setRequestProperty("Content-Length", "" + msg.length()); + DataOutputStream outStr = new DataOutputStream(httpConn.getOutputStream()); + outStr.write(msg.getBytes()); + outStr.close(); + + // Read response + BufferedReader respRdr; + + LOG.info("Response: " + httpConn.getResponseCode() + " " + httpConn.getResponseMessage()); + + if (httpConn.getResponseCode() < 300) { + + respRdr = new BufferedReader(new InputStreamReader(httpConn.getInputStream())); + } else { + respRdr = new BufferedReader(new InputStreamReader(httpConn.getErrorStream())); + } + + StringBuffer respBuff = new StringBuffer(); + + String respLn; + + while ((respLn = respRdr.readLine()) != null) { + respBuff.append(respLn + "\n"); + } + respRdr.close(); + + String respString = respBuff.toString(); + + LOG.info("Response body :\n" + respString); + + return (respString); + + } + + +} diff --git a/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncServiceModel.java b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncServiceModel.java new file mode 100644 index 000000000..86a4d2a25 --- /dev/null +++ b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncServiceModel.java @@ -0,0 +1,98 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 ONAP 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.northbound.uebclient; + +import org.openecomp.sdc.tosca.parser.api.ISdcCsarHelper; +import org.openecomp.sdc.tosca.parser.impl.SdcPropertyNames; +import org.openecomp.sdc.toscaparser.api.Metadata; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SdncServiceModel extends SdncBaseModel { + + private static final Logger LOG = LoggerFactory + .getLogger(SdncServiceModel.class); + + private String UUID = null; + private String serviceInstanceNamePrefix = null; + private String filename = null; + + public SdncServiceModel(ISdcCsarHelper sdcCsarHelper, Metadata metadata) { + + super(sdcCsarHelper, metadata); + + UUID = extractValue(metadata, SdcPropertyNames.PROPERTY_NAME_UUID); + + // extract service topology template input data + addParameter("ecomp_naming",extractBooleanInputDefaultValue(SdcPropertyNames.PROPERTY_NAME_SERVICENAMING_DEFAULT_ECOMPGENERATEDNAMING)); + addParameter("naming_policy",extractInputDefaultValue(SdcPropertyNames.PROPERTY_NAME_SERVICENAMING_DEFAULT_NAMINGPOLICY)); + } + + public String getServiceUUID() { + return ("\"" + UUID + "\""); + } + public void setServiceUUID(String serviceUUID) { + this.UUID = serviceUUID; + } + public String getServiceInstanceNamePrefix() { + return serviceInstanceNamePrefix; + } + public void setServiceInstanceNamePrefix(String serviceInstanceNamePrefix) { + if (serviceInstanceNamePrefix != null && !serviceInstanceNamePrefix.isEmpty()) { + this.serviceInstanceNamePrefix = serviceInstanceNamePrefix; + params.put("service_instance_name_prefix", "\"" + serviceInstanceNamePrefix + "\""); + } + } + public String getFilename() { + return filename; + } + public void setFilename(String filename) { + this.filename = filename; + } + + public String getSql(String model_yaml) { + + StringBuilder sb = new StringBuilder(); + sb.append("INSERT into SERVICE_MODEL (service_uuid, model_yaml, filename, "); + + int paramCount = 0; + for (String paramKey : params.keySet()) { + paramCount++; + sb.append(paramKey); + if (paramCount < params.size()) sb.append(", "); + } + + sb.append(") values (" + getServiceUUID() + ", \"" + model_yaml + "\", \"" + filename + "\", "); + + paramCount = 0; + for (String paramKey : params.keySet()) { + paramCount++; + String paramValue = params.get(paramKey); + sb.append(paramValue); + if (paramCount < params.size()) sb.append(", "); + } + + sb.append(");"); + return sb.toString(); + } + +} diff --git a/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncUebCallback.java b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncUebCallback.java new file mode 100644 index 000000000..fd304208c --- /dev/null +++ b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncUebCallback.java @@ -0,0 +1,1125 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 ONAP 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.northbound.uebclient; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.net.Authenticator; +import java.net.HttpURLConnection; +import java.net.PasswordAuthentication; +import java.net.URL; +import java.nio.file.DirectoryStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.sql.SQLException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +import javax.sql.rowset.CachedRowSet; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.transform.Source; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.stream.StreamResult; +import javax.xml.transform.stream.StreamSource; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathFactory; + +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.lang3.tuple.Pair; +import org.onap.ccsdk.sli.core.dblib.DBResourceManager; +import org.onap.ccsdk.sli.northbound.uebclient.SdncArtifactMap.SdncArtifactType; +import org.openecomp.sdc.api.IDistributionClient; +import org.openecomp.sdc.api.consumer.IDistributionStatusMessage; +import org.openecomp.sdc.api.consumer.INotificationCallback; +import org.openecomp.sdc.api.notification.IArtifactInfo; +import org.openecomp.sdc.api.notification.INotificationData; +import org.openecomp.sdc.api.notification.IResourceInstance; +import org.openecomp.sdc.api.results.IDistributionClientDownloadResult; +import org.openecomp.sdc.api.results.IDistributionClientResult; +import org.openecomp.sdc.tosca.parser.api.ISdcCsarHelper; +import org.openecomp.sdc.tosca.parser.exceptions.SdcToscaParserException; +import org.openecomp.sdc.tosca.parser.impl.SdcPropertyNames; +import org.openecomp.sdc.tosca.parser.impl.SdcToscaParserFactory; +import org.openecomp.sdc.toscaparser.api.Group; +import org.openecomp.sdc.toscaparser.api.Metadata; +import org.openecomp.sdc.toscaparser.api.NodeTemplate; +import org.openecomp.sdc.utils.ArtifactTypeEnum; +import org.openecomp.sdc.utils.DistributionActionResultEnum; +import org.openecomp.sdc.utils.DistributionStatusEnum; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +public class SdncUebCallback implements INotificationCallback { + + private static final Logger LOG = LoggerFactory + .getLogger(SdncUebCallback.class); + + private static DBResourceManager jdbcDataSource = null; + private static final String SDNC_CONFIG_DIR = "SDNC_CONFIG_DIR"; + + + private class SdncAuthenticator extends Authenticator { + + private final String user; + private final String passwd; + + SdncAuthenticator(String user, String passwd) { + this.user = user; + this.passwd = passwd; + } + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(user, passwd.toCharArray()); + } + + } + + private class DeployableArtifact { + SdncArtifactType type; + IArtifactInfo artifactInfo; + String svcName; + String resourceName; + String artifactName; + String artifactVersion; + File file; + + public String getArtifactName() { + return artifactName; + } + + + + public String getArtifactVersion() { + return artifactVersion; + } + + + public SdncArtifactType getType() { + return type; + } + + + + public IArtifactInfo getArtifactInfo() { + return artifactInfo; + } + + + public File getFile() { + return file; + } + + + + + public DeployableArtifact(SdncArtifactType type, String svcName, String resourceName, IArtifactInfo artifactInfo, File file) { + this.type = type; + this.artifactInfo = artifactInfo; + this.svcName = svcName; + this.resourceName = resourceName; + this.artifactName = artifactInfo.getArtifactName(); + this.artifactVersion = artifactInfo.getArtifactVersion(); + this.file = file; + } + + + public DeployableArtifact(SdncArtifactType type, String svcName, String resourceName, String artifactName, String artifactVersion, File file) { + this.type = type; + this.artifactInfo = null; + this.svcName = svcName; + this.resourceName = resourceName; + this.artifactName = artifactName; + this.artifactVersion = artifactVersion; + this.file = file; + } + + + + public String getSvcName() { + return svcName; + } + + + + public String getResourceName() { + return resourceName; + } + + } + + private final IDistributionClient client; + private final SdncUebConfiguration config; + + private LinkedList deployList[]; + + private static void setJdbcDataSource() throws IOException { + + String propPath = null; + String propDir = System.getenv(SDNC_CONFIG_DIR); + if (propDir == null) { + + propDir = "/opt/sdnc/data/properties"; + } + propPath = propDir + "/dblib.properties"; + File propFile = new File(propPath); + + if (!propFile.exists()) { + + throw new FileNotFoundException( + "Missing configuration properties file : " + + propFile); + } + + Properties props = new Properties(); + props.load(new FileInputStream(propFile)); + + try { + jdbcDataSource = DBResourceManager.create(props); + } catch(Throwable exc) { + LOG.error("", exc); + } + + if(((DBResourceManager)jdbcDataSource).isActive()){ + LOG.warn( "DBLIB: JDBC DataSource has been initialized."); + } else { + LOG.warn( "DBLIB: JDBC DataSource did not initialize successfully."); + } + } + + private static void loadArtifactMap() { + + } + + public SdncUebCallback(IDistributionClient client, SdncUebConfiguration config) { + this.client = client; + this.config = config; + + } + + @Override + public void activateCallback(INotificationData data) { + + LOG.info("Received notification : ("+data.getDistributionID()+","+data.getServiceName()+","+data.getServiceVersion()+ + ","+data.getServiceDescription() + ")"); + + String incomingDirName = config.getIncomingDir(); + String archiveDirName = config.getArchiveDir(); + + File incomingDir = null; + File archiveDir = null; + + if (!incomingDir.exists()) { + incomingDir.mkdirs(); + } + + + if (!archiveDir.exists()) { + archiveDir.mkdirs(); + } + + // Process service level artifacts + List artifactList = data.getServiceArtifacts(); + + if (artifactList != null) { + + incomingDir = new File(incomingDirName + "/" + escapeFilename(data.getServiceName())); + if (!incomingDir.exists()) { + incomingDir.mkdirs(); + } + + archiveDir = new File(archiveDirName + "/" + escapeFilename(data.getServiceName())); + if (!archiveDir.exists()) { + archiveDir.mkdirs(); + } + for (IArtifactInfo curArtifact : artifactList) + { + + LOG.info("Received artifact " + curArtifact.getArtifactName()); + + handleArtifact(data, data.getServiceName(), null, null, curArtifact, incomingDir, archiveDir); + } + } + + + // Process resource level artifacts + for (IResourceInstance curResource : data.getResources()) { + + LOG.info("Received resource : "+curResource.getResourceName()); + artifactList = curResource.getArtifacts(); + + if (artifactList != null) { + + incomingDir = new File(incomingDirName + "/" + escapeFilename(data.getServiceName()) + "/" + escapeFilename(curResource.getResourceName())); + if (!incomingDir.exists()) { + incomingDir.mkdirs(); + } + + archiveDir = new File(archiveDirName + "/" + escapeFilename(data.getServiceName()) + "/" + escapeFilename(curResource.getResourceName())); + if (!archiveDir.exists()) { + archiveDir.mkdirs(); + } + for (IArtifactInfo curArtifact : artifactList) + { + + LOG.info("Received artifact " + curArtifact.getArtifactName()); + + handleArtifact(data, data.getServiceName(), curResource.getResourceName(), curResource.getResourceType(), curArtifact, incomingDir, archiveDir); + } + } + } + + deployDownloadedFiles(incomingDir, archiveDir, data); + + + } + + + public void deployDownloadedFiles(File incomingDir, File archiveDir, INotificationData data) { + + if (incomingDir == null) { + incomingDir = new File(config.getIncomingDir()); + + if (!incomingDir.exists()) { + incomingDir.mkdirs(); + } + + } + + if (archiveDir == null) { + archiveDir = new File(config.getArchiveDir()); + + if (!archiveDir.exists()) { + archiveDir.mkdirs(); + } + } + + String curFileName = ""; + try (DirectoryStream stream = Files.newDirectoryStream(incomingDir.toPath())) { + for (Path file: stream) { + curFileName = file.toString(); + handleSuccessfulDownload(null,null, null, null, file.toFile(), archiveDir); + } + } catch (Exception x) { + // IOException can never be thrown by the iteration. + // In this snippet, it can only be thrown by newDirectoryStream. + LOG.warn("Cannot process spool file "+ curFileName, x); + } + + // Deploy scheduled deployments + int numPasses = config.getMaxPasses(); + + deployList = new LinkedList[numPasses]; + + for (int i = 0 ; i < numPasses ; i++) { + deployList[i] = new LinkedList(); + } + for (int pass = 0 ; pass < config.getMaxPasses() ; pass++) { + + if (deployList[pass] != null) { + while (! deployList[pass].isEmpty()) { + DeployableArtifact artifact = deployList[pass].pop(); + + DistributionStatusEnum deployResult = DistributionStatusEnum.DEPLOY_ERROR; + + + try { + + deployResult = deploySpoolFile(artifact); + } catch (Exception e) { + LOG.error("Caught exception trying to deploy file", e); + } + + + IArtifactInfo artifactInfo = artifact.getArtifactInfo(); + + if ((artifactInfo != null) && (data != null)) { + IDistributionClientResult deploymentStatus; + deploymentStatus = client.sendDeploymentStatus(buildStatusMessage( + client, data, artifactInfo, + deployResult)); + } + + } + } + } + } + + private void handleArtifact(INotificationData data, String svcName, String resourceName, String resourceType, IArtifactInfo artifact, File incomingDir, File archiveDir) { + + // Download Artifact + IDistributionClientDownloadResult downloadResult = client + .download(artifact); + + if (downloadResult == null) { + + handleFailedDownload(data, artifact); + return; + } + + byte[] payloadBytes = downloadResult.getArtifactPayload(); + + if (payloadBytes == null) { + handleFailedDownload(data, artifact); + return; + } + + String payload = new String(payloadBytes); + + + File spoolFile = new File(incomingDir.getAbsolutePath() + "/" + artifact.getArtifactName()); + + boolean writeSucceeded = false; + + try { + FileWriter spoolFileWriter = new FileWriter(spoolFile); + spoolFileWriter.write(payload); + spoolFileWriter.close(); + writeSucceeded = true; + } catch (Exception e) { + LOG.error("Unable to save downloaded file to spool directory ("+ incomingDir.getAbsolutePath() +")", e); + } + + + if (writeSucceeded && (downloadResult.getDistributionActionResult() == DistributionActionResultEnum.SUCCESS)) { + handleSuccessfulDownload(data, svcName, resourceName, artifact, spoolFile, archiveDir); + + + } else { + handleFailedDownload(data, artifact); + } + + } + + private void handleFailedDownload(INotificationData data, + IArtifactInfo relevantArtifact) { + // Send Download Status + IDistributionClientResult sendDownloadStatus = client + .sendDownloadStatus(buildStatusMessage(client, data, + relevantArtifact, DistributionStatusEnum.DOWNLOAD_ERROR)); + } + + private void handleSuccessfulDownload(INotificationData data, String svcName, String resourceName, + IArtifactInfo artifact, File spoolFile, File archiveDir) { + + if ((data != null) && (artifact != null)) { + // Send Download Status + IDistributionClientResult sendDownloadStatus = client + .sendDownloadStatus(buildStatusMessage(client, data, artifact, DistributionStatusEnum.DOWNLOAD_OK)); + } + + // If an override file exists, read that instead of the file we just downloaded + ArtifactTypeEnum artifactEnum = ArtifactTypeEnum.YANG_XML; + + boolean toscaYamlType = false; + if (artifact != null) { + String artifactTypeString = artifact.getArtifactType(); + if (artifactTypeString.contains("TOSCA_TEMPLATE")) { + toscaYamlType = true; + } + } else { + if (spoolFile.toString().contains(".yml") || spoolFile.toString().contains(".csar")) { + toscaYamlType = true; + } + } + String overrideFileName = config.getOverrideFile(); + if ((overrideFileName != null) && (overrideFileName.length() > 0)) { + File overrideFile = new File(overrideFileName); + + if (overrideFile.exists()) { + artifactEnum = ArtifactTypeEnum.YANG_XML; + spoolFile = overrideFile; + } + + } + + if (toscaYamlType == true) { + processToscaYaml (data, svcName, resourceName, artifact, spoolFile, archiveDir); + + try { + Path source = spoolFile.toPath(); + Path targetDir = archiveDir.toPath(); + + Files.move(source, targetDir.resolve(source.getFileName()), StandardCopyOption.REPLACE_EXISTING); + } catch (IOException e) { + LOG.warn("Could not move "+spoolFile.getAbsolutePath()+" to "+archiveDir.getAbsolutePath(), e); + } + + return; + } + + // Process spool file + Document spoolDoc = null; + File transformedFile = null; + + // Apply XSLTs and get Doc object + try { + if (!spoolFile.isDirectory()) { + transformedFile = applyXslts(spoolFile); + } + } catch (Exception e) { + LOG.error("Caught exception trying to parse XML file", e); + } + + if (transformedFile != null) { + try { + + try { + + DocumentBuilderFactory dbf = DocumentBuilderFactory + .newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + + spoolDoc = db.parse(transformedFile); + } catch (Exception e) { + LOG.error( + "Caught exception trying to parse transformed XML file " + + transformedFile.getAbsolutePath(), e); + } + + } catch (Exception e) { + LOG.error("Caught exception trying to deploy file", e); + } + } + + + if (spoolDoc != null) { + // Analyze file type + SdncArtifactType artifactType = analyzeFileType(artifactEnum, + spoolFile, spoolDoc); + + if (artifactType != null) { + + scheduleDeployment(artifactType, svcName, resourceName, artifact, spoolFile.getName(), transformedFile); + + } + + // SDNGC-2660 : Move file to archive directory even if it is an unrecognized type so that + // we do not keep trying and failing to process it. + try { + Path source = spoolFile.toPath(); + Path targetDir = archiveDir.toPath(); + + Files.move(source, targetDir.resolve(source.getFileName()), StandardCopyOption.REPLACE_EXISTING); + } catch (IOException e) { + LOG.warn("Could not move "+spoolFile.getAbsolutePath()+" to "+archiveDir.getAbsolutePath(), e); + } + } + + + } + + + private void processToscaYaml(INotificationData data, String svcName, String resourceName, + IArtifactInfo artifact, File spoolFile, File archiveDir) { + + // Use ASDC Dist Client 1.1.5 with TOSCA parsing APIs to extract relevant TOSCA model data + + // TOSCA data extraction flow 1707: + // Use ASDC dist-client to get yaml string - not yet available + String model_yaml = null; + LOG.info("Process TOSCA YAML file: "+spoolFile.toString()); + + SdcToscaParserFactory factory = SdcToscaParserFactory.getInstance(); + ISdcCsarHelper sdcCsarHelper = null; + try { + sdcCsarHelper = factory.getSdcCsarHelper(spoolFile.getAbsolutePath()); + } catch (SdcToscaParserException e) { + LOG.error("Could not create SDC TOSCA Parser ", e); + factory.close(); + return; + } + + // Ingest Service Data - 1707 + Metadata serviceMetadata = sdcCsarHelper.getServiceMetadata(); + SdncServiceModel serviceModel = new SdncServiceModel(sdcCsarHelper, serviceMetadata); + serviceModel.setFilename(spoolFile.toString().substring(spoolFile.toString().lastIndexOf("/")+1)); // will be csar file name + serviceModel.setServiceInstanceNamePrefix(SdncBaseModel.extractSubstitutionMappingTypeName(sdcCsarHelper).substring(SdncBaseModel.extractSubstitutionMappingTypeName(sdcCsarHelper).lastIndexOf(".")+1)); + + try { + cleanUpExistingToscaServiceData(serviceModel.getServiceUUID()); + LOG.info("Call insertToscaData for SERVICE_MODEL serviceUUID = " + serviceModel.getServiceUUID()); + insertToscaData(serviceModel.getSql(model_yaml)); + } catch (IOException e) { + LOG.error("Could not insert Tosca YAML data into the SERVICE_MODEL table ", e); + factory.close(); + return; + } + + // Ingest Network (VL) Data - 1707 + //List vlNodeTemplatesList = sdcCsarHelper.getServiceNodeTemplatesByType("VL"); + List vlNodeTemplatesList = sdcCsarHelper.getServiceVlList(); + + for (NodeTemplate nodeTemplate : vlNodeTemplatesList) { + SdncNodeModel nodeModel = new SdncNodeModel (sdcCsarHelper, nodeTemplate); + nodeModel.setServiceUUID(serviceModel.getServiceUUID()); + nodeModel.setEcompGeneratedNaming(SdncBaseModel.extractBooleanInputDefaultValue(sdcCsarHelper, SdcPropertyNames.PROPERTY_NAME_SERVICENAMING_DEFAULT_ECOMPGENERATEDNAMING));//service_naming#default#ecomp_generated_naming + + try { + cleanUpExistingToscaData("NETWORK_MODEL", "customization_uuid", nodeModel.getCustomizationUUID()); + cleanUpExistingToscaData("VPN_BINDINGS", "network_customization_uuid", nodeModel.getCustomizationUUID()); + LOG.info("Call insertToscaData for NETWORK_MODEL customizationUUID = " + nodeModel.getCustomizationUUID()); + // using ASDC dist-client use method for get yaml string + insertToscaData(nodeModel.getSql(model_yaml)); + insertToscaData(nodeModel.getVpnBindingsSql()); + } catch (IOException e) { + LOG.error("Could not insert Tosca YAML data into the NETWORK_MODEL table ", e); + } + } + + // Ingest Allotted Resource Data - 1707 + List arNodeTemplatesList = sdcCsarHelper.getAllottedResources(); + + for (NodeTemplate nodeTemplate : arNodeTemplatesList) { + SdncARModel nodeModel = new SdncARModel (sdcCsarHelper, nodeTemplate); + + try { + cleanUpExistingToscaData("ALLOTTED_RESOURCE_MODEL", "customization_uuid", nodeModel.getCustomizationUUID()); + LOG.info("Call insertToscaData for ALLOTTED_RESOURCE_MODEL customizationUUID = " + nodeModel.getCustomizationUUID()); + // using ASDC dist-client use method for get yaml string + insertToscaData(nodeModel.getSql("ALLOTTED_RESOURCE_MODEL", model_yaml)); + } catch (IOException e) { + LOG.error("Could not insert Tosca YAML data into the NETWORK_MODEL table ", e); + } + } + + // Ingest Network (VF) Data - 1707 + //List nodeTemplatesList = sdcCsarHelper.getServiceNodeTemplatesByType("VF"); + List vfNodeTemplatesList = sdcCsarHelper.getServiceVfList(); + + for (NodeTemplate nodeTemplate : vfNodeTemplatesList) { + SdncVFModel vfNodeModel = new SdncVFModel (sdcCsarHelper, nodeTemplate); + + try { + cleanUpExistingToscaData("VF_MODEL", "customization_uuid", vfNodeModel.getCustomizationUUID()) ; + LOG.info("Call insertToscaData for VF_MODEL customizationUUID = " + vfNodeModel.getCustomizationUUID()); + insertToscaData(vfNodeModel.getSql("VF_MODEL", model_yaml)); + } catch (IOException e) { + LOG.error("Could not insert Tosca YAML data into the VF_MODEL table ", e); + } + + // For each VF, insert VF_MODULE_MODEL data + List vfModules = sdcCsarHelper.getVfModulesByVf(vfNodeModel.getCustomizationUUIDNoQuotes()); + for (Group group : vfModules){ + SdncVFModuleModel vfModuleModel = new SdncVFModuleModel(sdcCsarHelper, group); + + try { + cleanUpExistingToscaData("VF_MODULE_MODEL", "customization_uuid", vfModuleModel.getCustomizationUUID()); + LOG.info("Call insertToscaData for VF_MODULE_MODEL customizationUUID = " + vfModuleModel.getCustomizationUUID()); + insertToscaData(vfModuleModel.getSql("VF_MODULE_MODEL", model_yaml)); + } catch (IOException e) { + LOG.error("Could not insert Tosca YAML data into the VF_MODULE_MODEL table ", e); + } + + // For each VF Module, get the VFC list, insert VF_MODULE_TO_VFC_MAPPING data + // List groupMembers = sdcCsarHelper.getMembersOfGroup(group); - old version + // For each vfcNode (group member) in the groupMembers list, extract vm_type and vm_count. + // Insert vf_module.customizationUUID, vfcNode.customizationUUID and vm_type and vm_count into VF_MODULE_TO_VFC_MAPPING + List groupMembers = sdcCsarHelper.getMembersOfVfModule(nodeTemplate, group); // not yet available + for (NodeTemplate vfcNode : groupMembers){ + SdncVFCModel vfcModel = new SdncVFCModel(sdcCsarHelper, vfcNode); + + try { + cleanUpExistingToscaData("VF_MODULE_TO_VFC_MAPPING", "vf_module_customization_uuid", vfModuleModel.getCustomizationUUID()); + LOG.info("Call insertToscaData for VF_MODULE_TO_VFC_MAPPING customizationUUID = " + vfModuleModel.getCustomizationUUID()); + insertToscaData("insert into VF_MODULE_TO_VFC_MAPPING (vf_module_customization_uuid, vfc_customization_uuid, vm_type, vm_count) values (" + + vfModuleModel.getCustomizationUUID() + ", " + vfcModel.getCustomizationUUID() + ", \"" + vfcModel.getVmType() + "\", \"" + vfcModel.getVmCount() + "\")"); + } catch (IOException e) { + LOG.error("Could not insert Tosca YAML data into the VF_MODULE_TO_VFC_MAPPING table ", e); + } + + } + + } + + // For each VF, insert VFC_MODEL data + List vfcNodes = sdcCsarHelper.getVfcListByVf(vfNodeModel.getCustomizationUUIDNoQuotes()); + for (NodeTemplate vfcNode : vfcNodes){ + SdncVFCModel vfcModel = new SdncVFCModel(sdcCsarHelper, vfcNode); + + try { + cleanUpExistingToscaData("VFC_MODEL", "customization_uuid", vfcModel.getCustomizationUUID()); + LOG.info("Call insertToscaData for VFC_MODEL customizationUUID = " + vfcModel.getCustomizationUUID()); + insertToscaData(vfcModel.getSql("VFC_MODEL", model_yaml)); + } catch (IOException e) { + LOG.error("Could not insert Tosca YAML data into the VFC_MODEL table ", e); + } + + } + + // For each VF, insert VF_TO_NETWORK_ROLE_MAPPING data + List cpNodes = sdcCsarHelper.getCpListByVf(vfNodeModel.getCustomizationUUIDNoQuotes()); + for (NodeTemplate cpNode : cpNodes){ + + // Insert into VF_TO_NETWORK_ROLE_MAPPING vf_customization_uuid and network_role + String cpNetworkRole = sdcCsarHelper.getNodeTemplatePropertyLeafValue(cpNode, "network_role_tag"); + + try { + cleanUpExistingToscaData("VF_TO_NETWORK_ROLE_MAPPING", "vf_customization_uuid", vfNodeModel.getCustomizationUUID()); + LOG.info("Call insertToscaData for VF_TO_NETWORK_ROLE_MAPPING vfCustomizationUUID = " + vfNodeModel.getCustomizationUUID()); + insertToscaData("insert into VF_TO_NETWORK_ROLE_MAPPING (vf_customization_uuid, network_role) values (" + + vfNodeModel.getCustomizationUUID() + ", \"" + cpNetworkRole + "\")"); + } catch (IOException e) { + LOG.error("Could not insert Tosca YAML data into the VF_TO_NETWORK_ROLE_MAPPING table ", e); + } + + // Insert VFC_TO_NETWORK_ROLE_MAPPING data + Map mappingParams = new HashMap(); + //String cpNetworkRoleTag = "\"" + sdcCsarHelper.getNodeTemplatePropertyLeafValue(cpNode, SdcPropertyNames.PROPERTY_NAME_NETWORKROLETAG) + "\""; + // extract network_role, network_role_tag and virtual_binding from this cpNode + SdncBaseModel.addParameter("network_role", SdncBaseModel.extractValue(sdcCsarHelper, cpNode, "network_role"), mappingParams); + SdncBaseModel.addParameter("network_role_tag", SdncBaseModel.extractValue(sdcCsarHelper, cpNode, "network_role_tag"), mappingParams); + String virtualBinding = "\"" + SdncBaseModel.extractValue(sdcCsarHelper, cpNode, "requirements#virtualBinding") + "\""; + + // get list of cpNodes and vfcNodes with matching virtualBinding + List> matchList = sdcCsarHelper.getNodeTemplatePairsByReqName(sdcCsarHelper.getCpListByVf(vfNodeModel.getCustomizationUUIDNoQuotes()), sdcCsarHelper.getVfcListByVf(vfNodeModel.getCustomizationUUIDNoQuotes()), virtualBinding); + for (Pair match : matchList) { // should be 1 match? + + // extract values from the left "CP" Node + SdncBaseModel.addParameter("ipv4_use_dhcp", SdncBaseModel.extractBooleanValue(sdcCsarHelper, match.getLeft(), SdcPropertyNames.PROPERTY_NAME_NETWORKASSIGNMENTS_IPV4SUBNETDEFAULTASSIGNMENTS_DHCPENABLED), mappingParams); + //SdncBaseModel.addParameter("ipv4_ip_version", SdncBaseModel.extractValue(sdcCsarHelper, match.getLeft(), SdcPropertyNames.PROPERTY_NAME_NETWORKASSIGNMENTS_IPV4SUBNETDEFAULTASSIGNMENTS_IPVERSION), mappingParams); + SdncBaseModel.addParameter("ipv4_ip_version", "dummy_ipv4_vers", mappingParams); + SdncBaseModel.addParameter("ipv6_use_dhcp", SdncBaseModel.extractBooleanValue(sdcCsarHelper, match.getLeft(), SdcPropertyNames.PROPERTY_NAME_NETWORKASSIGNMENTS_IPV6SUBNETDEFAULTASSIGNMENTS_DHCPENABLED), mappingParams); + //SdncBaseModel.addParameter("ipv6_ip_version", SdncBaseModel.extractValue(sdcCsarHelper, match.getLeft(), SdcPropertyNames.PROPERTY_NAME_NETWORKASSIGNMENTS_IPV6SUBNETDEFAULTASSIGNMENTS_IPVERSION), mappingParams); + SdncBaseModel.addParameter("ipv6_ip_version", "dummy_ipv6_vers", mappingParams); + //String extcp_subnetpool_id = "\"" + SdncBaseModel.extractValue(sdcCsarHelper, match.getLeft(), SdcPropertyNames.PROPERTY_NAME_SUBNETPOOLID) + "\""; // need path to subnetpoolid + + // extract values from the right "VFC" Node + String vfcCustomizationUuid = "\"" + SdncBaseModel.extractValue(sdcCsarHelper, match.getRight().getMetadata(), "customization_uuid") + "\""; + SdncBaseModel.addParameter("vm_type", SdncBaseModel.extractValue(sdcCsarHelper, match.getRight(), SdcPropertyNames.PROPERTY_NAME_VMTYPE), mappingParams); + SdncBaseModel.addIntParameter("ipv4_count", SdncBaseModel.extractValue(sdcCsarHelper, match.getRight(), SdcPropertyNames.PROPERTY_NAME_NETWORKASSIGNMENTS_IPV4SUBNETDEFAULTASSIGNMENTS_MINSUBNETSCOUNT), mappingParams); + SdncBaseModel.addIntParameter("ipv6_count", SdncBaseModel.extractValue(sdcCsarHelper, match.getRight(), SdcPropertyNames.PROPERTY_NAME_NETWORKASSIGNMENTS_IPV6SUBNETDEFAULTASSIGNMENTS_MINSUBNETSCOUNT), mappingParams); + + try { + cleanUpExistingToscaData("VFC_TO_NETWORK_ROLE_MAPPING", "vfc_customization_uuid", vfcCustomizationUuid); + LOG.info("Call insertToscaData for VFC_TO_NETWORK_ROLE_MAPPING vfcCustomizationUUID = " + vfcCustomizationUuid); + insertToscaData(SdncBaseModel.getSql("VFC_TO_NETWORK_ROLE_MAPPING", "vfc_customization_uuid", vfcCustomizationUuid, "", mappingParams)); + } catch (IOException e) { + LOG.error("Could not insert Tosca YAML data into the VFC_TO_NETWORK_ROLE_MAPPING table ", e); + } + + } + + } // CP loop + + } // VF loop + + // Close ASDC TOSCA Parser factory - we are done processing this distribution + factory.close(); + + if ((artifact != null) && (data != null)) { + LOG.info("Update to SDN-C succeeded"); + IDistributionClientResult deploymentStatus; + deploymentStatus = client.sendDeploymentStatus(buildStatusMessage( + client, data, artifact, + DistributionStatusEnum.DEPLOY_OK)); + } + + } + + private void cleanUpExistingToscaData(String tableName, String keyName, String keyValue) throws IOException + { + + if (jdbcDataSource == null) { + setJdbcDataSource(); + } + try { + int rowCount = 0; + CachedRowSet data = jdbcDataSource.getData("SELECT * from " + tableName + " where " + keyName + " = " + keyValue + ";", null, ""); + while(data.next()) { + rowCount ++; + } + if (rowCount != 0) { + LOG.info("cleanUpExistingToscaData: " + keyValue); + jdbcDataSource.writeData("DELETE from " + tableName + " where " + keyName + " = " + keyValue + ";", null, null); + } + + } catch (SQLException e) { + LOG.error("Could not clean up existing " + tableName + " for " + keyValue, e); + } + + } + + + private void cleanUpExistingToscaServiceData(String serviceUUID) throws IOException + { + + if (jdbcDataSource == null) { + setJdbcDataSource(); + } + try { + int rowCount = 0; + CachedRowSet data = jdbcDataSource.getData("SELECT * from SERVICE_MODEL where service_uuid = " + serviceUUID + ";", null, ""); + while(data.next()) { + rowCount ++; + } + if (rowCount != 0) { + LOG.info("cleanUpExistingToscaData: " + serviceUUID); + jdbcDataSource.writeData("DELETE from NETWORK_MODEL where service_uuid = " + serviceUUID + ";", null, null); + jdbcDataSource.writeData("DELETE from SERVICE_MODEL where service_uuid = " + serviceUUID + ";", null, null); + } + + } catch (SQLException e) { + LOG.error("Could not clean up existing NETWORK_MODEL and SERVICE_MODEL for service_UUID " + serviceUUID, e); + } + + } + + + private void insertToscaData(String toscaDataString) throws IOException + { + LOG.debug("insertToscaData: " + toscaDataString); + + if (jdbcDataSource == null) { + setJdbcDataSource(); + } + try { + + jdbcDataSource.writeData(toscaDataString, null, null); + + } catch (SQLException e) { + LOG.error("Could not insert Tosca YAML data into the database ", e); + } + + } + + + private SdncArtifactType analyzeFileType(ArtifactTypeEnum artifactType, File spoolFile, Document spoolDoc) { + + if (artifactType != ArtifactTypeEnum.YANG_XML) { + LOG.error("Unexpected artifact type - expecting YANG_XML, got "+artifactType); + return (null); + } + + // Examine outer tag + + try { + + + Element root = spoolDoc.getDocumentElement(); + + String rootName = root.getTagName(); + + if (rootName.contains(":")) { + String[] rootNameElems = rootName.split(":"); + rootName = rootNameElems[rootNameElems.length - 1]; + } + + if (rootName != null) { + SdncArtifactType mapEntry = config.getMapping(rootName); + + + if (mapEntry == null) { + + LOG.error("Unexpected file contents - root tag is "+rootName); + } + return(mapEntry); + } else { + LOG.error("Cannot get root tag from file"); + return(null); + } + + } catch (Exception e) { + LOG.error("Could not parse YANG_XML file "+spoolFile.getName(), e); + return(null); + } + } + + private void scheduleDeployment(SdncArtifactType type, String svcName, String resourceName, IArtifactInfo artifactInfo, String spoolFileName, File spoolFile) { + + if (type.getPass() < deployList.length) { + + if (artifactInfo != null) { + LOG.debug("Scheduling "+artifactInfo.getArtifactName()+" version "+artifactInfo.getArtifactVersion()+" for deployment"); + + deployList[type.getPass()].add(new DeployableArtifact(type, svcName, resourceName, artifactInfo, spoolFile)); + } else { + SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss.SSS");//dd/MM/yyyy + Date now = new Date(); + String artifactVersion = sdfDate.format(now); + LOG.debug("Scheduling "+spoolFileName+" version "+artifactVersion+" for deployment"); + String artifactName = spoolFileName; + if (artifactInfo != null) { + artifactName = artifactInfo.getArtifactName(); + } + deployList[type.getPass()].add(new DeployableArtifact(type, svcName, resourceName, artifactName, artifactVersion, spoolFile)); + } + } else { + LOG.info("Pass for type "+type.getTag()+" is "+type.getPass()+" which is not <= "+deployList.length); + } + } + + + private DistributionStatusEnum deploySpoolFile(DeployableArtifact artifact) { + + DistributionStatusEnum deployResult = DistributionStatusEnum.DEPLOY_OK; + + StringBuffer msgBuffer = new StringBuffer(); + + + String namespace = config.getAsdcApiNamespace(); + if ((namespace == null) || (namespace.length() == 0)) { + namespace="com:att:sdnctl:asdcapi"; + } + + msgBuffer.append("\n"); + + String svcName = artifact.getSvcName(); + String resourceName = artifact.getResourceName(); + String artifactName = artifact.getArtifactName(); + + if (svcName != null) { + if (resourceName != null) { + artifactName = svcName + "/" + resourceName + "/" + artifactName; + } else { + artifactName = svcName + "/" + artifactName; + } + } + + msgBuffer.append(""+artifactName+"\n"); + msgBuffer.append(""+artifact.getArtifactVersion()+"\n"); + + + try { + BufferedReader rdr = new BufferedReader(new FileReader(artifact.getFile())); + + String curLine = rdr.readLine(); + + while (curLine != null) { + + if (!curLine.startsWith("\n"); + + + byte[] msgBytes = msgBuffer.toString().getBytes(); + + Document results = postRestXml(artifact.getType().getRpcUrl(config.getAsdcApiBaseUrl()), msgBytes); + + if (results == null) { + + deployResult = DistributionStatusEnum.DEPLOY_ERROR; + } else { + + XPathFactory xpf = XPathFactory.newInstance(); + XPath xp = xpf.newXPath(); + + String asdcApiResponseCode = "500"; + + try { + + asdcApiResponseCode = xp.evaluate("//asdc-api-response-code[position()=1]/text()", results.getDocumentElement()); + } catch (Exception e) { + LOG.error("Caught exception retrying to evaluate xpath", e); + } + + if (asdcApiResponseCode.contains("200")) { + LOG.info("Update to SDN-C succeeded"); + deployResult = DistributionStatusEnum.DEPLOY_OK; + } else { + LOG.info("Update to SDN-C failed (response code "+asdcApiResponseCode+")"); + + if (asdcApiResponseCode.contains("409")) { + deployResult = DistributionStatusEnum.ALREADY_DEPLOYED; + } else { + + deployResult = DistributionStatusEnum.DEPLOY_ERROR; + } + } + } + + + + return(deployResult); + } + + + + + + public static IDistributionStatusMessage buildStatusMessage( + final IDistributionClient client, final INotificationData data, + final IArtifactInfo relevantArtifact, + final DistributionStatusEnum status) { + IDistributionStatusMessage statusMessage = new IDistributionStatusMessage() { + + @Override + public long getTimestamp() { + long currentTimeMillis = System.currentTimeMillis(); + return currentTimeMillis; + } + + @Override + public DistributionStatusEnum getStatus() { + return status; + } + + @Override + public String getDistributionID() { + return data.getDistributionID(); + } + + @Override + public String getConsumerID() { + return client.getConfiguration().getConsumerID(); + } + + @Override + public String getArtifactURL() { + return relevantArtifact.getArtifactURL(); + } + }; + return statusMessage; + + } + + private HttpURLConnection getRestXmlConnection(String urlString, String method) throws IOException + { + URL sdncUrl = new URL(urlString); + Authenticator.setDefault(new SdncAuthenticator(config.getSdncUser(), config.getSdncPasswd())); + + HttpURLConnection conn = (HttpURLConnection) sdncUrl.openConnection(); + + String authStr = config.getSdncUser()+":"+config.getSdncPasswd(); + String encodedAuthStr = new String(Base64.encodeBase64(authStr.getBytes())); + + conn.addRequestProperty("Authentication", "Basic "+encodedAuthStr); + + conn.setRequestMethod(method); + conn.setRequestProperty("Content-Type", "application/xml"); + conn.setRequestProperty("Accept", "application/xml"); + + conn.setDoInput(true); + conn.setDoOutput(true); + conn.setUseCaches(false); + + return(conn); + + } + + private Document postRestXml(String urlString, byte[] msgBytes) { + Document response = null; + + try { + SdncOdlConnection odlConn = SdncOdlConnection.newInstance(urlString, config.getSdncUser(), config.getSdncPasswd()); + + String sdncResp = odlConn.send("POST", "application/xml", new String(msgBytes)); + + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + + + response = db.parse(new ByteArrayInputStream(sdncResp.getBytes())); + } catch (Exception e) { + LOG.error("Caught exception posting to ODL tier", e); + } + + return(response); + + } + + private File applyXslts(File srcFile) { + + Document doc = null; + + + File inFile = srcFile; + File outFile = null; + + String xsltPathList = config.getXsltPathList(); + + if ((xsltPathList == null) || (xsltPathList.length() == 0)) { + outFile = inFile; + } else { + + String[] xsltPaths = xsltPathList.split(","); + + for (String xsltPath : xsltPaths) { + try{ + + outFile = File.createTempFile("tmp", "xml"); + TransformerFactory factory = TransformerFactory.newInstance(); + Source xslt = new StreamSource(new File(xsltPath)); + Transformer transformer = factory.newTransformer(xslt); + Source text = new StreamSource(inFile); + + + transformer.transform(text, new StreamResult(outFile)); + + inFile = outFile; + + } catch (Exception e) { + LOG.error("Caught exception trying to apply XSLT template "+xsltPath, e); + + } + + } + } + + // After transformations, parse transformed XML + + + return(outFile); + } + + private String escapeFilename(String str) { + StringBuffer retval = new StringBuffer(); + + for (int i = 0 ; i < str.length() ; i++) { + char curchar = str.charAt(i); + if (Character.isJavaIdentifierPart(curchar)) { + retval.append(curchar); + } + } + + return(retval.toString()); + + } + +} diff --git a/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncUebClient.java b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncUebClient.java new file mode 100644 index 000000000..e8ffc3333 --- /dev/null +++ b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncUebClient.java @@ -0,0 +1,65 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 ONAP 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.northbound.uebclient; + +import org.openecomp.sdc.api.IDistributionClient; +import org.openecomp.sdc.api.results.IDistributionClientResult; +import org.openecomp.sdc.impl.DistributionClientFactory; +import org.openecomp.sdc.utils.DistributionActionResultEnum; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SdncUebClient { + + private static final Logger LOG = LoggerFactory + .getLogger(SdncUebConfiguration.class); + + public static void main(String[] args) { + IDistributionClient client = DistributionClientFactory + .createDistributionClient(); + + SdncUebConfiguration config = new SdncUebConfiguration(); + + SdncUebCallback cb = new SdncUebCallback(client, config); + + LOG.info("Scanning for local distribution artifacts before starting client"); + cb.deployDownloadedFiles(null, null, null); + + LOG.info("Initializing ASDC distribution client"); + + IDistributionClientResult result = client.init( + config, cb); + + LOG.info("Initialized ASDC distribution client - results = " + + result.getDistributionMessageResult()); + + if (result.getDistributionActionResult() == DistributionActionResultEnum.SUCCESS) { + LOG.info("Starting client..."); + IDistributionClientResult start = client.start(); + LOG.info("Client startup result = " + + start.getDistributionMessageResult()); + } + + + } + +} diff --git a/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncUebConfiguration.java b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncUebConfiguration.java new file mode 100644 index 000000000..bf0d5b823 --- /dev/null +++ b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncUebConfiguration.java @@ -0,0 +1,280 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 ONAP 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.northbound.uebclient; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.LinkedList; +import java.util.List; +import java.util.Properties; + +import org.openecomp.sdc.api.consumer.IConfiguration; +import org.openecomp.sdc.utils.ArtifactTypeEnum; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SdncUebConfiguration implements IConfiguration{ + + private static final String SDNC_CONFIG_DIR = "SDNC_CONFIG_DIR"; + private static final Logger LOG = LoggerFactory + .getLogger(SdncUebConfiguration.class); + + private String asdcAddress = null; + private String consumerGroup = null; + private String consumerID = null; + private String environmentName = null; + private String password = null; + private int pollingInterval = 30; + private int pollingTimeout = 15; + private List relevantArtifactTypes = null; + private String user = null; + + private String sdncUser = null; + private String sdncPasswd = null; + private String asdcApiBaseUrl = null; + private String asdcApiNamespace = null; + + private SdncArtifactMap artifactMap = SdncArtifactMap.getInstance(); + + public String getAsdcApiNamespace() { + return asdcApiNamespace; + } + + private String incomingDir = null; + + private String archiveDir = null; + + private String overrideFile = null; + + private boolean activateServerTLSAuth; + private String keyStorePassword; + private String keyStorePath; + + private String xsltPathList; + + public String getXsltPathList() { + return xsltPathList; + } + + public String getOverrideFile() { + return overrideFile; + } + + public SdncUebConfiguration() { + + try { + init(); + } catch (Exception e) { + LOG.error("Cannot initialize SdncUebConfiguration", e); + } + } + + public void init() throws IOException { + String propPath = null; + String propDir = System.getenv(SDNC_CONFIG_DIR); + if (propDir == null) { + + propDir = "/opt/sdnc/data/properties"; + } + propPath = propDir + "/ueb-listener.properties"; + File propFile = new File(propPath); + + + if (!propFile.exists()) { + + throw new FileNotFoundException( + "Missing configuration properties file : " + + propFile); + } + + Properties props = new Properties(); + props.load(new FileInputStream(propFile)); + + asdcAddress = props.getProperty("org.onap.ccsdk.sli.northbound.uebclient.asdc-address"); + consumerGroup = props.getProperty("org.onap.ccsdk.sli.northbound.uebclient.consumer-group"); + consumerID = props.getProperty("org.onap.ccsdk.sli.northbound.uebclient.consumer-id"); + environmentName = props.getProperty("org.onap.ccsdk.sli.northbound.uebclient.environment-name"); + password = props.getProperty("org.onap.ccsdk.sli.northbound.uebclient.password"); + user = props.getProperty("org.onap.ccsdk.sli.northbound.uebclient.user"); + + sdncUser = props.getProperty("org.onap.ccsdk.sli.northbound.uebclient.sdnc-user"); + sdncPasswd = props.getProperty("org.onap.ccsdk.sli.northbound.uebclient.sdnc-passwd"); + asdcApiBaseUrl = props.getProperty("org.onap.ccsdk.sli.northbound.uebclient.asdc-api-base-url"); + asdcApiNamespace = props.getProperty("org.onap.ccsdk.sli.northbound.uebclient.asdc-api-namespace"); + + incomingDir = props.getProperty("org.onap.ccsdk.sli.northbound.uebclient.spool.incoming"); + archiveDir = props.getProperty("org.onap.ccsdk.sli.northbound.uebclient.spool.archive"); + overrideFile = props.getProperty("org.onap.ccsdk.sli.northbound.uebclient.override-file"); + + String curval = props.getProperty("org.onap.ccsdk.sli.northbound.uebclient.polling-interval"); + if ((curval != null) && (curval.length() > 0)) { + try { + pollingInterval = Integer.parseInt(curval); + } catch (Exception e) { + LOG.warn("Illegal value for org.onap.ccsdk.sli.northbound.uebclient.polling-interval ("+curval+")"); + } + } + + curval = props.getProperty("org.onap.ccsdk.sli.northbound.uebclient.polling-timeout"); + if ((curval != null) && (curval.length() > 0)) { + try { + pollingTimeout = Integer.parseInt(curval); + } catch (Exception e) { + LOG.warn("Illegal value for org.onap.ccsdk.sli.northbound.uebclient.polling-timeout ("+curval+")"); + } + } + + curval = props.getProperty("org.onap.ccsdk.sli.northbound.uebclient.relevant-artifact-types"); + if ((curval != null) && (curval.length() > 0)) { + String[] artifactTypes = curval.split(","); + + relevantArtifactTypes = new LinkedList(); + + for (int i = 0 ; i < artifactTypes.length ; i++) { + try { + if (ArtifactTypeEnum.valueOf(artifactTypes[i]) != null) { + relevantArtifactTypes.add(artifactTypes[i]); + } else { + LOG.warn("Skipping unrecognized artifact type "+artifactTypes[i]); + } + } catch (Exception e) { + + LOG.warn("Caught exception validating artifact type "+artifactTypes[i], e); + } + + } + + } + + curval = props.getProperty("org.onap.ccsdk.sli.northbound.uebclient.activate-server-tls-auth", "false"); + activateServerTLSAuth = "true".equalsIgnoreCase(curval); + keyStorePath = props.getProperty("org.onap.ccsdk.sli.northbound.uebclient.keystore-path"); + keyStorePassword = props.getProperty("org.onap.ccsdk.sli.northbound.uebclient.keystore-password"); + xsltPathList = props.getProperty("org.onap.ccsdk.sli.northbound.uebclient.xslt-path-list"); + + + String artifactMapFile = props.getProperty("org.onap.ccsdk.sli.northbound.uebclient.artifact-map"); + if (artifactMapFile != null) { + artifactMap.load(artifactMapFile); + } + + } + + @Override + public String getAsdcAddress() { + return asdcAddress; + } + + @Override + public String getConsumerGroup() { + return consumerGroup; + } + + @Override + public String getConsumerID() { + return consumerID; + } + + @Override + public String getEnvironmentName() { + return environmentName; + } + + @Override + public String getPassword() { + return password; + } + + @Override + public int getPollingInterval() { + return pollingInterval; + } + + @Override + public int getPollingTimeout() { + return pollingTimeout; + } + + @Override + public List getRelevantArtifactTypes() { + return relevantArtifactTypes; + } + + @Override + public String getUser() { + return user; + } + + + public String getSdncUser() { + return sdncUser; + } + + public String getSdncPasswd() { + return sdncPasswd; + } + + public String getAsdcApiBaseUrl() { + return asdcApiBaseUrl; + } + + @Override + public boolean activateServerTLSAuth() { + return activateServerTLSAuth; + } + + @Override + public String getKeyStorePassword() { + return keyStorePassword; + } + + @Override + public String getKeyStorePath() { + return keyStorePath; + } + + public String getIncomingDir() { + return incomingDir; + } + + public String getArchiveDir() { + return archiveDir; + } + + public int getMaxPasses() { + return(artifactMap.getNumPasses()); + } + + public SdncArtifactMap.SdncArtifactType getMapping(String tag) { + return(artifactMap.getMapping(tag)); + } + + @Override + public boolean isFilterInEmptyResources() { + // TODO Auto-generated method stub + return false; + } + + +} diff --git a/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncVFCModel.java b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncVFCModel.java new file mode 100644 index 000000000..76f015f9a --- /dev/null +++ b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncVFCModel.java @@ -0,0 +1,69 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 ONAP 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.northbound.uebclient; + +import org.openecomp.sdc.tosca.parser.api.ISdcCsarHelper; +import org.openecomp.sdc.tosca.parser.impl.SdcPropertyNames; +import org.openecomp.sdc.toscaparser.api.NodeTemplate; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SdncVFCModel extends SdncBaseModel { + + private static final Logger LOG = LoggerFactory + .getLogger(SdncVFCModel.class); + + private String vmType = null; + private String vmCount = null; + + public SdncVFCModel(ISdcCsarHelper sdcCsarHelper, NodeTemplate nodeTemplate) { + + super(sdcCsarHelper, nodeTemplate); + + // extract properties + vmType = extractValue (nodeTemplate, SdcPropertyNames.PROPERTY_NAME_VMTYPE); + //vmCount = extractValue (sdcCsarHelper, nodeTemplate, SdcPropertyNames.PROPERTY_NAME_VMCOUNT); - need path to vm_count + vmCount = "1"; + addParameter("vm_type", vmType); + addParameter("vm_type_tag", extractValue (nodeTemplate, SdcPropertyNames.PROPERTY_NAME_VMTYPETAG)); + addParameter("ecomp_generated_naming", extractBooleanValue (nodeTemplate, SdcPropertyNames.PROPERTY_NAME_VFCNAMING_ECOMPGENERATEDNAMING)); + addParameter("naming_policy", extractValue (nodeTemplate, SdcPropertyNames.PROPERTY_NAME_VFCNAMING_NAMINGPOLICY)); + addParameter("nfc_naming_code", extractValue (nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFCCODE)); + } + + public String getVmType() { + return vmType; + } + + public void setVmType(String vmType) { + this.vmType = vmType; + } + + public String getVmCount() { + return vmCount; + } + + public void setVmCount(String vmCount) { + this.vmCount = vmCount; + } + +} diff --git a/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncVFModel.java b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncVFModel.java new file mode 100644 index 000000000..cd79689b4 --- /dev/null +++ b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncVFModel.java @@ -0,0 +1,56 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 ONAP 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.northbound.uebclient; + +import org.openecomp.sdc.tosca.parser.api.ISdcCsarHelper; +import org.openecomp.sdc.tosca.parser.impl.SdcPropertyNames; +import org.openecomp.sdc.toscaparser.api.Metadata; +import org.openecomp.sdc.toscaparser.api.NodeTemplate; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SdncVFModel extends SdncBaseModel { + + private static final Logger LOG = LoggerFactory + .getLogger(SdncVFModel.class); + + public SdncVFModel(ISdcCsarHelper sdcCsarHelper, NodeTemplate nodeTemplate) { + + super(sdcCsarHelper, nodeTemplate); + + // extract metadata + Metadata metadata = nodeTemplate.getMetadata(); + addParameter("name", extractValue(metadata, SdcPropertyNames.PROPERTY_NAME_NAME)); + addParameter("vendor", extractValue (metadata, SdcPropertyNames.PROPERTY_NAME_RESOURCEVENDOR)); + addParameter("vendor_version", extractValue (metadata, SdcPropertyNames.PROPERTY_NAME_RESOURCEVENDORRELEASE)); + + // extract properties + addParameter("ecomp_generated_naming", extractBooleanValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_VNFECOMPNAMING_ECOMPGENERATEDNAMING)); + addParameter("naming_policy", extractValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_VNFECOMPNAMING_NAMINGPOLICY)); + addParameter("nf_type", extractValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFTYPE)); + addParameter("nf_role", extractValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFROLE)); + addParameter("nf_code", extractValue( nodeTemplate, "nf_naming_code")); + addParameter("nf_function", extractValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFFUNCTION)); + addParameter("avail_zone_max_count", extractValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_AVAILABILITYZONEMAXCOUNT)); + } + +} diff --git a/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncVFModuleModel.java b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncVFModuleModel.java new file mode 100644 index 000000000..7ae6c3107 --- /dev/null +++ b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncVFModuleModel.java @@ -0,0 +1,45 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 ONAP 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.northbound.uebclient; + +import org.openecomp.sdc.tosca.parser.api.ISdcCsarHelper; +import org.openecomp.sdc.tosca.parser.impl.SdcPropertyNames; +import org.openecomp.sdc.toscaparser.api.Group; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SdncVFModuleModel extends SdncBaseModel { + + private static final Logger LOG = LoggerFactory + .getLogger(SdncVFModuleModel.class); + + public SdncVFModuleModel(ISdcCsarHelper sdcCsarHelper, Group group) { + + super(sdcCsarHelper, group); + + // extract properties + addParameter("vf_module_type", extractValue(group, SdcPropertyNames.PROPERTY_NAME_VFMODULETYPE)); + addIntParameter("availability_zone_count", extractValue(group, SdcPropertyNames.PROPERTY_NAME_AVAILABILITYZONECOUNT)); + addParameter("ecomp_generated_vm_assignments", extractBooleanValue(group, SdcPropertyNames.PROPERTY_NAME_ECOMPGENERATEDVMASSIGNMENTS)); + } + +} diff --git a/ueb-listener/src/main/java/org/openecomp/sdnc/uebclient/SdncARModel.java b/ueb-listener/src/main/java/org/openecomp/sdnc/uebclient/SdncARModel.java deleted file mode 100644 index 3472b443a..000000000 --- a/ueb-listener/src/main/java/org/openecomp/sdnc/uebclient/SdncARModel.java +++ /dev/null @@ -1,53 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 ONAP 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.openecomp.sdnc.uebclient; - -import org.openecomp.sdc.tosca.parser.api.ISdcCsarHelper; -import org.openecomp.sdc.tosca.parser.impl.SdcPropertyNames; -import org.openecomp.sdc.toscaparser.api.Metadata; -import org.openecomp.sdc.toscaparser.api.NodeTemplate; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class SdncARModel extends SdncBaseModel { - - private static final Logger LOG = LoggerFactory - .getLogger(SdncARModel.class); - - public SdncARModel(ISdcCsarHelper sdcCsarHelper, NodeTemplate nodeTemplate) { - - super(sdcCsarHelper, nodeTemplate); - - // extract metadata - Metadata metadata = nodeTemplate.getMetadata(); - addParameter("type", extractValue (metadata, SdcPropertyNames.PROPERTY_NAME_TYPE)); - - // extract properties - //addParameter("role", extractValue (sdcCsarHelper, nodeTemplate, SdcPropertyNames.PROPERTY_NAME_ROLE)); - //addParameter("type", extractValue (nodeTemplate, SdcPropertyNames.PROPERTY_NAME_TYPE)); - wrong location, get from metadata - addParameter("ecomp_generated_naming", extractBooleanValue (nodeTemplate, SdcPropertyNames.PROPERTY_NAME_VFCNAMING_ECOMPGENERATEDNAMING)); - addParameter("naming_policy", extractValue (nodeTemplate, SdcPropertyNames.PROPERTY_NAME_VFCNAMING_NAMINGPOLICY)); - //addParameter("depending_service", extractValue (sdcCsarHelper, nodeTemplate, SdcPropertyNames.PROPERTY_NAME_DEPENDINGSERVICE)); - //addParameter("service_dependency", extractValue (sdcCsarHelper, nodeTemplate, SdcPropertyNames.PROPERTY_NAME_SERVICEDEPENDENCY)); - } - -} diff --git a/ueb-listener/src/main/java/org/openecomp/sdnc/uebclient/SdncArtifactMap.java b/ueb-listener/src/main/java/org/openecomp/sdnc/uebclient/SdncArtifactMap.java deleted file mode 100644 index 4a9f02a8e..000000000 --- a/ueb-listener/src/main/java/org/openecomp/sdnc/uebclient/SdncArtifactMap.java +++ /dev/null @@ -1,134 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 ONAP 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.openecomp.sdnc.uebclient; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class SdncArtifactMap { - - private static final Logger LOG = LoggerFactory - .getLogger(SdncArtifactMap.class); - - public class SdncArtifactType { - private String tag; - private String artifactType; - private String rpc; - private int pass; - - public String getTag() { - return tag; - } - public String getArtifactType() { - return artifactType; - } - public String getRpc() { - return rpc; - } - - public int getPass() { - return pass; - } - - public String getRpcUrl(String base) { - return(base+rpc); - } - - private SdncArtifactType(String tag, String rpc, String pass) { - this.tag = tag; - this.rpc = rpc; - try { - this.pass = Integer.parseInt(pass); - } catch (Exception e) { - LOG.error("Invalid pass value for artifact map entry ("+tag+","+rpc+","+pass+")"); - } - } - } - - - - private Map mapItems = new HashMap(); - - private int NumPasses = 1; - - public int getNumPasses() { - return NumPasses; - } - - public void load(String fileName) { - - File mapFile = new File(fileName); - - if (mapFile.exists() && mapFile.canRead()) { - - BufferedReader rdr = null; - try { - - rdr = new BufferedReader(new FileReader(mapFile)); - - for (String ln ; (ln = rdr.readLine()) != null ; ) { - String[] lnFields = ln.split(","); - if (lnFields.length == 3) { - SdncArtifactType entry = new SdncArtifactType(lnFields[0], lnFields[1], lnFields[2]); - mapItems.put(entry.getTag(), entry); - if (entry.getPass() + 1 > NumPasses ) { - NumPasses = entry.getPass() + 1; - } - } - } - - - } catch (Exception e) { - LOG.error("Caught exception reading artifact map", e); - return; - } finally { - if (rdr != null) { - try { - rdr.close(); - } catch (IOException e) { - - } - } - } - } - } - - public SdncArtifactType getMapping(String tag) { - if (mapItems.containsKey(tag)) { - return(mapItems.get(tag)); - } else { - return(null); - } - } - - public static SdncArtifactMap getInstance() { - return new SdncArtifactMap(); - } - -} diff --git a/ueb-listener/src/main/java/org/openecomp/sdnc/uebclient/SdncBaseModel.java b/ueb-listener/src/main/java/org/openecomp/sdnc/uebclient/SdncBaseModel.java deleted file mode 100644 index 39c50aed0..000000000 --- a/ueb-listener/src/main/java/org/openecomp/sdnc/uebclient/SdncBaseModel.java +++ /dev/null @@ -1,297 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 ONAP 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.openecomp.sdnc.uebclient; - -import java.util.HashMap; -import java.util.Map; - -import org.openecomp.sdc.tosca.parser.api.ISdcCsarHelper; -import org.openecomp.sdc.tosca.parser.impl.SdcPropertyNames; -import org.openecomp.sdc.toscaparser.api.Group; -import org.openecomp.sdc.toscaparser.api.Metadata; -import org.openecomp.sdc.toscaparser.api.NodeTemplate; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class SdncBaseModel { - - private static final Logger LOG = LoggerFactory - .getLogger(SdncBaseModel.class); - - protected String customizationUUID = null; - protected String invariantUUID = null; - protected String model_yaml = null; - protected String version = null; - - protected Map params = null; - protected ISdcCsarHelper sdcCsarHelper = null; - - public SdncBaseModel() { - - } - - public SdncBaseModel(ISdcCsarHelper sdcCsarHelper, Metadata metadata) { - - params = new HashMap(); - this.sdcCsarHelper = sdcCsarHelper; - - // extract service metadata - invariantUUID = extractValue(metadata, SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID); - addParameter("invariant_uuid",invariantUUID); - addParameter("version",extractValue(metadata, SdcPropertyNames.PROPERTY_NAME_VERSION)); - addParameter("name",extractValue(metadata, SdcPropertyNames.PROPERTY_NAME_NAME)); - addParameter("description",extractValue(metadata, SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)); - addParameter("type",extractValue(metadata, SdcPropertyNames.PROPERTY_NAME_TYPE)); - addParameter("category",extractValue(metadata, SdcPropertyNames.PROPERTY_NAME_CATEGORY)); - } - - public SdncBaseModel(ISdcCsarHelper sdcCsarHelper, NodeTemplate nodeTemplate) { - - params = new HashMap(); - this.sdcCsarHelper = sdcCsarHelper; - - // extract nodeTemplate metadata - Metadata metadata = nodeTemplate.getMetadata(); - customizationUUID = extractValue (metadata, SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID); - addParameter("invariant_uuid", extractValue (metadata, SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)); - addParameter("uuid", extractValue (metadata, SdcPropertyNames.PROPERTY_NAME_UUID)); - addParameter("version", extractValue (metadata, SdcPropertyNames.PROPERTY_NAME_VERSION)); - } - - public SdncBaseModel(ISdcCsarHelper sdcCsarHelper, Group group) { - - params = new HashMap(); - this.sdcCsarHelper = sdcCsarHelper; - - // extract group metadata - Metadata metadata = group.getMetadata(); - //customizationUUID = extractValue (metadata, SdcPropertyNames.PROPERTY_NAME_VFMODULECUSTOMIZATIONUUID); - returning null - customizationUUID = extractValue (metadata, "vfModuleModelCustomizationUUID"); - addParameter("invariant_uuid", extractValue (metadata, SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELINVARIANTUUID)); - addParameter("uuid", extractValue (metadata, SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELUUID)); - addParameter("version", extractValue (metadata, SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELVERSION)); - } - - protected void addParameter (String name, String value) { - if (value != null && !value.isEmpty()) { - params.put(name, "\"" + value + "\""); - } - } - - protected void addIntParameter (String name, String value) { - if (value != null && !value.isEmpty()) { - params.put(name, value); - } - } - - public static void addIntParameter (String name, String value, Map params) { - if (value != null && !value.isEmpty()) { - params.put(name, value); - } - } - - public static void addParameter (String name, String value, Map params) { - if (value != null && !value.isEmpty()) { - params.put(name, "\"" + value + "\""); - } - } - - protected String extractValue (Metadata metadata, String name) { - String value = sdcCsarHelper.getMetadataPropertyValue(metadata, name); - if (value != null) { - return value; - } else { - return ""; - } - } - - public static String extractValue (ISdcCsarHelper sdcCsarHelper, Metadata metadata, String name) { - String value = sdcCsarHelper.getMetadataPropertyValue(metadata, name); - if (value != null) { - return value; - } else { - return ""; - } - } - - protected String extractValue (NodeTemplate nodeTemplate, String name) { - String value = sdcCsarHelper.getNodeTemplatePropertyLeafValue(nodeTemplate, name); - if (value != null) { - return value; - } else { - return ""; - } - } - - public static String extractValue (ISdcCsarHelper sdcCsarHelper, NodeTemplate nodeTemplate, String name) { - String value = sdcCsarHelper.getNodeTemplatePropertyLeafValue(nodeTemplate, name); - if (value != null) { - return value; - } else { - return ""; - } - } - - protected String extractBooleanValue (NodeTemplate nodeTemplate, String name) { - String value = sdcCsarHelper.getNodeTemplatePropertyLeafValue(nodeTemplate, name); - if (value != null && !value.isEmpty()) { - return value.contains("true") ? "Y" : "N"; - } else { - return ""; - } - } - - public static String extractBooleanValue (ISdcCsarHelper sdcCsarHelper, NodeTemplate nodeTemplate, String name) { - String value = sdcCsarHelper.getNodeTemplatePropertyLeafValue(nodeTemplate, name); - if (value != null && !value.isEmpty()) { - return value.contains("true") ? "Y" : "N"; - } else { - return ""; - } - } - - protected String extractValue (Group group, String name) { - String value = sdcCsarHelper.getGroupPropertyLeafValue(group, name); - if (value != null) { - return value; - } else { - return ""; - } - } - - protected String extractBooleanValue (Group group, String name) { - String value = sdcCsarHelper.getGroupPropertyLeafValue(group, name); - if (value != null && !value.isEmpty()) { - return value.contains("true") ? "Y" : "N"; - } else { - return ""; - } - } - - protected String extractInputDefaultValue (String name) { - String value = sdcCsarHelper.getServiceInputLeafValueOfDefault(name); - if (value != null) { - return value; - } else { - return ""; - } - } - - protected String extractBooleanInputDefaultValue (String name) { - String value = sdcCsarHelper.getServiceInputLeafValueOfDefault(name); - if (value != null && !value.isEmpty()) { - return value.contains("true") ? "Y" : "N"; - } else { - return ""; - } - } - - public static String extractInputDefaultValue (ISdcCsarHelper sdcCsarHelper, String name) { - String value = sdcCsarHelper.getServiceInputLeafValueOfDefault(name); - if (value != null) { - return value; - } else { - return ""; - } - } - - public static String extractBooleanInputDefaultValue (ISdcCsarHelper sdcCsarHelper, String name) { - String value = sdcCsarHelper.getServiceInputLeafValueOfDefault(name); - if (value != null && !value.isEmpty()) { - return value.contains("true") ? "Y" : "N"; - } else { - return ""; - } - } - - public static String extractSubstitutionMappingTypeName (ISdcCsarHelper sdcCsarHelper) { - String value = sdcCsarHelper.getServiceSubstitutionMappingsTypeName(); - if (value != null) { - return value; - } else { - return ""; - } - } - - public String getCustomizationUUID() { - return ("\"" + customizationUUID + "\""); - } - public String getCustomizationUUIDNoQuotes() { - return (customizationUUID); - } - public void setCustomizationUUID(String customizationUUID) { - this.customizationUUID = customizationUUID; - } - - public String getSql(String tableName, String model_yaml) { - - StringBuilder sb = new StringBuilder(); - sb.append("INSERT into " + tableName + " (customization_uuid, model_yaml, "); - - int paramCount = 0; - for (String paramKey : params.keySet()) { - paramCount++; - sb.append(paramKey); - if (paramCount < params.size()) sb.append(", "); - } - - sb.append(") values (" + getCustomizationUUID() + ", \"" + model_yaml + "\", "); - - paramCount = 0; - for (String paramKey : params.keySet()) { - paramCount++; - String paramValue = params.get(paramKey); - sb.append(paramValue); - if (paramCount < params.size()) sb.append(", "); - } - - sb.append(");"); - return sb.toString(); - } - - public static String getSql(String tableName, String keyName, String keyValue, String model_yaml, Map params) { - - StringBuilder sb = new StringBuilder(); - sb.append("INSERT into " + tableName + " (" + keyName + ", "); - - int paramCount = 0; - for (String paramKey : params.keySet()) { - paramCount++; - sb.append(paramKey); - if (paramCount < params.size()) sb.append(", "); - } - - sb.append(") values (" + keyValue + ", "); - - paramCount = 0; - for (String paramKey : params.keySet()) { - paramCount++; - String paramValue = params.get(paramKey); - sb.append(paramValue); - if (paramCount < params.size()) sb.append(", "); - } - - sb.append(");"); - return sb.toString(); - } - -} diff --git a/ueb-listener/src/main/java/org/openecomp/sdnc/uebclient/SdncNodeModel.java b/ueb-listener/src/main/java/org/openecomp/sdnc/uebclient/SdncNodeModel.java deleted file mode 100644 index f8e5a5b8f..000000000 --- a/ueb-listener/src/main/java/org/openecomp/sdnc/uebclient/SdncNodeModel.java +++ /dev/null @@ -1,145 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 ONAP 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.openecomp.sdnc.uebclient; - -import org.openecomp.sdc.tosca.parser.api.ISdcCsarHelper; -import org.openecomp.sdc.tosca.parser.impl.SdcPropertyNames; -import org.openecomp.sdc.toscaparser.api.NodeTemplate; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class SdncNodeModel extends SdncBaseModel { - - private static final Logger LOG = LoggerFactory - .getLogger(SdncNodeModel.class); - - private String serviceUUID = null; - private String ecompGeneratedNaming = null; - private String [] bindingUuids = null; - - // Using ASDC TOSCA Parser 17.07 - public SdncNodeModel(ISdcCsarHelper sdcCsarHelper, NodeTemplate nodeTemplate) { - - super(sdcCsarHelper, nodeTemplate); - - // extract inputs - String ecompGeneratedNaming = extractBooleanInputDefaultValue(SdcPropertyNames.PROPERTY_NAME_SERVICENAMING_DEFAULT_ECOMPGENERATEDNAMING); - addParameter("ecomp_generated_naming",ecompGeneratedNaming); - addParameter("naming_policy", extractInputDefaultValue(SdcPropertyNames.PROPERTY_NAME_SERVICENAMING_DEFAULT_NAMINGPOLICY)); - - // extract properties - addParameter("network_type", extractValue (nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKTYPE)); - addParameter("network_role", extractValue (nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKROLE)); - addParameter("network_scope", extractValue (nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKSCOPE)); - addParameter("network_technology", extractValue (nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKTECHNOLOGY)); - - // extract properties - network_assignments - addParameter("is_shared_network", extractBooleanValue (nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKASSIGNMENTS_ISSHAREDNETWORK)); - addParameter("is_external_network", extractBooleanValue (nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKASSIGNMENTS_ISEXTERNALNETWORK)); - - // extract properties - network_assignments - ipv4_subnet_default_assignment - String useIpv4 = extractBooleanValue(nodeTemplate, "network_assignments#ipv4_subnet_default_assignment#use_ipv4"); - addParameter("use_ipv4", useIpv4); - addParameter("ipv4_dhcp_enabled", extractBooleanValue(nodeTemplate, "network_assignments#ipv4_subnet_default_assignment#dhcp_enabled")); - if (useIpv4.contains("Y")) { - addParameter("ipv4_ip_version", "ipv4"); - } - addParameter("ipv4_cidr_mask", extractValue(nodeTemplate, "network_assignments#ipv4_subnet_default_assignment#cidr_mask")); - addParameter("eipam_v4_address_plan", extractValue(nodeTemplate, "network_assignments#ipv4_subnet_default_assignment#ip_network_address_plan")); - - // extract properties - network_assignments - ipv6_subnet_default_assignment - String useIpv6 = extractBooleanValue(nodeTemplate, "network_assignments#ipv6_subnet_default_assignment#use_ipv6"); - addParameter("use_ipv6", useIpv6); - addParameter("ipv6_dhcp_enabled", extractBooleanValue(nodeTemplate, "network_assignments#ipv6_subnet_default_assignment#dhcp_enabled")); - if (useIpv6.contains("Y")) { - addParameter("ipv6_ip_version", "ipv6"); - } - addParameter("ipv6_cidr_mask", extractValue(nodeTemplate, "network_assignments#ipv6_subnet_default_assignment#cidr_mask")); - addParameter("eipam_v6_address_plan", extractValue(nodeTemplate, "network_assignments#ipv6_subnet_default_assignment#ip_network_address_plan")); - - // extract properties - provider_network - addParameter("is_provider_network", extractBooleanValue (nodeTemplate, SdcPropertyNames.PROPERTY_NAME_PROVIDERNETWORK_ISPROVIDERNETWORK)); - addParameter("physical_network_name", extractValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_PROVIDERNETWORK_PHYSICALNETWORKNAME)); - - // extract properties - network_flows - addParameter("is_bound_to_vpn", extractBooleanValue (nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKFLOWS_ISBOUNDTOVPN)); - - // extract properties - network_flows - vpn_bindings - String vpnBindingString = extractValue (nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKFLOWS_VPNBINDING); - bindingUuids = vpnBindingString.split(","); - -} - - public String getServiceUUID() { - return serviceUUID; - } - public void setServiceUUID(String serviceUUID) { - this.serviceUUID = serviceUUID; - } - - public String getEcompGeneratedNaming() { - return ecompGeneratedNaming; - } - public void setEcompGeneratedNaming(String ecompGeneratedNaming) { - this.ecompGeneratedNaming = ecompGeneratedNaming; - if (ecompGeneratedNaming != null && !ecompGeneratedNaming.isEmpty()) { - params.put("ecomp_generated_naming", "\"" + ecompGeneratedNaming + "\""); - } - } - - public String getSql(String model_yaml) { - - StringBuilder sb = new StringBuilder(); - sb.append("INSERT into NETWORK_MODEL (service_uuid, customization_uuid, model_yaml, "); - - int paramCount = 0; - for (String paramKey : params.keySet()) { - paramCount++; - sb.append(paramKey); - if (paramCount < params.size()) sb.append(", "); - } - - sb.append(") values (" + serviceUUID + ", " + getCustomizationUUID() + ", \"" + model_yaml + "\", "); - - paramCount = 0; - for (String paramKey : params.keySet()) { - paramCount++; - String paramValue = params.get(paramKey); - sb.append(paramValue); - if (paramCount < params.size()) sb.append(", "); - } - - sb.append(");"); - return sb.toString(); - } - - public String getVpnBindingsSql() { - - StringBuilder sb = new StringBuilder(); - for (int i=0; i < bindingUuids.length; i++) { - sb.append("INSERT into VPN_BINDINGS (network_customization_uuid, binding_uuid) values (" + getCustomizationUUID() + ", \"" + bindingUuids[i] + "\"); "); - } - - return sb.toString(); - } - -} diff --git a/ueb-listener/src/main/java/org/openecomp/sdnc/uebclient/SdncOdlConnection.java b/ueb-listener/src/main/java/org/openecomp/sdnc/uebclient/SdncOdlConnection.java deleted file mode 100644 index 4e0cffab1..000000000 --- a/ueb-listener/src/main/java/org/openecomp/sdnc/uebclient/SdncOdlConnection.java +++ /dev/null @@ -1,158 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 ONAP 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.openecomp.sdnc.uebclient; - -import java.io.BufferedReader; -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.net.Authenticator; -import java.net.HttpURLConnection; -import java.net.PasswordAuthentication; -import java.net.URL; - -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.HttpsURLConnection; -import javax.net.ssl.SSLSession; - -import org.apache.commons.codec.binary.Base64; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - - -public class SdncOdlConnection { - - private static final Logger LOG = LoggerFactory - .getLogger(SdncOdlConnection.class); - - private HttpURLConnection httpConn = null; - - private String url = null; - private String user = null; - private String password = null; - - private class SdncAuthenticator extends Authenticator { - - private String user; - private String passwd; - - SdncAuthenticator(String user, String passwd) { - this.user = user; - this.passwd = passwd; - } - @Override - protected PasswordAuthentication getPasswordAuthentication() { - return new PasswordAuthentication(user, passwd.toCharArray()); - } - - } - - private SdncOdlConnection() { - - } - - private SdncOdlConnection(String url, String user, String password) { - this.url = url; - this.user = user; - this.password = password; - - try { - URL sdncUrl = new URL(url); - Authenticator.setDefault(new SdncAuthenticator(user, password)); - - this.httpConn = (HttpURLConnection) sdncUrl.openConnection(); - } catch (Exception e) { - LOG.error("Unable to create http connection", e); - } - } - - public static SdncOdlConnection newInstance(String url, String user, String password) throws IOException - { - return (new SdncOdlConnection(url, user, password)); - } - - - - public String send(String method, String contentType, String msg) throws IOException { - - LOG.info("Sending REST " + method + " to " + url); - LOG.info("Message body:\n" + msg); - String authStr = user + ":" + password; - String encodedAuthStr = new String(Base64.encodeBase64(authStr.getBytes())); - - httpConn.addRequestProperty("Authentication", "Basic " + encodedAuthStr); - - httpConn.setRequestMethod(method); - httpConn.setRequestProperty("Content-Type", contentType); - httpConn.setRequestProperty("Accept", contentType); - - httpConn.setDoInput(true); - httpConn.setDoOutput(true); - httpConn.setUseCaches(false); - - if (httpConn instanceof HttpsURLConnection) { - HostnameVerifier hostnameVerifier = new HostnameVerifier() { - @Override - public boolean verify(String hostname, SSLSession session) { - return true; - } - }; - ((HttpsURLConnection) httpConn).setHostnameVerifier(hostnameVerifier); - } - - // Write message - httpConn.setRequestProperty("Content-Length", "" + msg.length()); - DataOutputStream outStr = new DataOutputStream(httpConn.getOutputStream()); - outStr.write(msg.getBytes()); - outStr.close(); - - // Read response - BufferedReader respRdr; - - LOG.info("Response: " + httpConn.getResponseCode() + " " + httpConn.getResponseMessage()); - - if (httpConn.getResponseCode() < 300) { - - respRdr = new BufferedReader(new InputStreamReader(httpConn.getInputStream())); - } else { - respRdr = new BufferedReader(new InputStreamReader(httpConn.getErrorStream())); - } - - StringBuffer respBuff = new StringBuffer(); - - String respLn; - - while ((respLn = respRdr.readLine()) != null) { - respBuff.append(respLn + "\n"); - } - respRdr.close(); - - String respString = respBuff.toString(); - - LOG.info("Response body :\n" + respString); - - return (respString); - - } - - -} diff --git a/ueb-listener/src/main/java/org/openecomp/sdnc/uebclient/SdncServiceModel.java b/ueb-listener/src/main/java/org/openecomp/sdnc/uebclient/SdncServiceModel.java deleted file mode 100644 index 0f645d7a3..000000000 --- a/ueb-listener/src/main/java/org/openecomp/sdnc/uebclient/SdncServiceModel.java +++ /dev/null @@ -1,98 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 ONAP 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.openecomp.sdnc.uebclient; - -import org.openecomp.sdc.tosca.parser.api.ISdcCsarHelper; -import org.openecomp.sdc.tosca.parser.impl.SdcPropertyNames; -import org.openecomp.sdc.toscaparser.api.Metadata; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class SdncServiceModel extends SdncBaseModel { - - private static final Logger LOG = LoggerFactory - .getLogger(SdncServiceModel.class); - - private String UUID = null; - private String serviceInstanceNamePrefix = null; - private String filename = null; - - public SdncServiceModel(ISdcCsarHelper sdcCsarHelper, Metadata metadata) { - - super(sdcCsarHelper, metadata); - - UUID = extractValue(metadata, SdcPropertyNames.PROPERTY_NAME_UUID); - - // extract service topology template input data - addParameter("ecomp_naming",extractBooleanInputDefaultValue(SdcPropertyNames.PROPERTY_NAME_SERVICENAMING_DEFAULT_ECOMPGENERATEDNAMING)); - addParameter("naming_policy",extractInputDefaultValue(SdcPropertyNames.PROPERTY_NAME_SERVICENAMING_DEFAULT_NAMINGPOLICY)); - } - - public String getServiceUUID() { - return ("\"" + UUID + "\""); - } - public void setServiceUUID(String serviceUUID) { - this.UUID = serviceUUID; - } - public String getServiceInstanceNamePrefix() { - return serviceInstanceNamePrefix; - } - public void setServiceInstanceNamePrefix(String serviceInstanceNamePrefix) { - if (serviceInstanceNamePrefix != null && !serviceInstanceNamePrefix.isEmpty()) { - this.serviceInstanceNamePrefix = serviceInstanceNamePrefix; - params.put("service_instance_name_prefix", "\"" + serviceInstanceNamePrefix + "\""); - } - } - public String getFilename() { - return filename; - } - public void setFilename(String filename) { - this.filename = filename; - } - - public String getSql(String model_yaml) { - - StringBuilder sb = new StringBuilder(); - sb.append("INSERT into SERVICE_MODEL (service_uuid, model_yaml, filename, "); - - int paramCount = 0; - for (String paramKey : params.keySet()) { - paramCount++; - sb.append(paramKey); - if (paramCount < params.size()) sb.append(", "); - } - - sb.append(") values (" + getServiceUUID() + ", \"" + model_yaml + "\", \"" + filename + "\", "); - - paramCount = 0; - for (String paramKey : params.keySet()) { - paramCount++; - String paramValue = params.get(paramKey); - sb.append(paramValue); - if (paramCount < params.size()) sb.append(", "); - } - - sb.append(");"); - return sb.toString(); - } - -} diff --git a/ueb-listener/src/main/java/org/openecomp/sdnc/uebclient/SdncUebCallback.java b/ueb-listener/src/main/java/org/openecomp/sdnc/uebclient/SdncUebCallback.java deleted file mode 100644 index 496c2cef8..000000000 --- a/ueb-listener/src/main/java/org/openecomp/sdnc/uebclient/SdncUebCallback.java +++ /dev/null @@ -1,1125 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 ONAP 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.openecomp.sdnc.uebclient; - -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.net.Authenticator; -import java.net.HttpURLConnection; -import java.net.PasswordAuthentication; -import java.net.URL; -import java.nio.file.DirectoryStream; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.StandardCopyOption; -import java.sql.SQLException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Properties; - -import javax.sql.rowset.CachedRowSet; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.transform.Source; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.stream.StreamResult; -import javax.xml.transform.stream.StreamSource; -import javax.xml.xpath.XPath; -import javax.xml.xpath.XPathFactory; - -import org.apache.commons.codec.binary.Base64; -import org.apache.commons.lang3.tuple.Pair; -import org.onap.ccsdk.sli.core.dblib.DBResourceManager; -import org.openecomp.sdc.api.IDistributionClient; -import org.openecomp.sdc.api.consumer.IDistributionStatusMessage; -import org.openecomp.sdc.api.consumer.INotificationCallback; -import org.openecomp.sdc.api.notification.IArtifactInfo; -import org.openecomp.sdc.api.notification.INotificationData; -import org.openecomp.sdc.api.notification.IResourceInstance; -import org.openecomp.sdc.api.results.IDistributionClientDownloadResult; -import org.openecomp.sdc.api.results.IDistributionClientResult; -import org.openecomp.sdc.tosca.parser.api.ISdcCsarHelper; -import org.openecomp.sdc.tosca.parser.exceptions.SdcToscaParserException; -import org.openecomp.sdc.tosca.parser.impl.SdcPropertyNames; -import org.openecomp.sdc.tosca.parser.impl.SdcToscaParserFactory; -import org.openecomp.sdc.toscaparser.api.Group; -import org.openecomp.sdc.toscaparser.api.Metadata; -import org.openecomp.sdc.toscaparser.api.NodeTemplate; -import org.openecomp.sdc.utils.ArtifactTypeEnum; -import org.openecomp.sdc.utils.DistributionActionResultEnum; -import org.openecomp.sdc.utils.DistributionStatusEnum; -import org.openecomp.sdnc.uebclient.SdncArtifactMap.SdncArtifactType; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.w3c.dom.Document; -import org.w3c.dom.Element; - -public class SdncUebCallback implements INotificationCallback { - - private static final Logger LOG = LoggerFactory - .getLogger(SdncUebCallback.class); - - private static DBResourceManager jdbcDataSource = null; - private static final String SDNC_CONFIG_DIR = "SDNC_CONFIG_DIR"; - - - private class SdncAuthenticator extends Authenticator { - - private final String user; - private final String passwd; - - SdncAuthenticator(String user, String passwd) { - this.user = user; - this.passwd = passwd; - } - @Override - protected PasswordAuthentication getPasswordAuthentication() { - return new PasswordAuthentication(user, passwd.toCharArray()); - } - - } - - private class DeployableArtifact { - SdncArtifactType type; - IArtifactInfo artifactInfo; - String svcName; - String resourceName; - String artifactName; - String artifactVersion; - File file; - - public String getArtifactName() { - return artifactName; - } - - - - public String getArtifactVersion() { - return artifactVersion; - } - - - public SdncArtifactType getType() { - return type; - } - - - - public IArtifactInfo getArtifactInfo() { - return artifactInfo; - } - - - public File getFile() { - return file; - } - - - - - public DeployableArtifact(SdncArtifactType type, String svcName, String resourceName, IArtifactInfo artifactInfo, File file) { - this.type = type; - this.artifactInfo = artifactInfo; - this.svcName = svcName; - this.resourceName = resourceName; - this.artifactName = artifactInfo.getArtifactName(); - this.artifactVersion = artifactInfo.getArtifactVersion(); - this.file = file; - } - - - public DeployableArtifact(SdncArtifactType type, String svcName, String resourceName, String artifactName, String artifactVersion, File file) { - this.type = type; - this.artifactInfo = null; - this.svcName = svcName; - this.resourceName = resourceName; - this.artifactName = artifactName; - this.artifactVersion = artifactVersion; - this.file = file; - } - - - - public String getSvcName() { - return svcName; - } - - - - public String getResourceName() { - return resourceName; - } - - } - - private final IDistributionClient client; - private final SdncUebConfiguration config; - - private LinkedList deployList[]; - - private static void setJdbcDataSource() throws IOException { - - String propPath = null; - String propDir = System.getenv(SDNC_CONFIG_DIR); - if (propDir == null) { - - propDir = "/opt/sdnc/data/properties"; - } - propPath = propDir + "/dblib.properties"; - File propFile = new File(propPath); - - if (!propFile.exists()) { - - throw new FileNotFoundException( - "Missing configuration properties file : " - + propFile); - } - - Properties props = new Properties(); - props.load(new FileInputStream(propFile)); - - try { - jdbcDataSource = DBResourceManager.create(props); - } catch(Throwable exc) { - LOG.error("", exc); - } - - if(((DBResourceManager)jdbcDataSource).isActive()){ - LOG.warn( "DBLIB: JDBC DataSource has been initialized."); - } else { - LOG.warn( "DBLIB: JDBC DataSource did not initialize successfully."); - } - } - - private static void loadArtifactMap() { - - } - - public SdncUebCallback(IDistributionClient client, SdncUebConfiguration config) { - this.client = client; - this.config = config; - - } - - @Override - public void activateCallback(INotificationData data) { - - LOG.info("Received notification : ("+data.getDistributionID()+","+data.getServiceName()+","+data.getServiceVersion()+ - ","+data.getServiceDescription() + ")"); - - String incomingDirName = config.getIncomingDir(); - String archiveDirName = config.getArchiveDir(); - - File incomingDir = null; - File archiveDir = null; - - if (!incomingDir.exists()) { - incomingDir.mkdirs(); - } - - - if (!archiveDir.exists()) { - archiveDir.mkdirs(); - } - - // Process service level artifacts - List artifactList = data.getServiceArtifacts(); - - if (artifactList != null) { - - incomingDir = new File(incomingDirName + "/" + escapeFilename(data.getServiceName())); - if (!incomingDir.exists()) { - incomingDir.mkdirs(); - } - - archiveDir = new File(archiveDirName + "/" + escapeFilename(data.getServiceName())); - if (!archiveDir.exists()) { - archiveDir.mkdirs(); - } - for (IArtifactInfo curArtifact : artifactList) - { - - LOG.info("Received artifact " + curArtifact.getArtifactName()); - - handleArtifact(data, data.getServiceName(), null, null, curArtifact, incomingDir, archiveDir); - } - } - - - // Process resource level artifacts - for (IResourceInstance curResource : data.getResources()) { - - LOG.info("Received resource : "+curResource.getResourceName()); - artifactList = curResource.getArtifacts(); - - if (artifactList != null) { - - incomingDir = new File(incomingDirName + "/" + escapeFilename(data.getServiceName()) + "/" + escapeFilename(curResource.getResourceName())); - if (!incomingDir.exists()) { - incomingDir.mkdirs(); - } - - archiveDir = new File(archiveDirName + "/" + escapeFilename(data.getServiceName()) + "/" + escapeFilename(curResource.getResourceName())); - if (!archiveDir.exists()) { - archiveDir.mkdirs(); - } - for (IArtifactInfo curArtifact : artifactList) - { - - LOG.info("Received artifact " + curArtifact.getArtifactName()); - - handleArtifact(data, data.getServiceName(), curResource.getResourceName(), curResource.getResourceType(), curArtifact, incomingDir, archiveDir); - } - } - } - - deployDownloadedFiles(incomingDir, archiveDir, data); - - - } - - - public void deployDownloadedFiles(File incomingDir, File archiveDir, INotificationData data) { - - if (incomingDir == null) { - incomingDir = new File(config.getIncomingDir()); - - if (!incomingDir.exists()) { - incomingDir.mkdirs(); - } - - } - - if (archiveDir == null) { - archiveDir = new File(config.getArchiveDir()); - - if (!archiveDir.exists()) { - archiveDir.mkdirs(); - } - } - - String curFileName = ""; - try (DirectoryStream stream = Files.newDirectoryStream(incomingDir.toPath())) { - for (Path file: stream) { - curFileName = file.toString(); - handleSuccessfulDownload(null,null, null, null, file.toFile(), archiveDir); - } - } catch (Exception x) { - // IOException can never be thrown by the iteration. - // In this snippet, it can only be thrown by newDirectoryStream. - LOG.warn("Cannot process spool file "+ curFileName, x); - } - - // Deploy scheduled deployments - int numPasses = config.getMaxPasses(); - - deployList = new LinkedList[numPasses]; - - for (int i = 0 ; i < numPasses ; i++) { - deployList[i] = new LinkedList(); - } - for (int pass = 0 ; pass < config.getMaxPasses() ; pass++) { - - if (deployList[pass] != null) { - while (! deployList[pass].isEmpty()) { - DeployableArtifact artifact = deployList[pass].pop(); - - DistributionStatusEnum deployResult = DistributionStatusEnum.DEPLOY_ERROR; - - - try { - - deployResult = deploySpoolFile(artifact); - } catch (Exception e) { - LOG.error("Caught exception trying to deploy file", e); - } - - - IArtifactInfo artifactInfo = artifact.getArtifactInfo(); - - if ((artifactInfo != null) && (data != null)) { - IDistributionClientResult deploymentStatus; - deploymentStatus = client.sendDeploymentStatus(buildStatusMessage( - client, data, artifactInfo, - deployResult)); - } - - } - } - } - } - - private void handleArtifact(INotificationData data, String svcName, String resourceName, String resourceType, IArtifactInfo artifact, File incomingDir, File archiveDir) { - - // Download Artifact - IDistributionClientDownloadResult downloadResult = client - .download(artifact); - - if (downloadResult == null) { - - handleFailedDownload(data, artifact); - return; - } - - byte[] payloadBytes = downloadResult.getArtifactPayload(); - - if (payloadBytes == null) { - handleFailedDownload(data, artifact); - return; - } - - String payload = new String(payloadBytes); - - - File spoolFile = new File(incomingDir.getAbsolutePath() + "/" + artifact.getArtifactName()); - - boolean writeSucceeded = false; - - try { - FileWriter spoolFileWriter = new FileWriter(spoolFile); - spoolFileWriter.write(payload); - spoolFileWriter.close(); - writeSucceeded = true; - } catch (Exception e) { - LOG.error("Unable to save downloaded file to spool directory ("+ incomingDir.getAbsolutePath() +")", e); - } - - - if (writeSucceeded && (downloadResult.getDistributionActionResult() == DistributionActionResultEnum.SUCCESS)) { - handleSuccessfulDownload(data, svcName, resourceName, artifact, spoolFile, archiveDir); - - - } else { - handleFailedDownload(data, artifact); - } - - } - - private void handleFailedDownload(INotificationData data, - IArtifactInfo relevantArtifact) { - // Send Download Status - IDistributionClientResult sendDownloadStatus = client - .sendDownloadStatus(buildStatusMessage(client, data, - relevantArtifact, DistributionStatusEnum.DOWNLOAD_ERROR)); - } - - private void handleSuccessfulDownload(INotificationData data, String svcName, String resourceName, - IArtifactInfo artifact, File spoolFile, File archiveDir) { - - if ((data != null) && (artifact != null)) { - // Send Download Status - IDistributionClientResult sendDownloadStatus = client - .sendDownloadStatus(buildStatusMessage(client, data, artifact, DistributionStatusEnum.DOWNLOAD_OK)); - } - - // If an override file exists, read that instead of the file we just downloaded - ArtifactTypeEnum artifactEnum = ArtifactTypeEnum.YANG_XML; - - boolean toscaYamlType = false; - if (artifact != null) { - String artifactTypeString = artifact.getArtifactType(); - if (artifactTypeString.contains("TOSCA_TEMPLATE")) { - toscaYamlType = true; - } - } else { - if (spoolFile.toString().contains(".yml") || spoolFile.toString().contains(".csar")) { - toscaYamlType = true; - } - } - String overrideFileName = config.getOverrideFile(); - if ((overrideFileName != null) && (overrideFileName.length() > 0)) { - File overrideFile = new File(overrideFileName); - - if (overrideFile.exists()) { - artifactEnum = ArtifactTypeEnum.YANG_XML; - spoolFile = overrideFile; - } - - } - - if (toscaYamlType == true) { - processToscaYaml (data, svcName, resourceName, artifact, spoolFile, archiveDir); - - try { - Path source = spoolFile.toPath(); - Path targetDir = archiveDir.toPath(); - - Files.move(source, targetDir.resolve(source.getFileName()), StandardCopyOption.REPLACE_EXISTING); - } catch (IOException e) { - LOG.warn("Could not move "+spoolFile.getAbsolutePath()+" to "+archiveDir.getAbsolutePath(), e); - } - - return; - } - - // Process spool file - Document spoolDoc = null; - File transformedFile = null; - - // Apply XSLTs and get Doc object - try { - if (!spoolFile.isDirectory()) { - transformedFile = applyXslts(spoolFile); - } - } catch (Exception e) { - LOG.error("Caught exception trying to parse XML file", e); - } - - if (transformedFile != null) { - try { - - try { - - DocumentBuilderFactory dbf = DocumentBuilderFactory - .newInstance(); - DocumentBuilder db = dbf.newDocumentBuilder(); - - spoolDoc = db.parse(transformedFile); - } catch (Exception e) { - LOG.error( - "Caught exception trying to parse transformed XML file " - + transformedFile.getAbsolutePath(), e); - } - - } catch (Exception e) { - LOG.error("Caught exception trying to deploy file", e); - } - } - - - if (spoolDoc != null) { - // Analyze file type - SdncArtifactType artifactType = analyzeFileType(artifactEnum, - spoolFile, spoolDoc); - - if (artifactType != null) { - - scheduleDeployment(artifactType, svcName, resourceName, artifact, spoolFile.getName(), transformedFile); - - } - - // SDNGC-2660 : Move file to archive directory even if it is an unrecognized type so that - // we do not keep trying and failing to process it. - try { - Path source = spoolFile.toPath(); - Path targetDir = archiveDir.toPath(); - - Files.move(source, targetDir.resolve(source.getFileName()), StandardCopyOption.REPLACE_EXISTING); - } catch (IOException e) { - LOG.warn("Could not move "+spoolFile.getAbsolutePath()+" to "+archiveDir.getAbsolutePath(), e); - } - } - - - } - - - private void processToscaYaml(INotificationData data, String svcName, String resourceName, - IArtifactInfo artifact, File spoolFile, File archiveDir) { - - // Use ASDC Dist Client 1.1.5 with TOSCA parsing APIs to extract relevant TOSCA model data - - // TOSCA data extraction flow 1707: - // Use ASDC dist-client to get yaml string - not yet available - String model_yaml = null; - LOG.info("Process TOSCA YAML file: "+spoolFile.toString()); - - SdcToscaParserFactory factory = SdcToscaParserFactory.getInstance(); - ISdcCsarHelper sdcCsarHelper = null; - try { - sdcCsarHelper = factory.getSdcCsarHelper(spoolFile.getAbsolutePath()); - } catch (SdcToscaParserException e) { - LOG.error("Could not create SDC TOSCA Parser ", e); - factory.close(); - return; - } - - // Ingest Service Data - 1707 - Metadata serviceMetadata = sdcCsarHelper.getServiceMetadata(); - SdncServiceModel serviceModel = new SdncServiceModel(sdcCsarHelper, serviceMetadata); - serviceModel.setFilename(spoolFile.toString().substring(spoolFile.toString().lastIndexOf("/")+1)); // will be csar file name - serviceModel.setServiceInstanceNamePrefix(SdncBaseModel.extractSubstitutionMappingTypeName(sdcCsarHelper).substring(SdncBaseModel.extractSubstitutionMappingTypeName(sdcCsarHelper).lastIndexOf(".")+1)); - - try { - cleanUpExistingToscaServiceData(serviceModel.getServiceUUID()); - LOG.info("Call insertToscaData for SERVICE_MODEL serviceUUID = " + serviceModel.getServiceUUID()); - insertToscaData(serviceModel.getSql(model_yaml)); - } catch (IOException e) { - LOG.error("Could not insert Tosca YAML data into the SERVICE_MODEL table ", e); - factory.close(); - return; - } - - // Ingest Network (VL) Data - 1707 - //List vlNodeTemplatesList = sdcCsarHelper.getServiceNodeTemplatesByType("VL"); - List vlNodeTemplatesList = sdcCsarHelper.getServiceVlList(); - - for (NodeTemplate nodeTemplate : vlNodeTemplatesList) { - SdncNodeModel nodeModel = new SdncNodeModel (sdcCsarHelper, nodeTemplate); - nodeModel.setServiceUUID(serviceModel.getServiceUUID()); - nodeModel.setEcompGeneratedNaming(SdncBaseModel.extractBooleanInputDefaultValue(sdcCsarHelper, SdcPropertyNames.PROPERTY_NAME_SERVICENAMING_DEFAULT_ECOMPGENERATEDNAMING));//service_naming#default#ecomp_generated_naming - - try { - cleanUpExistingToscaData("NETWORK_MODEL", "customization_uuid", nodeModel.getCustomizationUUID()); - cleanUpExistingToscaData("VPN_BINDINGS", "network_customization_uuid", nodeModel.getCustomizationUUID()); - LOG.info("Call insertToscaData for NETWORK_MODEL customizationUUID = " + nodeModel.getCustomizationUUID()); - // using ASDC dist-client use method for get yaml string - insertToscaData(nodeModel.getSql(model_yaml)); - insertToscaData(nodeModel.getVpnBindingsSql()); - } catch (IOException e) { - LOG.error("Could not insert Tosca YAML data into the NETWORK_MODEL table ", e); - } - } - - // Ingest Allotted Resource Data - 1707 - List arNodeTemplatesList = sdcCsarHelper.getAllottedResources(); - - for (NodeTemplate nodeTemplate : arNodeTemplatesList) { - SdncARModel nodeModel = new SdncARModel (sdcCsarHelper, nodeTemplate); - - try { - cleanUpExistingToscaData("ALLOTTED_RESOURCE_MODEL", "customization_uuid", nodeModel.getCustomizationUUID()); - LOG.info("Call insertToscaData for ALLOTTED_RESOURCE_MODEL customizationUUID = " + nodeModel.getCustomizationUUID()); - // using ASDC dist-client use method for get yaml string - insertToscaData(nodeModel.getSql("ALLOTTED_RESOURCE_MODEL", model_yaml)); - } catch (IOException e) { - LOG.error("Could not insert Tosca YAML data into the NETWORK_MODEL table ", e); - } - } - - // Ingest Network (VF) Data - 1707 - //List nodeTemplatesList = sdcCsarHelper.getServiceNodeTemplatesByType("VF"); - List vfNodeTemplatesList = sdcCsarHelper.getServiceVfList(); - - for (NodeTemplate nodeTemplate : vfNodeTemplatesList) { - SdncVFModel vfNodeModel = new SdncVFModel (sdcCsarHelper, nodeTemplate); - - try { - cleanUpExistingToscaData("VF_MODEL", "customization_uuid", vfNodeModel.getCustomizationUUID()) ; - LOG.info("Call insertToscaData for VF_MODEL customizationUUID = " + vfNodeModel.getCustomizationUUID()); - insertToscaData(vfNodeModel.getSql("VF_MODEL", model_yaml)); - } catch (IOException e) { - LOG.error("Could not insert Tosca YAML data into the VF_MODEL table ", e); - } - - // For each VF, insert VF_MODULE_MODEL data - List vfModules = sdcCsarHelper.getVfModulesByVf(vfNodeModel.getCustomizationUUIDNoQuotes()); - for (Group group : vfModules){ - SdncVFModuleModel vfModuleModel = new SdncVFModuleModel(sdcCsarHelper, group); - - try { - cleanUpExistingToscaData("VF_MODULE_MODEL", "customization_uuid", vfModuleModel.getCustomizationUUID()); - LOG.info("Call insertToscaData for VF_MODULE_MODEL customizationUUID = " + vfModuleModel.getCustomizationUUID()); - insertToscaData(vfModuleModel.getSql("VF_MODULE_MODEL", model_yaml)); - } catch (IOException e) { - LOG.error("Could not insert Tosca YAML data into the VF_MODULE_MODEL table ", e); - } - - // For each VF Module, get the VFC list, insert VF_MODULE_TO_VFC_MAPPING data - // List groupMembers = sdcCsarHelper.getMembersOfGroup(group); - old version - // For each vfcNode (group member) in the groupMembers list, extract vm_type and vm_count. - // Insert vf_module.customizationUUID, vfcNode.customizationUUID and vm_type and vm_count into VF_MODULE_TO_VFC_MAPPING - List groupMembers = sdcCsarHelper.getMembersOfVfModule(nodeTemplate, group); // not yet available - for (NodeTemplate vfcNode : groupMembers){ - SdncVFCModel vfcModel = new SdncVFCModel(sdcCsarHelper, vfcNode); - - try { - cleanUpExistingToscaData("VF_MODULE_TO_VFC_MAPPING", "vf_module_customization_uuid", vfModuleModel.getCustomizationUUID()); - LOG.info("Call insertToscaData for VF_MODULE_TO_VFC_MAPPING customizationUUID = " + vfModuleModel.getCustomizationUUID()); - insertToscaData("insert into VF_MODULE_TO_VFC_MAPPING (vf_module_customization_uuid, vfc_customization_uuid, vm_type, vm_count) values (" + - vfModuleModel.getCustomizationUUID() + ", " + vfcModel.getCustomizationUUID() + ", \"" + vfcModel.getVmType() + "\", \"" + vfcModel.getVmCount() + "\")"); - } catch (IOException e) { - LOG.error("Could not insert Tosca YAML data into the VF_MODULE_TO_VFC_MAPPING table ", e); - } - - } - - } - - // For each VF, insert VFC_MODEL data - List vfcNodes = sdcCsarHelper.getVfcListByVf(vfNodeModel.getCustomizationUUIDNoQuotes()); - for (NodeTemplate vfcNode : vfcNodes){ - SdncVFCModel vfcModel = new SdncVFCModel(sdcCsarHelper, vfcNode); - - try { - cleanUpExistingToscaData("VFC_MODEL", "customization_uuid", vfcModel.getCustomizationUUID()); - LOG.info("Call insertToscaData for VFC_MODEL customizationUUID = " + vfcModel.getCustomizationUUID()); - insertToscaData(vfcModel.getSql("VFC_MODEL", model_yaml)); - } catch (IOException e) { - LOG.error("Could not insert Tosca YAML data into the VFC_MODEL table ", e); - } - - } - - // For each VF, insert VF_TO_NETWORK_ROLE_MAPPING data - List cpNodes = sdcCsarHelper.getCpListByVf(vfNodeModel.getCustomizationUUIDNoQuotes()); - for (NodeTemplate cpNode : cpNodes){ - - // Insert into VF_TO_NETWORK_ROLE_MAPPING vf_customization_uuid and network_role - String cpNetworkRole = sdcCsarHelper.getNodeTemplatePropertyLeafValue(cpNode, "network_role_tag"); - - try { - cleanUpExistingToscaData("VF_TO_NETWORK_ROLE_MAPPING", "vf_customization_uuid", vfNodeModel.getCustomizationUUID()); - LOG.info("Call insertToscaData for VF_TO_NETWORK_ROLE_MAPPING vfCustomizationUUID = " + vfNodeModel.getCustomizationUUID()); - insertToscaData("insert into VF_TO_NETWORK_ROLE_MAPPING (vf_customization_uuid, network_role) values (" + - vfNodeModel.getCustomizationUUID() + ", \"" + cpNetworkRole + "\")"); - } catch (IOException e) { - LOG.error("Could not insert Tosca YAML data into the VF_TO_NETWORK_ROLE_MAPPING table ", e); - } - - // Insert VFC_TO_NETWORK_ROLE_MAPPING data - Map mappingParams = new HashMap(); - //String cpNetworkRoleTag = "\"" + sdcCsarHelper.getNodeTemplatePropertyLeafValue(cpNode, SdcPropertyNames.PROPERTY_NAME_NETWORKROLETAG) + "\""; - // extract network_role, network_role_tag and virtual_binding from this cpNode - SdncBaseModel.addParameter("network_role", SdncBaseModel.extractValue(sdcCsarHelper, cpNode, "network_role"), mappingParams); - SdncBaseModel.addParameter("network_role_tag", SdncBaseModel.extractValue(sdcCsarHelper, cpNode, "network_role_tag"), mappingParams); - String virtualBinding = "\"" + SdncBaseModel.extractValue(sdcCsarHelper, cpNode, "requirements#virtualBinding") + "\""; - - // get list of cpNodes and vfcNodes with matching virtualBinding - List> matchList = sdcCsarHelper.getNodeTemplatePairsByReqName(sdcCsarHelper.getCpListByVf(vfNodeModel.getCustomizationUUIDNoQuotes()), sdcCsarHelper.getVfcListByVf(vfNodeModel.getCustomizationUUIDNoQuotes()), virtualBinding); - for (Pair match : matchList) { // should be 1 match? - - // extract values from the left "CP" Node - SdncBaseModel.addParameter("ipv4_use_dhcp", SdncBaseModel.extractBooleanValue(sdcCsarHelper, match.getLeft(), SdcPropertyNames.PROPERTY_NAME_NETWORKASSIGNMENTS_IPV4SUBNETDEFAULTASSIGNMENTS_DHCPENABLED), mappingParams); - //SdncBaseModel.addParameter("ipv4_ip_version", SdncBaseModel.extractValue(sdcCsarHelper, match.getLeft(), SdcPropertyNames.PROPERTY_NAME_NETWORKASSIGNMENTS_IPV4SUBNETDEFAULTASSIGNMENTS_IPVERSION), mappingParams); - SdncBaseModel.addParameter("ipv4_ip_version", "dummy_ipv4_vers", mappingParams); - SdncBaseModel.addParameter("ipv6_use_dhcp", SdncBaseModel.extractBooleanValue(sdcCsarHelper, match.getLeft(), SdcPropertyNames.PROPERTY_NAME_NETWORKASSIGNMENTS_IPV6SUBNETDEFAULTASSIGNMENTS_DHCPENABLED), mappingParams); - //SdncBaseModel.addParameter("ipv6_ip_version", SdncBaseModel.extractValue(sdcCsarHelper, match.getLeft(), SdcPropertyNames.PROPERTY_NAME_NETWORKASSIGNMENTS_IPV6SUBNETDEFAULTASSIGNMENTS_IPVERSION), mappingParams); - SdncBaseModel.addParameter("ipv6_ip_version", "dummy_ipv6_vers", mappingParams); - //String extcp_subnetpool_id = "\"" + SdncBaseModel.extractValue(sdcCsarHelper, match.getLeft(), SdcPropertyNames.PROPERTY_NAME_SUBNETPOOLID) + "\""; // need path to subnetpoolid - - // extract values from the right "VFC" Node - String vfcCustomizationUuid = "\"" + SdncBaseModel.extractValue(sdcCsarHelper, match.getRight().getMetadata(), "customization_uuid") + "\""; - SdncBaseModel.addParameter("vm_type", SdncBaseModel.extractValue(sdcCsarHelper, match.getRight(), SdcPropertyNames.PROPERTY_NAME_VMTYPE), mappingParams); - SdncBaseModel.addIntParameter("ipv4_count", SdncBaseModel.extractValue(sdcCsarHelper, match.getRight(), SdcPropertyNames.PROPERTY_NAME_NETWORKASSIGNMENTS_IPV4SUBNETDEFAULTASSIGNMENTS_MINSUBNETSCOUNT), mappingParams); - SdncBaseModel.addIntParameter("ipv6_count", SdncBaseModel.extractValue(sdcCsarHelper, match.getRight(), SdcPropertyNames.PROPERTY_NAME_NETWORKASSIGNMENTS_IPV6SUBNETDEFAULTASSIGNMENTS_MINSUBNETSCOUNT), mappingParams); - - try { - cleanUpExistingToscaData("VFC_TO_NETWORK_ROLE_MAPPING", "vfc_customization_uuid", vfcCustomizationUuid); - LOG.info("Call insertToscaData for VFC_TO_NETWORK_ROLE_MAPPING vfcCustomizationUUID = " + vfcCustomizationUuid); - insertToscaData(SdncBaseModel.getSql("VFC_TO_NETWORK_ROLE_MAPPING", "vfc_customization_uuid", vfcCustomizationUuid, "", mappingParams)); - } catch (IOException e) { - LOG.error("Could not insert Tosca YAML data into the VFC_TO_NETWORK_ROLE_MAPPING table ", e); - } - - } - - } // CP loop - - } // VF loop - - // Close ASDC TOSCA Parser factory - we are done processing this distribution - factory.close(); - - if ((artifact != null) && (data != null)) { - LOG.info("Update to SDN-C succeeded"); - IDistributionClientResult deploymentStatus; - deploymentStatus = client.sendDeploymentStatus(buildStatusMessage( - client, data, artifact, - DistributionStatusEnum.DEPLOY_OK)); - } - - } - - private void cleanUpExistingToscaData(String tableName, String keyName, String keyValue) throws IOException - { - - if (jdbcDataSource == null) { - setJdbcDataSource(); - } - try { - int rowCount = 0; - CachedRowSet data = jdbcDataSource.getData("SELECT * from " + tableName + " where " + keyName + " = " + keyValue + ";", null, ""); - while(data.next()) { - rowCount ++; - } - if (rowCount != 0) { - LOG.info("cleanUpExistingToscaData: " + keyValue); - jdbcDataSource.writeData("DELETE from " + tableName + " where " + keyName + " = " + keyValue + ";", null, null); - } - - } catch (SQLException e) { - LOG.error("Could not clean up existing " + tableName + " for " + keyValue, e); - } - - } - - - private void cleanUpExistingToscaServiceData(String serviceUUID) throws IOException - { - - if (jdbcDataSource == null) { - setJdbcDataSource(); - } - try { - int rowCount = 0; - CachedRowSet data = jdbcDataSource.getData("SELECT * from SERVICE_MODEL where service_uuid = " + serviceUUID + ";", null, ""); - while(data.next()) { - rowCount ++; - } - if (rowCount != 0) { - LOG.info("cleanUpExistingToscaData: " + serviceUUID); - jdbcDataSource.writeData("DELETE from NETWORK_MODEL where service_uuid = " + serviceUUID + ";", null, null); - jdbcDataSource.writeData("DELETE from SERVICE_MODEL where service_uuid = " + serviceUUID + ";", null, null); - } - - } catch (SQLException e) { - LOG.error("Could not clean up existing NETWORK_MODEL and SERVICE_MODEL for service_UUID " + serviceUUID, e); - } - - } - - - private void insertToscaData(String toscaDataString) throws IOException - { - LOG.debug("insertToscaData: " + toscaDataString); - - if (jdbcDataSource == null) { - setJdbcDataSource(); - } - try { - - jdbcDataSource.writeData(toscaDataString, null, null); - - } catch (SQLException e) { - LOG.error("Could not insert Tosca YAML data into the database ", e); - } - - } - - - private SdncArtifactType analyzeFileType(ArtifactTypeEnum artifactType, File spoolFile, Document spoolDoc) { - - if (artifactType != ArtifactTypeEnum.YANG_XML) { - LOG.error("Unexpected artifact type - expecting YANG_XML, got "+artifactType); - return (null); - } - - // Examine outer tag - - try { - - - Element root = spoolDoc.getDocumentElement(); - - String rootName = root.getTagName(); - - if (rootName.contains(":")) { - String[] rootNameElems = rootName.split(":"); - rootName = rootNameElems[rootNameElems.length - 1]; - } - - if (rootName != null) { - SdncArtifactType mapEntry = config.getMapping(rootName); - - - if (mapEntry == null) { - - LOG.error("Unexpected file contents - root tag is "+rootName); - } - return(mapEntry); - } else { - LOG.error("Cannot get root tag from file"); - return(null); - } - - } catch (Exception e) { - LOG.error("Could not parse YANG_XML file "+spoolFile.getName(), e); - return(null); - } - } - - private void scheduleDeployment(SdncArtifactType type, String svcName, String resourceName, IArtifactInfo artifactInfo, String spoolFileName, File spoolFile) { - - if (type.getPass() < deployList.length) { - - if (artifactInfo != null) { - LOG.debug("Scheduling "+artifactInfo.getArtifactName()+" version "+artifactInfo.getArtifactVersion()+" for deployment"); - - deployList[type.getPass()].add(new DeployableArtifact(type, svcName, resourceName, artifactInfo, spoolFile)); - } else { - SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss.SSS");//dd/MM/yyyy - Date now = new Date(); - String artifactVersion = sdfDate.format(now); - LOG.debug("Scheduling "+spoolFileName+" version "+artifactVersion+" for deployment"); - String artifactName = spoolFileName; - if (artifactInfo != null) { - artifactName = artifactInfo.getArtifactName(); - } - deployList[type.getPass()].add(new DeployableArtifact(type, svcName, resourceName, artifactName, artifactVersion, spoolFile)); - } - } else { - LOG.info("Pass for type "+type.getTag()+" is "+type.getPass()+" which is not <= "+deployList.length); - } - } - - - private DistributionStatusEnum deploySpoolFile(DeployableArtifact artifact) { - - DistributionStatusEnum deployResult = DistributionStatusEnum.DEPLOY_OK; - - StringBuffer msgBuffer = new StringBuffer(); - - - String namespace = config.getAsdcApiNamespace(); - if ((namespace == null) || (namespace.length() == 0)) { - namespace="com:att:sdnctl:asdcapi"; - } - - msgBuffer.append("\n"); - - String svcName = artifact.getSvcName(); - String resourceName = artifact.getResourceName(); - String artifactName = artifact.getArtifactName(); - - if (svcName != null) { - if (resourceName != null) { - artifactName = svcName + "/" + resourceName + "/" + artifactName; - } else { - artifactName = svcName + "/" + artifactName; - } - } - - msgBuffer.append(""+artifactName+"\n"); - msgBuffer.append(""+artifact.getArtifactVersion()+"\n"); - - - try { - BufferedReader rdr = new BufferedReader(new FileReader(artifact.getFile())); - - String curLine = rdr.readLine(); - - while (curLine != null) { - - if (!curLine.startsWith("\n"); - - - byte[] msgBytes = msgBuffer.toString().getBytes(); - - Document results = postRestXml(artifact.getType().getRpcUrl(config.getAsdcApiBaseUrl()), msgBytes); - - if (results == null) { - - deployResult = DistributionStatusEnum.DEPLOY_ERROR; - } else { - - XPathFactory xpf = XPathFactory.newInstance(); - XPath xp = xpf.newXPath(); - - String asdcApiResponseCode = "500"; - - try { - - asdcApiResponseCode = xp.evaluate("//asdc-api-response-code[position()=1]/text()", results.getDocumentElement()); - } catch (Exception e) { - LOG.error("Caught exception retrying to evaluate xpath", e); - } - - if (asdcApiResponseCode.contains("200")) { - LOG.info("Update to SDN-C succeeded"); - deployResult = DistributionStatusEnum.DEPLOY_OK; - } else { - LOG.info("Update to SDN-C failed (response code "+asdcApiResponseCode+")"); - - if (asdcApiResponseCode.contains("409")) { - deployResult = DistributionStatusEnum.ALREADY_DEPLOYED; - } else { - - deployResult = DistributionStatusEnum.DEPLOY_ERROR; - } - } - } - - - - return(deployResult); - } - - - - - - public static IDistributionStatusMessage buildStatusMessage( - final IDistributionClient client, final INotificationData data, - final IArtifactInfo relevantArtifact, - final DistributionStatusEnum status) { - IDistributionStatusMessage statusMessage = new IDistributionStatusMessage() { - - @Override - public long getTimestamp() { - long currentTimeMillis = System.currentTimeMillis(); - return currentTimeMillis; - } - - @Override - public DistributionStatusEnum getStatus() { - return status; - } - - @Override - public String getDistributionID() { - return data.getDistributionID(); - } - - @Override - public String getConsumerID() { - return client.getConfiguration().getConsumerID(); - } - - @Override - public String getArtifactURL() { - return relevantArtifact.getArtifactURL(); - } - }; - return statusMessage; - - } - - private HttpURLConnection getRestXmlConnection(String urlString, String method) throws IOException - { - URL sdncUrl = new URL(urlString); - Authenticator.setDefault(new SdncAuthenticator(config.getSdncUser(), config.getSdncPasswd())); - - HttpURLConnection conn = (HttpURLConnection) sdncUrl.openConnection(); - - String authStr = config.getSdncUser()+":"+config.getSdncPasswd(); - String encodedAuthStr = new String(Base64.encodeBase64(authStr.getBytes())); - - conn.addRequestProperty("Authentication", "Basic "+encodedAuthStr); - - conn.setRequestMethod(method); - conn.setRequestProperty("Content-Type", "application/xml"); - conn.setRequestProperty("Accept", "application/xml"); - - conn.setDoInput(true); - conn.setDoOutput(true); - conn.setUseCaches(false); - - return(conn); - - } - - private Document postRestXml(String urlString, byte[] msgBytes) { - Document response = null; - - try { - SdncOdlConnection odlConn = SdncOdlConnection.newInstance(urlString, config.getSdncUser(), config.getSdncPasswd()); - - String sdncResp = odlConn.send("POST", "application/xml", new String(msgBytes)); - - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - DocumentBuilder db = dbf.newDocumentBuilder(); - - - response = db.parse(new ByteArrayInputStream(sdncResp.getBytes())); - } catch (Exception e) { - LOG.error("Caught exception posting to ODL tier", e); - } - - return(response); - - } - - private File applyXslts(File srcFile) { - - Document doc = null; - - - File inFile = srcFile; - File outFile = null; - - String xsltPathList = config.getXsltPathList(); - - if ((xsltPathList == null) || (xsltPathList.length() == 0)) { - outFile = inFile; - } else { - - String[] xsltPaths = xsltPathList.split(","); - - for (String xsltPath : xsltPaths) { - try{ - - outFile = File.createTempFile("tmp", "xml"); - TransformerFactory factory = TransformerFactory.newInstance(); - Source xslt = new StreamSource(new File(xsltPath)); - Transformer transformer = factory.newTransformer(xslt); - Source text = new StreamSource(inFile); - - - transformer.transform(text, new StreamResult(outFile)); - - inFile = outFile; - - } catch (Exception e) { - LOG.error("Caught exception trying to apply XSLT template "+xsltPath, e); - - } - - } - } - - // After transformations, parse transformed XML - - - return(outFile); - } - - private String escapeFilename(String str) { - StringBuffer retval = new StringBuffer(); - - for (int i = 0 ; i < str.length() ; i++) { - char curchar = str.charAt(i); - if (Character.isJavaIdentifierPart(curchar)) { - retval.append(curchar); - } - } - - return(retval.toString()); - - } - -} diff --git a/ueb-listener/src/main/java/org/openecomp/sdnc/uebclient/SdncUebClient.java b/ueb-listener/src/main/java/org/openecomp/sdnc/uebclient/SdncUebClient.java deleted file mode 100644 index df5dfc0a9..000000000 --- a/ueb-listener/src/main/java/org/openecomp/sdnc/uebclient/SdncUebClient.java +++ /dev/null @@ -1,65 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 ONAP 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.openecomp.sdnc.uebclient; - -import org.openecomp.sdc.api.IDistributionClient; -import org.openecomp.sdc.api.results.IDistributionClientResult; -import org.openecomp.sdc.impl.DistributionClientFactory; -import org.openecomp.sdc.utils.DistributionActionResultEnum; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class SdncUebClient { - - private static final Logger LOG = LoggerFactory - .getLogger(SdncUebConfiguration.class); - - public static void main(String[] args) { - IDistributionClient client = DistributionClientFactory - .createDistributionClient(); - - SdncUebConfiguration config = new SdncUebConfiguration(); - - SdncUebCallback cb = new SdncUebCallback(client, config); - - LOG.info("Scanning for local distribution artifacts before starting client"); - cb.deployDownloadedFiles(null, null, null); - - LOG.info("Initializing ASDC distribution client"); - - IDistributionClientResult result = client.init( - config, cb); - - LOG.info("Initialized ASDC distribution client - results = " - + result.getDistributionMessageResult()); - - if (result.getDistributionActionResult() == DistributionActionResultEnum.SUCCESS) { - LOG.info("Starting client..."); - IDistributionClientResult start = client.start(); - LOG.info("Client startup result = " - + start.getDistributionMessageResult()); - } - - - } - -} diff --git a/ueb-listener/src/main/java/org/openecomp/sdnc/uebclient/SdncUebConfiguration.java b/ueb-listener/src/main/java/org/openecomp/sdnc/uebclient/SdncUebConfiguration.java deleted file mode 100644 index 7855b5ba4..000000000 --- a/ueb-listener/src/main/java/org/openecomp/sdnc/uebclient/SdncUebConfiguration.java +++ /dev/null @@ -1,280 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 ONAP 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.openecomp.sdnc.uebclient; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.LinkedList; -import java.util.List; -import java.util.Properties; - -import org.openecomp.sdc.api.consumer.IConfiguration; -import org.openecomp.sdc.utils.ArtifactTypeEnum; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class SdncUebConfiguration implements IConfiguration{ - - private static final String SDNC_CONFIG_DIR = "SDNC_CONFIG_DIR"; - private static final Logger LOG = LoggerFactory - .getLogger(SdncUebConfiguration.class); - - private String asdcAddress = null; - private String consumerGroup = null; - private String consumerID = null; - private String environmentName = null; - private String password = null; - private int pollingInterval = 30; - private int pollingTimeout = 15; - private List relevantArtifactTypes = null; - private String user = null; - - private String sdncUser = null; - private String sdncPasswd = null; - private String asdcApiBaseUrl = null; - private String asdcApiNamespace = null; - - private SdncArtifactMap artifactMap = SdncArtifactMap.getInstance(); - - public String getAsdcApiNamespace() { - return asdcApiNamespace; - } - - private String incomingDir = null; - - private String archiveDir = null; - - private String overrideFile = null; - - private boolean activateServerTLSAuth; - private String keyStorePassword; - private String keyStorePath; - - private String xsltPathList; - - public String getXsltPathList() { - return xsltPathList; - } - - public String getOverrideFile() { - return overrideFile; - } - - public SdncUebConfiguration() { - - try { - init(); - } catch (Exception e) { - LOG.error("Cannot initialize SdncUebConfiguration", e); - } - } - - public void init() throws IOException { - String propPath = null; - String propDir = System.getenv(SDNC_CONFIG_DIR); - if (propDir == null) { - - propDir = "/opt/sdnc/data/properties"; - } - propPath = propDir + "/ueb-listener.properties"; - File propFile = new File(propPath); - - - if (!propFile.exists()) { - - throw new FileNotFoundException( - "Missing configuration properties file : " - + propFile); - } - - Properties props = new Properties(); - props.load(new FileInputStream(propFile)); - - asdcAddress = props.getProperty("org.openecomp.sdnc.uebclient.asdc-address"); - consumerGroup = props.getProperty("org.openecomp.sdnc.uebclient.consumer-group"); - consumerID = props.getProperty("org.openecomp.sdnc.uebclient.consumer-id"); - environmentName = props.getProperty("org.openecomp.sdnc.uebclient.environment-name"); - password = props.getProperty("org.openecomp.sdnc.uebclient.password"); - user = props.getProperty("org.openecomp.sdnc.uebclient.user"); - - sdncUser = props.getProperty("org.openecomp.sdnc.uebclient.sdnc-user"); - sdncPasswd = props.getProperty("org.openecomp.sdnc.uebclient.sdnc-passwd"); - asdcApiBaseUrl = props.getProperty("org.openecomp.sdnc.uebclient.asdc-api-base-url"); - asdcApiNamespace = props.getProperty("org.openecomp.sdnc.uebclient.asdc-api-namespace"); - - incomingDir = props.getProperty("org.openecomp.sdnc.uebclient.spool.incoming"); - archiveDir = props.getProperty("org.openecomp.sdnc.uebclient.spool.archive"); - overrideFile = props.getProperty("org.openecomp.sdnc.uebclient.override-file"); - - String curval = props.getProperty("org.openecomp.sdnc.uebclient.polling-interval"); - if ((curval != null) && (curval.length() > 0)) { - try { - pollingInterval = Integer.parseInt(curval); - } catch (Exception e) { - LOG.warn("Illegal value for org.openecomp.sdnc.uebclient.polling-interval ("+curval+")"); - } - } - - curval = props.getProperty("org.openecomp.sdnc.uebclient.polling-timeout"); - if ((curval != null) && (curval.length() > 0)) { - try { - pollingTimeout = Integer.parseInt(curval); - } catch (Exception e) { - LOG.warn("Illegal value for org.openecomp.sdnc.uebclient.polling-timeout ("+curval+")"); - } - } - - curval = props.getProperty("org.openecomp.sdnc.uebclient.relevant-artifact-types"); - if ((curval != null) && (curval.length() > 0)) { - String[] artifactTypes = curval.split(","); - - relevantArtifactTypes = new LinkedList(); - - for (int i = 0 ; i < artifactTypes.length ; i++) { - try { - if (ArtifactTypeEnum.valueOf(artifactTypes[i]) != null) { - relevantArtifactTypes.add(artifactTypes[i]); - } else { - LOG.warn("Skipping unrecognized artifact type "+artifactTypes[i]); - } - } catch (Exception e) { - - LOG.warn("Caught exception validating artifact type "+artifactTypes[i], e); - } - - } - - } - - curval = props.getProperty("org.openecomp.sdnc.uebclient.activate-server-tls-auth", "false"); - activateServerTLSAuth = "true".equalsIgnoreCase(curval); - keyStorePath = props.getProperty("org.openecomp.sdnc.uebclient.keystore-path"); - keyStorePassword = props.getProperty("org.openecomp.sdnc.uebclient.keystore-password"); - xsltPathList = props.getProperty("org.openecomp.sdnc.uebclient.xslt-path-list"); - - - String artifactMapFile = props.getProperty("org.openecomp.sdnc.uebclient.artifact-map"); - if (artifactMapFile != null) { - artifactMap.load(artifactMapFile); - } - - } - - @Override - public String getAsdcAddress() { - return asdcAddress; - } - - @Override - public String getConsumerGroup() { - return consumerGroup; - } - - @Override - public String getConsumerID() { - return consumerID; - } - - @Override - public String getEnvironmentName() { - return environmentName; - } - - @Override - public String getPassword() { - return password; - } - - @Override - public int getPollingInterval() { - return pollingInterval; - } - - @Override - public int getPollingTimeout() { - return pollingTimeout; - } - - @Override - public List getRelevantArtifactTypes() { - return relevantArtifactTypes; - } - - @Override - public String getUser() { - return user; - } - - - public String getSdncUser() { - return sdncUser; - } - - public String getSdncPasswd() { - return sdncPasswd; - } - - public String getAsdcApiBaseUrl() { - return asdcApiBaseUrl; - } - - @Override - public boolean activateServerTLSAuth() { - return activateServerTLSAuth; - } - - @Override - public String getKeyStorePassword() { - return keyStorePassword; - } - - @Override - public String getKeyStorePath() { - return keyStorePath; - } - - public String getIncomingDir() { - return incomingDir; - } - - public String getArchiveDir() { - return archiveDir; - } - - public int getMaxPasses() { - return(artifactMap.getNumPasses()); - } - - public SdncArtifactMap.SdncArtifactType getMapping(String tag) { - return(artifactMap.getMapping(tag)); - } - - @Override - public boolean isFilterInEmptyResources() { - // TODO Auto-generated method stub - return false; - } - - -} diff --git a/ueb-listener/src/main/java/org/openecomp/sdnc/uebclient/SdncVFCModel.java b/ueb-listener/src/main/java/org/openecomp/sdnc/uebclient/SdncVFCModel.java deleted file mode 100644 index 67b786896..000000000 --- a/ueb-listener/src/main/java/org/openecomp/sdnc/uebclient/SdncVFCModel.java +++ /dev/null @@ -1,69 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 ONAP 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.openecomp.sdnc.uebclient; - -import org.openecomp.sdc.tosca.parser.api.ISdcCsarHelper; -import org.openecomp.sdc.tosca.parser.impl.SdcPropertyNames; -import org.openecomp.sdc.toscaparser.api.NodeTemplate; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class SdncVFCModel extends SdncBaseModel { - - private static final Logger LOG = LoggerFactory - .getLogger(SdncVFCModel.class); - - private String vmType = null; - private String vmCount = null; - - public SdncVFCModel(ISdcCsarHelper sdcCsarHelper, NodeTemplate nodeTemplate) { - - super(sdcCsarHelper, nodeTemplate); - - // extract properties - vmType = extractValue (nodeTemplate, SdcPropertyNames.PROPERTY_NAME_VMTYPE); - //vmCount = extractValue (sdcCsarHelper, nodeTemplate, SdcPropertyNames.PROPERTY_NAME_VMCOUNT); - need path to vm_count - vmCount = "1"; - addParameter("vm_type", vmType); - addParameter("vm_type_tag", extractValue (nodeTemplate, SdcPropertyNames.PROPERTY_NAME_VMTYPETAG)); - addParameter("ecomp_generated_naming", extractBooleanValue (nodeTemplate, SdcPropertyNames.PROPERTY_NAME_VFCNAMING_ECOMPGENERATEDNAMING)); - addParameter("naming_policy", extractValue (nodeTemplate, SdcPropertyNames.PROPERTY_NAME_VFCNAMING_NAMINGPOLICY)); - addParameter("nfc_naming_code", extractValue (nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFCCODE)); - } - - public String getVmType() { - return vmType; - } - - public void setVmType(String vmType) { - this.vmType = vmType; - } - - public String getVmCount() { - return vmCount; - } - - public void setVmCount(String vmCount) { - this.vmCount = vmCount; - } - -} diff --git a/ueb-listener/src/main/java/org/openecomp/sdnc/uebclient/SdncVFModel.java b/ueb-listener/src/main/java/org/openecomp/sdnc/uebclient/SdncVFModel.java deleted file mode 100644 index 4e95e46ba..000000000 --- a/ueb-listener/src/main/java/org/openecomp/sdnc/uebclient/SdncVFModel.java +++ /dev/null @@ -1,56 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 ONAP 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.openecomp.sdnc.uebclient; - -import org.openecomp.sdc.tosca.parser.api.ISdcCsarHelper; -import org.openecomp.sdc.tosca.parser.impl.SdcPropertyNames; -import org.openecomp.sdc.toscaparser.api.Metadata; -import org.openecomp.sdc.toscaparser.api.NodeTemplate; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class SdncVFModel extends SdncBaseModel { - - private static final Logger LOG = LoggerFactory - .getLogger(SdncVFModel.class); - - public SdncVFModel(ISdcCsarHelper sdcCsarHelper, NodeTemplate nodeTemplate) { - - super(sdcCsarHelper, nodeTemplate); - - // extract metadata - Metadata metadata = nodeTemplate.getMetadata(); - addParameter("name", extractValue(metadata, SdcPropertyNames.PROPERTY_NAME_NAME)); - addParameter("vendor", extractValue (metadata, SdcPropertyNames.PROPERTY_NAME_RESOURCEVENDOR)); - addParameter("vendor_version", extractValue (metadata, SdcPropertyNames.PROPERTY_NAME_RESOURCEVENDORRELEASE)); - - // extract properties - addParameter("ecomp_generated_naming", extractBooleanValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_VNFECOMPNAMING_ECOMPGENERATEDNAMING)); - addParameter("naming_policy", extractValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_VNFECOMPNAMING_NAMINGPOLICY)); - addParameter("nf_type", extractValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFTYPE)); - addParameter("nf_role", extractValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFROLE)); - addParameter("nf_code", extractValue( nodeTemplate, "nf_naming_code")); - addParameter("nf_function", extractValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFFUNCTION)); - addParameter("avail_zone_max_count", extractValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_AVAILABILITYZONEMAXCOUNT)); - } - -} diff --git a/ueb-listener/src/main/java/org/openecomp/sdnc/uebclient/SdncVFModuleModel.java b/ueb-listener/src/main/java/org/openecomp/sdnc/uebclient/SdncVFModuleModel.java deleted file mode 100644 index 86df8b2ab..000000000 --- a/ueb-listener/src/main/java/org/openecomp/sdnc/uebclient/SdncVFModuleModel.java +++ /dev/null @@ -1,45 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 ONAP 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.openecomp.sdnc.uebclient; - -import org.openecomp.sdc.tosca.parser.api.ISdcCsarHelper; -import org.openecomp.sdc.tosca.parser.impl.SdcPropertyNames; -import org.openecomp.sdc.toscaparser.api.Group; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class SdncVFModuleModel extends SdncBaseModel { - - private static final Logger LOG = LoggerFactory - .getLogger(SdncVFModuleModel.class); - - public SdncVFModuleModel(ISdcCsarHelper sdcCsarHelper, Group group) { - - super(sdcCsarHelper, group); - - // extract properties - addParameter("vf_module_type", extractValue(group, SdcPropertyNames.PROPERTY_NAME_VFMODULETYPE)); - addIntParameter("availability_zone_count", extractValue(group, SdcPropertyNames.PROPERTY_NAME_AVAILABILITYZONECOUNT)); - addParameter("ecomp_generated_vm_assignments", extractBooleanValue(group, SdcPropertyNames.PROPERTY_NAME_ECOMPGENERATEDVMASSIGNMENTS)); - } - -} -- cgit 1.2.3-korg From 1027b0c07b488bb5f4542bd38501f9a99da5c2cf Mon Sep 17 00:00:00 2001 From: Dan Timoney Date: Tue, 15 Aug 2017 15:18:54 -0400 Subject: Port sli/northbound to Carbon Updated sli/northbound repo to compile against OpenDaylight Carbon SR1 release Change-Id: I6aec68cf436e11f5fd5b7094eb5616536bead44f Issue-ID: CCSDK-25 Signed-off-by: Dan Timoney --- asdcApi/features/pom.xml | 2 +- asdcApi/features/src/main/resources/features.xml | 4 ++-- asdcApi/installer/pom.xml | 5 ++--- asdcApi/installer/src/assembly/assemble_installer_zip.xml | 4 ++-- asdcApi/installer/src/assembly/assemble_mvnrepo_zip.xml | 4 ++-- asdcApi/installer/src/main/resources/scripts/install-feature.sh | 4 ++-- asdcApi/model/pom.xml | 6 +++--- asdcApi/pom.xml | 4 ++-- asdcApi/provider/pom.xml | 4 ++-- .../org/onap/ccsdk/sli/northbound/asdcapi/AsdcApiProvider.java | 4 ++-- .../org/onap/ccsdk/sli/northbound/asdcapi/AsdcApiSliClient.java | 4 ++-- .../java/org/onap/ccsdk/sli/northbound/asdcapi/AsdcApiUtil.java | 4 ++-- .../asdcapi/provider/impl/rev140523/AsdcApiProviderModule.java | 4 ++-- .../provider/impl/rev140523/AsdcApiProviderModuleFactory.java | 4 ++-- asdcApi/provider/src/main/resources/initial/asdcApi-provider.xml | 4 ++-- dataChange/features/pom.xml | 4 ++-- dataChange/features/src/main/resources/features.xml | 4 ++-- dataChange/installer/pom.xml | 5 ++--- dataChange/installer/src/assembly/assemble_installer_zip.xml | 4 ++-- dataChange/installer/src/assembly/assemble_mvnrepo_zip.xml | 4 ++-- dataChange/installer/src/main/resources/scripts/install-feature.sh | 4 ++-- dataChange/model/pom.xml | 6 +++--- dataChange/pom.xml | 4 ++-- dataChange/provider/pom.xml | 7 +++---- .../main/java/org/onap/ccsdk/sli/northbound/DataChangeClient.java | 4 ++-- .../java/org/onap/ccsdk/sli/northbound/DataChangeProvider.java | 4 ++-- .../provider/impl/rev140523/DataChangeProviderModule.java | 4 ++-- .../provider/impl/rev140523/DataChangeProviderModuleFactory.java | 4 ++-- .../provider/src/main/resources/initial/dataChange-provider.xml | 4 ++-- dmaap-listener/pom.xml | 5 +++-- dmaap-listener/src/assembly/assemble_zip.xml | 4 ++-- .../org/onap/ccsdk/sli/northbound/dmaapclient/DmaapListener.java | 4 ++-- .../onap/ccsdk/sli/northbound/dmaapclient/DummyDmaapConsumer.java | 4 ++-- .../ccsdk/sli/northbound/dmaapclient/InvalidMessageException.java | 4 ++-- .../onap/ccsdk/sli/northbound/dmaapclient/SdncDmaapConsumer.java | 4 ++-- .../sli/northbound/dmaapclient/SdncFlatJsonDmaapConsumer.java | 4 ++-- .../onap/ccsdk/sli/northbound/dmaapclient/SdncOdlConnection.java | 4 ++-- dmaap-listener/src/main/resources/log4j.properties | 4 ++-- dmaap-listener/src/main/scripts/start-dmaap-listener.sh | 4 ++-- dmaap-listener/src/main/scripts/stop-dmaap-listener.sh | 4 ++-- dmaap-listener/src/site/apt/index.apt | 4 ++-- dmaap-listener/src/site/site.xml | 4 ++-- pom.xml | 7 +++---- ueb-listener/pom.xml | 5 +++-- ueb-listener/src/assembly/assemble_zip.xml | 4 ++-- .../java/org/onap/ccsdk/sli/northbound/uebclient/SdncARModel.java | 4 ++-- .../org/onap/ccsdk/sli/northbound/uebclient/SdncArtifactMap.java | 4 ++-- .../org/onap/ccsdk/sli/northbound/uebclient/SdncBaseModel.java | 4 ++-- .../org/onap/ccsdk/sli/northbound/uebclient/SdncNodeModel.java | 4 ++-- .../org/onap/ccsdk/sli/northbound/uebclient/SdncOdlConnection.java | 4 ++-- .../org/onap/ccsdk/sli/northbound/uebclient/SdncServiceModel.java | 4 ++-- .../org/onap/ccsdk/sli/northbound/uebclient/SdncUebCallback.java | 4 ++-- .../org/onap/ccsdk/sli/northbound/uebclient/SdncUebClient.java | 4 ++-- .../onap/ccsdk/sli/northbound/uebclient/SdncUebConfiguration.java | 4 ++-- .../java/org/onap/ccsdk/sli/northbound/uebclient/SdncVFCModel.java | 4 ++-- .../java/org/onap/ccsdk/sli/northbound/uebclient/SdncVFModel.java | 4 ++-- .../org/onap/ccsdk/sli/northbound/uebclient/SdncVFModuleModel.java | 4 ++-- ueb-listener/src/main/resources/log4j.properties | 4 ++-- ueb-listener/src/main/scripts/start-ueb-listener.sh | 4 ++-- ueb-listener/src/main/scripts/stop-ueb-listener.sh | 4 ++-- ueb-listener/src/site/apt/index.apt | 4 ++-- ueb-listener/src/site/site.xml | 4 ++-- 62 files changed, 129 insertions(+), 131 deletions(-) (limited to 'dmaap-listener/src') diff --git a/asdcApi/features/pom.xml b/asdcApi/features/pom.xml index 774d9e529..e6af34c57 100755 --- a/asdcApi/features/pom.xml +++ b/asdcApi/features/pom.xml @@ -4,7 +4,7 @@ asdcApi org.onap.ccsdk.sli.northbound - 0.0.1-SNAPSHOT + 0.1.0-SNAPSHOT asdcApi-features diff --git a/asdcApi/features/src/main/resources/features.xml b/asdcApi/features/src/main/resources/features.xml index f9aa81a66..9006f1b94 100644 --- a/asdcApi/features/src/main/resources/features.xml +++ b/asdcApi/features/src/main/resources/features.xml @@ -3,8 +3,8 @@ ============LICENSE_START======================================================= openECOMP : SDN-C ================================================================================ - Copyright (C) 2017 ONAP Intellectual Property. All rights - reserved. + Copyright (C) 2017 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. diff --git a/asdcApi/installer/pom.xml b/asdcApi/installer/pom.xml index b4f32934a..32f505053 100755 --- a/asdcApi/installer/pom.xml +++ b/asdcApi/installer/pom.xml @@ -1,11 +1,10 @@ - + 4.0.0 asdcApi org.onap.ccsdk.sli.northbound - 0.0.1-SNAPSHOT + 0.1.0-SNAPSHOT asdcApi-installer asdcApi - Karaf Installer diff --git a/asdcApi/installer/src/assembly/assemble_installer_zip.xml b/asdcApi/installer/src/assembly/assemble_installer_zip.xml index e278872a1..3bed4b5ef 100644 --- a/asdcApi/installer/src/assembly/assemble_installer_zip.xml +++ b/asdcApi/installer/src/assembly/assemble_installer_zip.xml @@ -2,8 +2,8 @@ ============LICENSE_START======================================================= openECOMP : SDN-C ================================================================================ - Copyright (C) 2017 ONAP Intellectual Property. All rights - reserved. + Copyright (C) 2017 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. diff --git a/asdcApi/installer/src/assembly/assemble_mvnrepo_zip.xml b/asdcApi/installer/src/assembly/assemble_mvnrepo_zip.xml index 608200da1..5c24d73ff 100644 --- a/asdcApi/installer/src/assembly/assemble_mvnrepo_zip.xml +++ b/asdcApi/installer/src/assembly/assemble_mvnrepo_zip.xml @@ -2,8 +2,8 @@ ============LICENSE_START======================================================= openECOMP : SDN-C ================================================================================ - Copyright (C) 2017 ONAP Intellectual Property. All rights - reserved. + Copyright (C) 2017 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. diff --git a/asdcApi/installer/src/main/resources/scripts/install-feature.sh b/asdcApi/installer/src/main/resources/scripts/install-feature.sh index 9a47d2225..e986764b9 100644 --- a/asdcApi/installer/src/main/resources/scripts/install-feature.sh +++ b/asdcApi/installer/src/main/resources/scripts/install-feature.sh @@ -4,8 +4,8 @@ # ============LICENSE_START======================================================= # openECOMP : SDN-C # ================================================================================ -# Copyright (C) 2017 ONAP Intellectual Property. All rights -# reserved. +# Copyright (C) 2017 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. diff --git a/asdcApi/model/pom.xml b/asdcApi/model/pom.xml index b9f48326d..327b8627e 100755 --- a/asdcApi/model/pom.xml +++ b/asdcApi/model/pom.xml @@ -4,11 +4,11 @@ asdcApi org.onap.ccsdk.sli.northbound - 0.0.1-SNAPSHOT + 0.1.0-SNAPSHOT org.onap.ccsdk.sli.northbound asdcApi-model - 0.0.1-SNAPSHOT + 0.1.0-SNAPSHOT bundle @@ -45,7 +45,7 @@ ${yang.file.directory} - org.opendaylight.yangtools.maven.sal.api.gen.plugin.CodeGeneratorImpl + org.opendaylight.mdsal.binding.maven.api.gen.plugin.CodeGeneratorImpl ${salGeneratorPath} diff --git a/asdcApi/pom.xml b/asdcApi/pom.xml index b4d538abd..9f8d906c3 100755 --- a/asdcApi/pom.xml +++ b/asdcApi/pom.xml @@ -5,13 +5,13 @@ org.onap.ccsdk.sli.northbound sdnc-northbound - 0.0.1-SNAPSHOT + 0.1.0-SNAPSHOT pom org.onap.ccsdk.sli.northbound asdcApi - 0.0.1-SNAPSHOT + 0.1.0-SNAPSHOT asdcApi diff --git a/asdcApi/provider/pom.xml b/asdcApi/provider/pom.xml index e8769fd7d..7b7ed4bee 100755 --- a/asdcApi/provider/pom.xml +++ b/asdcApi/provider/pom.xml @@ -4,7 +4,7 @@ asdcApi org.onap.ccsdk.sli.northbound - 0.0.1-SNAPSHOT + 0.1.0-SNAPSHOT asdcApi-provider bundle @@ -42,7 +42,7 @@ - org.opendaylight.yangtools.maven.sal.api.gen.plugin.CodeGeneratorImpl + org.opendaylight.mdsal.binding.maven.api.gen.plugin.CodeGeneratorImpl ${salGeneratorPath} diff --git a/asdcApi/provider/src/main/java/org/onap/ccsdk/sli/northbound/asdcapi/AsdcApiProvider.java b/asdcApi/provider/src/main/java/org/onap/ccsdk/sli/northbound/asdcapi/AsdcApiProvider.java index c6e1921b7..bd5f74a4f 100644 --- a/asdcApi/provider/src/main/java/org/onap/ccsdk/sli/northbound/asdcapi/AsdcApiProvider.java +++ b/asdcApi/provider/src/main/java/org/onap/ccsdk/sli/northbound/asdcapi/AsdcApiProvider.java @@ -2,8 +2,8 @@ * ============LICENSE_START======================================================= * openECOMP : SDN-C * ================================================================================ - * Copyright (C) 2017 ONAP Intellectual Property. All rights - * reserved. + * Copyright (C) 2017 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. diff --git a/asdcApi/provider/src/main/java/org/onap/ccsdk/sli/northbound/asdcapi/AsdcApiSliClient.java b/asdcApi/provider/src/main/java/org/onap/ccsdk/sli/northbound/asdcapi/AsdcApiSliClient.java index 0fa90ea7e..5b268bc28 100644 --- a/asdcApi/provider/src/main/java/org/onap/ccsdk/sli/northbound/asdcapi/AsdcApiSliClient.java +++ b/asdcApi/provider/src/main/java/org/onap/ccsdk/sli/northbound/asdcapi/AsdcApiSliClient.java @@ -2,8 +2,8 @@ * ============LICENSE_START======================================================= * openECOMP : SDN-C * ================================================================================ - * Copyright (C) 2017 ONAP Intellectual Property. All rights - * reserved. + * Copyright (C) 2017 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. diff --git a/asdcApi/provider/src/main/java/org/onap/ccsdk/sli/northbound/asdcapi/AsdcApiUtil.java b/asdcApi/provider/src/main/java/org/onap/ccsdk/sli/northbound/asdcapi/AsdcApiUtil.java index 6498f13b5..602b389cb 100644 --- a/asdcApi/provider/src/main/java/org/onap/ccsdk/sli/northbound/asdcapi/AsdcApiUtil.java +++ b/asdcApi/provider/src/main/java/org/onap/ccsdk/sli/northbound/asdcapi/AsdcApiUtil.java @@ -2,8 +2,8 @@ * ============LICENSE_START======================================================= * openECOMP : SDN-C * ================================================================================ - * Copyright (C) 2017 ONAP Intellectual Property. All rights - * reserved. + * Copyright (C) 2017 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. diff --git a/asdcApi/provider/src/main/java/org/opendaylight/yang/gen/v1/org/onap/ccsdk/sli/northbound/asdcapi/provider/impl/rev140523/AsdcApiProviderModule.java b/asdcApi/provider/src/main/java/org/opendaylight/yang/gen/v1/org/onap/ccsdk/sli/northbound/asdcapi/provider/impl/rev140523/AsdcApiProviderModule.java index 0a2272d35..ddf8093fb 100644 --- a/asdcApi/provider/src/main/java/org/opendaylight/yang/gen/v1/org/onap/ccsdk/sli/northbound/asdcapi/provider/impl/rev140523/AsdcApiProviderModule.java +++ b/asdcApi/provider/src/main/java/org/opendaylight/yang/gen/v1/org/onap/ccsdk/sli/northbound/asdcapi/provider/impl/rev140523/AsdcApiProviderModule.java @@ -2,8 +2,8 @@ * ============LICENSE_START======================================================= * openECOMP : SDN-C * ================================================================================ - * Copyright (C) 2017 ONAP Intellectual Property. All rights - * reserved. + * Copyright (C) 2017 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. diff --git a/asdcApi/provider/src/main/java/org/opendaylight/yang/gen/v1/org/onap/ccsdk/sli/northbound/asdcapi/provider/impl/rev140523/AsdcApiProviderModuleFactory.java b/asdcApi/provider/src/main/java/org/opendaylight/yang/gen/v1/org/onap/ccsdk/sli/northbound/asdcapi/provider/impl/rev140523/AsdcApiProviderModuleFactory.java index c2d15b890..513e61cff 100644 --- a/asdcApi/provider/src/main/java/org/opendaylight/yang/gen/v1/org/onap/ccsdk/sli/northbound/asdcapi/provider/impl/rev140523/AsdcApiProviderModuleFactory.java +++ b/asdcApi/provider/src/main/java/org/opendaylight/yang/gen/v1/org/onap/ccsdk/sli/northbound/asdcapi/provider/impl/rev140523/AsdcApiProviderModuleFactory.java @@ -2,8 +2,8 @@ * ============LICENSE_START======================================================= * openECOMP : SDN-C * ================================================================================ - * Copyright (C) 2017 ONAP Intellectual Property. All rights - * reserved. + * Copyright (C) 2017 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. diff --git a/asdcApi/provider/src/main/resources/initial/asdcApi-provider.xml b/asdcApi/provider/src/main/resources/initial/asdcApi-provider.xml index 53f5a11d0..aefdec281 100644 --- a/asdcApi/provider/src/main/resources/initial/asdcApi-provider.xml +++ b/asdcApi/provider/src/main/resources/initial/asdcApi-provider.xml @@ -3,8 +3,8 @@ ============LICENSE_START======================================================= openECOMP : SDN-C ================================================================================ - Copyright (C) 2017 ONAP Intellectual Property. All rights - reserved. + Copyright (C) 2017 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. diff --git a/dataChange/features/pom.xml b/dataChange/features/pom.xml index 123404479..cd48d3f52 100755 --- a/dataChange/features/pom.xml +++ b/dataChange/features/pom.xml @@ -4,11 +4,11 @@ dataChange org.onap.ccsdk.sli.northbound - 0.0.1-SNAPSHOT + 0.1.0-SNAPSHOT org.onap.ccsdk.sli.northbound dataChange-features - 0.0.1-SNAPSHOT + 0.1.0-SNAPSHOT jar diff --git a/dataChange/features/src/main/resources/features.xml b/dataChange/features/src/main/resources/features.xml index 9cc8cc57b..47cdcfd9f 100644 --- a/dataChange/features/src/main/resources/features.xml +++ b/dataChange/features/src/main/resources/features.xml @@ -3,8 +3,8 @@ ============LICENSE_START======================================================= openECOMP : SDN-C ================================================================================ - Copyright (C) 2017 ONAP Intellectual Property. All rights - reserved. + Copyright (C) 2017 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. diff --git a/dataChange/installer/pom.xml b/dataChange/installer/pom.xml index 63fda23ab..940144f53 100755 --- a/dataChange/installer/pom.xml +++ b/dataChange/installer/pom.xml @@ -1,11 +1,10 @@ - + 4.0.0 dataChange org.onap.ccsdk.sli.northbound - 0.0.1-SNAPSHOT + 0.1.0-SNAPSHOT dataChange-installer dataChange - Karaf Installer diff --git a/dataChange/installer/src/assembly/assemble_installer_zip.xml b/dataChange/installer/src/assembly/assemble_installer_zip.xml index e278872a1..3bed4b5ef 100644 --- a/dataChange/installer/src/assembly/assemble_installer_zip.xml +++ b/dataChange/installer/src/assembly/assemble_installer_zip.xml @@ -2,8 +2,8 @@ ============LICENSE_START======================================================= openECOMP : SDN-C ================================================================================ - Copyright (C) 2017 ONAP Intellectual Property. All rights - reserved. + Copyright (C) 2017 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. diff --git a/dataChange/installer/src/assembly/assemble_mvnrepo_zip.xml b/dataChange/installer/src/assembly/assemble_mvnrepo_zip.xml index 608200da1..5c24d73ff 100644 --- a/dataChange/installer/src/assembly/assemble_mvnrepo_zip.xml +++ b/dataChange/installer/src/assembly/assemble_mvnrepo_zip.xml @@ -2,8 +2,8 @@ ============LICENSE_START======================================================= openECOMP : SDN-C ================================================================================ - Copyright (C) 2017 ONAP Intellectual Property. All rights - reserved. + Copyright (C) 2017 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. diff --git a/dataChange/installer/src/main/resources/scripts/install-feature.sh b/dataChange/installer/src/main/resources/scripts/install-feature.sh index 9a47d2225..e986764b9 100644 --- a/dataChange/installer/src/main/resources/scripts/install-feature.sh +++ b/dataChange/installer/src/main/resources/scripts/install-feature.sh @@ -4,8 +4,8 @@ # ============LICENSE_START======================================================= # openECOMP : SDN-C # ================================================================================ -# Copyright (C) 2017 ONAP Intellectual Property. All rights -# reserved. +# Copyright (C) 2017 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. diff --git a/dataChange/model/pom.xml b/dataChange/model/pom.xml index 0d16ebfc0..20dddeb97 100755 --- a/dataChange/model/pom.xml +++ b/dataChange/model/pom.xml @@ -4,11 +4,11 @@ dataChange org.onap.ccsdk.sli.northbound - 0.0.1-SNAPSHOT + 0.1.0-SNAPSHOT org.onap.ccsdk.sli.northbound dataChange-model - 0.0.1-SNAPSHOT + 0.1.0-SNAPSHOT bundle @@ -45,7 +45,7 @@ ${yang.file.directory} - org.opendaylight.yangtools.maven.sal.api.gen.plugin.CodeGeneratorImpl + org.opendaylight.mdsal.binding.maven.api.gen.plugin.CodeGeneratorImpl ${salGeneratorPath} diff --git a/dataChange/pom.xml b/dataChange/pom.xml index 2e3d87494..90e22d219 100755 --- a/dataChange/pom.xml +++ b/dataChange/pom.xml @@ -5,13 +5,13 @@ org.onap.ccsdk.sli.northbound sdnc-northbound - 0.0.1-SNAPSHOT + 0.1.0-SNAPSHOT pom org.onap.ccsdk.sli.northbound dataChange - 0.0.1-SNAPSHOT + 0.1.0-SNAPSHOT dataChange diff --git a/dataChange/provider/pom.xml b/dataChange/provider/pom.xml index 5a7c7003d..c73c00980 100755 --- a/dataChange/provider/pom.xml +++ b/dataChange/provider/pom.xml @@ -1,11 +1,10 @@ - + 4.0.0 dataChange org.onap.ccsdk.sli.northbound - 0.0.1-SNAPSHOT + 0.1.0-SNAPSHOT dataChange-provider bundle @@ -44,7 +43,7 @@ - org.opendaylight.yangtools.maven.sal.api.gen.plugin.CodeGeneratorImpl + org.opendaylight.mdsal.binding.maven.api.gen.plugin.CodeGeneratorImpl ${salGeneratorPath} diff --git a/dataChange/provider/src/main/java/org/onap/ccsdk/sli/northbound/DataChangeClient.java b/dataChange/provider/src/main/java/org/onap/ccsdk/sli/northbound/DataChangeClient.java index 81da74161..75cc0a02e 100644 --- a/dataChange/provider/src/main/java/org/onap/ccsdk/sli/northbound/DataChangeClient.java +++ b/dataChange/provider/src/main/java/org/onap/ccsdk/sli/northbound/DataChangeClient.java @@ -2,8 +2,8 @@ * ============LICENSE_START======================================================= * openECOMP : SDN-C * ================================================================================ - * Copyright (C) 2017 ONAP Intellectual Property. All rights - * reserved. + * Copyright (C) 2017 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. diff --git a/dataChange/provider/src/main/java/org/onap/ccsdk/sli/northbound/DataChangeProvider.java b/dataChange/provider/src/main/java/org/onap/ccsdk/sli/northbound/DataChangeProvider.java index 40d30a792..dcfbf6ee2 100644 --- a/dataChange/provider/src/main/java/org/onap/ccsdk/sli/northbound/DataChangeProvider.java +++ b/dataChange/provider/src/main/java/org/onap/ccsdk/sli/northbound/DataChangeProvider.java @@ -2,8 +2,8 @@ * ============LICENSE_START======================================================= * openECOMP : SDN-C * ================================================================================ - * Copyright (C) 2017 ONAP Intellectual Property. All rights - * reserved. + * Copyright (C) 2017 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. diff --git a/dataChange/provider/src/main/java/org/opendaylight/yang/gen/v1/org/onap/ccsdk/sli/northbound/datachange/provider/impl/rev140523/DataChangeProviderModule.java b/dataChange/provider/src/main/java/org/opendaylight/yang/gen/v1/org/onap/ccsdk/sli/northbound/datachange/provider/impl/rev140523/DataChangeProviderModule.java index f8267cf32..0655ae20a 100644 --- a/dataChange/provider/src/main/java/org/opendaylight/yang/gen/v1/org/onap/ccsdk/sli/northbound/datachange/provider/impl/rev140523/DataChangeProviderModule.java +++ b/dataChange/provider/src/main/java/org/opendaylight/yang/gen/v1/org/onap/ccsdk/sli/northbound/datachange/provider/impl/rev140523/DataChangeProviderModule.java @@ -2,8 +2,8 @@ * ============LICENSE_START======================================================= * openECOMP : SDN-C * ================================================================================ - * Copyright (C) 2017 ONAP Intellectual Property. All rights - * reserved. + * Copyright (C) 2017 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. diff --git a/dataChange/provider/src/main/java/org/opendaylight/yang/gen/v1/org/onap/ccsdk/sli/northbound/datachange/provider/impl/rev140523/DataChangeProviderModuleFactory.java b/dataChange/provider/src/main/java/org/opendaylight/yang/gen/v1/org/onap/ccsdk/sli/northbound/datachange/provider/impl/rev140523/DataChangeProviderModuleFactory.java index 5852788c4..468989998 100644 --- a/dataChange/provider/src/main/java/org/opendaylight/yang/gen/v1/org/onap/ccsdk/sli/northbound/datachange/provider/impl/rev140523/DataChangeProviderModuleFactory.java +++ b/dataChange/provider/src/main/java/org/opendaylight/yang/gen/v1/org/onap/ccsdk/sli/northbound/datachange/provider/impl/rev140523/DataChangeProviderModuleFactory.java @@ -2,8 +2,8 @@ * ============LICENSE_START======================================================= * openECOMP : SDN-C * ================================================================================ - * Copyright (C) 2017 ONAP Intellectual Property. All rights - * reserved. + * Copyright (C) 2017 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. diff --git a/dataChange/provider/src/main/resources/initial/dataChange-provider.xml b/dataChange/provider/src/main/resources/initial/dataChange-provider.xml index 3038201ba..2da0546aa 100644 --- a/dataChange/provider/src/main/resources/initial/dataChange-provider.xml +++ b/dataChange/provider/src/main/resources/initial/dataChange-provider.xml @@ -3,8 +3,8 @@ ============LICENSE_START======================================================= openECOMP : SDN-C ================================================================================ - Copyright (C) 2017 ONAP Intellectual Property. All rights - reserved. + Copyright (C) 2017 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. diff --git a/dmaap-listener/pom.xml b/dmaap-listener/pom.xml index 9ab23cdea..ac65c16f8 100755 --- a/dmaap-listener/pom.xml +++ b/dmaap-listener/pom.xml @@ -1,16 +1,17 @@ + 4.0.0 org.onap.ccsdk.sli.northbound jar dmaap-listener - 0.0.1-SNAPSHOT + 0.1.0-SNAPSHOT DMAAP Listener DMAAP Listener org.onap.ccsdk.sli.northbound sdnc-northbound - 0.0.1-SNAPSHOT + 0.1.0-SNAPSHOT 1.1.7-SNAPSHOT diff --git a/dmaap-listener/src/assembly/assemble_zip.xml b/dmaap-listener/src/assembly/assemble_zip.xml index 15f6bf4d2..f8873ab41 100644 --- a/dmaap-listener/src/assembly/assemble_zip.xml +++ b/dmaap-listener/src/assembly/assemble_zip.xml @@ -2,8 +2,8 @@ ============LICENSE_START======================================================= openECOMP : SDN-C ================================================================================ - Copyright (C) 2017 ONAP Intellectual Property. All rights - reserved. + Copyright (C) 2017 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. diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/DmaapListener.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/DmaapListener.java index b2976294b..91afe1d1a 100644 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/DmaapListener.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/DmaapListener.java @@ -2,8 +2,8 @@ * ============LICENSE_START======================================================= * openECOMP : SDN-C * ================================================================================ - * Copyright (C) 2017 ONAP Intellectual Property. All rights - * reserved. + * Copyright (C) 2017 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. diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/DummyDmaapConsumer.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/DummyDmaapConsumer.java index a3bc46153..a8336342f 100644 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/DummyDmaapConsumer.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/DummyDmaapConsumer.java @@ -2,8 +2,8 @@ * ============LICENSE_START======================================================= * openECOMP : SDN-C * ================================================================================ - * Copyright (C) 2017 ONAP Intellectual Property. All rights - * reserved. + * Copyright (C) 2017 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. diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/InvalidMessageException.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/InvalidMessageException.java index b54adaf06..cab8b901c 100644 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/InvalidMessageException.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/InvalidMessageException.java @@ -2,8 +2,8 @@ * ============LICENSE_START======================================================= * openECOMP : SDN-C * ================================================================================ - * Copyright (C) 2017 ONAP Intellectual Property. All rights - * reserved. + * Copyright (C) 2017 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. diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncDmaapConsumer.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncDmaapConsumer.java index f6d8ff862..c1320d6b4 100644 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncDmaapConsumer.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncDmaapConsumer.java @@ -2,8 +2,8 @@ * ============LICENSE_START======================================================= * openECOMP : SDN-C * ================================================================================ - * Copyright (C) 2017 ONAP Intellectual Property. All rights - * reserved. + * Copyright (C) 2017 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. diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncFlatJsonDmaapConsumer.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncFlatJsonDmaapConsumer.java index 0e2a32646..abd395bfb 100644 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncFlatJsonDmaapConsumer.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncFlatJsonDmaapConsumer.java @@ -2,8 +2,8 @@ * ============LICENSE_START======================================================= * openECOMP : SDN-C * ================================================================================ - * Copyright (C) 2017 ONAP Intellectual Property. All rights - * reserved. + * Copyright (C) 2017 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. diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncOdlConnection.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncOdlConnection.java index 4d16dd2a0..e31219a23 100644 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncOdlConnection.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncOdlConnection.java @@ -2,8 +2,8 @@ * ============LICENSE_START======================================================= * openECOMP : SDN-C * ================================================================================ - * Copyright (C) 2017 ONAP Intellectual Property. All rights - * reserved. + * Copyright (C) 2017 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. diff --git a/dmaap-listener/src/main/resources/log4j.properties b/dmaap-listener/src/main/resources/log4j.properties index ba815871b..8db00762b 100644 --- a/dmaap-listener/src/main/resources/log4j.properties +++ b/dmaap-listener/src/main/resources/log4j.properties @@ -2,8 +2,8 @@ # ============LICENSE_START======================================================= # openECOMP : SDN-C # ================================================================================ -# Copyright (C) 2017 ONAP Intellectual Property. All rights -# reserved. +# Copyright (C) 2017 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. diff --git a/dmaap-listener/src/main/scripts/start-dmaap-listener.sh b/dmaap-listener/src/main/scripts/start-dmaap-listener.sh index 5eeb62bbf..805105863 100644 --- a/dmaap-listener/src/main/scripts/start-dmaap-listener.sh +++ b/dmaap-listener/src/main/scripts/start-dmaap-listener.sh @@ -4,8 +4,8 @@ # ============LICENSE_START======================================================= # openECOMP : SDN-C # ================================================================================ -# Copyright (C) 2017 ONAP Intellectual Property. All rights -# reserved. +# Copyright (C) 2017 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. diff --git a/dmaap-listener/src/main/scripts/stop-dmaap-listener.sh b/dmaap-listener/src/main/scripts/stop-dmaap-listener.sh index 42de474fb..61be1a141 100644 --- a/dmaap-listener/src/main/scripts/stop-dmaap-listener.sh +++ b/dmaap-listener/src/main/scripts/stop-dmaap-listener.sh @@ -4,8 +4,8 @@ # ============LICENSE_START======================================================= # openECOMP : SDN-C # ================================================================================ -# Copyright (C) 2017 ONAP Intellectual Property. All rights -# reserved. +# Copyright (C) 2017 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. diff --git a/dmaap-listener/src/site/apt/index.apt b/dmaap-listener/src/site/apt/index.apt index dd9d3ec39..370ddd4db 100644 --- a/dmaap-listener/src/site/apt/index.apt +++ b/dmaap-listener/src/site/apt/index.apt @@ -2,8 +2,8 @@ ~~ ============LICENSE_START======================================================= ~~ openECOMP : SDN-C ~~ ================================================================================ -~~ Copyright (C) 2017 ONAP Intellectual Property. All rights -~~ reserved. +~~ Copyright (C) 2017 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. diff --git a/dmaap-listener/src/site/site.xml b/dmaap-listener/src/site/site.xml index 356c9c959..6b97d925e 100644 --- a/dmaap-listener/src/site/site.xml +++ b/dmaap-listener/src/site/site.xml @@ -3,8 +3,8 @@ ============LICENSE_START======================================================= openECOMP : SDN-C ================================================================================ - Copyright (C) 2017 ONAP Intellectual Property. All rights - reserved. + Copyright (C) 2017 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. diff --git a/pom.xml b/pom.xml index 4d2bb2092..c0f7ac616 100644 --- a/pom.xml +++ b/pom.xml @@ -1,10 +1,9 @@ - + org.onap.ccsdk.parent - odlparent-boron-sr3 + odlparent-carbon-sr1 0.0.1-SNAPSHOT @@ -113,7 +112,7 @@ AT&T - 0.0.1-SNAPSHOT + 0.1.0-SNAPSHOT diff --git a/ueb-listener/pom.xml b/ueb-listener/pom.xml index e0b96aaf4..5f8d5ca1b 100755 --- a/ueb-listener/pom.xml +++ b/ueb-listener/pom.xml @@ -1,16 +1,17 @@ + 4.0.0 org.onap.ccsdk.sli.northbound jar ueb-listener - 0.0.1-SNAPSHOT + 0.1.0-SNAPSHOT UEB Listener UEB Listener org.onap.ccsdk.sli.northbound sdnc-northbound - 0.0.1-SNAPSHOT + 0.1.0-SNAPSHOT 1.1.7-SNAPSHOT diff --git a/ueb-listener/src/assembly/assemble_zip.xml b/ueb-listener/src/assembly/assemble_zip.xml index d1f6679e1..97a229d2c 100644 --- a/ueb-listener/src/assembly/assemble_zip.xml +++ b/ueb-listener/src/assembly/assemble_zip.xml @@ -2,8 +2,8 @@ ============LICENSE_START======================================================= openECOMP : SDN-C ================================================================================ - Copyright (C) 2017 ONAP Intellectual Property. All rights - reserved. + Copyright (C) 2017 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. diff --git a/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncARModel.java b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncARModel.java index 3be906181..75b19cd2e 100644 --- a/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncARModel.java +++ b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncARModel.java @@ -2,8 +2,8 @@ * ============LICENSE_START======================================================= * openECOMP : SDN-C * ================================================================================ - * Copyright (C) 2017 ONAP Intellectual Property. All rights - * reserved. + * Copyright (C) 2017 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. diff --git a/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncArtifactMap.java b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncArtifactMap.java index d979a3206..4c08949c0 100644 --- a/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncArtifactMap.java +++ b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncArtifactMap.java @@ -2,8 +2,8 @@ * ============LICENSE_START======================================================= * openECOMP : SDN-C * ================================================================================ - * Copyright (C) 2017 ONAP Intellectual Property. All rights - * reserved. + * Copyright (C) 2017 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. diff --git a/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncBaseModel.java b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncBaseModel.java index 707eee7e4..1b6049278 100644 --- a/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncBaseModel.java +++ b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncBaseModel.java @@ -2,8 +2,8 @@ * ============LICENSE_START======================================================= * openECOMP : SDN-C * ================================================================================ - * Copyright (C) 2017 ONAP Intellectual Property. All rights - * reserved. + * Copyright (C) 2017 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. diff --git a/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncNodeModel.java b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncNodeModel.java index dcf668ed8..2fec84cb1 100644 --- a/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncNodeModel.java +++ b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncNodeModel.java @@ -2,8 +2,8 @@ * ============LICENSE_START======================================================= * openECOMP : SDN-C * ================================================================================ - * Copyright (C) 2017 ONAP Intellectual Property. All rights - * reserved. + * Copyright (C) 2017 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. diff --git a/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncOdlConnection.java b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncOdlConnection.java index 7bee801d2..821057ef3 100644 --- a/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncOdlConnection.java +++ b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncOdlConnection.java @@ -2,8 +2,8 @@ * ============LICENSE_START======================================================= * openECOMP : SDN-C * ================================================================================ - * Copyright (C) 2017 ONAP Intellectual Property. All rights - * reserved. + * Copyright (C) 2017 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. diff --git a/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncServiceModel.java b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncServiceModel.java index 86a4d2a25..3df27be6e 100644 --- a/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncServiceModel.java +++ b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncServiceModel.java @@ -2,8 +2,8 @@ * ============LICENSE_START======================================================= * openECOMP : SDN-C * ================================================================================ - * Copyright (C) 2017 ONAP Intellectual Property. All rights - * reserved. + * Copyright (C) 2017 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. diff --git a/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncUebCallback.java b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncUebCallback.java index fd304208c..1e6b19db0 100644 --- a/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncUebCallback.java +++ b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncUebCallback.java @@ -2,8 +2,8 @@ * ============LICENSE_START======================================================= * openECOMP : SDN-C * ================================================================================ - * Copyright (C) 2017 ONAP Intellectual Property. All rights - * reserved. + * Copyright (C) 2017 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. diff --git a/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncUebClient.java b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncUebClient.java index e8ffc3333..e19646e39 100644 --- a/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncUebClient.java +++ b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncUebClient.java @@ -2,8 +2,8 @@ * ============LICENSE_START======================================================= * openECOMP : SDN-C * ================================================================================ - * Copyright (C) 2017 ONAP Intellectual Property. All rights - * reserved. + * Copyright (C) 2017 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. diff --git a/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncUebConfiguration.java b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncUebConfiguration.java index bf0d5b823..3c561118e 100644 --- a/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncUebConfiguration.java +++ b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncUebConfiguration.java @@ -2,8 +2,8 @@ * ============LICENSE_START======================================================= * openECOMP : SDN-C * ================================================================================ - * Copyright (C) 2017 ONAP Intellectual Property. All rights - * reserved. + * Copyright (C) 2017 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. diff --git a/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncVFCModel.java b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncVFCModel.java index 76f015f9a..55814ac3a 100644 --- a/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncVFCModel.java +++ b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncVFCModel.java @@ -2,8 +2,8 @@ * ============LICENSE_START======================================================= * openECOMP : SDN-C * ================================================================================ - * Copyright (C) 2017 ONAP Intellectual Property. All rights - * reserved. + * Copyright (C) 2017 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. diff --git a/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncVFModel.java b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncVFModel.java index cd79689b4..deed20cf4 100644 --- a/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncVFModel.java +++ b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncVFModel.java @@ -2,8 +2,8 @@ * ============LICENSE_START======================================================= * openECOMP : SDN-C * ================================================================================ - * Copyright (C) 2017 ONAP Intellectual Property. All rights - * reserved. + * Copyright (C) 2017 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. diff --git a/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncVFModuleModel.java b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncVFModuleModel.java index 7ae6c3107..3663c97c3 100644 --- a/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncVFModuleModel.java +++ b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncVFModuleModel.java @@ -2,8 +2,8 @@ * ============LICENSE_START======================================================= * openECOMP : SDN-C * ================================================================================ - * Copyright (C) 2017 ONAP Intellectual Property. All rights - * reserved. + * Copyright (C) 2017 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. diff --git a/ueb-listener/src/main/resources/log4j.properties b/ueb-listener/src/main/resources/log4j.properties index 670e48e11..f2f4ed26b 100644 --- a/ueb-listener/src/main/resources/log4j.properties +++ b/ueb-listener/src/main/resources/log4j.properties @@ -2,8 +2,8 @@ # ============LICENSE_START======================================================= # openECOMP : SDN-C # ================================================================================ -# Copyright (C) 2017 ONAP Intellectual Property. All rights -# reserved. +# Copyright (C) 2017 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. diff --git a/ueb-listener/src/main/scripts/start-ueb-listener.sh b/ueb-listener/src/main/scripts/start-ueb-listener.sh index db00726be..80ede3c8b 100644 --- a/ueb-listener/src/main/scripts/start-ueb-listener.sh +++ b/ueb-listener/src/main/scripts/start-ueb-listener.sh @@ -4,8 +4,8 @@ # ============LICENSE_START======================================================= # openECOMP : SDN-C # ================================================================================ -# Copyright (C) 2017 ONAP Intellectual Property. All rights -# reserved. +# Copyright (C) 2017 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. diff --git a/ueb-listener/src/main/scripts/stop-ueb-listener.sh b/ueb-listener/src/main/scripts/stop-ueb-listener.sh index 2e3b4dd2b..cf110c5cc 100644 --- a/ueb-listener/src/main/scripts/stop-ueb-listener.sh +++ b/ueb-listener/src/main/scripts/stop-ueb-listener.sh @@ -4,8 +4,8 @@ # ============LICENSE_START======================================================= # openECOMP : SDN-C # ================================================================================ -# Copyright (C) 2017 ONAP Intellectual Property. All rights -# reserved. +# Copyright (C) 2017 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. diff --git a/ueb-listener/src/site/apt/index.apt b/ueb-listener/src/site/apt/index.apt index dd9d3ec39..370ddd4db 100644 --- a/ueb-listener/src/site/apt/index.apt +++ b/ueb-listener/src/site/apt/index.apt @@ -2,8 +2,8 @@ ~~ ============LICENSE_START======================================================= ~~ openECOMP : SDN-C ~~ ================================================================================ -~~ Copyright (C) 2017 ONAP Intellectual Property. All rights -~~ reserved. +~~ Copyright (C) 2017 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. diff --git a/ueb-listener/src/site/site.xml b/ueb-listener/src/site/site.xml index 356c9c959..6b97d925e 100644 --- a/ueb-listener/src/site/site.xml +++ b/ueb-listener/src/site/site.xml @@ -3,8 +3,8 @@ ============LICENSE_START======================================================= openECOMP : SDN-C ================================================================================ - Copyright (C) 2017 ONAP Intellectual Property. All rights - reserved. + Copyright (C) 2017 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. -- cgit 1.2.3-korg From ce4a541b00557f52860f16643aff0593178a2a91 Mon Sep 17 00:00:00 2001 From: Brian Freeman Date: Fri, 25 Aug 2017 17:16:00 +0000 Subject: Fix to start script and annotation dependency Change-Id: I38d4ffad440ea5866a398b8a6a7244d8bf156138 Signed-off-by: Brian Freeman Issue-Id: SDNC-67 --- dmaap-listener/pom.xml | 5 +++++ dmaap-listener/src/main/scripts/start-dmaap-listener.sh | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/pom.xml b/dmaap-listener/pom.xml index ac65c16f8..dcdc5ca5a 100755 --- a/dmaap-listener/pom.xml +++ b/dmaap-listener/pom.xml @@ -57,6 +57,11 @@ jackson-databind ${fasterxml.jackson.version} + + com.fasterxml.jackson.core + jackson-annotations + ${fasterxml.jackson.version} + junit junit diff --git a/dmaap-listener/src/main/scripts/start-dmaap-listener.sh b/dmaap-listener/src/main/scripts/start-dmaap-listener.sh index 805105863..164ade332 100644 --- a/dmaap-listener/src/main/scripts/start-dmaap-listener.sh +++ b/dmaap-listener/src/main/scripts/start-dmaap-listener.sh @@ -60,7 +60,7 @@ do LISTENERCLASSPATH=$LISTENERCLASSPATH:$file done -${JAVA} ${JAVA_OPTS} -Dlog4j.configuration=file:${UEBLISTENERROOT}/lib/log4j.properties -cp ${LISTENERCLASSPATH} com.att.sdnctl.dmaapclient.DmaapListener & +${JAVA} ${JAVA_OPTS} -Dlog4j.configuration=file:${UEBLISTENERROOT}/lib/log4j.properties -cp ${LISTENERCLASSPATH} org.onap.ccsdk.sli.northbound.dmaapclient.DmaapListener & echo $! > $PIDFILE -- cgit 1.2.3-korg From ea0aabe54bc7b5d609b587e87ce85765f73fecbc Mon Sep 17 00:00:00 2001 From: Gaurav Agrawal Date: Fri, 8 Sep 2017 19:28:18 +0530 Subject: Fix few Blocker sonar issues Fix few Blocker sonar issues in CCSDK SLI Northbound https://sonar.onap.org/component_issues/index?id=org.onap.ccsdk.sli.northbound%3Accsdk-sli-northbound#resolved=false|severities=BLOCKER Change-Id: I8a2f2e9f3bc5bc5c007076e42f77fbf5da1304ac Issue-Id: CCSDK-67 Signed-off-by: Gaurav Agrawal --- .../northbound/dmaapclient/SdncFlatJsonDmaapConsumer.java | 5 ++--- .../ccsdk/sli/northbound/uebclient/SdncArtifactMap.java | 13 +------------ 2 files changed, 3 insertions(+), 15 deletions(-) (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncFlatJsonDmaapConsumer.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncFlatJsonDmaapConsumer.java index abd395bfb..1754957da 100644 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncFlatJsonDmaapConsumer.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncFlatJsonDmaapConsumer.java @@ -164,10 +164,9 @@ public class SdncFlatJsonDmaapConsumer extends SdncDmaapConsumer { return(null); } - try { - BufferedReader mapReader = new BufferedReader(new FileReader(mapFile)); + try (BufferedReader mapReader = new BufferedReader(new FileReader(mapFile))) { - String curLine = null; + String curLine; while ((curLine = mapReader.readLine()) != null) { curLine = curLine.trim(); diff --git a/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncArtifactMap.java b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncArtifactMap.java index 4c08949c0..dd9437ce9 100644 --- a/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncArtifactMap.java +++ b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncArtifactMap.java @@ -87,10 +87,7 @@ public class SdncArtifactMap { if (mapFile.exists() && mapFile.canRead()) { - BufferedReader rdr = null; - try { - - rdr = new BufferedReader(new FileReader(mapFile)); + try (BufferedReader rdr = new BufferedReader(new FileReader(mapFile))) { for (String ln ; (ln = rdr.readLine()) != null ; ) { String[] lnFields = ln.split(","); @@ -107,14 +104,6 @@ public class SdncArtifactMap { } catch (Exception e) { LOG.error("Caught exception reading artifact map", e); return; - } finally { - if (rdr != null) { - try { - rdr.close(); - } catch (IOException e) { - - } - } } } } -- cgit 1.2.3-korg From bb315ff0cce96b31f8e741b3af0981a011e66095 Mon Sep 17 00:00:00 2001 From: surya-huawei Date: Tue, 19 Sep 2017 15:32:16 +0530 Subject: Fix Sonar Issues few major issues in sli/northbound *Remove unused imports *Iterate over the "entrySet" instead of the "keySet" *Replace the type specification with the diamond operator ("<>") Issue-Id: CCSDK-87 Signed-off-by: surya-huawei Change-Id: Ib2a6f97d3de759b937c1e2acd2e39312e88ad10b --- .../dmaapclient/SdncFlatJsonDmaapConsumer.java | 22 +++++----------------- 1 file changed, 5 insertions(+), 17 deletions(-) (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncFlatJsonDmaapConsumer.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncFlatJsonDmaapConsumer.java index 1754957da..a3d70c8d9 100644 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncFlatJsonDmaapConsumer.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncFlatJsonDmaapConsumer.java @@ -22,24 +22,12 @@ package org.onap.ccsdk.sli.northbound.dmaapclient; import java.io.BufferedReader; -import java.io.DataOutputStream; import java.io.File; import java.io.FileReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.net.Authenticator; -import java.net.HttpURLConnection; -import java.net.PasswordAuthentication; -import java.net.URL; import java.util.HashMap; import java.util.Iterator; import java.util.Map; -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.HttpsURLConnection; -import javax.net.ssl.SSLSession; - -import org.apache.commons.codec.binary.Base64; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -108,14 +96,14 @@ public class SdncFlatJsonDmaapConsumer extends SdncDmaapConsumer { ObjectNode inputNode = oMapper.createObjectNode(); - for (String fromField : fieldMap.keySet()) { + for (Map.Entry entry: fieldMap.entrySet()) { - if (!SDNC_ENDPOINT.equals(fromField)) { - JsonNode curNode = instarRootNode.get(fromField); + if (!SDNC_ENDPOINT.equals(entry.getKey())) { + JsonNode curNode = instarRootNode.get(entry.getKey()); if (curNode != null) { String fromValue = curNode.textValue(); - inputNode.put(fieldMap.get(fromField), fromValue); + inputNode.put(entry.getValue(), fromValue); } } } @@ -141,7 +129,7 @@ public class SdncFlatJsonDmaapConsumer extends SdncDmaapConsumer { } private Map loadMap(String msgType, String mapDirName) { - Map results = new HashMap(); + Map results = new HashMap<>(); if (mapDirName == null) { -- cgit 1.2.3-korg From c0696b9b0ce62d3f10cd46eae8ac5a5ca99d3b1d Mon Sep 17 00:00:00 2001 From: Gaurav Agrawal Date: Tue, 19 Sep 2017 19:06:33 +0530 Subject: Fix critical sonar issues Fix critical sonar issues in CCSDK SLI Northbound by either logging or rethrowing the exception https://sonar.onap.org/component_issues/index?id=org.onap.ccsdk.sli.northbound%3Accsdk-sli-northbound#resolved=false|severities=CRITICAL Change-Id: I718f13b5801ea9d69b5c36f75b5387a0ae59cc6a Issue-Id: CCSDK-67 Signed-off-by: Gaurav Agrawal --- .../java/org/onap/ccsdk/sli/northbound/asdcapi/AsdcApiProvider.java | 3 +-- .../java/org/onap/ccsdk/sli/northbound/dmaapclient/DmaapListener.java | 2 +- .../ccsdk/sli/northbound/dmaapclient/SdncFlatJsonDmaapConsumer.java | 2 +- .../java/org/onap/ccsdk/sli/northbound/uebclient/SdncArtifactMap.java | 2 +- .../org/onap/ccsdk/sli/northbound/uebclient/SdncUebConfiguration.java | 4 ++-- 5 files changed, 6 insertions(+), 7 deletions(-) (limited to 'dmaap-listener/src') diff --git a/asdcApi/provider/src/main/java/org/onap/ccsdk/sli/northbound/asdcapi/AsdcApiProvider.java b/asdcApi/provider/src/main/java/org/onap/ccsdk/sli/northbound/asdcapi/AsdcApiProvider.java index b9c897ec0..cebcb9986 100644 --- a/asdcApi/provider/src/main/java/org/onap/ccsdk/sli/northbound/asdcapi/AsdcApiProvider.java +++ b/asdcApi/provider/src/main/java/org/onap/ccsdk/sli/northbound/asdcapi/AsdcApiProvider.java @@ -157,8 +157,7 @@ public class AsdcApiProvider implements AutoCloseable, ASDCAPIService { LOG.info("Create Containers succeeded!: "); } catch (InterruptedException | ExecutionException e) { - LOG.error("Create Containers Failed: " + e); - e.printStackTrace(); + LOG.error("Create Containers Failed: ", e); } } else { LOG.warn("createContainers : cannot find dataBroker to create containers"); diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/DmaapListener.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/DmaapListener.java index 91afe1d1a..ec34fe402 100644 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/DmaapListener.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/DmaapListener.java @@ -106,7 +106,7 @@ public class DmaapListener { try { consumerClass = Class.forName(consumerClassName); } catch (Exception e) { - LOG.error("Could not find DMaap consumer class " + consumerClassName); + LOG.error("Could not find DMaap consumer class {}", consumerClassName, e); } if (consumerClass != null) { diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncFlatJsonDmaapConsumer.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncFlatJsonDmaapConsumer.java index 1754957da..7196c90a7 100644 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncFlatJsonDmaapConsumer.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncFlatJsonDmaapConsumer.java @@ -135,7 +135,7 @@ public class SdncFlatJsonDmaapConsumer extends SdncDmaapConsumer { LOG.info("POST message body would be:\n"+rpcMsgbody); } } catch (Exception e) { - + LOG.error("Unable to process message", e); } } diff --git a/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncArtifactMap.java b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncArtifactMap.java index dd9437ce9..9b36cb6b3 100644 --- a/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncArtifactMap.java +++ b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncArtifactMap.java @@ -66,7 +66,7 @@ public class SdncArtifactMap { try { this.pass = Integer.parseInt(pass); } catch (Exception e) { - LOG.error("Invalid pass value for artifact map entry ("+tag+","+rpc+","+pass+")"); + LOG.error("Invalid pass value for artifact map entry ({} {} {})", tag, rpc, pass, e); } } } diff --git a/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncUebConfiguration.java b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncUebConfiguration.java index 3c561118e..3ea092d47 100644 --- a/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncUebConfiguration.java +++ b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncUebConfiguration.java @@ -132,7 +132,7 @@ public class SdncUebConfiguration implements IConfiguration{ try { pollingInterval = Integer.parseInt(curval); } catch (Exception e) { - LOG.warn("Illegal value for org.onap.ccsdk.sli.northbound.uebclient.polling-interval ("+curval+")"); + LOG.warn("Illegal value for org.onap.ccsdk.sli.northbound.uebclient.polling-interval ({}) ", curval, e); } } @@ -141,7 +141,7 @@ public class SdncUebConfiguration implements IConfiguration{ try { pollingTimeout = Integer.parseInt(curval); } catch (Exception e) { - LOG.warn("Illegal value for org.onap.ccsdk.sli.northbound.uebclient.polling-timeout ("+curval+")"); + LOG.warn("Illegal value for org.onap.ccsdk.sli.northbound.uebclient.polling-timeout ({}) ", curval, e); } } -- cgit 1.2.3-korg From a74ffcd839da0b212cc2bca502977f225682dc33 Mon Sep 17 00:00:00 2001 From: surya-huawei Date: Wed, 20 Sep 2017 16:18:41 +0530 Subject: Remove useless assigment to local variables *Removed dead stores This is done to avoid waste of resources Issue-Id: CCSDK-87 Change-Id: Ie36255c6583792e2535000ee1bd5b2a3018632ff Signed-off-by: surya-huawei --- .../ccsdk/sli/northbound/dmaapclient/SdncFlatJsonDmaapConsumer.java | 4 ++-- .../org/onap/ccsdk/sli/northbound/uebclient/SdncUebCallback.java | 5 ++--- .../onap/ccsdk/sli/northbound/uebclient/SdncUebConfiguration.java | 2 +- 3 files changed, 5 insertions(+), 6 deletions(-) (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncFlatJsonDmaapConsumer.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncFlatJsonDmaapConsumer.java index aa3f7261a..60a508e51 100644 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncFlatJsonDmaapConsumer.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncFlatJsonDmaapConsumer.java @@ -59,8 +59,8 @@ public class SdncFlatJsonDmaapConsumer extends SdncDmaapConsumer { } ObjectMapper oMapper = new ObjectMapper(); - JsonNode instarRootNode = null; - ObjectNode sdncRootNode = null; + JsonNode instarRootNode ; + ObjectNode sdncRootNode; String instarMsgName = null; diff --git a/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncUebCallback.java b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncUebCallback.java index e7a42bcb8..6a0c8c394 100644 --- a/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncUebCallback.java +++ b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncUebCallback.java @@ -189,7 +189,7 @@ public class SdncUebCallback implements INotificationCallback { private static void setJdbcDataSource() throws IOException { - String propPath = null; + String propPath; String propDir = System.getenv(SDNC_CONFIG_DIR); if (propDir == null) { @@ -1056,8 +1056,7 @@ public class SdncUebCallback implements INotificationCallback { private File applyXslts(File srcFile) { - Document doc = null; - + Document doc; File inFile = srcFile; File outFile = null; diff --git a/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncUebConfiguration.java b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncUebConfiguration.java index 3ea092d47..fdae95d11 100644 --- a/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncUebConfiguration.java +++ b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncUebConfiguration.java @@ -91,7 +91,7 @@ public class SdncUebConfiguration implements IConfiguration{ } public void init() throws IOException { - String propPath = null; + String propPath; String propDir = System.getenv(SDNC_CONFIG_DIR); if (propDir == null) { -- cgit 1.2.3-korg From b5603e3052857610ac4ee677bbe5164af3e8d520 Mon Sep 17 00:00:00 2001 From: surya-huawei Date: Thu, 21 Sep 2017 15:55:14 +0530 Subject: Use Integer.toString for type conversion *Used Integer.toString instead of implicit type conversion This is done to make use of static and reduce cycles *Removed one unused import *Removed unnecessary parantheses Sometimes useless parantheses can be misleading hence removed Issue-Id: CCSDK-87 Change-Id: I23f56cb7c5a6dafa79f64d5cd8faa0994f0ff288 Signed-off-by: surya-huawei --- .../onap/ccsdk/sli/northbound/dmaapclient/SdncOdlConnection.java | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncOdlConnection.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncOdlConnection.java index e31219a23..6aaf41cd9 100644 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncOdlConnection.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncOdlConnection.java @@ -28,7 +28,6 @@ import java.io.InputStreamReader; import java.net.Authenticator; import java.net.HttpURLConnection; import java.net.PasswordAuthentication; -import java.net.ProtocolException; import java.net.URL; import javax.net.ssl.HostnameVerifier; @@ -88,7 +87,7 @@ public class SdncOdlConnection { public static SdncOdlConnection newInstance(String url, String user, String password) throws IOException { - return (new SdncOdlConnection(url, user, password)); + return new SdncOdlConnection(url, user, password); } @@ -121,7 +120,7 @@ public class SdncOdlConnection { } // Write message - httpConn.setRequestProperty("Content-Length", "" + msg.length()); + httpConn.setRequestProperty("Content-Length", Integer.toString(msg.length())); DataOutputStream outStr = new DataOutputStream(httpConn.getOutputStream()); outStr.write(msg.getBytes()); outStr.close(); @@ -151,7 +150,7 @@ public class SdncOdlConnection { LOG.info("Response body :\n" + respString); - return (respString); + return respString; } -- cgit 1.2.3-korg From 40289adf50be8419eda4d5e49d27b86a016312b7 Mon Sep 17 00:00:00 2001 From: Bharat saraswal Date: Thu, 21 Sep 2017 18:25:09 +0530 Subject: Resolved below sonar issues. Method complextity. Redudant code and varibales. Exception handling. Refacting of code. Issue-Id:CCSDK-87 Change-Id: I757c6a6d3c403f81f725ad97a7759225d0709468 Signed-off-by: Bharat saraswal --- .../sli/northbound/dmaapclient/DmaapListener.java | 280 +++++++++++---------- .../northbound/dmaapclient/SdncDmaapConsumer.java | 234 ++++++++--------- .../dmaapclient/SdncFlatJsonDmaapConsumer.java | 211 ++++++++-------- .../northbound/dmaapclient/SdncOdlConnection.java | 225 ++++++++--------- 4 files changed, 475 insertions(+), 475 deletions(-) (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/DmaapListener.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/DmaapListener.java index ec34fe402..de76e454e 100644 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/DmaapListener.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/DmaapListener.java @@ -26,140 +26,156 @@ import java.io.FileInputStream; import java.util.LinkedList; import java.util.List; import java.util.Properties; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DmaapListener { - - private static final String DMAAP_LISTENER_PROPERTIES = "dmaap-listener.properties"; - private static final String SDNC_CONFIG_DIR = "SDNC_CONFIG_DIR"; - private static final Logger LOG = LoggerFactory - .getLogger(DmaapListener.class); - - public static void main(String[] args) { - - Properties properties = new Properties(); - - - String propFileName = DMAAP_LISTENER_PROPERTIES; - - if (args.length > 0) { - propFileName = args[0]; - } - - String propPath = null; - String propDir = System.getenv(SDNC_CONFIG_DIR); - - List consumers = new LinkedList(); - - if (propDir == null) { - - propDir = "/opt/sdnc/data/properties"; - } - - if (!propFileName.startsWith("/")) { - propPath = propDir + "/" + propFileName; - } - - File propFile = new File(propPath); - - if (!propFile.canRead()) { - LOG.error("Cannot read properties file "+propPath); - System.exit(1); - } - - try { - properties.load(new FileInputStream(propFile)); - } catch (Exception e) { - LOG.error("Caught exception loading properties from "+propPath, e); - System.exit(1); - } - - String subscriptionStr = properties.getProperty("subscriptions"); - - boolean threadsRunning = false; - - LOG.debug("Dmaap subscriptions : "+subscriptionStr); - - if (subscriptionStr != null) { - String[] subscriptions = subscriptionStr.split(";"); - - for (int i = 0; i < subscriptions.length; i++) { - String[] subscription = subscriptions[i].split(":"); - String consumerClassName = subscription[0]; - String propertyPath = subscription[1]; - - LOG.debug("Handling subscription [" + consumerClassName + "," + propertyPath + "]"); - - if (propertyPath == null) { - LOG.error("Invalid subscription (" + subscriptions[i] + ") property file missing"); - continue; - } - - if (!propertyPath.startsWith("/")) { - propertyPath = propDir + "/" + propertyPath; - } - - Class consumerClass = null; - - try { - consumerClass = Class.forName(consumerClassName); - } catch (Exception e) { - LOG.error("Could not find DMaap consumer class {}", consumerClassName, e); - } - - if (consumerClass != null) { - - SdncDmaapConsumer consumer = null; - - try { - consumer = (SdncDmaapConsumer) consumerClass.newInstance(); - } catch (Exception e) { - LOG.error("Could not create consumer from class " + consumerClassName, e); - } - - if (consumer != null) { - LOG.debug("Initializing consumer " + consumerClassName + "(" + propertyPath + ")"); - consumer.init(properties, propertyPath); - - if (consumer.isReady()) { - Thread consumerThread = new Thread(consumer); - consumerThread.start(); - consumers.add(consumer); - threadsRunning = true; - LOG.info("Started consumer thread (" + consumerClassName + " : " + propertyPath + ")"); - } else { - LOG.debug("Consumer " + consumerClassName + " is not ready"); - } - } - - } - - } - } - - while (threadsRunning) { - - threadsRunning = false; - for (SdncDmaapConsumer consumer : consumers) { - if (consumer.isRunning()) { - threadsRunning = true; - } - } - - if (!threadsRunning) { - break; - } - - try { - Thread.sleep(10000); - } catch (InterruptedException e) { - - } - } - - LOG.info("No listener threads running - exitting"); - - } + + private static final String DMAAP_LISTENER_PROPERTIES = "dmaap-listener.properties"; + private static final String DMAAP_LISTENER_PROPERTIES_DIR = "/opt/sdnc/data/properties"; + private static final String SDNC_CONFIG_DIR = "SDNC_CONFIG_DIR"; + private static final Logger LOG = LoggerFactory.getLogger(DmaapListener.class); + + public static void main(String[] args) { + + Properties properties = new Properties(); + String propFileName = DMAAP_LISTENER_PROPERTIES; + String propPath = null; + String propDir = System.getenv(SDNC_CONFIG_DIR); + List consumers = new LinkedList<>(); + + if (args.length > 0) { + propFileName = args[0]; + } + + if (propDir == null) { + propDir = DMAAP_LISTENER_PROPERTIES_DIR; + } + + if (!propFileName.startsWith("/")) { + propPath = propDir + "/" + propFileName; + } + + if (propPath != null) { + properties = loadProperties(propPath, properties); + + String subscriptionStr = properties.getProperty("subscriptions"); + + boolean threadsRunning = false; + + LOG.debug("Dmaap subscriptions : " + subscriptionStr); + + if (subscriptionStr != null) { + threadsRunning = handleSubscriptions(subscriptionStr, propDir, properties, consumers); + } + + while (threadsRunning) { + threadsRunning = updateThreadState(consumers); + if (!threadsRunning) { + break; + } + + try { + Thread.sleep(10000); + } catch (InterruptedException e) { + LOG.error(e.getLocalizedMessage(), e); + } + } + + LOG.info("No listener threads running - exiting"); + } + } + + private static boolean updateThreadState(List consumers) { + boolean threadsRunning = false; + for (SdncDmaapConsumer consumer : consumers) { + if (consumer.isRunning()) { + threadsRunning = true; + } + } + return threadsRunning; + } + + private static Properties loadProperties(String propPath, Properties properties) { + File propFile = new File(propPath); + + if (!propFile.canRead()) { + LOG.error("Cannot read properties file " + propPath); + System.exit(1); + } + + try (FileInputStream in = new FileInputStream(propFile)) { + properties.load(in); + } catch (Exception e) { + LOG.error("Caught exception loading properties from " + propPath, e); + System.exit(1); + } + return properties; + } + + private static boolean handleSubscriptions(String subscriptionStr, String propDir, Properties properties, + List consumers) { + String[] subscriptions = subscriptionStr.split(";"); + + for (String subscription1 : subscriptions) { + String[] subscription = subscription1.split(":"); + String consumerClassName = subscription[0]; + String propertyPath = subscription[1]; + + LOG.debug(String.format("Handling subscription [%s,%s]", consumerClassName, propertyPath)); + + if (propertyPath == null) { + LOG.error(String.format("Invalid subscription (%s) property file missing", subscription1)); + continue; + } + + if (!propertyPath.startsWith("/")) { + propertyPath = propDir + "/" + propertyPath; + } + + Class consumerClass = null; + + try { + consumerClass = Class.forName(consumerClassName); + } catch (Exception e) { + LOG.error("Could not find DMaap consumer class {}", consumerClassName, e); + } + + if (consumerClass != null) { + return handleConsumerClass(consumerClass, consumerClassName, propertyPath, + properties, consumers); + } + } + return false; + } + + private static boolean handleConsumerClass(Class consumerClass, String consumerClassName, String propertyPath, + Properties properties, List consumers) { + + SdncDmaapConsumer consumer = null; + + try { + consumer = (SdncDmaapConsumer) consumerClass.newInstance(); + } catch (Exception e) { + LOG.error("Could not create consumer from class " + consumerClassName, e); + } + + if (consumer != null) { + LOG.debug(String.format("Initializing consumer %s(%s)", consumerClassName, propertyPath)); + consumer.init(properties, propertyPath); + + if (consumer.isReady()) { + Thread consumerThread = new Thread(consumer); + consumerThread.start(); + consumers.add(consumer); + + LOG.info(String.format("Started consumer thread (%s : %s)", consumerClassName, + propertyPath)); + return true; + } else { + LOG.debug(String.format("Consumer %s is not ready", consumerClassName)); + } + } + return false; + } } diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncDmaapConsumer.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncDmaapConsumer.java index c1320d6b4..a0c555303 100644 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncDmaapConsumer.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncDmaapConsumer.java @@ -21,126 +21,132 @@ package org.onap.ccsdk.sli.northbound.dmaapclient; +import com.att.nsa.mr.client.MRClientFactory; +import com.att.nsa.mr.client.MRConsumer; +import com.att.nsa.mr.client.response.MRConsumerResponse; import java.io.File; import java.io.FileInputStream; import java.util.Properties; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.att.nsa.mr.client.MRClientFactory; -import com.att.nsa.mr.client.MRConsumer; -import com.att.nsa.mr.client.response.MRConsumerResponse; - public abstract class SdncDmaapConsumer implements Runnable { - private static final Logger LOG = LoggerFactory - .getLogger(SdncDmaapConsumer.class); - - private String propertiesPath = ""; - private Properties properties = null; - MRConsumer consumer = null; - MRConsumerResponse consumerResponse = null; - boolean running = false; - boolean ready = false; - int fetchPause = 5000; // Default pause between fetchs - 5 seconds - - public boolean isReady() { - return ready; - } - - int timeout = 15000; // Default timeout - 15 seconds - - public boolean isRunning() { - return running; - } - - public SdncDmaapConsumer() { - - } - - public SdncDmaapConsumer(Properties properties, String propertiesPath) { - init(properties, propertiesPath); - } - - public String getProperty(String name) { - return(properties.getProperty(name, "")); - } - - public void init(Properties properties, String propertiesPath) { - - this.propertiesPath = propertiesPath; - - try { - - this.properties = (Properties) properties.clone(); - - this.properties.load(new FileInputStream(new File(propertiesPath))); - - String timeoutStr = properties.getProperty("timeout"); - - if ((timeoutStr != null) && (timeoutStr.length() > 0)) { - try { - timeout = Integer.parseInt(timeoutStr); - } catch (NumberFormatException e) { - LOG.error("Non-numeric value specified for timeout ("+timeoutStr+")"); - } - } - - String fetchPauseStr = properties.getProperty("fetchPause"); - if ((fetchPauseStr != null) && (fetchPauseStr.length() > 0)) { - try { - fetchPause = Integer.parseInt(fetchPauseStr); - } catch (NumberFormatException e) { - LOG.error("Non-numeric valud specified for fetchPause ("+fetchPauseStr+")"); - } - } - - this.consumer = MRClientFactory.createConsumer(propertiesPath); - ready = true; - } catch (Exception e) { - LOG.error("Error initializing DMaaP consumer from file "+propertiesPath, e); - } - } - - - @Override - public void run() { - if (ready) { - - running = true; - - while (running) { - - try { - boolean noData = true; - consumerResponse = consumer.fetchWithReturnConsumerResponse(timeout, -1); - for (String msg : consumerResponse.getActualMessages()) { - noData = false; - LOG.info("Received message from DMaaP:\n"+msg); - processMsg(msg); - } - - if (noData) { - if (fetchPause > 0) { - - LOG.info("No data received from fetch. Pausing "+fetchPause+" ms before retry"); - Thread.sleep(fetchPause); - } else { - - LOG.info("No data received from fetch. No fetch pause specified - retrying immediately"); - } - } - } catch (Exception e) { - LOG.error("Caught exception reading from DMaaP", e); - running = false; - } - - - } - } - - } - - abstract public void processMsg(String msg) throws InvalidMessageException; + private static final Logger LOG = LoggerFactory + .getLogger(SdncDmaapConsumer.class); + + private String propertiesPath = ""; + private Properties properties = null; + private MRConsumer consumer = null; + private MRConsumerResponse consumerResponse = null; + private boolean running = false; + private boolean ready = false; + private int fetchPause = 5000; // Default pause between fetch - 5 seconds + private int timeout = 15000; // Default timeout - 15 seconds + + public boolean isReady() { + return ready; + } + + + public boolean isRunning() { + return running; + } + + public SdncDmaapConsumer() { + + } + + public SdncDmaapConsumer(Properties properties, String propertiesPath) { + init(properties, propertiesPath); + } + + public String getProperty(String name) { + return (properties.getProperty(name, "")); + } + + public void init(Properties properties, String propertiesPath) { + + this.propertiesPath = propertiesPath; + + try (FileInputStream in = new FileInputStream(new File(propertiesPath))) { + + this.properties = (Properties) properties.clone(); + this.properties.load(in); + + String timeoutStr = properties.getProperty("timeout"); + + if ((timeoutStr != null) && (timeoutStr.length() > 0)) { + timeout = parseTimeOutValue(timeoutStr); + } + + String fetchPauseStr = properties.getProperty("fetchPause"); + if ((fetchPauseStr != null) && (fetchPauseStr.length() > 0)) { + fetchPause = parseFetchPause(fetchPauseStr); + } + + this.consumer = MRClientFactory.createConsumer(propertiesPath); + ready = true; + } catch (Exception e) { + LOG.error("Error initializing DMaaP consumer from file " + propertiesPath, e); + } + } + + private int parseTimeOutValue(String timeoutStr) { + try { + return Integer.parseInt(timeoutStr); + } catch (NumberFormatException e) { + LOG.error("Non-numeric value specified for timeout (" + timeoutStr + ")"); + } + return timeout; + } + + private int parseFetchPause(String fetchPauseStr) { + try { + return Integer.parseInt(fetchPauseStr); + } catch (NumberFormatException e) { + LOG.error("Non-numeric value specified for fetchPause (" + fetchPauseStr + ")"); + } + return fetchPause; + } + + + @Override + public void run() { + if (ready) { + + running = true; + + while (running) { + + try { + boolean noData = true; + consumerResponse = consumer.fetchWithReturnConsumerResponse(timeout, -1); + for (String msg : consumerResponse.getActualMessages()) { + noData = false; + LOG.info("Received message from DMaaP:\n" + msg); + processMsg(msg); + } + + if (noData) { + pauseThread(); + } + } catch (Exception e) { + LOG.error("Caught exception reading from DMaaP", e); + running = false; + } + } + } + } + + private void pauseThread() throws InterruptedException { + if (fetchPause > 0) { + LOG.info(String.format("No data received from fetch. Pausing %d ms before retry", fetchPause)); + Thread.sleep(fetchPause); + } else { + LOG.info("No data received from fetch. No fetch pause specified - retrying immediately"); + } + } + + abstract public void processMsg(String msg) throws InvalidMessageException; } diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncFlatJsonDmaapConsumer.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncFlatJsonDmaapConsumer.java index 60a508e51..1d499a1e7 100644 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncFlatJsonDmaapConsumer.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncFlatJsonDmaapConsumer.java @@ -21,163 +21,148 @@ package org.onap.ccsdk.sli.northbound.dmaapclient; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.HashMap; import java.util.Iterator; import java.util.Map; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ObjectNode; - public class SdncFlatJsonDmaapConsumer extends SdncDmaapConsumer { - private static final Logger LOG = LoggerFactory - .getLogger(SdncFlatJsonDmaapConsumer.class); - - private static final String DMAAPLISTENERROOT = "DMAAPLISTENERROOT"; - private static final String SDNC_ENDPOINT = "SDNC.endpoint"; - - - - @Override - public void processMsg(String msg) throws InvalidMessageException { - - processMsg(msg, null); - } - - public void processMsg(String msg, String mapDirName) throws InvalidMessageException { - - if (msg == null) { - throw new InvalidMessageException("Null message"); - } - - ObjectMapper oMapper = new ObjectMapper(); - JsonNode instarRootNode ; - ObjectNode sdncRootNode; - - String instarMsgName = null; - - try { - instarRootNode = oMapper.readTree(msg); - } catch (Exception e) { - throw new InvalidMessageException("Cannot parse json object", e); - } + private static final Logger LOG = LoggerFactory.getLogger(SdncFlatJsonDmaapConsumer.class); - Iterator> instarFields = instarRootNode.fields(); + private static final String DMAAPLISTENERROOT = "DMAAPLISTENERROOT"; + private static final String SDNC_ENDPOINT = "SDNC.endpoint"; - while (instarFields.hasNext()) { - Map.Entry entry = instarFields.next(); + @Override + public void processMsg(String msg) throws InvalidMessageException { - instarMsgName = entry.getKey(); - instarRootNode = entry.getValue(); - break; - } + processMsg(msg, null); + } - Map fieldMap = loadMap(instarMsgName, mapDirName); + public void processMsg(String msg, String mapDirName) throws InvalidMessageException { - if (fieldMap == null) { - throw new InvalidMessageException("Unable to process message - cannot load field mappings"); - } + if (msg == null) { + throw new InvalidMessageException("Null message"); + } - if (!fieldMap.containsKey(SDNC_ENDPOINT)) { - throw new InvalidMessageException("No SDNC endpoint known for message "+instarMsgName); - } + ObjectMapper oMapper = new ObjectMapper(); + JsonNode instarRootNode; + ObjectNode sdncRootNode; - String sdncEndpoint = fieldMap.get(SDNC_ENDPOINT); + String instarMsgName = null; - sdncRootNode = oMapper.createObjectNode(); - ObjectNode inputNode = oMapper.createObjectNode(); + try { + instarRootNode = oMapper.readTree(msg); + } catch (Exception e) { + throw new InvalidMessageException("Cannot parse json object", e); + } + Iterator> instarFields = instarRootNode.fields(); - for (Map.Entry entry: fieldMap.entrySet()) { + while (instarFields.hasNext()) { + Map.Entry entry = instarFields.next(); - if (!SDNC_ENDPOINT.equals(entry.getKey())) { - JsonNode curNode = instarRootNode.get(entry.getKey()); - if (curNode != null) { - String fromValue = curNode.textValue(); + instarMsgName = entry.getKey(); + instarRootNode = entry.getValue(); + break; + } - inputNode.put(entry.getValue(), fromValue); - } - } - } - sdncRootNode.put("input", inputNode); + Map fieldMap = loadMap(instarMsgName, mapDirName); - try { - String rpcMsgbody = oMapper.writeValueAsString(sdncRootNode); - String odlUrlBase = getProperty("sdnc.odl.url-base"); - String odlUser = getProperty("sdnc.odl.user"); - String odlPassword = getProperty("sdnc.odl.password"); + if (fieldMap == null) { + throw new InvalidMessageException("Unable to process message - cannot load field mappings"); + } - if ((odlUrlBase != null) && (odlUrlBase.length() > 0)) { - SdncOdlConnection conn = SdncOdlConnection.newInstance(odlUrlBase + sdncEndpoint, odlUser, odlPassword); + if (!fieldMap.containsKey(SDNC_ENDPOINT)) { + throw new InvalidMessageException("No SDNC endpoint known for message " + instarMsgName); + } - conn.send("POST", "application/json", rpcMsgbody); - } else { - LOG.info("POST message body would be:\n"+rpcMsgbody); - } - } catch (Exception e) { - LOG.error("Unable to process message", e); - } + String sdncEndpoint = fieldMap.get(SDNC_ENDPOINT); - } + sdncRootNode = oMapper.createObjectNode(); + ObjectNode inputNode = oMapper.createObjectNode(); - private Map loadMap(String msgType, String mapDirName) { - Map results = new HashMap<>(); + for (Map.Entry entry : fieldMap.entrySet()) { + if (!SDNC_ENDPOINT.equals(entry.getKey())) { + JsonNode curNode = instarRootNode.get(entry.getKey()); + if (curNode != null) { + String fromValue = curNode.textValue(); - if (mapDirName == null) { - String rootdir = System.getenv(DMAAPLISTENERROOT); + inputNode.put(entry.getValue(), fromValue); + } + } + } + sdncRootNode.put("input", inputNode); - if ((rootdir == null) || (rootdir.length() == 0)) { - rootdir = "/opt/app/dmaap-listener"; - } + try { + String rpcMsgbody = oMapper.writeValueAsString(sdncRootNode); + String odlUrlBase = getProperty("sdnc.odl.url-base"); + String odlUser = getProperty("sdnc.odl.user"); + String odlPassword = getProperty("sdnc.odl.password"); - mapDirName = rootdir + "/lib"; + if ((odlUrlBase != null) && (odlUrlBase.length() > 0)) { + SdncOdlConnection conn = SdncOdlConnection.newInstance(odlUrlBase + sdncEndpoint, odlUser, odlPassword); - } + conn.send("POST", "application/json", rpcMsgbody); + } else { + LOG.info("POST message body would be:\n" + rpcMsgbody); + } + } catch (Exception e) { + LOG.error("Unable to process message", e); + } + } - String mapFilename = mapDirName + "/" + msgType + ".map"; + private Map loadMap(String msgType, String mapDirName) { + Map results = new HashMap<>(); - File mapFile = new File(mapFilename); + if (mapDirName == null) { + String rootdir = System.getenv(DMAAPLISTENERROOT); - if (!mapFile.canRead()) { - LOG.error("Cannot read map file ("+mapFilename+")"); - return(null); - } + if ((rootdir == null) || (rootdir.length() == 0)) { + rootdir = "/opt/app/dmaap-listener"; + } - try (BufferedReader mapReader = new BufferedReader(new FileReader(mapFile))) { + mapDirName = rootdir + "/lib"; + } - String curLine; + String mapFilename = mapDirName + "/" + msgType + ".map"; - while ((curLine = mapReader.readLine()) != null) { - curLine = curLine.trim(); + File mapFile = new File(mapFilename); - if ((curLine.length() > 0) && (!curLine.startsWith("#"))) { + if (!mapFile.canRead()) { + LOG.error(String.format("Cannot read map file (%s)", mapFilename)); + return (null); + } - if (curLine.contains("=>")) { - String[] entry = curLine.split("=>"); - if (entry.length == 2) { - results.put(entry[0].trim(), entry[1].trim()); - } - } - } - } - mapReader.close(); - } catch (Exception e) { - LOG.error("Caught exception reading map "+mapFilename, e); - return(null); - } + try (BufferedReader mapReader = new BufferedReader(new FileReader(mapFile))) { - return(results); - } + String curLine; + while ((curLine = mapReader.readLine()) != null) { + curLine = curLine.trim(); + if ((curLine.length() > 0) && (!curLine.startsWith("#")) && curLine.contains("=>")) { + String[] entry = curLine.split("=>"); + if (entry.length == 2) { + results.put(entry[0].trim(), entry[1].trim()); + } + } + } + mapReader.close(); + } catch (Exception e) { + LOG.error("Caught exception reading map " + mapFilename, e); + return (null); + } + return (results); + } } diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncOdlConnection.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncOdlConnection.java index 6aaf41cd9..f88f7bf8c 100644 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncOdlConnection.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncOdlConnection.java @@ -29,130 +29,123 @@ import java.net.Authenticator; import java.net.HttpURLConnection; import java.net.PasswordAuthentication; import java.net.URL; - import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLSession; - import org.apache.commons.codec.binary.Base64; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SdncOdlConnection { - - private static final Logger LOG = LoggerFactory - .getLogger(SdncOdlConnection.class); - - private HttpURLConnection httpConn = null; - - private String url = null; - private String user = null; - private String password = null; - - private class SdncAuthenticator extends Authenticator { - - private String user; - private String passwd; - - SdncAuthenticator(String user, String passwd) { - this.user = user; - this.passwd = passwd; - } - @Override - protected PasswordAuthentication getPasswordAuthentication() { - return new PasswordAuthentication(user, passwd.toCharArray()); - } - - } - - private SdncOdlConnection() { - - } - - private SdncOdlConnection(String url, String user, String password) { - this.url = url; - this.user = user; - this.password = password; - - try { - URL sdncUrl = new URL(url); - Authenticator.setDefault(new SdncAuthenticator(user, password)); - - this.httpConn = (HttpURLConnection) sdncUrl.openConnection(); - } catch (Exception e) { - LOG.error("Unable to create http connection", e); - } - } - - public static SdncOdlConnection newInstance(String url, String user, String password) throws IOException - { - return new SdncOdlConnection(url, user, password); - } - - - - public String send(String method, String contentType, String msg) throws IOException { - - LOG.info("Sending REST " + method + " to " + url); - LOG.info("Message body:\n" + msg); - String authStr = user + ":" + password; - String encodedAuthStr = new String(Base64.encodeBase64(authStr.getBytes())); - - httpConn.addRequestProperty("Authentication", "Basic " + encodedAuthStr); - - httpConn.setRequestMethod(method); - httpConn.setRequestProperty("Content-Type", contentType); - httpConn.setRequestProperty("Accept", contentType); - - httpConn.setDoInput(true); - httpConn.setDoOutput(true); - httpConn.setUseCaches(false); - - if (httpConn instanceof HttpsURLConnection) { - HostnameVerifier hostnameVerifier = new HostnameVerifier() { - @Override - public boolean verify(String hostname, SSLSession session) { - return true; - } - }; - ((HttpsURLConnection) httpConn).setHostnameVerifier(hostnameVerifier); - } - - // Write message - httpConn.setRequestProperty("Content-Length", Integer.toString(msg.length())); - DataOutputStream outStr = new DataOutputStream(httpConn.getOutputStream()); - outStr.write(msg.getBytes()); - outStr.close(); - - // Read response - BufferedReader respRdr; - - LOG.info("Response: " + httpConn.getResponseCode() + " " + httpConn.getResponseMessage()); - - if (httpConn.getResponseCode() < 300) { - - respRdr = new BufferedReader(new InputStreamReader(httpConn.getInputStream())); - } else { - respRdr = new BufferedReader(new InputStreamReader(httpConn.getErrorStream())); - } - - StringBuffer respBuff = new StringBuffer(); - - String respLn; - - while ((respLn = respRdr.readLine()) != null) { - respBuff.append(respLn + "\n"); - } - respRdr.close(); - - String respString = respBuff.toString(); - - LOG.info("Response body :\n" + respString); - - return respString; - - } - + private static final Logger LOG = LoggerFactory + .getLogger(SdncOdlConnection.class); + + private HttpURLConnection httpConn = null; + + private String url = null; + private String user = null; + private String password = null; + + private class SdncAuthenticator extends Authenticator { + + private String user; + private String passwd; + + SdncAuthenticator(String user, String passwd) { + this.user = user; + this.passwd = passwd; + } + + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(user, passwd.toCharArray()); + } + } + + private SdncOdlConnection() { + + } + + private SdncOdlConnection(String url, String user, String password) { + this.url = url; + this.user = user; + this.password = password; + + try { + URL sdncUrl = new URL(url); + Authenticator.setDefault(new SdncAuthenticator(user, password)); + + this.httpConn = (HttpURLConnection) sdncUrl.openConnection(); + } catch (Exception e) { + LOG.error("Unable to create http connection", e); + } + } + + public static SdncOdlConnection newInstance(String url, String user, String password) throws IOException { + return new SdncOdlConnection(url, user, password); + } + + + public String send(String method, String contentType, String msg) throws IOException { + + LOG.info(String.format("Sending REST %s to %s", method, url)); + LOG.info(String.format("Message body:%n%s", msg)); + String authStr = user + ":" + password; + String encodedAuthStr = new String(Base64.encodeBase64(authStr.getBytes())); + + httpConn.addRequestProperty("Authentication", "Basic " + encodedAuthStr); + + httpConn.setRequestMethod(method); + httpConn.setRequestProperty("Content-Type", contentType); + httpConn.setRequestProperty("Accept", contentType); + + httpConn.setDoInput(true); + httpConn.setDoOutput(true); + httpConn.setUseCaches(false); + + if (httpConn instanceof HttpsURLConnection) { + HostnameVerifier hostnameVerifier = new HostnameVerifier() { + @Override + public boolean verify(String hostname, SSLSession session) { + return true; + } + }; + ((HttpsURLConnection) httpConn).setHostnameVerifier(hostnameVerifier); + } + + // Write message + httpConn.setRequestProperty("Content-Length", Integer.toString(msg.length())); + DataOutputStream outStr = new DataOutputStream(httpConn.getOutputStream()); + outStr.write(msg.getBytes()); + outStr.close(); + + // Read response + BufferedReader respRdr; + + LOG.info("Response: " + httpConn.getResponseCode() + " " + httpConn.getResponseMessage()); + + if (httpConn.getResponseCode() < 300) { + + respRdr = new BufferedReader(new InputStreamReader(httpConn.getInputStream())); + } else { + respRdr = new BufferedReader(new InputStreamReader(httpConn.getErrorStream())); + } + + StringBuilder respBuff = new StringBuilder(); + + String respLn; + + while ((respLn = respRdr.readLine()) != null) { + respBuff.append(respLn).append("\n"); + } + respRdr.close(); + + String respString = respBuff.toString(); + + LOG.info(String.format("Response body :%n%s", respString)); + + return respString; + } } -- cgit 1.2.3-korg From 12d893efa353bc5bd5054cd59998a623f5d058d0 Mon Sep 17 00:00:00 2001 From: Dan Timoney Date: Tue, 3 Oct 2017 07:34:22 -0400 Subject: Add unit test for dmaap-listener Add unit test case for dmaap-listener. Change-Id: I501614016c96d8300bc15cdf1819691f95c467f4 Issue-ID: CCSDK-106 Signed-off-by: Dan Timoney --- .../sli/northbound/dmaapclient/DmaapListener.java | 8 ++-- .../northbound/dmaapclient/TestDmaapListener.java | 52 ++++++++++++++++++++++ .../src/test/resources/dmaap-consumer-1.properties | 35 +++++++++++++++ .../resources/dmaap-listener.preferredRoute.txt | 1 + .../src/test/resources/dmaap-listener.properties | 1 + 5 files changed, 93 insertions(+), 4 deletions(-) create mode 100644 dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestDmaapListener.java create mode 100755 dmaap-listener/src/test/resources/dmaap-consumer-1.properties create mode 100755 dmaap-listener/src/test/resources/dmaap-listener.preferredRoute.txt create mode 100755 dmaap-listener/src/test/resources/dmaap-listener.properties (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/DmaapListener.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/DmaapListener.java index de76e454e..ce099cd64 100644 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/DmaapListener.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/DmaapListener.java @@ -8,9 +8,9 @@ * 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. @@ -96,7 +96,7 @@ public class DmaapListener { return threadsRunning; } - private static Properties loadProperties(String propPath, Properties properties) { + static Properties loadProperties(String propPath, Properties properties) { File propFile = new File(propPath); if (!propFile.canRead()) { @@ -113,7 +113,7 @@ public class DmaapListener { return properties; } - private static boolean handleSubscriptions(String subscriptionStr, String propDir, Properties properties, + static boolean handleSubscriptions(String subscriptionStr, String propDir, Properties properties, List consumers) { String[] subscriptions = subscriptionStr.split(";"); diff --git a/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestDmaapListener.java b/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestDmaapListener.java new file mode 100644 index 000000000..943ef0204 --- /dev/null +++ b/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestDmaapListener.java @@ -0,0 +1,52 @@ +package org.onap.ccsdk.sli.northbound.dmaapclient; + +import static org.junit.Assert.*; + +import java.util.LinkedList; +import java.util.List; +import java.util.Properties; + +import org.junit.Before; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class TestDmaapListener { + + private static final String DMAAP_LISTENER_PROPERTIES = "dmaap-listener.properties"; + private static final String DMAAP_LISTENER_PROPERTIES_DIR = "src/test/resources"; + + private static final Logger LOG = LoggerFactory.getLogger(TestDmaapListener.class); + + @Before + public void setUp() throws Exception { + } + + @Test + public void test() { + Properties properties = new Properties(); + String propFileName = DMAAP_LISTENER_PROPERTIES; + String propPath = null; + String propDir = DMAAP_LISTENER_PROPERTIES_DIR; + + List consumers = new LinkedList<>(); + + + propPath = propDir + "/" + propFileName; + + if (propPath != null) { + properties = DmaapListener.loadProperties(propPath, properties); + + String subscriptionStr = properties.getProperty("subscriptions"); + + boolean threadsRunning = false; + + LOG.debug("Dmaap subscriptions : " + subscriptionStr); + + if (subscriptionStr != null) { + threadsRunning = DmaapListener.handleSubscriptions(subscriptionStr, propDir, properties, consumers); + } + } + } + +} diff --git a/dmaap-listener/src/test/resources/dmaap-consumer-1.properties b/dmaap-listener/src/test/resources/dmaap-consumer-1.properties new file mode 100755 index 000000000..ae83ef8c2 --- /dev/null +++ b/dmaap-listener/src/test/resources/dmaap-consumer-1.properties @@ -0,0 +1,35 @@ +TransportType=HTTPAAF +Latitude =40.397443 +Longitude =-74.135602 +Version =1.0 +ServiceName =localhost/events +Environment =DEV +Partner = +SubContextPath =/ +Protocol =http +MethodType =GET +username =test +password =test +contenttype =application/json +authKey=ABC123 +authDate=2016-05-10T13:13:50-0700 +host=localhost:3904 +topic=ccsdk-topic +group=ccsdk-unittest +id=ccsdk_unittest +timeout=15000 +limit=1000 +filter= +AFT_DME2_EXCHANGE_REQUEST_HANDLERS=com.att.nsa.test.PreferredRouteRequestHandler +AFT_DME2_EXCHANGE_REPLY_HANDLERS=com.att.nsa.test.PreferredRouteReplyHandler +AFT_DME2_REQ_TRACE_ON=true +AFT_ENVIRONMENT=AFTUAT +AFT_DME2_EP_CONN_TIMEOUT=15000 +AFT_DME2_ROUNDTRIP_TIMEOUT_MS=240000 +AFT_DME2_EP_READ_TIMEOUT_MS=50000 +sessionstickinessrequired=NO +DME2preferredRouterFilePath=src/test/resources/dmaap-listener.preferredRoute.txt +sdnc.odl.user=admin +sdnc.odl.password=admin +sdnc.odl.url-base=http://localhost:8282/restconf/operations + diff --git a/dmaap-listener/src/test/resources/dmaap-listener.preferredRoute.txt b/dmaap-listener/src/test/resources/dmaap-listener.preferredRoute.txt new file mode 100755 index 000000000..88705f73b --- /dev/null +++ b/dmaap-listener/src/test/resources/dmaap-listener.preferredRoute.txt @@ -0,0 +1 @@ +preferredRouteKey=ABC123 \ No newline at end of file diff --git a/dmaap-listener/src/test/resources/dmaap-listener.properties b/dmaap-listener/src/test/resources/dmaap-listener.properties new file mode 100755 index 000000000..ed180e515 --- /dev/null +++ b/dmaap-listener/src/test/resources/dmaap-listener.properties @@ -0,0 +1 @@ +subscriptions=org.onap.ccsdk.sli.northbound.dmaapclient.DummyDmaapConsumer:dmaap-consumer-1.properties \ No newline at end of file -- cgit 1.2.3-korg From 905f1d2016e8bc4d02a801017a31b20c4eb2119e Mon Sep 17 00:00:00 2001 From: surya-huawei Date: Thu, 5 Oct 2017 15:20:33 +0530 Subject: Add a test for SdncJsonDmaapConsumer *Add a unit test in sli/northbound module This Test checks whether an InvalidMessageException is thrown when null is passed to processMsg method Issue-Id: CCSDK-106 Change-Id: I52327377f4582d8c24cef87f0360b977f2f216fc Signed-off-by: surya-huawei --- .../dmaapclient/TestSdncJsonDmaapConsumer.java | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestSdncJsonDmaapConsumer.java (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestSdncJsonDmaapConsumer.java b/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestSdncJsonDmaapConsumer.java new file mode 100644 index 000000000..0d65231da --- /dev/null +++ b/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestSdncJsonDmaapConsumer.java @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2017. Lorem ipsum dolor sit amet, consectetur adipiscing elit. + * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan. + * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna. + * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus. + * Vestibulum commodo. Ut rhoncus gravida arcu. + */ + +package org.onap.ccsdk.sli.northbound.dmaapclient; + +import org.junit.Test; + +public class TestSdncJsonDmaapConsumer { + private static final String DMAAP_LISTENER_PROPERTIES = "dmaap-listener.properties"; + private static final String DMAAP_LISTENER_PROPERTIES_DIR = "src/test/resources"; + + @Test(expected = InvalidMessageException.class) + public void testProcessMsg_shouldThrowException() throws Exception { + SdncFlatJsonDmaapConsumer consumer = new SdncFlatJsonDmaapConsumer(); + consumer.processMsg(null); + } +} -- cgit 1.2.3-korg From 1aab3d043fca73edbdb5da1972a947d92ce85a77 Mon Sep 17 00:00:00 2001 From: surya-huawei Date: Thu, 5 Oct 2017 15:49:13 +0530 Subject: Add a test for DummyDmaapConsumer *Add a unit test in sli/northbound module This is to improve code coverage of DummyDmaapConsumer class Issue-Id: CCSDK-106 Change-Id: Iecd4970a0cd82c94a219b1a2e861fcc3da11f23c Signed-off-by: surya-huawei --- .../dmaapclient/TestDummyDmaapConsumer.java | 26 ++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestDummyDmaapConsumer.java (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestDummyDmaapConsumer.java b/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestDummyDmaapConsumer.java new file mode 100644 index 000000000..47330c622 --- /dev/null +++ b/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestDummyDmaapConsumer.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2017. Lorem ipsum dolor sit amet, consectetur adipiscing elit. + * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan. + * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna. + * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus. + * Vestibulum commodo. Ut rhoncus gravida arcu. + */ + +package org.onap.ccsdk.sli.northbound.dmaapclient; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class TestDummyDmaapConsumer { + private static final String DMAAP_LISTENER_PROPERTIES = "dmaap-listener.properties"; + private static final String DMAAP_LISTENER_PROPERTIES_DIR = "src/test/resources"; + + DummyDmaapConsumer consumer = new DummyDmaapConsumer(); + + @Test + public void testProcessMsg(){ + consumer.processMsg(null); + } + +} -- cgit 1.2.3-korg From 806de96eefaaf8ad6685a2c24b7dea03eb629ba2 Mon Sep 17 00:00:00 2001 From: surya-huawei Date: Thu, 12 Oct 2017 12:17:55 +0530 Subject: Remove IOException in method declaration *This is done because IOException cannot be thrown from the method and is hence superflous Issue-Id: CCSDK-117 Change-Id: I0712cfbf610f815e76ed33b0039ecb5e3cc7bbbe Signed-off-by: surya-huawei --- .../org/onap/ccsdk/sli/northbound/dmaapclient/SdncOdlConnection.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncOdlConnection.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncOdlConnection.java index f88f7bf8c..6eeef9b48 100644 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncOdlConnection.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncOdlConnection.java @@ -83,7 +83,7 @@ public class SdncOdlConnection { } } - public static SdncOdlConnection newInstance(String url, String user, String password) throws IOException { + public static SdncOdlConnection newInstance(String url, String user, String password) { return new SdncOdlConnection(url, user, password); } -- cgit 1.2.3-korg From 292cce64a1a610283306a5f2280c787d8edb916d Mon Sep 17 00:00:00 2001 From: Dan Timoney Date: Thu, 9 Nov 2017 15:18:24 -0500 Subject: Add dhcp event handler Add event handler for DHCP event Change-Id: I2e23ace8ae481bf100f236a4e2723d721eec3470 Issue-ID: CCSDK-142 Signed-off-by: Dan Timoney --- dmaap-listener/pom.xml | 9 +- .../dmaapclient/SdncDhcpEventConsumer.java | 136 +++++++++++++++++++++ .../dmaapclient/TestSdncDhcpEventConsumer.java | 130 ++++++++++++++++++++ dmaap-listener/src/test/resources/dblib.properties | 38 ++++++ 4 files changed, 312 insertions(+), 1 deletion(-) create mode 100644 dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncDhcpEventConsumer.java create mode 100644 dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestSdncDhcpEventConsumer.java create mode 100644 dmaap-listener/src/test/resources/dblib.properties (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/pom.xml b/dmaap-listener/pom.xml index 6746cdd89..d1e173ca0 100755 --- a/dmaap-listener/pom.xml +++ b/dmaap-listener/pom.xml @@ -34,7 +34,7 @@ org.slf4j slf4j-api - 1.7.10 + 1.7.21 org.slf4j @@ -68,6 +68,13 @@ ${junit.version} test + + ch.vorburger.mariaDB4j + mariaDB4j + 2.2.3 + test + + org.onap.ccsdk.sli.core dblib-provider diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncDhcpEventConsumer.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncDhcpEventConsumer.java new file mode 100644 index 000000000..666ed68e1 --- /dev/null +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncDhcpEventConsumer.java @@ -0,0 +1,136 @@ +package org.onap.ccsdk.sli.northbound.dmaapclient; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.sql.SQLException; +import java.util.Iterator; +import java.util.Map; +import java.util.Properties; + +import org.onap.ccsdk.sli.core.dblib.DBResourceManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; + +public class SdncDhcpEventConsumer extends SdncDmaapConsumer { + private static final Logger LOG = LoggerFactory.getLogger(SdncDhcpEventConsumer.class); + + private static final String MAC_ADDR_TAG = "macaddr"; + private static final String MSG_NAME_TAG = "msg_name"; + private static final String IP_ADDR_TAG = "yiaddr"; + + private static DBResourceManager jdbcDataSource = null; + private static final String SDNC_CONFIG_DIR = "SDNC_CONFIG_DIR"; + + private class MissingDhcpAttributeException extends InvalidMessageException { + + public MissingDhcpAttributeException(String fieldName) { + super("Invalid DHCP event - missing " + fieldName + " attribute"); + } + } + + private static void setJdbcDataSource() throws IOException { + + String propPath; + String propDir = System.getenv(SDNC_CONFIG_DIR); + if (propDir == null) { + propDir = "/opt/onap/sdnc/data/properties"; + } + propPath = propDir + "/dblib.properties"; + File propFile = new File(propPath); + + if (!propFile.exists()) { + + throw new FileNotFoundException("Missing configuration properties file : " + propFile); + } + + Properties props = new Properties(); + props.load(new FileInputStream(propFile)); + + setJdbcDataSource(new DBResourceManager(props)); + + } + + static void setJdbcDataSource(DBResourceManager dbMgr) { + + jdbcDataSource = dbMgr; + + if (jdbcDataSource.isActive()) { + LOG.warn("DBLIB: JDBC DataSource has been initialized."); + } else { + LOG.warn("DBLIB: JDBC DataSource did not initialize successfully."); + } + } + + @Override + public void processMsg(String msg) throws InvalidMessageException { + if (msg == null) { + throw new InvalidMessageException("Null message"); + } + + ObjectMapper oMapper = new ObjectMapper(); + + JsonNode dhcpRootNode; + String msgName; + String macAddr; + String ipAddr; + + try { + dhcpRootNode = oMapper.readTree(msg); + + } catch (IOException e) { + throw new InvalidMessageException("Cannot parse json object", e); + } + + JsonNode msgNameNode = dhcpRootNode.get(MSG_NAME_TAG); + if (msgNameNode != null) { + msgName = msgNameNode.textValue(); + + } else { + throw new MissingDhcpAttributeException(MSG_NAME_TAG); + } + + JsonNode macAddrNode = dhcpRootNode.get(MAC_ADDR_TAG); + if (macAddrNode != null) { + macAddr = macAddrNode.textValue(); + + } else { + throw new MissingDhcpAttributeException(MAC_ADDR_TAG); + } + + JsonNode ipAddrNode = dhcpRootNode.get(IP_ADDR_TAG); + if (ipAddrNode != null) { + ipAddr = ipAddrNode.textValue(); + + } else { + throw new MissingDhcpAttributeException(IP_ADDR_TAG); + } + + LOG.debug("Got DHCP event : msg name {}; mac addr {}; ip addr {}", msgName, macAddr, ipAddr); + + if (jdbcDataSource == null) { + try { + setJdbcDataSource(); + } catch (IOException e) { + LOG.error("Could not create JDBC connection", e); + return; + } + } + + try { + + jdbcDataSource.writeData("INSERT INTO DHCP_MAP(mac_addr, ip_addr) VALUES('" + macAddr + "','" + ipAddr + "')", + null, null); + + } catch (SQLException e) { + LOG.error("Could not insert DHCP event data into the database ", e); + } + + } + +} diff --git a/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestSdncDhcpEventConsumer.java b/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestSdncDhcpEventConsumer.java new file mode 100644 index 000000000..8c3a839c2 --- /dev/null +++ b/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestSdncDhcpEventConsumer.java @@ -0,0 +1,130 @@ +/** + * + */ +package org.onap.ccsdk.sli.northbound.dmaapclient; + +import static org.junit.Assert.*; + +import java.io.InputStream; +import java.net.URL; +import java.sql.SQLException; +import java.util.Properties; + +import javax.sql.rowset.CachedRowSet; + +import org.junit.After; +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.ccsdk.sli.core.dblib.DBResourceManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ch.vorburger.mariadb4j.DB; +import ch.vorburger.mariadb4j.DBConfigurationBuilder; + +/** + * @author dt5972 + * + */ +public class TestSdncDhcpEventConsumer { + + private static final Logger LOG = LoggerFactory.getLogger(TestSdncDhcpEventConsumer.class); + + + private static final String DHCP_MAP_TABLE = "CREATE TABLE `DHCP_MAP` (\n" + + " mac_addr varchar(80) NOT NULL,\n" + + " ip_addr varchar(80),\n" + + " PRIMARY KEY(`mac_addr`)\n" + + ")"; + + + + private static final String VALID_DHCP_EVENT = "{\"msg_name\":\"DHCPACK\"," + + "\"macaddr\":\"fa:16:3e:8f:ea:68\"," + + "\"yiaddr\":\"10.3.0.2\"}"; + private static final String MISSING_MSG_NAME_DHCP_EVENT = "{\"macaddr\":\"fa:16:3e:8f:ea:68\"," + + "\"yiaddr\":\"10.3.0.2\"}"; + private static final String MISSING_MAC_ADDR_DHCP_EVENT = "{\"msg_name\":\"DHCPACK\"," + + "\"yiaddr\":\"10.3.0.2\"}"; + private static final String MISSING_IP_ADDR_DHCP_EVENT = "{\"msg_name\":\"DHCPACK\"," + + "\"macaddr\":\"fa:16:3e:8f:ea:68\"}"; + + private static final String GET_DHCP_MAPPING = "SELECT * FROM DHCP_MAP WHERE mac_addr = 'fa:16:3e:8f:ea:68'"; + + + private static DBResourceManager dblibSvc; + private static DB db; + + private static SdncDhcpEventConsumer consumer; + + /** + * @throws java.lang.Exception + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception { + + LOG.debug("Setting up DHCP event testing"); + + InputStream propStr = TestSdncDhcpEventConsumer.class.getResourceAsStream("/dblib.properties"); + + Properties props = new Properties(); + + props.load(propStr); + + + // Start MariaDB4j database + + LOG.debug("Starting MariaDB instance"); + DBConfigurationBuilder config = DBConfigurationBuilder.newBuilder(); + config.setPort(0); // 0 => autom. detect free port + db = DB.newEmbeddedDB(config.build()); + db.start(); + + + // Override jdbc URL and database name + props.setProperty("org.onap.ccsdk.sli.jdbc.database", "test"); + props.setProperty("org.onap.ccsdk.sli.jdbc.url", config.getURL("test")); + + + // Create dblib connection + + LOG.debug("Getting DBResourceManager instance"); + dblibSvc = new DBResourceManager(props); + + // Create DHCP_MAP table + dblibSvc.writeData(DHCP_MAP_TABLE, null, null); + + consumer = new SdncDhcpEventConsumer(); + consumer.setJdbcDataSource(dblibSvc); + LOG.debug("Setup complete"); + + } + + + @Test + public void testValid() throws InvalidMessageException, SQLException { + consumer.processMsg(VALID_DHCP_EVENT); + + CachedRowSet results = dblibSvc.getData(GET_DHCP_MAPPING, null, null); + + if (!results.next()) { + fail("Test query ["+GET_DHCP_MAPPING+"] returned no data"); + } + + } + + @Test (expected = InvalidMessageException.class) + public void testMissingMsgName() throws InvalidMessageException { + consumer.processMsg(MISSING_MSG_NAME_DHCP_EVENT); + } + + @Test (expected = InvalidMessageException.class) + public void testMissingMacAddress() throws InvalidMessageException { + consumer.processMsg(MISSING_MAC_ADDR_DHCP_EVENT); + } + + @Test (expected = InvalidMessageException.class) + public void testMissingIpAddress() throws InvalidMessageException { + consumer.processMsg(MISSING_IP_ADDR_DHCP_EVENT); + } +} diff --git a/dmaap-listener/src/test/resources/dblib.properties b/dmaap-listener/src/test/resources/dblib.properties new file mode 100644 index 000000000..9506ac8d1 --- /dev/null +++ b/dmaap-listener/src/test/resources/dblib.properties @@ -0,0 +1,38 @@ +### +# ============LICENSE_START======================================================= +# openECOMP : SDN-C +# ================================================================================ +# Copyright (C) 2017 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========================================================= +### + +# dblib.properrties +org.onap.ccsdk.sli.dbtype=jdbc + +org.onap.ccsdk.sli.jdbc.hosts=sdnctldb01 +org.onap.ccsdk.sli.jdbc.url=jdbc:mysql://dbhost:3306/sdnctl +org.onap.ccsdk.sli.jdbc.driver=org.mariadb.jdbc.Driver +org.onap.ccsdk.sli.jdbc.database=sdnctl +org.onap.ccsdk.sli.jdbc.user=sdnctl +org.onap.ccsdk.sli.jdbc.password=gamma +org.onap.ccsdk.sli.jdbc.connection.name=sdnctldb01 +org.onap.ccsdk.sli.jdbc.connection.timeout=50 +org.onap.ccsdk.sli.jdbc.request.timeout=100 +org.onap.ccsdk.sli.jdbc.limit.init=10 +org.onap.ccsdk.sli.jdbc.limit.min=10 +org.onap.ccsdk.sli.jdbc.limit.max=20 +org.onap.dblib.connection.recovery=false + -- cgit 1.2.3-korg From 024e6d1689ee38b37ac054636557b5dff8f26270 Mon Sep 17 00:00:00 2001 From: Brian Freeman Date: Sun, 12 Nov 2017 22:34:34 +0000 Subject: Change dmaapClient dependency Issue-ID: CCSDK-142 Change-Id: I5a3cd0626c71eadd414ab9939774d159638b99a6 Signed-off-by: Brian Freeman --- dmaap-listener/pom.xml | 20 ++++++++++++++++---- .../northbound/dmaapclient/SdncDmaapConsumer.java | 10 ++++++++-- 2 files changed, 24 insertions(+), 6 deletions(-) (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/pom.xml b/dmaap-listener/pom.xml index d1e173ca0..0ebde6ced 100755 --- a/dmaap-listener/pom.xml +++ b/dmaap-listener/pom.xml @@ -18,7 +18,8 @@ 2.9.0.pr1 true /opt/app/dmaap-listener - 0.2.12 + 1.0.0-SNAPSHOT + yyMMdd-HHmmss ${maven.build.timestamp} ${project.version}-${build.number} @@ -27,7 +28,7 @@ - com.att.nsa + org.onap.dmaap.messagerouter.dmaapclient dmaapClient ${dmaap.listener.version} @@ -97,8 +98,19 @@ 1.7 - - + + org.apache.maven.plugins + maven-jar-plugin + 2.6 + + + + true + org.onap.ccsdk.sli.northbound.dmaapclient.DmaapListener + + + + maven-assembly-plugin 2.6 diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncDmaapConsumer.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncDmaapConsumer.java index a0c555303..a51ea7c88 100644 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncDmaapConsumer.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncDmaapConsumer.java @@ -71,19 +71,25 @@ public abstract class SdncDmaapConsumer implements Runnable { try (FileInputStream in = new FileInputStream(new File(propertiesPath))) { + LOG.debug("propertiesPath: " + propertiesPath); this.properties = (Properties) properties.clone(); this.properties.load(in); - String timeoutStr = properties.getProperty("timeout"); + + String timeoutStr = this.properties.getProperty("timeout"); + LOG.debug("timeoutStr: " + timeoutStr); if ((timeoutStr != null) && (timeoutStr.length() > 0)) { timeout = parseTimeOutValue(timeoutStr); } - String fetchPauseStr = properties.getProperty("fetchPause"); + String fetchPauseStr = this.properties.getProperty("fetchPause"); + LOG.debug("fetchPause(Str): " + fetchPauseStr); if ((fetchPauseStr != null) && (fetchPauseStr.length() > 0)) { fetchPause = parseFetchPause(fetchPauseStr); } + LOG.debug("fetchPause: " + fetchPause); + this.consumer = MRClientFactory.createConsumer(propertiesPath); ready = true; -- cgit 1.2.3-korg From 32a9ecade35bc3e742dfbc9e86d887f25b5f49c9 Mon Sep 17 00:00:00 2001 From: Dan Timoney Date: Mon, 13 Nov 2017 10:04:11 -0500 Subject: Handle duplicate DHCP event Handle case where 2 DHCP events received for same mac addr. Should use most recent IP address. Change-Id: I90399ce3c39e07c2472366c78115812a64e9124b Issue-ID: CCSDK-142 Signed-off-by: Dan Timoney --- .../ccsdk/sli/northbound/dmaapclient/SdncDhcpEventConsumer.java | 3 +-- .../sli/northbound/dmaapclient/TestSdncDhcpEventConsumer.java | 9 +++++++++ 2 files changed, 10 insertions(+), 2 deletions(-) (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncDhcpEventConsumer.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncDhcpEventConsumer.java index 666ed68e1..03560d309 100644 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncDhcpEventConsumer.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncDhcpEventConsumer.java @@ -124,8 +124,7 @@ public class SdncDhcpEventConsumer extends SdncDmaapConsumer { try { - jdbcDataSource.writeData("INSERT INTO DHCP_MAP(mac_addr, ip_addr) VALUES('" + macAddr + "','" + ipAddr + "')", - null, null); + jdbcDataSource.writeData("INSERT INTO DHCP_MAP(mac_addr, ip_addr) VALUES('" + macAddr + "','" + ipAddr + "') ON DUPLICATE KEY UPDATE ip_addr = '"+ipAddr+"'", null, null); } catch (SQLException e) { LOG.error("Could not insert DHCP event data into the database ", e); diff --git a/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestSdncDhcpEventConsumer.java b/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestSdncDhcpEventConsumer.java index 8c3a839c2..04f098ade 100644 --- a/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestSdncDhcpEventConsumer.java +++ b/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestSdncDhcpEventConsumer.java @@ -42,6 +42,9 @@ public class TestSdncDhcpEventConsumer { private static final String VALID_DHCP_EVENT = "{\"msg_name\":\"DHCPACK\"," + "\"macaddr\":\"fa:16:3e:8f:ea:68\"," + "\"yiaddr\":\"10.3.0.2\"}"; + private static final String SECOND_DHCP_EVENT = "{\"msg_name\":\"DHCPACK\"," + + "\"macaddr\":\"fa:16:3e:8f:ea:68\"," + + "\"yiaddr\":\"10.3.0.3\"}"; private static final String MISSING_MSG_NAME_DHCP_EVENT = "{\"macaddr\":\"fa:16:3e:8f:ea:68\"," + "\"yiaddr\":\"10.3.0.2\"}"; private static final String MISSING_MAC_ADDR_DHCP_EVENT = "{\"msg_name\":\"DHCPACK\"," + @@ -104,11 +107,17 @@ public class TestSdncDhcpEventConsumer { @Test public void testValid() throws InvalidMessageException, SQLException { consumer.processMsg(VALID_DHCP_EVENT); + consumer.processMsg(SECOND_DHCP_EVENT); CachedRowSet results = dblibSvc.getData(GET_DHCP_MAPPING, null, null); if (!results.next()) { fail("Test query ["+GET_DHCP_MAPPING+"] returned no data"); + } else { + String ipAddr = results.getString("ip_addr"); + if (!"10.3.0.3".equals(ipAddr)) { + fail("Expecting ipAddr to be 10.3.0.3, but was "+ipAddr); + } } } -- cgit 1.2.3-korg From 613f3941a43afa5347c5df6e6e764869d0475973 Mon Sep 17 00:00:00 2001 From: root1 Date: Tue, 19 Dec 2017 20:28:25 +0530 Subject: Removal of useless parenthesis Change-Id: I6ef27a2795e91948b996055decffc051373d6113 Issue-ID: CCSDK-151 Signed-off-by: SRINIVAS V --- .../ccsdk/sli/northbound/dmaapclient/SdncFlatJsonDmaapConsumer.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncFlatJsonDmaapConsumer.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncFlatJsonDmaapConsumer.java index 1d499a1e7..231fa0e4f 100644 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncFlatJsonDmaapConsumer.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncFlatJsonDmaapConsumer.java @@ -140,7 +140,7 @@ public class SdncFlatJsonDmaapConsumer extends SdncDmaapConsumer { if (!mapFile.canRead()) { LOG.error(String.format("Cannot read map file (%s)", mapFilename)); - return (null); + return null; } try (BufferedReader mapReader = new BufferedReader(new FileReader(mapFile))) { @@ -160,9 +160,9 @@ public class SdncFlatJsonDmaapConsumer extends SdncDmaapConsumer { mapReader.close(); } catch (Exception e) { LOG.error("Caught exception reading map " + mapFilename, e); - return (null); + return null; } - return (results); + return results; } } -- cgit 1.2.3-korg From 0d27d85eb387bd56b1f8dab34a9381bcc20db7d5 Mon Sep 17 00:00:00 2001 From: root1 Date: Tue, 19 Dec 2017 19:02:44 +0530 Subject: Fixed as per Java Code Conventions Change-Id: Ib17c601ad6a2999e4396f84e18831b5f907557eb Issue-ID: CCSDK-151 Signed-off-by: SRINIVAS V --- .../sli/northbound/dmaapclient/SdncDmaapConsumer.java | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncDmaapConsumer.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncDmaapConsumer.java index a51ea7c88..ed71337a3 100644 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncDmaapConsumer.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncDmaapConsumer.java @@ -44,15 +44,6 @@ public abstract class SdncDmaapConsumer implements Runnable { private int fetchPause = 5000; // Default pause between fetch - 5 seconds private int timeout = 15000; // Default timeout - 15 seconds - public boolean isReady() { - return ready; - } - - - public boolean isRunning() { - return running; - } - public SdncDmaapConsumer() { } @@ -61,8 +52,16 @@ public abstract class SdncDmaapConsumer implements Runnable { init(properties, propertiesPath); } + public boolean isReady() { + return ready; + } + + public boolean isRunning() { + return running; + } + public String getProperty(String name) { - return (properties.getProperty(name, "")); + return properties.getProperty(name, ""); } public void init(Properties properties, String propertiesPath) { -- cgit 1.2.3-korg From 263950413073f5d1d7af3d2854052af8ec41d281 Mon Sep 17 00:00:00 2001 From: "prakash.e" Date: Thu, 21 Dec 2017 16:52:36 +0530 Subject: Removal of unused private field Change-Id: Ie2d33f7f9dba20a4d0fdf6a33f8574e953633a69 Issue-ID: CCSDK-151 Signed-off-by: prakash.e --- .../onap/ccsdk/sli/northbound/dmaapclient/SdncDmaapConsumer.java | 5 +---- .../ccsdk/sli/northbound/dmaapclient/SdncFlatJsonDmaapConsumer.java | 6 ++++-- 2 files changed, 5 insertions(+), 6 deletions(-) (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncDmaapConsumer.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncDmaapConsumer.java index a51ea7c88..a9f5fedad 100644 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncDmaapConsumer.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncDmaapConsumer.java @@ -35,7 +35,6 @@ public abstract class SdncDmaapConsumer implements Runnable { private static final Logger LOG = LoggerFactory .getLogger(SdncDmaapConsumer.class); - private String propertiesPath = ""; private Properties properties = null; private MRConsumer consumer = null; private MRConsumerResponse consumerResponse = null; @@ -62,13 +61,11 @@ public abstract class SdncDmaapConsumer implements Runnable { } public String getProperty(String name) { - return (properties.getProperty(name, "")); + return properties.getProperty(name, ""); } public void init(Properties properties, String propertiesPath) { - this.propertiesPath = propertiesPath; - try (FileInputStream in = new FileInputStream(new File(propertiesPath))) { LOG.debug("propertiesPath: " + propertiesPath); diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncFlatJsonDmaapConsumer.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncFlatJsonDmaapConsumer.java index 1d499a1e7..ce65e783e 100644 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncFlatJsonDmaapConsumer.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncFlatJsonDmaapConsumer.java @@ -124,6 +124,8 @@ public class SdncFlatJsonDmaapConsumer extends SdncDmaapConsumer { private Map loadMap(String msgType, String mapDirName) { Map results = new HashMap<>(); + String dirName = mapDirName; + if (mapDirName == null) { String rootdir = System.getenv(DMAAPLISTENERROOT); @@ -131,10 +133,10 @@ public class SdncFlatJsonDmaapConsumer extends SdncDmaapConsumer { rootdir = "/opt/app/dmaap-listener"; } - mapDirName = rootdir + "/lib"; + dirName = rootdir + "/lib"; } - String mapFilename = mapDirName + "/" + msgType + ".map"; + String mapFilename = dirName + "/" + msgType + ".map"; File mapFile = new File(mapFilename); -- cgit 1.2.3-korg From d43a8024c63c3c2b9c9882ec9ce3d05d20e3e8d0 Mon Sep 17 00:00:00 2001 From: "shashikanth.vh" Date: Tue, 16 Jan 2018 18:53:23 +0530 Subject: Fixed DmaapListener multiple consumer thread issue DmaapListener handleSubscriptions method returns after creating consumer thread for first subscription string, issue is fixed by removing return. https://jira.onap.org/browse/CCSDK-173 Issue-ID: CCSDK-173 Change-Id: I796b000b22762cda0a4f4fa929d5e2aabdcc7e8b Signed-off-by: shashikanth.vh --- .../java/org/onap/ccsdk/sli/northbound/dmaapclient/DmaapListener.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/DmaapListener.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/DmaapListener.java index ce099cd64..2be08cb8b 100644 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/DmaapListener.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/DmaapListener.java @@ -142,11 +142,11 @@ public class DmaapListener { } if (consumerClass != null) { - return handleConsumerClass(consumerClass, consumerClassName, propertyPath, + handleConsumerClass(consumerClass, consumerClassName, propertyPath, properties, consumers); } } - return false; + return !consumers.isEmpty(); } private static boolean handleConsumerClass(Class consumerClass, String consumerClassName, String propertyPath, -- cgit 1.2.3-korg From 4a8c2cb9920983f8b8af75be90f7511a59e923f5 Mon Sep 17 00:00:00 2001 From: Serban Popescu Date: Mon, 26 Mar 2018 13:36:17 +0000 Subject: Add Aai event listener Add support for Aai and Pserver incoming messages from Dmaap Change-Id: I57fedcaf6668d09189f0246571e8aaf515fc3fa0 Issue-ID: CCSDK-223 Signed-off-by: Serban Popescu --- dmaap-listener/pom.xml | 6 + dmaap-listener/src/assembly/assemble_zip.xml | 1 + .../dmaapclient/SdncAaiDmaapConsumer.java | 205 +++++++++++++++++++++ dmaap-listener/src/main/resources/pserver.map | 5 + .../src/main/resources/template-pserver.vt | 11 ++ .../dmaapclient/TestSdncPserverDmaapReceiver.java | 85 +++++++++ .../resources/dmaap-consumer-pserver.properties | 34 ++++ 7 files changed, 347 insertions(+) create mode 100644 dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncAaiDmaapConsumer.java create mode 100644 dmaap-listener/src/main/resources/pserver.map create mode 100644 dmaap-listener/src/main/resources/template-pserver.vt create mode 100644 dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestSdncPserverDmaapReceiver.java create mode 100644 dmaap-listener/src/test/resources/dmaap-consumer-pserver.properties (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/pom.xml b/dmaap-listener/pom.xml index f6d04e247..3a75fef0b 100755 --- a/dmaap-listener/pom.xml +++ b/dmaap-listener/pom.xml @@ -20,6 +20,7 @@ 1.2.0-SNAPSHOT 2.9.0.pr1 + 1.7 true /opt/app/dmaap-listener 1.1.0-SNAPSHOT @@ -67,6 +68,11 @@ jackson-annotations ${fasterxml.jackson.version} + + org.apache.velocity + velocity + ${velocity.version} + junit junit diff --git a/dmaap-listener/src/assembly/assemble_zip.xml b/dmaap-listener/src/assembly/assemble_zip.xml index f8873ab41..632172d77 100644 --- a/dmaap-listener/src/assembly/assemble_zip.xml +++ b/dmaap-listener/src/assembly/assemble_zip.xml @@ -48,6 +48,7 @@ *.properties *.map + *.vt diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncAaiDmaapConsumer.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncAaiDmaapConsumer.java new file mode 100644 index 000000000..4b695fcec --- /dev/null +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncAaiDmaapConsumer.java @@ -0,0 +1,205 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 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.northbound.dmaapclient; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.StringWriter; +import java.io.Writer; +import java.time.Instant; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +import org.apache.velocity.VelocityContext; +import org.apache.velocity.app.VelocityEngine; +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SdncAaiDmaapConsumer extends SdncDmaapConsumer { + + private static final Logger LOG = LoggerFactory.getLogger(SdncAaiDmaapConsumer.class); + private static final String SDNC_ENDPOINT = "SDNC.endpoint"; + private static final String TEMPLATE = "SDNC.template"; + private static final String DMAAPLISTENERROOT = "DMAAPLISTENERROOT"; + + private static final String AAI_EVENT = "AAI-EVENT"; + + private static final String EVENT_TYPE = "event-type"; + private static final String ENTITY_TYPE = "entity-type"; + private static final String EVENT_HEADER = "event-header"; + + private String rootDir; + + protected VelocityEngine velocityEngine; + + public SdncAaiDmaapConsumer() { + velocityEngine = new VelocityEngine(); + Properties props = new Properties(); + rootDir = System.getenv(DMAAPLISTENERROOT); + + if ((rootDir == null) || (rootDir.length() == 0)) { + rootDir = "/opt/app/dmaap-listener/lib/"; + } + else { + rootDir = rootDir + "/lib/"; + } + + props.put("file.resource.loader.path", rootDir); + velocityEngine.init(props); + } + + /* + * for testing purposes + */ + SdncAaiDmaapConsumer(Properties props) { + velocityEngine = new VelocityEngine(); + velocityEngine.init(props); + } + + protected String publish(String templatePath, String jsonString) throws IOException + { + JSONObject jsonObj = new JSONObject(jsonString); + VelocityContext context = new VelocityContext(); + for(Object key : jsonObj.keySet()) + { + context.put((String)key, jsonObj.get((String)key)); + } + + context.put("curr_time", Instant.now()); + + ObjectMapper oMapper = new ObjectMapper(); + + String rpcMsgbody = oMapper.writeValueAsString(jsonString); + context.put("full_message", rpcMsgbody); + + Writer writer = new StringWriter(); + velocityEngine.mergeTemplate(templatePath, "UTF-8", context, writer); + writer.flush(); + + return writer.toString(); + } + + @Override + public void processMsg(String msg) throws InvalidMessageException { + + if (msg == null) { + throw new InvalidMessageException("Null message"); + } + + ObjectMapper oMapper = new ObjectMapper(); + JsonNode aaiRootNode; + try { + aaiRootNode = oMapper.readTree(msg); + } catch (Exception e) { + throw new InvalidMessageException("Cannot parse json object", e); + } + + JsonNode eventHeaderNode = aaiRootNode.get(EVENT_HEADER); + if(eventHeaderNode == null) { + LOG.info("Missing Event Header node."); + return; + } + JsonNode eventTypeNode = eventHeaderNode.get(EVENT_TYPE); + String eventType = eventTypeNode.textValue(); + + if(AAI_EVENT.equals(eventType) == false) { + LOG.info("Unknown Event Type {}", eventType); + return; + } + + JsonNode entityTypeNode = eventHeaderNode.get(ENTITY_TYPE); + String entityType = entityTypeNode.textValue(); + + String mapFilename = rootDir + entityType + ".map"; + Map fieldMap = loadMap(mapFilename); + if (fieldMap == null) { + throw new InvalidMessageException("Unable to process message - cannot load mapping file"); + } + + if (!fieldMap.containsKey(SDNC_ENDPOINT)) { + throw new InvalidMessageException("No SDNC endpoint known for message " + entityType); + } + String sdncEndpoint = fieldMap.get(SDNC_ENDPOINT); + + if (!fieldMap.containsKey(TEMPLATE)) { + throw new InvalidMessageException("No SDNC template known for message " + entityType); + } + String templateName = fieldMap.get(TEMPLATE); + + try { + String rpcMsgbody = publish(templateName, msg); + String odlUrlBase = getProperty("sdnc.odl.url-base"); + String odlUser = getProperty("sdnc.odl.user"); + String odlPassword = getProperty("sdnc.odl.password"); + + if ((odlUrlBase != null) && (odlUrlBase.length() > 0)) { + SdncOdlConnection conn = SdncOdlConnection.newInstance(odlUrlBase + sdncEndpoint, odlUser, odlPassword); + + conn.send("POST", "application/json", rpcMsgbody); + } else { + LOG.info("POST message body would be:\n" + rpcMsgbody); + } + } catch (Exception e) { + LOG.error("Unable to process message", e); + } + } + + private Map loadMap(String mapFilename) { + File mapFile = new File(mapFilename); + + if (!mapFile.canRead()) { + LOG.error(String.format("Cannot read map file (%s)", mapFilename)); + return null; + } + + Map results = new HashMap<>(); + try (BufferedReader mapReader = new BufferedReader(new FileReader(mapFile))) { + + String curLine; + + while ((curLine = mapReader.readLine()) != null) { + curLine = curLine.trim(); + + if ((curLine.length() > 0) && (!curLine.startsWith("#")) && curLine.contains("=>")) { + String[] entry = curLine.split("=>"); + if (entry.length == 2) { + results.put(entry[0].trim(), entry[1].trim()); + } + } + } + mapReader.close(); + } catch (Exception e) { + LOG.error("Caught exception reading map " + mapFilename, e); + return null; + } + + return results; + } + +} diff --git a/dmaap-listener/src/main/resources/pserver.map b/dmaap-listener/src/main/resources/pserver.map new file mode 100644 index 000000000..8b3e463e7 --- /dev/null +++ b/dmaap-listener/src/main/resources/pserver.map @@ -0,0 +1,5 @@ +# SDN-C URL +SDNC.endpoint => config-selfservice-api:notification-callback + +# Field mapping +SDNC.template => template-pserver.vt diff --git a/dmaap-listener/src/main/resources/template-pserver.vt b/dmaap-listener/src/main/resources/template-pserver.vt new file mode 100644 index 000000000..1df659e09 --- /dev/null +++ b/dmaap-listener/src/main/resources/template-pserver.vt @@ -0,0 +1,11 @@ +{ + "input": { + "common-header": { + "request-id": "$event-header.id", + "timestamp": "$curr_time", + "originator-id": "AAI", + "api-ver": "2.00" + }, + "payload": $full_message + } +} \ No newline at end of file diff --git a/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestSdncPserverDmaapReceiver.java b/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestSdncPserverDmaapReceiver.java new file mode 100644 index 000000000..db7cbd72c --- /dev/null +++ b/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestSdncPserverDmaapReceiver.java @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2017. Lorem ipsum dolor sit amet, consectetur adipiscing elit. + * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan. + * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna. + * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus. + * Vestibulum commodo. Ut rhoncus gravida arcu. + */ + +package org.onap.ccsdk.sli.northbound.dmaapclient; + +import static org.junit.Assert.assertTrue; + +import java.util.Properties; + +import org.junit.Before; +import org.junit.Test; + +public class TestSdncPserverDmaapReceiver { + private static final String aaiInput = "{\r\n" + + " \"cambria.partition\": \"AAI\",\r\n" + + " \"event-header\": {\r\n" + + " \"severity\": \"NORMAL\",\r\n" + + " \"entity-type\": \"pserver\",\r\n" + + " \"top-entity-type\": \"pserver\",\r\n" + + " \"entity-link\": \"https://aai.com:8443/aai/v11/cloud-infrastructure/pservers/pserver/a3d3d3d3/\",\r\n" + + " \"event-type\": \"AAI-EVENT\",\r\n" + + " \"domain\": \"e2e\",\r\n" + + " \"action\": \"UPDATE\",\r\n" + + " \"sequence-number\": \"0\",\r\n" + + " \"id\": \"20170415000111-1234\",\r\n" + + " \"source-name\": \"testclient\",\r\n" + + " \"version\": \"v11\",\r\n" + + " \"timestamp\": \"20170415-00:01:11:979\"\r\n" + + " },\r\n" + + " \"entity\": {\r\n" + + " \"hostname\": \"host1\",\r\n" + + " \"ptnii-equip-name\": \"lat111\",\r\n" + + " \"equip-type\": \"server\",\r\n" + + " \"equip-vendor\": \"HP\",\r\n" + + " \"equip-model\": \"model1\",\r\n" + + " \"fqdn\": \"l.global.net\",\r\n" + + " \"ipv4-oam-address\": \"12.12.12.12\",\r\n" + + " \"in-maint\": false,\r\n" + + " \"resource-version\": \"11111111111\",\r\n" + + " \"purpose\": \"Gamma\",\r\n" + + " \"relationship-list\": {\r\n" + + " \"relationship\": [\r\n" + + " {\r\n" + + " \"related-to\": \"complex\",\r\n" + + " \"relationship-data\": [\r\n" + + " {\r\n" + + " \"relationship-value\": \"L1L2L3\",\r\n" + + " \"relationship-key\": \"complex.physical-location-id\"\r\n" + + " }\r\n" + + " ],\r\n" + + " \"related-link\": \"https://aai.com:8443/aai/v11/cloud-infrastructure/complexes/complex/cmpl1\"\r\n" + + " }\r\n" + + " ]\r\n" + + " },\r\n" + + " \"p-interfaces\": {\r\n" + + " \"p-interface\": []\r\n" + + " },\r\n" + + " \"lag-interfaces\": {\r\n" + + " \"lag-interface\": []\r\n" + + " }\r\n" + + " }\r\n" + + "}"; + + @Before + public void setUp() throws Exception { + } + + @Test + public void test() throws Exception { + Properties props = new Properties(); + + String rpcMsgbody = new SdncAaiDmaapConsumer(props).publish("src/main/resources/template-pserver.vt", aaiInput); + + assertTrue(rpcMsgbody.indexOf("input") != -1); + assertTrue(rpcMsgbody.indexOf("payload") != -1); + assertTrue(rpcMsgbody.indexOf("common-header") != -1); + } + + +} diff --git a/dmaap-listener/src/test/resources/dmaap-consumer-pserver.properties b/dmaap-listener/src/test/resources/dmaap-consumer-pserver.properties new file mode 100644 index 000000000..e3c4fdac8 --- /dev/null +++ b/dmaap-listener/src/test/resources/dmaap-consumer-pserver.properties @@ -0,0 +1,34 @@ +TransportType=DME2 +Latitude =47.778998 +Longitude =-122.182883 +Version =1.0 +ServiceName =dmaap-v1.dev.dmaap.dt.saat.acsi.att.com/events +Environment =TEST +Partner = +SubContextPath =/ +Protocol =https +MethodType =GET +username =test +password =test +contenttype =application/json +authKey=ABC123 +authDate=2016-05-10T13:13:50-0700 +host=localhost:3904 +topic=ccsdk-topic +group=pserver +id=1 +timeout=20000 +limit=10000 +filter={"class":"Equals","field":"event-header.entity-type","value":"pserver"} +AFT_DME2_EXCHANGE_REQUEST_HANDLERS=com.att.nsa.test.PreferredRouteRequestHandler +AFT_DME2_EXCHANGE_REPLY_HANDLERS=com.att.nsa.test.PreferredRouteReplyHandler +AFT_DME2_REQ_TRACE_ON=true +AFT_ENVIRONMENT=AFTUAT +AFT_DME2_EP_CONN_TIMEOUT=55000 +AFT_DME2_ROUNDTRIP_TIMEOUT_MS=240000 +AFT_DME2_EP_READ_TIMEOUT_MS=50000 +sessionstickinessrequired=NO +DME2preferredRouterFilePath=src/test/resources/dmaap-listener.preferredRoute.txt +sdnc.odl.user=admin +sdnc.odl.password=admin +sdnc.odl.url-base=http://localhost:8181/restconf/operations \ No newline at end of file -- cgit 1.2.3-korg From 22a9e045d42ad629010cc4200369a4453fbe0df7 Mon Sep 17 00:00:00 2001 From: "shashikanth.vh" Date: Mon, 26 Mar 2018 19:24:35 +0530 Subject: coverageSdncFlatJsonDmaapConsumer Coverage improvement for SdncFlatJsonDmaapConsumer https://jira.onap.org/browse/CCSDK-213?jql=project%20%3D%20CCSDK%20AND%20text%20~%20coverage Issue-ID: CCSDK-213 Change-Id: I95e824c5c83b9c36ce0c475368235182e851c254 Signed-off-by: shashikanth.vh --- .../northbound/dmaapclient/TestSdncJsonDmaapConsumer.java | 12 ++++++++++++ 1 file changed, 12 insertions(+) (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestSdncJsonDmaapConsumer.java b/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestSdncJsonDmaapConsumer.java index 0d65231da..01bd3cf28 100644 --- a/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestSdncJsonDmaapConsumer.java +++ b/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestSdncJsonDmaapConsumer.java @@ -19,4 +19,16 @@ public class TestSdncJsonDmaapConsumer { SdncFlatJsonDmaapConsumer consumer = new SdncFlatJsonDmaapConsumer(); consumer.processMsg(null); } + + @Test(expected = InvalidMessageException.class) + public void testProcessMsgNullFieldMap_shouldThrowException() throws Exception { + SdncFlatJsonDmaapConsumer consumer = new SdncFlatJsonDmaapConsumer(); + + String msg = "{\n" + + " \"input\" : { \n" + + " }\n" + + "}"; + + consumer.processMsg(msg); + } } -- cgit 1.2.3-korg From 7dee0c8d2680888271da556fedc7ea0d0bc773f9 Mon Sep 17 00:00:00 2001 From: "shashikanth.vh" Date: Tue, 27 Mar 2018 19:17:33 +0530 Subject: SdncOdlConnection coverage Coverage improvement for SdncOdlConnection https://jira.onap.org/browse/CCSDK-213?jql=project%20%3D%20CCSDK%20AND%20text%20~%20coverage Issue-ID: CCSDK-213 Change-Id: I8045722de77e8884be485bd6f1ed2243c08d2d2b Signed-off-by: shashikanth.vh --- .../dmaapclient/TestSdncOdlConnection.java | 26 +++++++++++++ .../uebclient/TestSdncOdlConnection.java | 45 ++++++++++++++++++++++ 2 files changed, 71 insertions(+) create mode 100644 dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestSdncOdlConnection.java create mode 100644 ueb-listener/src/test/java/org/onap/ccsdk/sli/northbound/uebclient/TestSdncOdlConnection.java (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestSdncOdlConnection.java b/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestSdncOdlConnection.java new file mode 100644 index 000000000..db24a4545 --- /dev/null +++ b/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestSdncOdlConnection.java @@ -0,0 +1,26 @@ +package org.onap.ccsdk.sli.northbound.dmaapclient; + +import org.junit.Test; + +import java.io.IOException; +import java.net.ConnectException; + +public class TestSdncOdlConnection { + + @Test + public void test() { + + try { + SdncOdlConnection sdncOdlConnection = SdncOdlConnection.newInstance("https://127.0.0.1:8447/aai/v11/network/pnfs/pnf/a8098c1a-f86e-11da-bd1a-00112444be1e", "", ""); + sdncOdlConnection.send("PUT", "application/json", "{\n" + + " \"input\" : { \n" + + " }\n" + + "}"); + } catch (ConnectException e) { + //Connection exception + } catch (IOException e) { + e.printStackTrace(); + } + } + +} diff --git a/ueb-listener/src/test/java/org/onap/ccsdk/sli/northbound/uebclient/TestSdncOdlConnection.java b/ueb-listener/src/test/java/org/onap/ccsdk/sli/northbound/uebclient/TestSdncOdlConnection.java new file mode 100644 index 000000000..1fac0c299 --- /dev/null +++ b/ueb-listener/src/test/java/org/onap/ccsdk/sli/northbound/uebclient/TestSdncOdlConnection.java @@ -0,0 +1,45 @@ +package org.onap.ccsdk.sli.northbound.uebclient; + +import ch.vorburger.mariadb4j.DB; +import ch.vorburger.mariadb4j.DBConfigurationBuilder; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.ccsdk.sli.core.dblib.DBResourceManager; +import org.openecomp.sdc.api.IDistributionClient; +import org.openecomp.sdc.api.notification.INotificationData; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.ConnectException; +import java.net.URL; +import java.nio.file.DirectoryStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.util.Properties; + +import static org.mockito.Mockito.mock; + +public class TestSdncOdlConnection { + + @Test + public void test() { + + try { + SdncOdlConnection sdncOdlConnection = SdncOdlConnection.newInstance("https://127.0.0.1:8447/aai/v11/network/pnfs/pnf/a8098c1a-f86e-11da-bd1a-00112444be1e", "", ""); + sdncOdlConnection.send("PUT", "application/json", "{\n" + + " \"input\" : { \n" + + " }\n" + + "}"); + } catch (ConnectException e) { + //Connection exception + } catch (IOException e) { + e.printStackTrace(); + } + } + +} -- cgit 1.2.3-korg From 448607990ac6b73d21f8d1b781e37ec798d7e29e Mon Sep 17 00:00:00 2001 From: "shashikanth.vh" Date: Wed, 28 Mar 2018 14:49:39 +0530 Subject: coverage SdncFlatJsonDmaapConsumer Coverage improvement for SdncFlatJsonDmaapConsumer https://jira.onap.org/browse/CCSDK-213?jql=project%20%3D%20CCSDK%20AND%20text%20~%20coverage Issue-ID: CCSDK-213 Change-Id: Idb08f426e1626f8aa2b12d2c53f1960474af59c2 Signed-off-by: shashikanth.vh --- .../dmaapclient/TestSdncJsonDmaapConsumer.java | 106 ++++++++++++++++++++- 1 file changed, 105 insertions(+), 1 deletion(-) (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestSdncJsonDmaapConsumer.java b/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestSdncJsonDmaapConsumer.java index 01bd3cf28..620098cb7 100644 --- a/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestSdncJsonDmaapConsumer.java +++ b/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestSdncJsonDmaapConsumer.java @@ -10,6 +10,16 @@ package org.onap.ccsdk.sli.northbound.dmaapclient; import org.junit.Test; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.InputStream; +import java.lang.reflect.Field; + +import java.util.Map; +import java.util.Properties; + public class TestSdncJsonDmaapConsumer { private static final String DMAAP_LISTENER_PROPERTIES = "dmaap-listener.properties"; private static final String DMAAP_LISTENER_PROPERTIES_DIR = "src/test/resources"; @@ -19,9 +29,103 @@ public class TestSdncJsonDmaapConsumer { SdncFlatJsonDmaapConsumer consumer = new SdncFlatJsonDmaapConsumer(); consumer.processMsg(null); } + + @Test + public void testProcessMsgFieldMap() throws Exception { + SdncFlatJsonDmaapConsumer consumer = new SdncFlatJsonDmaapConsumer(); + + String DMAAPLISTENERROOT = "DMAAPLISTENERROOT"; + File directory = new File("lib"); + + if (! directory.exists()){ + directory.mkdir(); + } + + File file = new File("lib" + "/" + "input.map"); + try{ + FileWriter fw = new FileWriter(file.getAbsoluteFile()); + BufferedWriter bw = new BufferedWriter(fw); + bw.write("SDNC.endpoint=>http://localhost:8282/restconf/operations"); + bw.close(); + } + catch (Exception e){ + e.printStackTrace(); + } + + try { + Map env = System.getenv(); + Class cl = env.getClass(); + Field field = cl.getDeclaredField("m"); + field.setAccessible(true); + Map writableEnv = (Map) field.get(env); + writableEnv.put(DMAAPLISTENERROOT, "."); + } catch (Exception e) { + throw new IllegalStateException("Failed to set environment variable", e); + } + + String msg = "{\n" + + " \"input\" : { \n" + + " }\n" + + "}"; + + InputStream propStr = TestSdncJsonDmaapConsumer.class.getResourceAsStream("/dmaap-consumer-pserver.properties"); + Properties props = new Properties(); + + props.load(propStr); + + consumer.init(props, "src/test/resources/dmaap-consumer-pserver.properties"); + consumer.processMsg(msg); + } + + @Test(expected = InvalidMessageException.class) + public void testProcessMsgFieldMapNoSdncEndPoint() throws Exception { + SdncFlatJsonDmaapConsumer consumer = new SdncFlatJsonDmaapConsumer(); + + String DMAAPLISTENERROOT = "DMAAPLISTENERROOT"; + File directory = new File("lib"); + + if (! directory.exists()){ + directory.mkdir(); + } + + File file = new File("lib" + "/" + "input.map"); + try{ + FileWriter fw = new FileWriter(file.getAbsoluteFile()); + BufferedWriter bw = new BufferedWriter(fw); + bw.write("SDNC"); + bw.close(); + } + catch (Exception e){ + e.printStackTrace(); + } + + try { + Map env = System.getenv(); + Class cl = env.getClass(); + Field field = cl.getDeclaredField("m"); + field.setAccessible(true); + Map writableEnv = (Map) field.get(env); + writableEnv.put(DMAAPLISTENERROOT, "."); + } catch (Exception e) { + throw new IllegalStateException("Failed to set environment variable", e); + } + + String msg = "{\n" + + " \"input\" : { \n" + + " }\n" + + "}"; + + InputStream propStr = TestSdncJsonDmaapConsumer.class.getResourceAsStream("/dmaap-consumer-pserver.properties"); + Properties props = new Properties(); + + props.load(propStr); + + consumer.init(props, "src/test/resources/dmaap-consumer-pserver.properties"); + consumer.processMsg(msg); + } @Test(expected = InvalidMessageException.class) - public void testProcessMsgNullFieldMap_shouldThrowException() throws Exception { + public void testProcessMsgFieldMapNoFieldMap() throws Exception { SdncFlatJsonDmaapConsumer consumer = new SdncFlatJsonDmaapConsumer(); String msg = "{\n" + -- cgit 1.2.3-korg From fa0fd7c1fe8dcb746cc8bdb9cc8d8e09ef10f7ad Mon Sep 17 00:00:00 2001 From: Serban Popescu Date: Wed, 28 Mar 2018 13:32:44 +0000 Subject: Add Aai event listener Add support for Aai and Pserver incoming messages from Dmaap Change-Id: I6ace2395476a1410ea3b7ffe0bebc1766d19e474 Issue-ID: CCSDK-223 Signed-off-by: Serban Popescu --- dmaap-listener/src/main/resources/generic-vnf.map | 5 ++++ .../src/main/resources/template-generic-vnf.vt | 15 ++++++++++ .../src/main/resources/template-pserver.vt | 4 +++ .../dmaapclient/TestSdncPserverDmaapReceiver.java | 20 +++++++++++-- .../dmaap-consumer-generic-vnf.properties | 34 ++++++++++++++++++++++ .../resources/dmaap-consumer-pserver.properties | 2 +- 6 files changed, 76 insertions(+), 4 deletions(-) create mode 100644 dmaap-listener/src/main/resources/generic-vnf.map create mode 100644 dmaap-listener/src/main/resources/template-generic-vnf.vt create mode 100644 dmaap-listener/src/test/resources/dmaap-consumer-generic-vnf.properties (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/src/main/resources/generic-vnf.map b/dmaap-listener/src/main/resources/generic-vnf.map new file mode 100644 index 000000000..bc375eb28 --- /dev/null +++ b/dmaap-listener/src/main/resources/generic-vnf.map @@ -0,0 +1,5 @@ +# SDN-C URL +SDNC.endpoint => config-selfservice-api:notification-callback + +# Field mapping +SDNC.template => template-generic-vnf.vt diff --git a/dmaap-listener/src/main/resources/template-generic-vnf.vt b/dmaap-listener/src/main/resources/template-generic-vnf.vt new file mode 100644 index 000000000..c8a6b78ea --- /dev/null +++ b/dmaap-listener/src/main/resources/template-generic-vnf.vt @@ -0,0 +1,15 @@ +{ + "input": { + "common-header": { + "request-id": "$event-header.id", + "timestamp": "$curr_time", + "originator-id": "AAI", + "api-ver": "2.00" + }, + "action-identifiers": { + "action-name": "dmaap-notification", + "mode": "async" + }, + "payload": $full_message + } +} \ No newline at end of file diff --git a/dmaap-listener/src/main/resources/template-pserver.vt b/dmaap-listener/src/main/resources/template-pserver.vt index 1df659e09..c8a6b78ea 100644 --- a/dmaap-listener/src/main/resources/template-pserver.vt +++ b/dmaap-listener/src/main/resources/template-pserver.vt @@ -6,6 +6,10 @@ "originator-id": "AAI", "api-ver": "2.00" }, + "action-identifiers": { + "action-name": "dmaap-notification", + "mode": "async" + }, "payload": $full_message } } \ No newline at end of file diff --git a/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestSdncPserverDmaapReceiver.java b/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestSdncPserverDmaapReceiver.java index db7cbd72c..b9b20a6cd 100644 --- a/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestSdncPserverDmaapReceiver.java +++ b/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestSdncPserverDmaapReceiver.java @@ -9,12 +9,16 @@ package org.onap.ccsdk.sli.northbound.dmaapclient; import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertEquals; import java.util.Properties; import org.junit.Before; import org.junit.Test; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + public class TestSdncPserverDmaapReceiver { private static final String aaiInput = "{\r\n" + " \"cambria.partition\": \"AAI\",\r\n" + @@ -75,10 +79,20 @@ public class TestSdncPserverDmaapReceiver { Properties props = new Properties(); String rpcMsgbody = new SdncAaiDmaapConsumer(props).publish("src/main/resources/template-pserver.vt", aaiInput); + + ObjectMapper oMapper = new ObjectMapper(); + JsonNode aaiRootNode; + try { + aaiRootNode = oMapper.readTree(rpcMsgbody); + } catch (Exception e) { + throw new InvalidMessageException("Cannot parse json object", e); + } - assertTrue(rpcMsgbody.indexOf("input") != -1); - assertTrue(rpcMsgbody.indexOf("payload") != -1); - assertTrue(rpcMsgbody.indexOf("common-header") != -1); + assertTrue(aaiRootNode.get("input").get("payload") != null); + assertTrue(aaiRootNode.get("input").get("common-header") != null); + + assertEquals(aaiRootNode.get("input").get("action-identifiers").get("action-name").textValue(), "dmaap-notification"); + assertEquals(aaiRootNode.get("input").get("action-identifiers").get("mode").textValue(), "async"); } diff --git a/dmaap-listener/src/test/resources/dmaap-consumer-generic-vnf.properties b/dmaap-listener/src/test/resources/dmaap-consumer-generic-vnf.properties new file mode 100644 index 000000000..710a7c7c9 --- /dev/null +++ b/dmaap-listener/src/test/resources/dmaap-consumer-generic-vnf.properties @@ -0,0 +1,34 @@ +TransportType=DME2 +Latitude =47.778998 +Longitude =-122.182883 +Version =1.0 +ServiceName =dmaap-v1.dev.dmaap.dt.saat.acsi.att.com/events +Environment =TEST +Partner = +SubContextPath =/ +Protocol =https +MethodType =GET +username =test +password =test +contenttype =application/json +authKey=ABC123 +authDate=2016-05-10T13:13:50-0700 +host=localhost:3904 +topic=AAI-EVENT +group=vnf +id=1 +timeout=20000 +limit=10000 +filter={"class":"And","filters":[{"class":"Equals","field":"event-header.entity-type","value":"generic-vnf"},{"class":"Equals","field":"entity.vnf-type","value":"kvm-vpe"}]} +AFT_DME2_EXCHANGE_REQUEST_HANDLERS=com.att.nsa.test.PreferredRouteRequestHandler +AFT_DME2_EXCHANGE_REPLY_HANDLERS=com.att.nsa.test.PreferredRouteReplyHandler +AFT_DME2_REQ_TRACE_ON=true +AFT_ENVIRONMENT=AFTUAT +AFT_DME2_EP_CONN_TIMEOUT=55000 +AFT_DME2_ROUNDTRIP_TIMEOUT_MS=240000 +AFT_DME2_EP_READ_TIMEOUT_MS=50000 +sessionstickinessrequired=NO +DME2preferredRouterFilePath=src/test/resources/dmaap-listener.preferredRoute.txt +sdnc.odl.user=admin +sdnc.odl.password=admin +sdnc.odl.url-base=http://localhost:8181/restconf/operations \ No newline at end of file diff --git a/dmaap-listener/src/test/resources/dmaap-consumer-pserver.properties b/dmaap-listener/src/test/resources/dmaap-consumer-pserver.properties index e3c4fdac8..9f5cfe71f 100644 --- a/dmaap-listener/src/test/resources/dmaap-consumer-pserver.properties +++ b/dmaap-listener/src/test/resources/dmaap-consumer-pserver.properties @@ -14,7 +14,7 @@ contenttype =application/json authKey=ABC123 authDate=2016-05-10T13:13:50-0700 host=localhost:3904 -topic=ccsdk-topic +topic=AAI-EVENT group=pserver id=1 timeout=20000 -- cgit 1.2.3-korg From 7fc8f9fe913e35121c8e9f6e222c9b741beefdda Mon Sep 17 00:00:00 2001 From: "shashikanth.vh" Date: Wed, 28 Mar 2018 17:32:01 +0530 Subject: coverage SdncAaiDmaapConsumer Coverage improvement for SdncAaiDmaapConsumer https://jira.onap.org/browse/CCSDK-213?jql=project%20%3D%20CCSDK%20AND%20text%20~%20coverage Issue-ID: CCSDK-213 Change-Id: Icc9af3a9f27d4bae543525b5651d1f6485ef8857 Signed-off-by: shashikanth.vh --- .../dmaapclient/TestSdncPserverDmaapReceiver.java | 90 +++++++++++++++++++++ .../incoming/src_test_resources_csars_nsepc.csar | Bin 0 -> 42569 bytes 2 files changed, 90 insertions(+) create mode 100644 ueb-listener/src/test/resources/incoming/src_test_resources_csars_nsepc.csar (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestSdncPserverDmaapReceiver.java b/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestSdncPserverDmaapReceiver.java index db7cbd72c..963b20d68 100644 --- a/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestSdncPserverDmaapReceiver.java +++ b/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestSdncPserverDmaapReceiver.java @@ -10,8 +10,15 @@ package org.onap.ccsdk.sli.northbound.dmaapclient; import static org.junit.Assert.assertTrue; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Field; +import java.util.Map; import java.util.Properties; +import org.apache.commons.io.FileUtils; + import org.junit.Before; import org.junit.Test; @@ -81,5 +88,88 @@ public class TestSdncPserverDmaapReceiver { assertTrue(rpcMsgbody.indexOf("common-header") != -1); } + @Test + public void testProcessMsgFieldMap() throws Exception { + + + String DMAAPLISTENERROOT = "DMAAPLISTENERROOT"; + File directory = new File("lib"); + + if (! directory.exists()){ + directory.mkdir(); + } + + File source = new File("src/main/resources"); + File dest = new File("lib/"); + try { + FileUtils.copyDirectory(source, dest); + } catch (IOException e) { + e.printStackTrace(); + } + + try { + Map env = System.getenv(); + Class cl = env.getClass(); + Field field = cl.getDeclaredField("m"); + field.setAccessible(true); + Map writableEnv = (Map) field.get(env); + writableEnv.put(DMAAPLISTENERROOT, "."); + } catch (Exception e) { + throw new IllegalStateException("Failed to set environment variable", e); + } + Properties props = new Properties(); + + SdncAaiDmaapConsumer consumer = new SdncAaiDmaapConsumer(); + + InputStream propStr = TestSdncPserverDmaapReceiver.class.getResourceAsStream("/dmaap-consumer-pserver.properties"); + + + props.load(propStr); + + consumer.init(props, "src/test/resources/dmaap-consumer-pserver.properties"); + consumer.processMsg(aaiInput); + } + + @Test(expected = InvalidMessageException.class) + public void testProcessMsgNullMessage() throws Exception { + Properties props = new Properties(); + + SdncAaiDmaapConsumer consumer = new SdncAaiDmaapConsumer(); + consumer.processMsg(null); + } + + @Test(expected = InvalidMessageException.class) + public void testProcessMsgInvalidMessage() throws Exception { + Properties props = new Properties(); + + SdncAaiDmaapConsumer consumer = new SdncAaiDmaapConsumer(); + consumer.processMsg("test"); + } + + @Test + public void testProcessMsgMissingEventHeader() throws Exception { + Properties props = new Properties(); + + SdncAaiDmaapConsumer consumer = new SdncAaiDmaapConsumer(); + consumer.processMsg("{\n" + + " \"input\" : { \n" + + " }\n" + + "}"); + } + + @Test + public void testProcessMsgInvalidEventType() throws Exception { + Properties props = new Properties(); + + String msg = "{\"cambria.partition\": \"AAI\",\r\n" + + " \"event-header\": {\"event-type\": \"TEST-EVENT\"}}"; + + SdncAaiDmaapConsumer consumer = new SdncAaiDmaapConsumer(); + consumer.processMsg(msg); + } + + + + } diff --git a/ueb-listener/src/test/resources/incoming/src_test_resources_csars_nsepc.csar b/ueb-listener/src/test/resources/incoming/src_test_resources_csars_nsepc.csar new file mode 100644 index 000000000..087d8c3d8 Binary files /dev/null and b/ueb-listener/src/test/resources/incoming/src_test_resources_csars_nsepc.csar differ -- cgit 1.2.3-korg From d3dff0bc0832ea02f53bd952ea9c180f8df94580 Mon Sep 17 00:00:00 2001 From: Serban Popescu Date: Wed, 28 Mar 2018 16:43:24 +0000 Subject: Add Aai event listener Add support for Aai and Pserver incoming messages from Dmaap Change-Id: Ie799cb57f5c00eed70c9f6fd30825f907962a094 Issue-ID: CCSDK-226 Signed-off-by: Serban Popescu --- .../onap/ccsdk/sli/northbound/dmaapclient/SdncAaiDmaapConsumer.java | 5 ++++- dmaap-listener/src/main/resources/template-generic-vnf.vt | 6 +----- dmaap-listener/src/main/resources/template-pserver.vt | 6 +----- .../sli/northbound/dmaapclient/TestSdncPserverDmaapReceiver.java | 3 --- 4 files changed, 6 insertions(+), 14 deletions(-) (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncAaiDmaapConsumer.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncAaiDmaapConsumer.java index 4b695fcec..0e12dfa2e 100644 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncAaiDmaapConsumer.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncAaiDmaapConsumer.java @@ -90,6 +90,9 @@ public class SdncAaiDmaapConsumer extends SdncDmaapConsumer { { context.put((String)key, jsonObj.get((String)key)); } + + String id = jsonObj.getJSONObject(EVENT_HEADER).get("id").toString(); + context.put("req_id", id); context.put("curr_time", Instant.now()); @@ -159,7 +162,7 @@ public class SdncAaiDmaapConsumer extends SdncDmaapConsumer { String odlPassword = getProperty("sdnc.odl.password"); if ((odlUrlBase != null) && (odlUrlBase.length() > 0)) { - SdncOdlConnection conn = SdncOdlConnection.newInstance(odlUrlBase + sdncEndpoint, odlUser, odlPassword); + SdncOdlConnection conn = SdncOdlConnection.newInstance(odlUrlBase + "/" + sdncEndpoint, odlUser, odlPassword); conn.send("POST", "application/json", rpcMsgbody); } else { diff --git a/dmaap-listener/src/main/resources/template-generic-vnf.vt b/dmaap-listener/src/main/resources/template-generic-vnf.vt index c8a6b78ea..d57c9a0a4 100644 --- a/dmaap-listener/src/main/resources/template-generic-vnf.vt +++ b/dmaap-listener/src/main/resources/template-generic-vnf.vt @@ -1,15 +1,11 @@ { "input": { "common-header": { - "request-id": "$event-header.id", + "request-id": "$req_id", "timestamp": "$curr_time", "originator-id": "AAI", "api-ver": "2.00" }, - "action-identifiers": { - "action-name": "dmaap-notification", - "mode": "async" - }, "payload": $full_message } } \ No newline at end of file diff --git a/dmaap-listener/src/main/resources/template-pserver.vt b/dmaap-listener/src/main/resources/template-pserver.vt index c8a6b78ea..d57c9a0a4 100644 --- a/dmaap-listener/src/main/resources/template-pserver.vt +++ b/dmaap-listener/src/main/resources/template-pserver.vt @@ -1,15 +1,11 @@ { "input": { "common-header": { - "request-id": "$event-header.id", + "request-id": "$req_id", "timestamp": "$curr_time", "originator-id": "AAI", "api-ver": "2.00" }, - "action-identifiers": { - "action-name": "dmaap-notification", - "mode": "async" - }, "payload": $full_message } } \ No newline at end of file diff --git a/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestSdncPserverDmaapReceiver.java b/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestSdncPserverDmaapReceiver.java index ec01df534..11201265d 100644 --- a/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestSdncPserverDmaapReceiver.java +++ b/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestSdncPserverDmaapReceiver.java @@ -9,7 +9,6 @@ package org.onap.ccsdk.sli.northbound.dmaapclient; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.assertEquals; import java.io.File; import java.io.IOException; @@ -98,8 +97,6 @@ public class TestSdncPserverDmaapReceiver { assertTrue(aaiRootNode.get("input").get("payload") != null); assertTrue(aaiRootNode.get("input").get("common-header") != null); - assertEquals(aaiRootNode.get("input").get("action-identifiers").get("action-name").textValue(), "dmaap-notification"); - assertEquals(aaiRootNode.get("input").get("action-identifiers").get("mode").textValue(), "async"); } @Test -- cgit 1.2.3-korg From c50170bc44f192a7c8e7efdfc773342d8b5c0437 Mon Sep 17 00:00:00 2001 From: Jeremy Wolf Date: Wed, 28 Mar 2018 17:22:09 +0000 Subject: coverage sli-northbound adding junit test files for AsdcApiSliClient, AsdcApiUtil, DataChangeClient, SdncFlatJsonDmaapConsumer, SdncARModel, SdncNodeModel, SdncVFCModel, SdncVFModuleModel, SdncUebCallback Change-Id: Ia7fb307b84957292f9080654c7ae31992434317f Issue-ID: CCSDK-230 Signed-off-by: Jeremy Wolf --- .../northbound/asdcapi/AsdcApiSliClientTest.java | 59 ++++++++++++++++ .../sli/northbound/asdcapi/AsdcApiUtilTest.java | 15 ++++ .../dataChange/DataChangeClientTest.java | 56 +++++++++++++++ .../dmaapclient/SdncFlatJsonDmaapConsumerTest.java | 41 +++++++++++ .../sli/northbound/uebclient/SdncARModelTest.java | 21 ++++++ .../northbound/uebclient/SdncNodeModelTest.java | 49 +++++++++++++ .../sli/northbound/uebclient/SdncVFCModelTest.java | 36 ++++++++++ .../uebclient/SdncVFModuleModelTest.java | 20 ++++++ .../northbound/uebclient/TestSdncUebCallback.java | 82 +++++++++++++++++++++- 9 files changed, 378 insertions(+), 1 deletion(-) create mode 100644 asdcApi/provider/src/test/java/org/onap/ccsdk/sli/northbound/asdcapi/AsdcApiSliClientTest.java create mode 100644 asdcApi/provider/src/test/java/org/onap/ccsdk/sli/northbound/asdcapi/AsdcApiUtilTest.java create mode 100644 dataChange/provider/src/test/java/org/onap/sdnc/northbound/dataChange/DataChangeClientTest.java create mode 100644 dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncFlatJsonDmaapConsumerTest.java create mode 100644 ueb-listener/src/test/java/org/onap/ccsdk/sli/northbound/uebclient/SdncARModelTest.java create mode 100644 ueb-listener/src/test/java/org/onap/ccsdk/sli/northbound/uebclient/SdncNodeModelTest.java create mode 100644 ueb-listener/src/test/java/org/onap/ccsdk/sli/northbound/uebclient/SdncVFCModelTest.java create mode 100644 ueb-listener/src/test/java/org/onap/ccsdk/sli/northbound/uebclient/SdncVFModuleModelTest.java (limited to 'dmaap-listener/src') diff --git a/asdcApi/provider/src/test/java/org/onap/ccsdk/sli/northbound/asdcapi/AsdcApiSliClientTest.java b/asdcApi/provider/src/test/java/org/onap/ccsdk/sli/northbound/asdcapi/AsdcApiSliClientTest.java new file mode 100644 index 000000000..5e6a9daf7 --- /dev/null +++ b/asdcApi/provider/src/test/java/org/onap/ccsdk/sli/northbound/asdcapi/AsdcApiSliClientTest.java @@ -0,0 +1,59 @@ +package org.onap.ccsdk.sli.northbound.asdcapi; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; + +import java.util.Properties; + +import org.junit.Before; +import org.junit.Test; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.provider.SvcLogicService; + +public class AsdcApiSliClientTest { + Properties mockProp; + Properties propReturn; + AsdcApiSliClient testAsdcApiSliClient; + + @Before + public void setup() { + SvcLogicService mockSvcLogic = mock(SvcLogicService.class); + mockProp = new Properties(); + mockProp.setProperty("test-value1", "value1"); + propReturn = new Properties(); + propReturn.setProperty("SvcLogic.status", "Success"); + propReturn.setProperty("Object1", "value1"); + try { + when(mockSvcLogic.hasGraph("TestModule", "TestRPC", "TestVersion", "TestMode")).thenReturn(true); + when(mockSvcLogic.hasGraph("NotExist", "TestRPC", "TestVersion", "TestMode")).thenReturn(false); + when(mockSvcLogic.execute("TestModule", "TestRPC", "TestVersion", "TestMode", mockProp)).thenReturn(propReturn); + } catch (Exception e) { + System.out.println(e); + } + + testAsdcApiSliClient = new AsdcApiSliClient(mockSvcLogic); + } + + @Test + public void testhasGraphGraphExsists() throws SvcLogicException { + assertTrue(testAsdcApiSliClient.hasGraph("TestModule", "TestRPC", "TestVersion", "TestMode")); + } + + @Test + public void testhasGraphnoGraph() throws SvcLogicException { + assertFalse(testAsdcApiSliClient.hasGraph("NotExist", "TestRPC", "TestVersion", "TestMode")); + } + + @Test + public void testExecutewithSvcLogicSuccess() throws SvcLogicException { + Properties result = testAsdcApiSliClient.execute("TestModule", "TestRPC", "TestVersion", "TestMode", mockProp); + assertEquals(result.getProperty("error-code"), "200"); + } + + @Test + public void testExecutewithSvcLogicFailure500() throws SvcLogicException { + propReturn.setProperty("SvcLogic.status", "failure"); + Properties result = testAsdcApiSliClient.execute("TestModule", "TestRPC", "TestVersion", "TestMode", mockProp); + assertEquals(result.getProperty("error-code"), "500"); + } +} \ No newline at end of file diff --git a/asdcApi/provider/src/test/java/org/onap/ccsdk/sli/northbound/asdcapi/AsdcApiUtilTest.java b/asdcApi/provider/src/test/java/org/onap/ccsdk/sli/northbound/asdcapi/AsdcApiUtilTest.java new file mode 100644 index 000000000..463e5ea0b --- /dev/null +++ b/asdcApi/provider/src/test/java/org/onap/ccsdk/sli/northbound/asdcapi/AsdcApiUtilTest.java @@ -0,0 +1,15 @@ +package org.onap.ccsdk.sli.northbound.asdcapi; + +import static org.junit.Assert.*; + +import org.junit.Test; + +public class AsdcApiUtilTest { + + @Test + public void testAsdcApiUtilConstructor() { + AsdcApiUtil asdcApiUtilTest = new AsdcApiUtil(); + assertNotNull(asdcApiUtilTest); + } + +} \ No newline at end of file diff --git a/dataChange/provider/src/test/java/org/onap/sdnc/northbound/dataChange/DataChangeClientTest.java b/dataChange/provider/src/test/java/org/onap/sdnc/northbound/dataChange/DataChangeClientTest.java new file mode 100644 index 000000000..9ba6c8742 --- /dev/null +++ b/dataChange/provider/src/test/java/org/onap/sdnc/northbound/dataChange/DataChangeClientTest.java @@ -0,0 +1,56 @@ +package org.onap.sdnc.northbound.dataChange; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; + +import java.util.Properties; + +import org.junit.Before; +import org.junit.Test; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.provider.MdsalHelper; +import org.onap.ccsdk.sli.core.sli.provider.SvcLogicService; +import org.onap.ccsdk.sli.northbound.DataChangeClient; +import org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.northbound.datachange.rev150519.DataChangeNotificationOutputBuilder; + +public class DataChangeClientTest { + + SvcLogicService mockSvcLogicService; + String module = "test-module"; + String rpc = "test-rpc"; + String version = "test-version"; + String mode = "test-mode"; + Properties localProp = new Properties(); + + @Before + public void setUp() throws Exception { + mockSvcLogicService = mock(SvcLogicService.class); + when(mockSvcLogicService.hasGraph(module, rpc, version, mode)).thenReturn(true); + } + + @Test + public void testDataChangeClientConstructor() { + DataChangeClient dataChangeClient = new DataChangeClient(mockSvcLogicService); + assertNotNull(dataChangeClient); + } + + @Test + public void testHasGraph() throws SvcLogicException { + DataChangeClient dataChangeClient = new DataChangeClient(mockSvcLogicService); + boolean result = dataChangeClient.hasGraph(module, rpc, version, mode); + assertTrue(result); + } + + @Test + public void testExecuteSvcLogicStatusFailure() throws SvcLogicException { + DataChangeNotificationOutputBuilder serviceData = mock(DataChangeNotificationOutputBuilder.class); + Properties parms = mock(Properties.class); + SvcLogicService svcLogicService = mock(SvcLogicService.class); + Properties properties = new Properties(); + properties.setProperty("SvcLogic.status", "failure"); + when(svcLogicService.execute(module, rpc, version, mode, properties)).thenReturn(properties); + DataChangeClient sliClient = new DataChangeClient(svcLogicService); + Properties prop = sliClient.execute(module, rpc, version, mode, serviceData, properties); + assertTrue(prop != null); + } +} \ No newline at end of file diff --git a/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncFlatJsonDmaapConsumerTest.java b/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncFlatJsonDmaapConsumerTest.java new file mode 100644 index 000000000..d1aee634d --- /dev/null +++ b/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncFlatJsonDmaapConsumerTest.java @@ -0,0 +1,41 @@ +package org.onap.ccsdk.sli.northbound.dmaapclient; + +import static org.junit.Assert.*; + + +import java.io.File; + +import org.junit.Before; +import org.junit.Test; + +public class SdncFlatJsonDmaapConsumerTest { + + private static final String DMAAP_LISTENER_PROPERTIES = "dmaap-listener.properties"; + private static final String DMAAP_LISTENER_PROPERTIES_DIR = "src/test/resources"; + + SdncFlatJsonDmaapConsumer consumer; + + @Before + public void setUp() throws Exception { + consumer = new SdncFlatJsonDmaapConsumer(); + } + + @Test(expected = InvalidMessageException.class) + public void testProcessMsgString_NullInvalidMessageException() throws InvalidMessageException { + // expected = InvalidMessageException: Null message + consumer.processMsg(null); + } + + @Test(expected = InvalidMessageException.class) + public void testProcessMsgString_UnformatedMessageInvalidMessageException() throws InvalidMessageException { + // expected = InvalidMessageException: Cannot parse json object + consumer.processMsg("TESTING", null); + } + + @Test(expected = InvalidMessageException.class) + public void testing()throws InvalidMessageException { + // Expected = InvalidMessageException: Unable to process message - cannot load field mappings + String msg = "{\"test\":\"string\"}"; + consumer.processMsg(msg, null); + } +} \ No newline at end of file diff --git a/ueb-listener/src/test/java/org/onap/ccsdk/sli/northbound/uebclient/SdncARModelTest.java b/ueb-listener/src/test/java/org/onap/ccsdk/sli/northbound/uebclient/SdncARModelTest.java new file mode 100644 index 000000000..0d152e5e0 --- /dev/null +++ b/ueb-listener/src/test/java/org/onap/ccsdk/sli/northbound/uebclient/SdncARModelTest.java @@ -0,0 +1,21 @@ +package org.onap.ccsdk.sli.northbound.uebclient; + + import static org.junit.Assert.*; + import static org.mockito.Mockito.*; + + import org.junit.Test; + import org.openecomp.sdc.tosca.parser.api.ISdcCsarHelper; + import org.openecomp.sdc.toscaparser.api.NodeTemplate; + + public class SdncARModelTest { + + @Test + public void testSdncARModelConstructor() { + ISdcCsarHelper mockCsarHelper = mock(ISdcCsarHelper.class); + NodeTemplate nodeTemplate = mock(NodeTemplate.class); + SdncARModel testSdncARModel = new SdncARModel(mockCsarHelper,nodeTemplate); + assertNotNull(testSdncARModel); + } + + } + diff --git a/ueb-listener/src/test/java/org/onap/ccsdk/sli/northbound/uebclient/SdncNodeModelTest.java b/ueb-listener/src/test/java/org/onap/ccsdk/sli/northbound/uebclient/SdncNodeModelTest.java new file mode 100644 index 000000000..4a66c0201 --- /dev/null +++ b/ueb-listener/src/test/java/org/onap/ccsdk/sli/northbound/uebclient/SdncNodeModelTest.java @@ -0,0 +1,49 @@ +package org.onap.ccsdk.sli.northbound.uebclient; + +import static org.junit.Assert.*; + +import static org.mockito.Mockito.*; + +import org.junit.Before; +import org.junit.Test; +import org.openecomp.sdc.tosca.parser.api.ISdcCsarHelper; +import org.openecomp.sdc.toscaparser.api.NodeTemplate; + +public class SdncNodeModelTest { + + SdncNodeModel sdncNodeModel; + + @Before + public void setUp() throws Exception { + ISdcCsarHelper isdcCsarHelper = mock(ISdcCsarHelper.class); + NodeTemplate nodeTemplate = mock(NodeTemplate.class); + sdncNodeModel = new SdncNodeModel(isdcCsarHelper, nodeTemplate); + sdncNodeModel.setServiceUUID("0e8d757f-1c80-40af-85de-31d64f1f5af8"); + sdncNodeModel.setEcompGeneratedNaming("hello-world"); + } + + @Test + public void testGetServiceUUID() { + String result = sdncNodeModel.getServiceUUID(); + assertNotNull(result != null); + } + + @Test + public void testGetEcompGeneratedNaming() { + String result = sdncNodeModel.getEcompGeneratedNaming(); + assertEquals("hello-world", result); + } + + @Test + public void testGetSqlString() { + String result = sdncNodeModel.getSql("TEST-HELLO"); + String test = "INSERT into NETWORK_MODEL (service_uuid, customization_uuid, model_yaml, ecomp_generated_naming) values (0e8d757f-1c80-40af-85de-31d64f1f5af8, \"\", \"TEST-HELLO\", \"hello-world\");"; + assertEquals(test, result); + } + + @Test + public void testGetVpnBindingsSql() { + String result = sdncNodeModel.getVpnBindingsSql(); + assertNotNull(result); + } +} \ No newline at end of file diff --git a/ueb-listener/src/test/java/org/onap/ccsdk/sli/northbound/uebclient/SdncVFCModelTest.java b/ueb-listener/src/test/java/org/onap/ccsdk/sli/northbound/uebclient/SdncVFCModelTest.java new file mode 100644 index 000000000..d2bafbf42 --- /dev/null +++ b/ueb-listener/src/test/java/org/onap/ccsdk/sli/northbound/uebclient/SdncVFCModelTest.java @@ -0,0 +1,36 @@ +package org.onap.ccsdk.sli.northbound.uebclient; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; + + +import org.junit.Before; +import org.junit.Test; +import org.openecomp.sdc.tosca.parser.api.ISdcCsarHelper; +import org.openecomp.sdc.toscaparser.api.NodeTemplate; + +public class SdncVFCModelTest { + + SdncVFCModel testSdncVFCModel; + + @Before + public void setup() { + ISdcCsarHelper mockCsarHelper = mock(ISdcCsarHelper.class); + NodeTemplate mockNodeTemplate = mock(NodeTemplate.class); + testSdncVFCModel = new SdncVFCModel(mockCsarHelper, mockNodeTemplate); + testSdncVFCModel.setVmType("Test-type"); + testSdncVFCModel.setVmCount("5"); + + } + + @Test + public void testSdncVFCModelGetVmType() { + assertEquals(testSdncVFCModel.getVmType(), "Test-type"); + } + + @Test + public void testSdncVFCModelGetVmCount() { + assertEquals(testSdncVFCModel.getVmCount(), "5"); + } + +} \ No newline at end of file diff --git a/ueb-listener/src/test/java/org/onap/ccsdk/sli/northbound/uebclient/SdncVFModuleModelTest.java b/ueb-listener/src/test/java/org/onap/ccsdk/sli/northbound/uebclient/SdncVFModuleModelTest.java new file mode 100644 index 000000000..218554357 --- /dev/null +++ b/ueb-listener/src/test/java/org/onap/ccsdk/sli/northbound/uebclient/SdncVFModuleModelTest.java @@ -0,0 +1,20 @@ +package org.onap.ccsdk.sli.northbound.uebclient; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.mock; + +import org.junit.Test; +import org.openecomp.sdc.tosca.parser.api.ISdcCsarHelper; +import org.openecomp.sdc.toscaparser.api.Group; + +public class SdncVFModuleModelTest { + + @Test + public void testSdncVFModuleModelConstructor() { + Group mockGroup = mock(Group.class); + ISdcCsarHelper mockCsarHelper = mock(ISdcCsarHelper.class); + SdncVFModuleModel testSdncVFModel = new SdncVFModuleModel(mockCsarHelper, mockGroup); + assertNotNull(testSdncVFModel); + } + +} \ No newline at end of file diff --git a/ueb-listener/src/test/java/org/onap/ccsdk/sli/northbound/uebclient/TestSdncUebCallback.java b/ueb-listener/src/test/java/org/onap/ccsdk/sli/northbound/uebclient/TestSdncUebCallback.java index 79a598ce5..21854f990 100644 --- a/ueb-listener/src/test/java/org/onap/ccsdk/sli/northbound/uebclient/TestSdncUebCallback.java +++ b/ueb-listener/src/test/java/org/onap/ccsdk/sli/northbound/uebclient/TestSdncUebCallback.java @@ -1,6 +1,7 @@ package org.onap.ccsdk.sli.northbound.uebclient; -import static org.mockito.Mockito.mock; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.*; import java.io.File; import java.io.InputStream; @@ -9,6 +10,8 @@ import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; +import java.util.ArrayList; +import java.util.List; import java.util.Properties; import org.junit.After; @@ -16,7 +19,9 @@ import org.junit.Before; import org.junit.Test; import org.onap.ccsdk.sli.core.dblib.DBResourceManager; import org.openecomp.sdc.api.IDistributionClient; +import org.openecomp.sdc.api.notification.IArtifactInfo; import org.openecomp.sdc.api.notification.INotificationData; +import org.openecomp.sdc.api.notification.IResourceInstance; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -149,6 +154,15 @@ public class TestSdncUebCallback { SdncUebConfiguration config; DBResourceManager dblibSvc; DB db; + List processLevelArtifactList; + List serviceLevelArtifactList; + ArrayList resourceList; + IArtifactInfo mockProcessArtifact1; + IArtifactInfo mockProcessArtifact2; + IArtifactInfo mockProcessArtifact3; + IArtifactInfo mockServiceArtifact1; + IResourceInstance resource; + @Before public void setUp() throws Exception { @@ -186,6 +200,42 @@ public class TestSdncUebCallback { dblibSvc.writeData(CRTBL_VF_MODEL, null, null); dblibSvc.writeData(CRTBL_VF_MODULE_MODEL, null, null); dblibSvc.writeData(CRTBL_ALLOTTED_RESOURCE_MODEL, null, null); + + processLevelArtifactList = new ArrayList<>(); + serviceLevelArtifactList = new ArrayList<>(); + resourceList = new ArrayList<>(); + + + mockProcessArtifact1 = mock(IArtifactInfo.class); + when(mockProcessArtifact1.getArtifactName()).thenReturn("mockProcessArtifact1"); + when(mockProcessArtifact1.getArtifactType()).thenReturn("HEAT"); + when(mockProcessArtifact1.getArtifactURL()).thenReturn("https://asdc.sdc.com/v1/catalog/services/srv1/2.0/resources/aaa/1.0/artifacts/aaa.yml"); + when(mockProcessArtifact1.getArtifactChecksum()).thenReturn("123tfg123 1234ftg"); + when(mockProcessArtifact1.getArtifactTimeout()).thenReturn(110); + + mockProcessArtifact2 = mock(IArtifactInfo.class); + when(mockProcessArtifact1.getArtifactName()).thenReturn("mockProcessArtifact2"); + when(mockProcessArtifact1.getArtifactType()).thenReturn("DG_XML"); + when(mockProcessArtifact1.getArtifactURL()).thenReturn("https://asdc.sdc.com/v1/catalog/services/srv1/2.0/resources/aaa/1.0/artifacts/aaa.yml"); + when(mockProcessArtifact1.getArtifactChecksum()).thenReturn("456jhgt 1234ftg"); + when(mockProcessArtifact1.getArtifactTimeout()).thenReturn(110); + + mockProcessArtifact3 = mock(IArtifactInfo.class); + when(mockProcessArtifact1.getArtifactName()).thenReturn("mockProcessArtifact3"); + when(mockProcessArtifact1.getArtifactType()).thenReturn("HEAT"); + when(mockProcessArtifact1.getArtifactURL()).thenReturn("https://asdc.sdc.com/v1/catalog/services/srv1/2.0/resources/aaa/1.0/artifacts/aaa.yml"); + when(mockProcessArtifact1.getArtifactChecksum()).thenReturn("123tfg123 543gtd"); + when(mockProcessArtifact1.getArtifactTimeout()).thenReturn(110); + + + mockServiceArtifact1 = mock(IArtifactInfo.class); + when(mockServiceArtifact1.getArtifactName()).thenReturn("mockProcessArtifact4"); + when(mockServiceArtifact1.getArtifactType()).thenReturn("HEAT"); + when(mockServiceArtifact1.getArtifactURL()).thenReturn("https://asdc.sdc.com/v1/catalog/services/srv1/2.0/resources/aaa/1.0/artifacts/aaa.yml"); + when(mockServiceArtifact1.getArtifactChecksum()).thenReturn("123t3455 543gtd"); + when(mockServiceArtifact1.getArtifactTimeout()).thenReturn(110); + + resource = mock(IResourceInstance.class); } @After @@ -219,5 +269,35 @@ public class TestSdncUebCallback { INotificationData iData = mock(INotificationData.class); cb.activateCallback(iData); } + + + + @Test + public void testServiceAndProcessArtifactsactivateCallback() { + + try { + processLevelArtifactList.add(mockProcessArtifact1); + processLevelArtifactList.add(mockProcessArtifact2); + processLevelArtifactList.add(mockProcessArtifact3); + + resourceList.add(resource); + serviceLevelArtifactList.add(mockServiceArtifact1); + when(resource.getArtifacts()).thenReturn(serviceLevelArtifactList); + when(resource.getResourceName()).thenReturn("Resource_service_name"); + + + IDistributionClient iDistClient1 = mock(IDistributionClient.class); + INotificationData mockData = mock(INotificationData.class); + when(mockData.getResources()).thenReturn(resourceList); + when(mockData.getServiceName()).thenReturn("Test_service_name"); + when(mockData.getServiceArtifacts()).thenReturn(processLevelArtifactList); + + SdncUebCallback cb1 = new SdncUebCallback(iDistClient1, config); + cb1.activateCallback(mockData); + assertTrue(true); + } catch (Exception e) { + assertTrue(false); + } + } } -- cgit 1.2.3-korg From c0299b921494a59940ab8575a00f1fc11503f1e6 Mon Sep 17 00:00:00 2001 From: Ruchira Agarwal Date: Thu, 3 May 2018 15:27:29 +0000 Subject: LCM Comsumer for DmaapClient Add LCM Consumer to DmaapCient for Software-Upgrade Change-Id: I0bda76bcd324dda92a6ccb225fd5a059414661f0 Issue-ID: CCSDK-263 Signed-off-by: Ruchira Agarwal --- .../dmaapclient/SdncLcmDmaapConsumer.java | 104 +++++++++++++ .../dmaapclient/TestSdncLcmDmaapConsumer.java | 166 +++++++++++++++++++++ 2 files changed, 270 insertions(+) create mode 100644 dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncLcmDmaapConsumer.java create mode 100644 dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestSdncLcmDmaapConsumer.java (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncLcmDmaapConsumer.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncLcmDmaapConsumer.java new file mode 100644 index 000000000..eb29111dc --- /dev/null +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncLcmDmaapConsumer.java @@ -0,0 +1,104 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : SDN-C + * ================================================================================ + * Copyright (C) 2017 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.northbound.dmaapclient; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SdncLcmDmaapConsumer extends SdncDmaapConsumer { + + private static final Logger LOG = LoggerFactory.getLogger(SdncLcmDmaapConsumer.class); + + private static final String PARTITION = "cambria.partition"; + private static final String PARTITION_VALUE = "SDNC"; + private static final String BODY = "body"; + private static final String RPC = "rpc-name"; + + @Override + public void processMsg(String msg) throws InvalidMessageException { + + if (msg == null) { + throw new InvalidMessageException("Null LCM message"); + } + + ObjectMapper oMapper = new ObjectMapper(); + JsonNode lcmRootNode; + try { + lcmRootNode = oMapper.readTree(msg); + } catch (Exception e) { + throw new InvalidMessageException("Cannot parse LCM json input", e); + } + + JsonNode partitionNode = lcmRootNode.get(PARTITION); + if (partitionNode != null) + { + String partition = partitionNode.textValue(); + if(PARTITION_VALUE.equals(partition) == false) { + LOG.warn("Unknown Partition in LCM message- " + partition); + return; + } + } + + JsonNode bodyNode = lcmRootNode.get(BODY); + if(bodyNode == null) { + LOG.warn("Missing body in LCM message"); + return; + } + String rpcMsgbody; + try { + ObjectMapper mapper = new ObjectMapper(); + rpcMsgbody = mapper.writeValueAsString(bodyNode); + + } catch (Exception e) { + LOG.error("Unable to parse body in LCM message", e); + return; + } + + JsonNode rpcNode = lcmRootNode.get(RPC); + if(rpcNode == null) { + LOG.warn("Missing node in LCM message- " + RPC); + return; + } + String rpc = rpcNode.textValue(); + String sdncEndpoint = "LCM:" + rpc; + + try { + String odlUrlBase = getProperty("sdnc.odl.url-base"); + String odlUser = getProperty("sdnc.odl.user"); + String odlPassword = getProperty("sdnc.odl.password"); + LOG.info("POST LCM Request " + rpcMsgbody); + if ((odlUrlBase != null) && (odlUrlBase.length() > 0)) { + SdncOdlConnection conn = SdncOdlConnection.newInstance(odlUrlBase + "/" + sdncEndpoint, odlUser, odlPassword); + + conn.send("POST", "application/json", rpcMsgbody); + } else { + LOG.warn("Unable to POST LCM message. SDNC URL not available. body:\n" + rpcMsgbody); + } + } catch (Exception e) { + LOG.error("Unable to process message", e); + } + } +} + diff --git a/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestSdncLcmDmaapConsumer.java b/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestSdncLcmDmaapConsumer.java new file mode 100644 index 000000000..4073b5542 --- /dev/null +++ b/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestSdncLcmDmaapConsumer.java @@ -0,0 +1,166 @@ +/* + * Copyright (c) 2017. Lorem ipsum dolor sit amet, consectetur adipiscing elit. + * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan. + * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna. + * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus. + * Vestibulum commodo. Ut rhoncus gravida arcu. + */ + +package org.onap.ccsdk.sli.northbound.dmaapclient; + +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Field; +import java.util.Map; +import java.util.Properties; + +import org.apache.commons.io.FileUtils; + +import org.junit.Before; +import org.junit.Test; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class TestSdncLcmDmaapConsumer { + private static final String lcmInput = + "{\r\n" + + " \"version\": \"lcm-dmaap.version\",\r\n" + + " \"cambria.partition\": \"SDNC\",\r\n" + + " \"correlation-id\": \"lcm-dmaap.correlation-id\",\r\n" + + " \"rpc-name\": \"upgrade-software\",\r\n" + + " \"type\": \"lcm-dmaap.type\",\r\n" + + " \"body\": {\r\n" + + " \"input\": {\r\n" + + " \"common-header\": {\r\n" + + " \"api-ver\": \"lcm-dmaap.api-ver\",\r\n" + + " \"flags\": {\r\n" + + " \"ttl\": \"lcm-dmaap.flags.mode\",\r\n" + + " \"force\": \"lcm-dmaap.flags.force\",\r\n" + + " \"mode\": \"lcm-dmaap.flags.mode\"\r\n" + + " },\r\n" + + " \"originator-id\": \"lcm-dmaap.originator-id\",\r\n" + + " \"request-id\": \"lcm-dmaap.request-id\",\r\n" + + " \"sub-request-id\": \"lcm-dmaap.sub-request-id\",\r\n" + + " \"timestamp\": \"lcm-dmaap.timestamp\"\r\n" + + " },\r\n" + + " \"payload\": \"lcm-dmaap.payload\"\r\n" + + " }\r\n" + + " }\r\n" + + "}"; + + + @Test + public void test() throws Exception { + Properties props = new Properties(); + + SdncLcmDmaapConsumer consumer = new SdncLcmDmaapConsumer(); + InputStream propStr = TestSdncLcmDmaapConsumer.class.getResourceAsStream("/dmaap-consumer-1.properties"); + props.load(propStr); + consumer.init(props, "src/test/resources/dmaap-consumer-1.properties"); + consumer.processMsg(lcmInput); + } + + @Test(expected = InvalidMessageException.class) + public void testProcessMsgNullMessage() throws Exception { + SdncLcmDmaapConsumer consumer = new SdncLcmDmaapConsumer(); + consumer.processMsg(null); + } + + @Test + public void testProcessMsgMissingBody() throws Exception { + String msg = "{\r\n" + + " \"version\": \"lcm-dmaap.version\",\r\n" + + " \"cambria.partition\": \"SDNC\",\r\n" + + " \"correlation-id\": \"lcm-dmaap.correlation-id\",\r\n" + + " \"rpc-name\": \"upgrade-software\",\r\n" + + " \"type\": \"lcm-dmaap.type\",\r\n" + + " \"body1\": {\r\n" + + " \"input\": {\r\n" + + " \"common-header\": {\r\n" + + " \"api-ver\": \"lcm-dmaap.api-ver\",\r\n" + + " \"flags\": {\r\n" + + " \"ttl\": \"lcm-dmaap.flags.mode\",\r\n" + + " \"force\": \"lcm-dmaap.flags.force\",\r\n" + + " \"mode\": \"lcm-dmaap.flags.mode\"\r\n" + + " },\r\n" + + " \"originator-id\": \"lcm-dmaap.originator-id\",\r\n" + + " \"request-id\": \"lcm-dmaap.request-id\",\r\n" + + " \"sub-request-id\": \"lcm-dmaap.sub-request-id\",\r\n" + + " \"timestamp\": \"lcm-dmaap.timestamp\"\r\n" + + " },\r\n" + + " \"payload\": \"lcm-dmaap.payload\"\r\n" + + " }\r\n" + + " }\r\n" + + "}"; + + SdncLcmDmaapConsumer consumer = new SdncLcmDmaapConsumer(); + consumer.processMsg(msg); + } + + @Test + public void testProcessMsgInvalidRPC() throws Exception { + String msg = "{\r\n" + + " \"version\": \"lcm-dmaap.version\",\r\n" + + " \"cambria.partition\": \"SDNC\",\r\n" + + " \"correlation-id\": \"lcm-dmaap.correlation-id\",\r\n" + + " \"rpc-name1\": \"upgrade-software\",\r\n" + + " \"type\": \"lcm-dmaap.type\",\r\n" + + " \"body\": {\r\n" + + " \"input\": {\r\n" + + " \"common-header\": {\r\n" + + " \"api-ver\": \"lcm-dmaap.api-ver\",\r\n" + + " \"flags\": {\r\n" + + " \"ttl\": \"lcm-dmaap.flags.mode\",\r\n" + + " \"force\": \"lcm-dmaap.flags.force\",\r\n" + + " \"mode\": \"lcm-dmaap.flags.mode\"\r\n" + + " },\r\n" + + " \"originator-id\": \"lcm-dmaap.originator-id\",\r\n" + + " \"request-id\": \"lcm-dmaap.request-id\",\r\n" + + " \"sub-request-id\": \"lcm-dmaap.sub-request-id\",\r\n" + + " \"timestamp\": \"lcm-dmaap.timestamp\"\r\n" + + " },\r\n" + + " \"payload\": \"lcm-dmaap.payload\"\r\n" + + " }\r\n" + + " }\r\n" + + "}"; + + SdncLcmDmaapConsumer consumer = new SdncLcmDmaapConsumer(); + consumer.processMsg(msg); + } + + @Test + public void testProcessMsgInvalidPartition() throws Exception { + String msg = "{\r\n" + + " \"version\": \"lcm-dmaap.version\",\r\n" + + " \"cambria.partition\": \"BAD\",\r\n" + + " \"correlation-id\": \"lcm-dmaap.correlation-id\",\r\n" + + " \"rpc-name\": \"upgrade-software\",\r\n" + + " \"type\": \"lcm-dmaap.type\",\r\n" + + " \"body\": {\r\n" + + " \"input\": {\r\n" + + " \"common-header\": {\r\n" + + " \"api-ver\": \"lcm-dmaap.api-ver\",\r\n" + + " \"flags\": {\r\n" + + " \"ttl\": \"lcm-dmaap.flags.mode\",\r\n" + + " \"force\": \"lcm-dmaap.flags.force\",\r\n" + + " \"mode\": \"lcm-dmaap.flags.mode\"\r\n" + + " },\r\n" + + " \"originator-id\": \"lcm-dmaap.originator-id\",\r\n" + + " \"request-id\": \"lcm-dmaap.request-id\",\r\n" + + " \"sub-request-id\": \"lcm-dmaap.sub-request-id\",\r\n" + + " \"timestamp\": \"lcm-dmaap.timestamp\"\r\n" + + " },\r\n" + + " \"payload\": \"lcm-dmaap.payload\"\r\n" + + " }\r\n" + + " }\r\n" + + "}"; + + + SdncLcmDmaapConsumer consumer = new SdncLcmDmaapConsumer(); + consumer.processMsg(msg); + } +} -- cgit 1.2.3-korg From e377e0205a7448af0c8c04dd349c018069d96ddf Mon Sep 17 00:00:00 2001 From: Ruchira Agarwal Date: Wed, 30 May 2018 21:39:35 +0000 Subject: LCMConsumer fix Remove partition edit Change-Id: Id4861a7c4bb46775b770d3511b7cf50f8c49637f Issue-ID: CCSDK-292 Signed-off-by: Ruchira Agarwal --- .../ccsdk/sli/northbound/dmaapclient/SdncLcmDmaapConsumer.java | 10 ---------- 1 file changed, 10 deletions(-) (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncLcmDmaapConsumer.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncLcmDmaapConsumer.java index eb29111dc..53fb6db0f 100644 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncLcmDmaapConsumer.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncLcmDmaapConsumer.java @@ -50,16 +50,6 @@ public class SdncLcmDmaapConsumer extends SdncDmaapConsumer { } catch (Exception e) { throw new InvalidMessageException("Cannot parse LCM json input", e); } - - JsonNode partitionNode = lcmRootNode.get(PARTITION); - if (partitionNode != null) - { - String partition = partitionNode.textValue(); - if(PARTITION_VALUE.equals(partition) == false) { - LOG.warn("Unknown Partition in LCM message- " + partition); - return; - } - } JsonNode bodyNode = lcmRootNode.get(BODY); if(bodyNode == null) { -- cgit 1.2.3-korg From f1b7fecfbe875059793a6ece34b3743f379bb030 Mon Sep 17 00:00:00 2001 From: "Smokowski, Kevin (ks6305)" Date: Tue, 5 Jun 2018 15:57:12 +0000 Subject: Introduce new dmaapClient for use with ccsdk Create an interface and turn existing class into impl file. Write new client which implements the new interface Change-Id: I127bef09bd7f07556a18b753e428e3cd75f5f498 Issue-ID: CCSDK-294 Signed-off-by: Smokowski, Kevin (ks6305) --- dmaap-listener/pom.xml | 15 +- .../northbound/dmaapclient/DummyDmaapConsumer.java | 2 +- .../dmaapclient/MessageRouterHttpClient.java | 194 +++++++++++++++++++++ .../dmaapclient/SdncAaiDmaapConsumer.java | 8 +- .../dmaapclient/SdncDhcpEventConsumer.java | 7 +- .../northbound/dmaapclient/SdncDmaapConsumer.java | 134 +------------- .../dmaapclient/SdncDmaapConsumerImpl.java | 159 +++++++++++++++++ .../dmaapclient/SdncFlatJsonDmaapConsumer.java | 8 +- .../dmaapclient/SdncLcmDmaapConsumer.java | 2 +- 9 files changed, 383 insertions(+), 146 deletions(-) create mode 100644 dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/MessageRouterHttpClient.java create mode 100644 dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncDmaapConsumerImpl.java (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/pom.xml b/dmaap-listener/pom.xml index 6e8b2c051..85f3028fa 100755 --- a/dmaap-listener/pom.xml +++ b/dmaap-listener/pom.xml @@ -30,6 +30,17 @@ ${project.version}-${build.number} + + + + + javax.ws.rs + javax.ws.rs-api + 2.1 + + + + @@ -105,8 +116,8 @@ 2.5.1 true - 1.7 - 1.7 + 1.8 + 1.8 diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/DummyDmaapConsumer.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/DummyDmaapConsumer.java index a8336342f..57fcd8809 100644 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/DummyDmaapConsumer.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/DummyDmaapConsumer.java @@ -24,7 +24,7 @@ package org.onap.ccsdk.sli.northbound.dmaapclient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class DummyDmaapConsumer extends SdncDmaapConsumer { +public class DummyDmaapConsumer extends SdncDmaapConsumerImpl { private static final Logger LOG = LoggerFactory .getLogger(DummyDmaapConsumer.class); diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/MessageRouterHttpClient.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/MessageRouterHttpClient.java new file mode 100644 index 000000000..234a2026b --- /dev/null +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/MessageRouterHttpClient.java @@ -0,0 +1,194 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 - 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.northbound.dmaapclient; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.net.URI; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.Properties; +import java.util.concurrent.TimeUnit; +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.Invocation; +import javax.ws.rs.client.Invocation.Builder; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriBuilder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/* + * jax-rs based client to build message router consumers + */ +public class MessageRouterHttpClient implements SdncDmaapConsumer { + private static final Logger Log = LoggerFactory.getLogger(MessageRouterHttpClient.class); + + protected Boolean isReady = false; + protected Boolean isRunning = false; + protected Client client; + protected URI uri; + protected Invocation getMessages; + protected Integer fetchPause; + protected Properties properties; + protected final String DEFAULT_CONNECT_TIMEOUT_SECONDS = "30"; + protected final String DEFAULT_READ_TIMEOUT_MINUTES = "3"; + protected final String DEFAULT_TIMEOUT_QUERY_PARAM_VALUE = "15000"; + protected final String DEFAULT_LIMIT = null; + + public MessageRouterHttpClient() { + + } + + @Override + public void run() { + if (isReady) { + isRunning = true; + while (isRunning) { + try { + Response response = getMessages.invoke(); + Log.info("GET " + uri + " returned http status " + response.getStatus()); + String entity = response.readEntity(String.class); + if (entity.contains("{")) { + // Get rid of opening [" + entity = entity.substring(2); + // Get rid of closing "] + entity = entity.substring(0, entity.length() - 2); + // This replacement effectively un-escapes the JSON + for (String message : entity.split("\",\"")) { + try { + processMsg(message.replace("\\\"", "\"")); + } catch (InvalidMessageException e) { + Log.error("Message could not be processed", e); + } + } + } else { + Log.info("Entity doesn't appear to contain JSON elements"); + } + } catch (Exception e) { + Log.error("GET " + uri + " failed.", e); + } finally { + Log.info("Pausing " + fetchPause + " milliseconds before fetching from " + uri + " again."); + try { + Thread.sleep(fetchPause); + } catch (InterruptedException e) { + Log.error("Could not sleep thread", e); + } + } + } + } + } + + @Override + public void init(Properties baseProperties, String consumerPropertiesPath) { + try { + baseProperties.load(new FileInputStream(new File(consumerPropertiesPath))); + this.properties = baseProperties; + String username = baseProperties.getProperty("username"); + String password = baseProperties.getProperty("password"); + String topic = baseProperties.getProperty("topic"); + String group = baseProperties.getProperty("group"); + String host = baseProperties.getProperty("host"); + String id = baseProperties.getProperty("id"); + + String filter = baseProperties.getProperty("filter"); + if (filter != null) { + if (filter.length() > 0) { + filter = URLEncoder.encode(filter, StandardCharsets.UTF_8.name()); + } else { + filter = null; + } + } + + String limitString = baseProperties.getProperty("limit", DEFAULT_LIMIT); + Integer limit = null; + if (limitString != null && limitString.length() > 0) { + limit = Integer.valueOf(limitString); + } + + Integer timeoutQueryParamValue = + Integer.valueOf(baseProperties.getProperty("timeout", DEFAULT_TIMEOUT_QUERY_PARAM_VALUE)); + Integer connectTimeoutSeconds = Integer + .valueOf(baseProperties.getProperty("connectTimeoutSeconds", DEFAULT_CONNECT_TIMEOUT_SECONDS)); + Integer readTimeoutMinutes = + Integer.valueOf(baseProperties.getProperty("readTimeoutMinutes", DEFAULT_READ_TIMEOUT_MINUTES)); + + String authorizationString = buildAuthorizationString(username, password); + this.uri = buildUri(topic, group, id, host, timeoutQueryParamValue, limit, filter); + this.client = getClient(connectTimeoutSeconds, readTimeoutMinutes); + Builder builder = + client.target(uri).request("application/json").header("Authorization", authorizationString); + this.getMessages = builder.buildGet(); + this.fetchPause = Integer.valueOf(baseProperties.getProperty("fetchPause")); + this.isReady = true; + } catch (FileNotFoundException e) { + Log.error("FileNotFoundException while reading consumer properties", e); + } catch (IOException e) { + Log.error("IOException while reading consumer properties", e); + } + } + + @Override + public void processMsg(String msg) throws InvalidMessageException { + System.out.println(msg); + } + + @Override + public boolean isReady() { + return isReady; + } + + @Override + public boolean isRunning() { + return isRunning; + } + + protected String buildAuthorizationString(String userName, String password) { + String basicAuthString = userName + ":" + password; + basicAuthString = Base64.getEncoder().encodeToString(basicAuthString.getBytes()); + return "Basic " + basicAuthString; + } + + protected Client getClient(Integer connectTimeoutSeconds, Integer readTimeoutMinutes) { + ClientBuilder clientBuilder = ClientBuilder.newBuilder(); + clientBuilder.connectTimeout(connectTimeoutSeconds, TimeUnit.SECONDS); + clientBuilder.readTimeout(readTimeoutMinutes, TimeUnit.MINUTES); + return clientBuilder.build(); + } + + protected URI buildUri(String topic, String consumerGroup, String consumerId, String host, Integer timeout, + Integer limit, String filter) { + UriBuilder builder = UriBuilder.fromPath("http://" + host + "/events/{topic}/{consumerGroup}/{consumderId}"); + builder.queryParam("timeout", timeout); + if (limit != null) { + builder.queryParam("limit", limit); + } + if (filter != null) { + builder.queryParam("filter", filter); + } + return builder.build(topic, consumerGroup, consumerId); + } + +} diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncAaiDmaapConsumer.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncAaiDmaapConsumer.java index 0e12dfa2e..2c4de7104 100644 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncAaiDmaapConsumer.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncAaiDmaapConsumer.java @@ -21,9 +21,6 @@ package org.onap.ccsdk.sli.northbound.dmaapclient; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - import java.io.BufferedReader; import java.io.File; import java.io.FileReader; @@ -34,14 +31,15 @@ import java.time.Instant; import java.util.HashMap; import java.util.Map; import java.util.Properties; - import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; -public class SdncAaiDmaapConsumer extends SdncDmaapConsumer { +public class SdncAaiDmaapConsumer extends SdncDmaapConsumerImpl { private static final Logger LOG = LoggerFactory.getLogger(SdncAaiDmaapConsumer.class); private static final String SDNC_ENDPOINT = "SDNC.endpoint"; diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncDhcpEventConsumer.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncDhcpEventConsumer.java index 03560d309..7b68ceb63 100644 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncDhcpEventConsumer.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncDhcpEventConsumer.java @@ -5,19 +5,14 @@ import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.SQLException; -import java.util.Iterator; -import java.util.Map; import java.util.Properties; - import org.onap.ccsdk.sli.core.dblib.DBResourceManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ObjectNode; -public class SdncDhcpEventConsumer extends SdncDmaapConsumer { +public class SdncDhcpEventConsumer extends SdncDmaapConsumerImpl { private static final Logger LOG = LoggerFactory.getLogger(SdncDhcpEventConsumer.class); private static final String MAC_ADDR_TAG = "macaddr"; diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncDmaapConsumer.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncDmaapConsumer.java index 2b416e7db..3fc769d35 100644 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncDmaapConsumer.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncDmaapConsumer.java @@ -2,8 +2,8 @@ * ============LICENSE_START======================================================= * openECOMP : SDN-C * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. + * Copyright (C) 2017 - 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. @@ -21,134 +21,14 @@ package org.onap.ccsdk.sli.northbound.dmaapclient; -import com.att.nsa.mr.client.MRClientFactory; -import com.att.nsa.mr.client.MRConsumer; -import com.att.nsa.mr.client.response.MRConsumerResponse; -import java.io.File; -import java.io.FileInputStream; import java.util.Properties; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -public abstract class SdncDmaapConsumer implements Runnable { +public abstract interface SdncDmaapConsumer extends Runnable { + public abstract void init(Properties baseProperties, String consumerPropertiesPath); - private static final Logger LOG = LoggerFactory - .getLogger(SdncDmaapConsumer.class); + public abstract void processMsg(String msg) throws InvalidMessageException; - private Properties properties = null; - private MRConsumer consumer = null; - private MRConsumerResponse consumerResponse = null; - private boolean running = false; - private boolean ready = false; - private int fetchPause = 5000; // Default pause between fetch - 5 seconds - private int timeout = 15000; // Default timeout - 15 seconds + public abstract boolean isReady(); - public SdncDmaapConsumer() { - - } - - public SdncDmaapConsumer(Properties properties, String propertiesPath) { - init(properties, propertiesPath); - } - - public boolean isReady() { - return ready; - } - - public boolean isRunning() { - return running; - } - - public String getProperty(String name) { - return properties.getProperty(name, ""); - } - - public void init(Properties properties, String propertiesPath) { - - try (FileInputStream in = new FileInputStream(new File(propertiesPath))) { - - LOG.debug("propertiesPath: " + propertiesPath); - this.properties = (Properties) properties.clone(); - this.properties.load(in); - - - String timeoutStr = this.properties.getProperty("timeout"); - LOG.debug("timeoutStr: " + timeoutStr); - - if ((timeoutStr != null) && (timeoutStr.length() > 0)) { - timeout = parseTimeOutValue(timeoutStr); - } - - String fetchPauseStr = this.properties.getProperty("fetchPause"); - LOG.debug("fetchPause(Str): " + fetchPauseStr); - if ((fetchPauseStr != null) && (fetchPauseStr.length() > 0)) { - fetchPause = parseFetchPause(fetchPauseStr); - } - LOG.debug("fetchPause: " + fetchPause); - - - this.consumer = MRClientFactory.createConsumer(propertiesPath); - ready = true; - } catch (Exception e) { - LOG.error("Error initializing DMaaP consumer from file " + propertiesPath, e); - } - } - - private int parseTimeOutValue(String timeoutStr) { - try { - return Integer.parseInt(timeoutStr); - } catch (NumberFormatException e) { - LOG.error("Non-numeric value specified for timeout (" + timeoutStr + ")"); - } - return timeout; - } - - private int parseFetchPause(String fetchPauseStr) { - try { - return Integer.parseInt(fetchPauseStr); - } catch (NumberFormatException e) { - LOG.error("Non-numeric value specified for fetchPause (" + fetchPauseStr + ")"); - } - return fetchPause; - } - - - @Override - public void run() { - if (ready) { - - running = true; - - while (running) { - - try { - boolean noData = true; - consumerResponse = consumer.fetchWithReturnConsumerResponse(timeout, -1); - for (String msg : consumerResponse.getActualMessages()) { - noData = false; - LOG.info("Received message from DMaaP:\n" + msg); - processMsg(msg); - } - - if (noData) { - pauseThread(); - } - } catch (Exception e) { - LOG.error("Caught exception reading from DMaaP", e); - running = false; - } - } - } - } - - private void pauseThread() throws InterruptedException { - if (fetchPause > 0) { - LOG.info(String.format("No data received from fetch. Pausing %d ms before retry", fetchPause)); - Thread.sleep(fetchPause); - } else { - LOG.info("No data received from fetch. No fetch pause specified - retrying immediately"); - } - } - - abstract public void processMsg(String msg) throws InvalidMessageException; + public abstract boolean isRunning(); } diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncDmaapConsumerImpl.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncDmaapConsumerImpl.java new file mode 100644 index 000000000..ddd871327 --- /dev/null +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncDmaapConsumerImpl.java @@ -0,0 +1,159 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 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.northbound.dmaapclient; + +import java.io.File; +import java.io.FileInputStream; +import java.util.Properties; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import com.att.nsa.mr.client.MRClientFactory; +import com.att.nsa.mr.client.MRConsumer; +import com.att.nsa.mr.client.response.MRConsumerResponse; + +public abstract class SdncDmaapConsumerImpl implements SdncDmaapConsumer { + + private static final Logger LOG = LoggerFactory + .getLogger(SdncDmaapConsumer.class); + + private final String name = this.getClass().getSimpleName(); + private Properties properties = null; + private MRConsumer consumer = null; + private MRConsumerResponse consumerResponse = null; + private boolean running = false; + private boolean ready = false; + private int fetchPause = 5000; // Default pause between fetch - 5 seconds + private int timeout = 15000; // Default timeout - 15 seconds + + public SdncDmaapConsumerImpl() { + + } + + public SdncDmaapConsumerImpl(Properties properties, String propertiesPath) { + init(properties, propertiesPath); + } + + public boolean isReady() { + return ready; + } + + public boolean isRunning() { + return running; + } + + public String getProperty(String name) { + return properties.getProperty(name, ""); + } + + public void init(Properties properties, String propertiesPath) { + + try (FileInputStream in = new FileInputStream(new File(propertiesPath))) { + + LOG.debug("propertiesPath: " + propertiesPath); + this.properties = (Properties) properties.clone(); + this.properties.load(in); + + + String timeoutStr = this.properties.getProperty("timeout"); + LOG.debug("timeoutStr: " + timeoutStr); + + if ((timeoutStr != null) && (timeoutStr.length() > 0)) { + timeout = parseTimeOutValue(timeoutStr); + } + + String fetchPauseStr = this.properties.getProperty("fetchPause"); + LOG.debug("fetchPause(Str): " + fetchPauseStr); + if ((fetchPauseStr != null) && (fetchPauseStr.length() > 0)) { + fetchPause = parseFetchPause(fetchPauseStr); + } + LOG.debug("fetchPause: " + fetchPause); + + + this.consumer = MRClientFactory.createConsumer(propertiesPath); + ready = true; + } catch (Exception e) { + LOG.error("Error initializing DMaaP consumer from file " + propertiesPath, e); + } + } + + private int parseTimeOutValue(String timeoutStr) { + try { + return Integer.parseInt(timeoutStr); + } catch (NumberFormatException e) { + LOG.error("Non-numeric value specified for timeout (" + timeoutStr + ")"); + } + return timeout; + } + + private int parseFetchPause(String fetchPauseStr) { + try { + return Integer.parseInt(fetchPauseStr); + } catch (NumberFormatException e) { + LOG.error("Non-numeric value specified for fetchPause (" + fetchPauseStr + ")"); + } + return fetchPause; + } + + + @Override + public void run() { + if (ready) { + + running = true; + + while (running) { + + try { + boolean noData = true; + consumerResponse = consumer.fetchWithReturnConsumerResponse(timeout, -1); + for (String msg : consumerResponse.getActualMessages()) { + noData = false; + LOG.info(name + " received ActualMessage from DMaaP:\n"+msg); + processMsg(msg); + } + + if (noData) { + LOG.info(name + " received ResponseCode: " + consumerResponse.getResponseCode()); + LOG.info(name + " received ResponseMessage: " + consumerResponse.getResponseMessage()); + pauseThread(); + } + } catch (Exception e) { + LOG.error("Caught exception reading from DMaaP", e); + running = false; + } + + + } + } + } + + private void pauseThread() throws InterruptedException { + if (fetchPause > 0) { + LOG.info(String.format("No data received from fetch. Pausing %d ms before retry", fetchPause)); + Thread.sleep(fetchPause); + } else { + LOG.info("No data received from fetch. No fetch pause specified - retrying immediately"); + } + } + + abstract public void processMsg(String msg) throws InvalidMessageException; +} diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncFlatJsonDmaapConsumer.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncFlatJsonDmaapConsumer.java index 06e8ebe95..6c90c7199 100644 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncFlatJsonDmaapConsumer.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncFlatJsonDmaapConsumer.java @@ -21,9 +21,6 @@ package org.onap.ccsdk.sli.northbound.dmaapclient; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ObjectNode; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; @@ -32,9 +29,12 @@ import java.util.Iterator; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; -public class SdncFlatJsonDmaapConsumer extends SdncDmaapConsumer { +public class SdncFlatJsonDmaapConsumer extends SdncDmaapConsumerImpl { private static final Logger LOG = LoggerFactory.getLogger(SdncFlatJsonDmaapConsumer.class); diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncLcmDmaapConsumer.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncLcmDmaapConsumer.java index 53fb6db0f..04f520bd9 100644 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncLcmDmaapConsumer.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncLcmDmaapConsumer.java @@ -27,7 +27,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class SdncLcmDmaapConsumer extends SdncDmaapConsumer { +public class SdncLcmDmaapConsumer extends SdncDmaapConsumerImpl { private static final Logger LOG = LoggerFactory.getLogger(SdncLcmDmaapConsumer.class); -- cgit 1.2.3-korg From a07b57086dd5c9c04f2b20a092da9935c7c5f817 Mon Sep 17 00:00:00 2001 From: "Smokowski, Kevin (ks6305)" Date: Fri, 22 Jun 2018 18:32:27 +0000 Subject: check for null usernamd and password only populate auth header if credentials are provided, this support was requested by a client Change-Id: I2fb60995260506a29482d340a031dfad72348b8c Issue-ID: CCSDK-310 Signed-off-by: Smokowski, Kevin (ks6305) --- .../sli/northbound/dmaapclient/MessageRouterHttpClient.java | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/MessageRouterHttpClient.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/MessageRouterHttpClient.java index 234a2026b..d261d1c49 100644 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/MessageRouterHttpClient.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/MessageRouterHttpClient.java @@ -135,11 +135,14 @@ public class MessageRouterHttpClient implements SdncDmaapConsumer { Integer readTimeoutMinutes = Integer.valueOf(baseProperties.getProperty("readTimeoutMinutes", DEFAULT_READ_TIMEOUT_MINUTES)); - String authorizationString = buildAuthorizationString(username, password); + Builder builder = client.target(uri).request("application/json"); + if (username != null && password != null && username.length() > 0 && password.length() > 0) { + String authorizationString = buildAuthorizationString(username, password); + builder.header("Authorization", authorizationString); + } this.uri = buildUri(topic, group, id, host, timeoutQueryParamValue, limit, filter); this.client = getClient(connectTimeoutSeconds, readTimeoutMinutes); - Builder builder = - client.target(uri).request("application/json").header("Authorization", authorizationString); + this.getMessages = builder.buildGet(); this.fetchPause = Integer.valueOf(baseProperties.getProperty("fetchPause")); this.isReady = true; -- cgit 1.2.3-korg From bef4edce8d51394a33fb0de4e57de6f1a39c3b39 Mon Sep 17 00:00:00 2001 From: "Smokowski, Kevin (ks6305)" Date: Thu, 28 Jun 2018 20:56:05 +0000 Subject: additional mr client additional mr client, fewer dependencies Change-Id: I36168fd6e82846a889cd9a01aadf2462bb767723 Issue-ID: CCSDK-327 Signed-off-by: Smokowski, Kevin (ks6305) --- .../dmaapclient/MessageRouterHttpClientJdk.java | 211 +++++++++++++++++++++ 1 file changed, 211 insertions(+) create mode 100644 dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/MessageRouterHttpClientJdk.java (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/MessageRouterHttpClientJdk.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/MessageRouterHttpClientJdk.java new file mode 100644 index 000000000..d720e5fcd --- /dev/null +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/MessageRouterHttpClientJdk.java @@ -0,0 +1,211 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 - 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.northbound.dmaapclient; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.UnsupportedEncodingException; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.Properties; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import java.net.HttpURLConnection; + +/* + * java.net based client to build message router consumers + */ +public class MessageRouterHttpClientJdk implements SdncDmaapConsumer { + private static final Logger Log = LoggerFactory.getLogger(MessageRouterHttpClientJdk.class); + + protected Boolean isReady = false; + protected Boolean isRunning = false; + protected URL url; + protected Integer fetchPause; + protected Properties properties; + protected final String DEFAULT_CONNECT_TIMEOUT = "30000"; + protected final String DEFAULT_READ_TIMEOUT = "180000"; + protected final String DEFAULT_TIMEOUT_QUERY_PARAM_VALUE = "15000"; + protected final String DEFAULT_LIMIT = null; + private String authorizationString; + protected Integer connectTimeout; + protected Integer readTimeout; + protected String topic; + + public MessageRouterHttpClientJdk() {} + + @Override + public void run() { + if (isReady) { + isRunning = true; + while (isRunning) { + HttpURLConnection httpUrlConnection = null; + try { + httpUrlConnection = (HttpURLConnection) url.openConnection(); + if (authorizationString != null) { + httpUrlConnection.addRequestProperty("Authorization", authorizationString); + } + httpUrlConnection.setRequestMethod("GET"); + httpUrlConnection.setRequestProperty("Accept", "application/json"); + httpUrlConnection.setUseCaches(false); + httpUrlConnection.setConnectTimeout(connectTimeout); + httpUrlConnection.setReadTimeout(readTimeout); + httpUrlConnection.connect(); + int status = httpUrlConnection.getResponseCode(); + Log.info("GET " + url + " returned http status " + status); + if (status < 300) { + BufferedReader br = + new BufferedReader(new InputStreamReader(httpUrlConnection.getInputStream())); + StringBuilder sb = new StringBuilder(); + String line; + while ((line = br.readLine()) != null) { + sb.append(line + "\n"); + } + br.close(); + String responseBody = sb.toString(); + if (responseBody.contains("{")) { + // Get rid of opening [" entity = + responseBody = responseBody.substring(2); + // Get rid of closing "] + responseBody = responseBody.substring(0, responseBody.length() - 2); + // Split the json array into individual elements to process + for (String message : responseBody.split("\",\"")) { + // unescape the json + message = message.replace("\\\"", "\""); + // Topic names cannot contain periods + processMsg(message); + } + } else { + Log.info("Entity doesn't appear to contain JSON elements, logging body"); + Log.info(responseBody); + } + } + } catch (Exception e) { + Log.error("GET " + url + " failed.", e); + } finally { + if (httpUrlConnection != null) { + httpUrlConnection.disconnect(); + } + Log.info("Pausing " + fetchPause + " milliseconds before fetching from " + url + " again."); + try { + Thread.sleep(fetchPause); + } catch (InterruptedException e) { + Log.error("Could not sleep thread", e); + } + } + } + } + } + + @Override + public void init(Properties baseProperties, String consumerPropertiesPath) { + try { + baseProperties.load(new FileInputStream(new File(consumerPropertiesPath))); + + this.properties = baseProperties; + String username = properties.getProperty("username"); + String password = properties.getProperty("password"); + topic = properties.getProperty("topic"); + String group = properties.getProperty("group"); + String host = properties.getProperty("host"); + String id = properties.getProperty("id"); + + String filter = properties.getProperty("filter"); + if (filter != null) { + if (filter.length() > 0) { + try { + filter = URLEncoder.encode(filter, StandardCharsets.UTF_8.name()); + } catch (UnsupportedEncodingException e) { + Log.error("Couldn't encode filter string", e); + } + } else { + filter = null; + } + } + + String limitString = properties.getProperty("limit", DEFAULT_LIMIT); + Integer limit = null; + if (limitString != null && limitString.length() > 0) { + limit = Integer.valueOf(limitString); + } + + Integer timeoutQueryParamValue = + Integer.valueOf(properties.getProperty("timeout", DEFAULT_TIMEOUT_QUERY_PARAM_VALUE)); + connectTimeout = Integer.valueOf(properties.getProperty("connectTimeoutSeconds", DEFAULT_CONNECT_TIMEOUT)); + readTimeout = Integer.valueOf(properties.getProperty("readTimeoutMinutes", DEFAULT_READ_TIMEOUT)); + if (username != null && password != null && username.length() > 0 && password.length() > 0) { + authorizationString = buildAuthorizationString(username, password); + } + String urlString = buildlUrlString(topic, group, id, host, timeoutQueryParamValue, limit, filter); + this.url = new URL(urlString); + this.fetchPause = Integer.valueOf(properties.getProperty("fetchPause")); + this.isReady = true; + } catch (FileNotFoundException e) { + Log.error("FileNotFoundException while reading consumer properties", e); + } catch (IOException e) { + Log.error("IOException while reading consumer properties", e); + } + } + + public void processMsg(String msg) { + Log.info(msg); + } + + protected String buildAuthorizationString(String userName, String password) { + String basicAuthString = userName + ":" + password; + basicAuthString = Base64.getEncoder().encodeToString(basicAuthString.getBytes()); + return "Basic " + basicAuthString; + } + + protected String buildlUrlString(String topic, String consumerGroup, String consumerId, String host, + Integer timeout, Integer limit, String filter) { + StringBuilder sb = new StringBuilder(); + sb.append("http://" + host + "/events/" + topic + "/" + consumerGroup + "/" + consumerId); + sb.append("?timeout=" + timeout); + + if (limit != null) { + sb.append("&limit=" + limit); + } + if (filter != null) { + sb.append("&filter=" + filter); + } + return sb.toString(); + } + + @Override + public boolean isReady() { + return isReady; + } + + @Override + public boolean isRunning() { + return isRunning; + } + +} -- cgit 1.2.3-korg From b13fc8a9b134c43a437d7a48ceb509295df4713a Mon Sep 17 00:00:00 2001 From: "Smokowski, Kevin (ks6305)" Date: Mon, 2 Jul 2018 20:01:02 +0000 Subject: Increase code coverage for MR clients Increase code coverage for MR clients Change-Id: I4493b13070f967bc6b20e6770fa16c4df97c2b8c Issue-ID: CCSDK-328 Signed-off-by: Smokowski, Kevin (ks6305) --- .../dmaapclient/MessageRouterHttpClient.java | 88 +++-- .../dmaapclient/MessageRouterHttpClientJdk.java | 432 +++++++++++---------- .../MessageRouterHttpClientJdkTest.java | 100 +++++ .../dmaapclient/MessageRouterHttpClientTest.java | 97 +++++ 4 files changed, 467 insertions(+), 250 deletions(-) create mode 100644 dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/MessageRouterHttpClientJdkTest.java create mode 100644 dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/MessageRouterHttpClientTest.java (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/MessageRouterHttpClient.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/MessageRouterHttpClient.java index d261d1c49..13146e4ec 100644 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/MessageRouterHttpClient.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/MessageRouterHttpClient.java @@ -25,6 +25,7 @@ import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; +import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; @@ -57,6 +58,7 @@ public class MessageRouterHttpClient implements SdncDmaapConsumer { protected final String DEFAULT_READ_TIMEOUT_MINUTES = "3"; protected final String DEFAULT_TIMEOUT_QUERY_PARAM_VALUE = "15000"; protected final String DEFAULT_LIMIT = null; + protected final String DEFAULT_FETCH_PAUSE = "5000"; public MessageRouterHttpClient() { @@ -105,52 +107,60 @@ public class MessageRouterHttpClient implements SdncDmaapConsumer { public void init(Properties baseProperties, String consumerPropertiesPath) { try { baseProperties.load(new FileInputStream(new File(consumerPropertiesPath))); - this.properties = baseProperties; - String username = baseProperties.getProperty("username"); - String password = baseProperties.getProperty("password"); - String topic = baseProperties.getProperty("topic"); - String group = baseProperties.getProperty("group"); - String host = baseProperties.getProperty("host"); - String id = baseProperties.getProperty("id"); - - String filter = baseProperties.getProperty("filter"); - if (filter != null) { - if (filter.length() > 0) { + processProperties(baseProperties); + } catch (FileNotFoundException e) { + Log.error("FileNotFoundException while reading consumer properties", e); + } catch (IOException e) { + Log.error("IOException while reading consumer properties", e); + } + } + + protected void processProperties(Properties properties) { + this.properties = properties; + String username = properties.getProperty("username"); + String password = properties.getProperty("password"); + String topic = properties.getProperty("topic"); + String group = properties.getProperty("group"); + String host = properties.getProperty("host"); + String id = properties.getProperty("id"); + + String filter = properties.getProperty("filter"); + if (filter != null) { + if (filter.length() > 0) { + try { filter = URLEncoder.encode(filter, StandardCharsets.UTF_8.name()); - } else { + } catch (UnsupportedEncodingException e) { + Log.error("Filter could not be encoded, setting to null", e); filter = null; } + } else { + filter = null; } + } - String limitString = baseProperties.getProperty("limit", DEFAULT_LIMIT); - Integer limit = null; - if (limitString != null && limitString.length() > 0) { - limit = Integer.valueOf(limitString); - } - - Integer timeoutQueryParamValue = - Integer.valueOf(baseProperties.getProperty("timeout", DEFAULT_TIMEOUT_QUERY_PARAM_VALUE)); - Integer connectTimeoutSeconds = Integer - .valueOf(baseProperties.getProperty("connectTimeoutSeconds", DEFAULT_CONNECT_TIMEOUT_SECONDS)); - Integer readTimeoutMinutes = - Integer.valueOf(baseProperties.getProperty("readTimeoutMinutes", DEFAULT_READ_TIMEOUT_MINUTES)); - - Builder builder = client.target(uri).request("application/json"); - if (username != null && password != null && username.length() > 0 && password.length() > 0) { - String authorizationString = buildAuthorizationString(username, password); - builder.header("Authorization", authorizationString); - } - this.uri = buildUri(topic, group, id, host, timeoutQueryParamValue, limit, filter); - this.client = getClient(connectTimeoutSeconds, readTimeoutMinutes); + String limitString = properties.getProperty("limit", DEFAULT_LIMIT); + Integer limit = null; + if (limitString != null && limitString.length() > 0) { + limit = Integer.valueOf(limitString); + } - this.getMessages = builder.buildGet(); - this.fetchPause = Integer.valueOf(baseProperties.getProperty("fetchPause")); - this.isReady = true; - } catch (FileNotFoundException e) { - Log.error("FileNotFoundException while reading consumer properties", e); - } catch (IOException e) { - Log.error("IOException while reading consumer properties", e); + Integer timeoutQueryParamValue = + Integer.valueOf(properties.getProperty("timeout", DEFAULT_TIMEOUT_QUERY_PARAM_VALUE)); + Integer connectTimeoutSeconds = Integer + .valueOf(properties.getProperty("connectTimeoutSeconds", DEFAULT_CONNECT_TIMEOUT_SECONDS)); + Integer readTimeoutMinutes = + Integer.valueOf(properties.getProperty("readTimeoutMinutes", DEFAULT_READ_TIMEOUT_MINUTES)); + this.client = getClient(connectTimeoutSeconds, readTimeoutMinutes); + this.uri = buildUri(topic, group, id, host, timeoutQueryParamValue, limit, filter); + Builder builder = client.target(uri).request("application/json"); + if (username != null && password != null && username.length() > 0 && password.length() > 0) { + String authorizationString = buildAuthorizationString(username, password); + builder.header("Authorization", authorizationString); } + + this.getMessages = builder.buildGet(); + this.fetchPause = Integer.valueOf(properties.getProperty("fetchPause",DEFAULT_FETCH_PAUSE)); + this.isReady = true; } @Override diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/MessageRouterHttpClientJdk.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/MessageRouterHttpClientJdk.java index d720e5fcd..3336b81f6 100644 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/MessageRouterHttpClientJdk.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/MessageRouterHttpClientJdk.java @@ -1,211 +1,221 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 - 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.northbound.dmaapclient; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.UnsupportedEncodingException; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLEncoder; -import java.nio.charset.StandardCharsets; -import java.util.Base64; -import java.util.Properties; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import java.net.HttpURLConnection; - -/* - * java.net based client to build message router consumers - */ -public class MessageRouterHttpClientJdk implements SdncDmaapConsumer { - private static final Logger Log = LoggerFactory.getLogger(MessageRouterHttpClientJdk.class); - - protected Boolean isReady = false; - protected Boolean isRunning = false; - protected URL url; - protected Integer fetchPause; - protected Properties properties; - protected final String DEFAULT_CONNECT_TIMEOUT = "30000"; - protected final String DEFAULT_READ_TIMEOUT = "180000"; - protected final String DEFAULT_TIMEOUT_QUERY_PARAM_VALUE = "15000"; - protected final String DEFAULT_LIMIT = null; - private String authorizationString; - protected Integer connectTimeout; - protected Integer readTimeout; - protected String topic; - - public MessageRouterHttpClientJdk() {} - - @Override - public void run() { - if (isReady) { - isRunning = true; - while (isRunning) { - HttpURLConnection httpUrlConnection = null; - try { - httpUrlConnection = (HttpURLConnection) url.openConnection(); - if (authorizationString != null) { - httpUrlConnection.addRequestProperty("Authorization", authorizationString); - } - httpUrlConnection.setRequestMethod("GET"); - httpUrlConnection.setRequestProperty("Accept", "application/json"); - httpUrlConnection.setUseCaches(false); - httpUrlConnection.setConnectTimeout(connectTimeout); - httpUrlConnection.setReadTimeout(readTimeout); - httpUrlConnection.connect(); - int status = httpUrlConnection.getResponseCode(); - Log.info("GET " + url + " returned http status " + status); - if (status < 300) { - BufferedReader br = - new BufferedReader(new InputStreamReader(httpUrlConnection.getInputStream())); - StringBuilder sb = new StringBuilder(); - String line; - while ((line = br.readLine()) != null) { - sb.append(line + "\n"); - } - br.close(); - String responseBody = sb.toString(); - if (responseBody.contains("{")) { - // Get rid of opening [" entity = - responseBody = responseBody.substring(2); - // Get rid of closing "] - responseBody = responseBody.substring(0, responseBody.length() - 2); - // Split the json array into individual elements to process - for (String message : responseBody.split("\",\"")) { - // unescape the json - message = message.replace("\\\"", "\""); - // Topic names cannot contain periods - processMsg(message); - } - } else { - Log.info("Entity doesn't appear to contain JSON elements, logging body"); - Log.info(responseBody); - } - } - } catch (Exception e) { - Log.error("GET " + url + " failed.", e); - } finally { - if (httpUrlConnection != null) { - httpUrlConnection.disconnect(); - } - Log.info("Pausing " + fetchPause + " milliseconds before fetching from " + url + " again."); - try { - Thread.sleep(fetchPause); - } catch (InterruptedException e) { - Log.error("Could not sleep thread", e); - } - } - } - } - } - - @Override - public void init(Properties baseProperties, String consumerPropertiesPath) { - try { - baseProperties.load(new FileInputStream(new File(consumerPropertiesPath))); - - this.properties = baseProperties; - String username = properties.getProperty("username"); - String password = properties.getProperty("password"); - topic = properties.getProperty("topic"); - String group = properties.getProperty("group"); - String host = properties.getProperty("host"); - String id = properties.getProperty("id"); - - String filter = properties.getProperty("filter"); - if (filter != null) { - if (filter.length() > 0) { - try { - filter = URLEncoder.encode(filter, StandardCharsets.UTF_8.name()); - } catch (UnsupportedEncodingException e) { - Log.error("Couldn't encode filter string", e); - } - } else { - filter = null; - } - } - - String limitString = properties.getProperty("limit", DEFAULT_LIMIT); - Integer limit = null; - if (limitString != null && limitString.length() > 0) { - limit = Integer.valueOf(limitString); - } - - Integer timeoutQueryParamValue = - Integer.valueOf(properties.getProperty("timeout", DEFAULT_TIMEOUT_QUERY_PARAM_VALUE)); - connectTimeout = Integer.valueOf(properties.getProperty("connectTimeoutSeconds", DEFAULT_CONNECT_TIMEOUT)); - readTimeout = Integer.valueOf(properties.getProperty("readTimeoutMinutes", DEFAULT_READ_TIMEOUT)); - if (username != null && password != null && username.length() > 0 && password.length() > 0) { - authorizationString = buildAuthorizationString(username, password); - } - String urlString = buildlUrlString(topic, group, id, host, timeoutQueryParamValue, limit, filter); - this.url = new URL(urlString); - this.fetchPause = Integer.valueOf(properties.getProperty("fetchPause")); - this.isReady = true; - } catch (FileNotFoundException e) { - Log.error("FileNotFoundException while reading consumer properties", e); - } catch (IOException e) { - Log.error("IOException while reading consumer properties", e); - } - } - - public void processMsg(String msg) { - Log.info(msg); - } - - protected String buildAuthorizationString(String userName, String password) { - String basicAuthString = userName + ":" + password; - basicAuthString = Base64.getEncoder().encodeToString(basicAuthString.getBytes()); - return "Basic " + basicAuthString; - } - - protected String buildlUrlString(String topic, String consumerGroup, String consumerId, String host, - Integer timeout, Integer limit, String filter) { - StringBuilder sb = new StringBuilder(); - sb.append("http://" + host + "/events/" + topic + "/" + consumerGroup + "/" + consumerId); - sb.append("?timeout=" + timeout); - - if (limit != null) { - sb.append("&limit=" + limit); - } - if (filter != null) { - sb.append("&filter=" + filter); - } - return sb.toString(); - } - - @Override - public boolean isReady() { - return isReady; - } - - @Override - public boolean isRunning() { - return isRunning; - } - -} +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 - 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.northbound.dmaapclient; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.UnsupportedEncodingException; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.Properties; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/* + * java.net based client to build message router consumers + */ +public class MessageRouterHttpClientJdk implements SdncDmaapConsumer { + private static final Logger Log = LoggerFactory.getLogger(MessageRouterHttpClientJdk.class); + + protected Boolean isReady = false; + protected Boolean isRunning = false; + protected URL url; + protected Integer fetchPause; + protected Properties properties; + protected final String DEFAULT_CONNECT_TIMEOUT = "30000"; + protected final String DEFAULT_READ_TIMEOUT = "180000"; + protected final String DEFAULT_TIMEOUT_QUERY_PARAM_VALUE = "15000"; + protected final String DEFAULT_LIMIT = null; + protected final String DEFAULT_FETCH_PAUSE = "5000"; + + private String authorizationString; + protected Integer connectTimeout; + protected Integer readTimeout; + protected String topic; + + public MessageRouterHttpClientJdk() {} + + @Override + public void run() { + if (isReady) { + isRunning = true; + while (isRunning) { + HttpURLConnection httpUrlConnection = null; + try { + httpUrlConnection = buildHttpURLConnection(); + httpUrlConnection.connect(); + int status = httpUrlConnection.getResponseCode(); + Log.info("GET " + url + " returned http status " + status); + if (status < 300) { + BufferedReader br = + new BufferedReader(new InputStreamReader(httpUrlConnection.getInputStream())); + StringBuilder sb = new StringBuilder(); + String line; + while ((line = br.readLine()) != null) { + sb.append(line + "\n"); + } + br.close(); + String responseBody = sb.toString(); + if (responseBody.contains("{")) { + // Get rid of opening [" entity = + responseBody = responseBody.substring(2); + // Get rid of closing "] + responseBody = responseBody.substring(0, responseBody.length() - 2); + // Split the json array into individual elements to process + for (String message : responseBody.split("\",\"")) { + // unescape the json + message = message.replace("\\\"", "\""); + // Topic names cannot contain periods + processMsg(message); + } + } else { + Log.info("Entity doesn't appear to contain JSON elements, logging body"); + Log.info(responseBody); + } + } + } catch (Exception e) { + Log.error("GET " + url + " failed.", e); + } finally { + if (httpUrlConnection != null) { + httpUrlConnection.disconnect(); + } + Log.info("Pausing " + fetchPause + " milliseconds before fetching from " + url + " again."); + try { + Thread.sleep(fetchPause); + } catch (InterruptedException e) { + Log.error("Could not sleep thread", e); + } + } + } + } + } + + @Override + public void init(Properties baseProperties, String consumerPropertiesPath) { + try { + baseProperties.load(new FileInputStream(new File(consumerPropertiesPath))); + processProperties(baseProperties); + } catch (FileNotFoundException e) { + Log.error("FileNotFoundException while reading consumer properties", e); + } catch (IOException e) { + Log.error("IOException while reading consumer properties", e); + } + } + + protected void processProperties(Properties properties) throws MalformedURLException { + this.properties = properties; + String username = properties.getProperty("username"); + String password = properties.getProperty("password"); + topic = properties.getProperty("topic"); + String group = properties.getProperty("group"); + String host = properties.getProperty("host"); + String id = properties.getProperty("id"); + + String filter = properties.getProperty("filter"); + if (filter != null) { + if (filter.length() > 0) { + try { + filter = URLEncoder.encode(filter, StandardCharsets.UTF_8.name()); + } catch (UnsupportedEncodingException e) { + Log.error("Couldn't encode filter string", e); + } + } else { + filter = null; + } + } + + String limitString = properties.getProperty("limit", DEFAULT_LIMIT); + Integer limit = null; + if (limitString != null && limitString.length() > 0) { + limit = Integer.valueOf(limitString); + } + + Integer timeoutQueryParamValue = + Integer.valueOf(properties.getProperty("timeout", DEFAULT_TIMEOUT_QUERY_PARAM_VALUE)); + connectTimeout = Integer.valueOf(properties.getProperty("connectTimeoutSeconds", DEFAULT_CONNECT_TIMEOUT)); + readTimeout = Integer.valueOf(properties.getProperty("readTimeoutMinutes", DEFAULT_READ_TIMEOUT)); + if (username != null && password != null && username.length() > 0 && password.length() > 0) { + authorizationString = buildAuthorizationString(username, password); + } + String urlString = buildlUrlString(topic, group, id, host, timeoutQueryParamValue, limit, filter); + this.url = new URL(urlString); + this.fetchPause = Integer.valueOf(properties.getProperty("fetchPause", DEFAULT_FETCH_PAUSE)); + this.isReady = true; + } + + public void processMsg(String msg) { + Log.info(msg); + } + + protected String buildAuthorizationString(String userName, String password) { + String basicAuthString = userName + ":" + password; + basicAuthString = Base64.getEncoder().encodeToString(basicAuthString.getBytes()); + return "Basic " + basicAuthString; + } + + protected String buildlUrlString(String topic, String consumerGroup, String consumerId, String host, + Integer timeout, Integer limit, String filter) { + StringBuilder sb = new StringBuilder(); + sb.append("http://" + host + "/events/" + topic + "/" + consumerGroup + "/" + consumerId); + sb.append("?timeout=" + timeout); + + if (limit != null) { + sb.append("&limit=" + limit); + } + if (filter != null) { + sb.append("&filter=" + filter); + } + return sb.toString(); + } + + @Override + public boolean isReady() { + return isReady; + } + + @Override + public boolean isRunning() { + return isRunning; + } + + protected HttpURLConnection buildHttpURLConnection() throws IOException { + HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection(); + if (authorizationString != null) { + httpUrlConnection.setRequestProperty("Authorization", authorizationString); + } + httpUrlConnection.setRequestMethod("GET"); + httpUrlConnection.setRequestProperty("Accept", "application/json"); + httpUrlConnection.setUseCaches(false); + httpUrlConnection.setConnectTimeout(connectTimeout); + httpUrlConnection.setReadTimeout(readTimeout); + return httpUrlConnection; + } + +} diff --git a/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/MessageRouterHttpClientJdkTest.java b/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/MessageRouterHttpClientJdkTest.java new file mode 100644 index 000000000..03f832801 --- /dev/null +++ b/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/MessageRouterHttpClientJdkTest.java @@ -0,0 +1,100 @@ +package org.onap.ccsdk.sli.northbound.dmaapclient; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.Properties; +import org.junit.Test; + +public class MessageRouterHttpClientJdkTest { + public MessageRouterHttpClientJdk getClient() throws MalformedURLException { + Properties properties = new Properties(); + properties.put("username", "my_user"); + properties.put("password", "my_password"); + properties.put("topic", "network_automation"); + properties.put("group", "message_processors"); + properties.put("host", "dmaap-server.com"); + properties.put("id", "machine_one"); + properties.put("fetchPause", "3000"); + MessageRouterHttpClientJdk client = new MessageRouterHttpClientJdk(); + client.processProperties(properties); + return client; + } + + @Test + public void processMsg() throws InvalidMessageException, MalformedURLException { + MessageRouterHttpClientJdk client = getClient(); + client.processMsg(null); + } + + @Test + public void isReady() throws InvalidMessageException, MalformedURLException { + MessageRouterHttpClientJdk client = getClient(); + assertEquals(true, client.isReady()); + } + + @Test + public void isRunning() throws InvalidMessageException, MalformedURLException { + MessageRouterHttpClientJdk client = getClient(); + assertEquals(false, client.isRunning()); + } + + @Test + public void buidUrl() throws InvalidMessageException, MalformedURLException { + MessageRouterHttpClientJdk client = getClient(); + assertEquals(new URL( + "http://dmaap-server.com/events/network_automation/message_processors/machine_one?timeout=15000"), + client.url); + } + + @Test + public void buidUrlWithFilter() throws InvalidMessageException, MalformedURLException { + Properties properties = new Properties(); + properties.put("username", "my_user"); + properties.put("password", "my_password"); + properties.put("topic", "network_automation"); + properties.put("group", "message_processors"); + properties.put("host", "dmaap-server.com"); + properties.put("id", "machine_one"); + properties.put("filter", "{\"class\":\"Contains\",\"string\":\"hello\",\"value\":\"world\"}"); + properties.put("fetchPause", "3000"); + MessageRouterHttpClientJdk client = new MessageRouterHttpClientJdk(); + client.processProperties(properties); + assertEquals(new URL( + "http://dmaap-server.com/events/network_automation/message_processors/machine_one?timeout=15000&filter=%7B%22class%22%3A%22Contains%22%2C%22string%22%3A%22hello%22%2C%22value%22%3A%22world%22%7D"), + client.url); + } + + @Test + public void buildAuthorizationString() throws InvalidMessageException, MalformedURLException { + MessageRouterHttpClientJdk client = getClient(); + String authString = client.buildAuthorizationString("Hello", "World"); + assertEquals("Basic SGVsbG86V29ybGQ=", authString); + } + + @Test + public void clientFromProperties() throws InvalidMessageException, MalformedURLException { + MessageRouterHttpClientJdk client = new MessageRouterHttpClientJdk(); + Properties props = new Properties(); + client.init(props, "src/test/resources/dmaap-consumer-1.properties"); + assertEquals(new URL( + "http://localhost:3904/events/ccsdk-topic/ccsdk-unittest/ccsdk_unittest?timeout=15000&limit=1000"), + client.url); + } + + @Test + public void buildHttpURLConnection() throws InvalidMessageException, IOException { + MessageRouterHttpClientJdk client = getClient(); + HttpURLConnection connection = client.buildHttpURLConnection(); + assertEquals("GET", connection.getRequestMethod()); + assertTrue(connection.getRequestProperties().get("Accept").contains("application/json")); + assertEquals(false, connection.getUseCaches()); + Integer defaultConnectTimeout = Integer.valueOf(client.DEFAULT_CONNECT_TIMEOUT); + Integer defaultReadTimeout = Integer.valueOf(client.DEFAULT_READ_TIMEOUT); + assertEquals(defaultConnectTimeout.intValue(), connection.getConnectTimeout()); + assertEquals(defaultReadTimeout.intValue(), connection.getReadTimeout()); + } +} diff --git a/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/MessageRouterHttpClientTest.java b/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/MessageRouterHttpClientTest.java new file mode 100644 index 000000000..7567e2a9e --- /dev/null +++ b/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/MessageRouterHttpClientTest.java @@ -0,0 +1,97 @@ +package org.onap.ccsdk.sli.northbound.dmaapclient; + +import static org.junit.Assert.assertEquals; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Properties; +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import org.junit.Test; + +public class MessageRouterHttpClientTest { + + class MockMessageRouterHttpClient extends MessageRouterHttpClient { + protected Client getClient(Integer connectTimeoutSeconds, Integer readTimeoutMinutes) { + ClientBuilder clientBuilder = ClientBuilder.newBuilder(); + return clientBuilder.build(); + } + } + + public MessageRouterHttpClient getClient() { + Properties properties = new Properties(); + properties.put("username", "my_user"); + properties.put("password", "my_password"); + properties.put("topic", "network_automation"); + properties.put("group", "message_processors"); + properties.put("host", "dmaap-server.com"); + properties.put("id", "machine_one"); + properties.put("fetch", "machine_one"); + + MockMessageRouterHttpClient client = new MockMessageRouterHttpClient(); + client.processProperties(properties); + return client; + } + + @Test + public void processMsg() throws InvalidMessageException, MalformedURLException { + MessageRouterHttpClient client = getClient(); + client.processMsg(null); + } + + @Test + public void isReady() throws InvalidMessageException, MalformedURLException { + MessageRouterHttpClient client = getClient(); + assertEquals(true, client.isReady()); + } + + @Test + public void isRunning() throws InvalidMessageException, MalformedURLException { + MessageRouterHttpClient client = getClient(); + assertEquals(false, client.isRunning()); + } + + @Test + public void buidUrl() throws InvalidMessageException, MalformedURLException, URISyntaxException { + MessageRouterHttpClient client = getClient(); + assertEquals(new URI( + "http://dmaap-server.com/events/network_automation/message_processors/machine_one?timeout=15000"), + client.uri); + } + + @Test + public void buidUrlWithFilter() throws InvalidMessageException, MalformedURLException, URISyntaxException { + Properties properties = new Properties(); + properties.put("username", "my_user"); + properties.put("password", "my_password"); + properties.put("topic", "network_automation"); + properties.put("group", "message_processors"); + properties.put("host", "dmaap-server.com"); + properties.put("id", "machine_one"); + properties.put("filter", "{\"class\":\"Contains\",\"string\":\"hello\",\"value\":\"world\"}"); + properties.put("fetchPause", "3000"); + MessageRouterHttpClient client = new MockMessageRouterHttpClient(); + client.processProperties(properties); + assertEquals(new URI( + "http://dmaap-server.com/events/network_automation/message_processors/machine_one?timeout=15000&filter=%7B%22class%22%3A%22Contains%22%2C%22string%22%3A%22hello%22%2C%22value%22%3A%22world%22%7D"), + client.uri); + } + + @Test + public void buildAuthorizationString() throws InvalidMessageException, MalformedURLException { + MessageRouterHttpClient client = getClient(); + String authString = client.buildAuthorizationString("Hello", "World"); + assertEquals("Basic SGVsbG86V29ybGQ=", authString); + } + + @Test + public void clientFromProperties() throws InvalidMessageException, MalformedURLException, URISyntaxException { + MessageRouterHttpClient client = new MockMessageRouterHttpClient(); + Properties props = new Properties(); + client.init(props, "src/test/resources/dmaap-consumer-1.properties"); + assertEquals(new URI( + "http://localhost:3904/events/ccsdk-topic/ccsdk-unittest/ccsdk_unittest?timeout=15000&limit=1000"), + client.uri); + } + +} -- cgit 1.2.3-korg From 16ecee44bc14dcb0a128cfdabf0ae8b17f1db057 Mon Sep 17 00:00:00 2001 From: Arindam Mondal Date: Tue, 10 Jul 2018 15:11:38 +0900 Subject: Sonar issue fix blocker, critical Issue-ID: CCSDK-332 Change-Id: I8741cb5bf68d71f0376105d2b1683ac05534a001 Signed-off-by: Arindam Mondal --- .../ccsdk/sli/northbound/dmaapclient/MessageRouterHttpClient.java | 1 + .../sli/northbound/dmaapclient/MessageRouterHttpClientJdk.java | 1 + .../org/onap/ccsdk/sli/northbound/uebclient/SdncUebCallback.java | 6 ++---- 3 files changed, 4 insertions(+), 4 deletions(-) (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/MessageRouterHttpClient.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/MessageRouterHttpClient.java index 13146e4ec..c02ec5df3 100644 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/MessageRouterHttpClient.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/MessageRouterHttpClient.java @@ -97,6 +97,7 @@ public class MessageRouterHttpClient implements SdncDmaapConsumer { Thread.sleep(fetchPause); } catch (InterruptedException e) { Log.error("Could not sleep thread", e); + Thread.currentThread().interrupt(); } } } diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/MessageRouterHttpClientJdk.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/MessageRouterHttpClientJdk.java index 3336b81f6..a6744045d 100644 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/MessageRouterHttpClientJdk.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/MessageRouterHttpClientJdk.java @@ -111,6 +111,7 @@ public class MessageRouterHttpClientJdk implements SdncDmaapConsumer { Thread.sleep(fetchPause); } catch (InterruptedException e) { Log.error("Could not sleep thread", e); + Thread.currentThread().interrupt(); } } } diff --git a/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncUebCallback.java b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncUebCallback.java index 8ea041e61..4ae5acd99 100644 --- a/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncUebCallback.java +++ b/ueb-listener/src/main/java/org/onap/ccsdk/sli/northbound/uebclient/SdncUebCallback.java @@ -399,8 +399,7 @@ public class SdncUebCallback implements INotificationCallback { // Save zip if TOSCA_CSAR if (artifact.getArtifactType().contains("TOSCA_CSAR") || artifact.getArtifactName().contains(".csar")) { - try { - FileOutputStream outFile = new FileOutputStream(incomingDir.getAbsolutePath() + "/" + artifact.getArtifactName()); + try(FileOutputStream outFile = new FileOutputStream(incomingDir.getAbsolutePath() + "/" + artifact.getArtifactName())) { outFile.write(payloadBytes, 0, payloadBytes.length); outFile.close(); writeSucceeded = true; @@ -411,8 +410,7 @@ public class SdncUebCallback implements INotificationCallback { } else { String payload = new String(payloadBytes); - try { - FileWriter spoolFileWriter = new FileWriter(spoolFile); + try(FileWriter spoolFileWriter = new FileWriter(spoolFile)) { spoolFileWriter.write(payload); spoolFileWriter.close(); writeSucceeded = true; -- cgit 1.2.3-korg From be74be10e66d9a5d127c6280f802ef173dbf17de Mon Sep 17 00:00:00 2001 From: "shashikanth.vh" Date: Thu, 19 Jul 2018 15:11:17 +0530 Subject: Added dmaap consumer for esr-thirdparty AAI events Modified SdncAaiDmaapConsumer.java to handle AAI EVENT for esr-thirdparty-sdnc and template Change-Id: I8aaa2e649a722d8d51f0b3329c94541396fde96b Issue-ID: CCSDK-389 Signed-off-by: shashikanth.vh --- .../dmaapclient/SdncAaiDmaapConsumer.java | 154 +++++++++++++++------ .../src/main/resources/esr-thirdparty-sdnc.map | 5 + .../main/resources/template-esr-thirdparty-sdnc.vt | 100 +++++++++++++ .../dmaapclient/TestSdncEsrDmaapReceiver.java | 140 +++++++++++++++++++ .../dmaap-consumer-esrsysteminfo.properties | 34 +++++ .../src/test/resources/dmaap-listener.properties | 2 +- 6 files changed, 391 insertions(+), 44 deletions(-) create mode 100644 dmaap-listener/src/main/resources/esr-thirdparty-sdnc.map create mode 100644 dmaap-listener/src/main/resources/template-esr-thirdparty-sdnc.vt create mode 100644 dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestSdncEsrDmaapReceiver.java create mode 100644 dmaap-listener/src/test/resources/dmaap-consumer-esrsysteminfo.properties (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncAaiDmaapConsumer.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncAaiDmaapConsumer.java index 2c4de7104..be2e36c1a 100644 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncAaiDmaapConsumer.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncAaiDmaapConsumer.java @@ -3,14 +3,14 @@ * openECOMP : SDN-C * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. + * reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. @@ -33,6 +33,7 @@ import java.util.Map; import java.util.Properties; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; +import org.json.JSONArray; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -46,66 +47,133 @@ public class SdncAaiDmaapConsumer extends SdncDmaapConsumerImpl { private static final String TEMPLATE = "SDNC.template"; private static final String DMAAPLISTENERROOT = "DMAAPLISTENERROOT"; + private static final String ESR_SYSTEM_INFO = "esr-system-info"; + private static final String RELATIONSHIP_LIST = "relationship-list"; + private static final String ESR_SYSTEM_INFO_LIST = "esr-system-info-list"; private static final String AAI_EVENT = "AAI-EVENT"; - + private static final String EVENT_TYPE = "event-type"; + private static final String ENTITY = "entity"; private static final String ENTITY_TYPE = "entity-type"; private static final String EVENT_HEADER = "event-header"; - + private String rootDir; protected VelocityEngine velocityEngine; - + public SdncAaiDmaapConsumer() { velocityEngine = new VelocityEngine(); - Properties props = new Properties(); + Properties props = new Properties(); rootDir = System.getenv(DMAAPLISTENERROOT); if ((rootDir == null) || (rootDir.length() == 0)) { - rootDir = "/opt/app/dmaap-listener/lib/"; + rootDir = "/opt/app/dmaap-listener/lib/"; } else { - rootDir = rootDir + "/lib/"; + rootDir = rootDir + "/lib/"; } - - props.put("file.resource.loader.path", rootDir); + + props.put("file.resource.loader.path", rootDir); velocityEngine.init(props); } - + /* * for testing purposes */ SdncAaiDmaapConsumer(Properties props) { - velocityEngine = new VelocityEngine(); + velocityEngine = new VelocityEngine(); velocityEngine.init(props); } - + protected String publish(String templatePath, String jsonString) throws IOException - { - JSONObject jsonObj = new JSONObject(jsonString); - VelocityContext context = new VelocityContext(); - for(Object key : jsonObj.keySet()) - { - context.put((String)key, jsonObj.get((String)key)); - } - - String id = jsonObj.getJSONObject(EVENT_HEADER).get("id").toString(); - context.put("req_id", id); - - context.put("curr_time", Instant.now()); - - ObjectMapper oMapper = new ObjectMapper(); - - String rpcMsgbody = oMapper.writeValueAsString(jsonString); - context.put("full_message", rpcMsgbody); - - Writer writer = new StringWriter(); - velocityEngine.mergeTemplate(templatePath, "UTF-8", context, writer); - writer.flush(); - - return writer.toString(); + { + if (templatePath.contains("esr-thirdparty-sdnc")){ + return publishEsrThirdPartySdnc(templatePath, jsonString); + } else { + return publishFullMessage(templatePath, jsonString); + } + } + + private String publishFullMessage(String templatePath, String jsonString) throws IOException + { + JSONObject jsonObj = new JSONObject(jsonString); + VelocityContext context = new VelocityContext(); + for(Object key : jsonObj.keySet()) + { + context.put((String)key, jsonObj.get((String)key)); + } + + String id = jsonObj.getJSONObject(EVENT_HEADER).get("id").toString(); + context.put("req_id", id); + + context.put("curr_time", Instant.now()); + + ObjectMapper oMapper = new ObjectMapper(); + + String rpcMsgbody = oMapper.writeValueAsString(jsonString); + context.put("full_message", rpcMsgbody); + + Writer writer = new StringWriter(); + velocityEngine.mergeTemplate(templatePath, "UTF-8", context, writer); + writer.flush(); + + return writer.toString(); + } + + private String publishEsrThirdPartySdnc(String templatePath, String jsonString) throws IOException + { + JSONObject jsonObj = new JSONObject(jsonString); + VelocityContext context = new VelocityContext(); + + JSONObject eventHeader = jsonObj.getJSONObject(EVENT_HEADER); + for(Object key : eventHeader.keySet()) + { + if (!key.equals("action")) { + context.put(((String)key).replaceAll("-", ""), eventHeader.get((String)key)); + } else { + String action = (String) eventHeader.get((String) key); + context.put((String)key, action.substring(0,1).toUpperCase() + + action.substring(1).toLowerCase()); + } + } + + JSONObject entityObj = jsonObj.getJSONObject(ENTITY); + for(Object key : entityObj.keySet()) + { + switch((String)key) + { + case ESR_SYSTEM_INFO_LIST : + JSONArray esrSystemInfo = entityObj.getJSONObject((String)key) + .getJSONArray(ESR_SYSTEM_INFO); + + for (int i = 0; i < esrSystemInfo.length(); i++) { + JSONObject objects = esrSystemInfo.getJSONObject(i); + + for (Object name : objects.keySet()) { + context.put(((String)name).replaceAll("-", ""), + objects.get((String)name).toString()); + } + } + break; + + case RELATIONSHIP_LIST : + //convertion not required for relationship + break; + + default : + context.put(((String)key).replaceAll("-", ""), + entityObj.get((String)key).toString()); + break; + } + } + + Writer writer = new StringWriter(); + velocityEngine.mergeTemplate(templatePath, "UTF-8", context, writer); + writer.flush(); + + return writer.toString(); } - + @Override public void processMsg(String msg) throws InvalidMessageException { @@ -171,14 +239,14 @@ public class SdncAaiDmaapConsumer extends SdncDmaapConsumerImpl { } } - private Map loadMap(String mapFilename) { - File mapFile = new File(mapFilename); + private Map loadMap(String mapFilename) { + File mapFile = new File(mapFilename); if (!mapFile.canRead()) { LOG.error(String.format("Cannot read map file (%s)", mapFilename)); return null; } - + Map results = new HashMap<>(); try (BufferedReader mapReader = new BufferedReader(new FileReader(mapFile))) { @@ -199,8 +267,8 @@ public class SdncAaiDmaapConsumer extends SdncDmaapConsumerImpl { LOG.error("Caught exception reading map " + mapFilename, e); return null; } - + return results; - } + } } diff --git a/dmaap-listener/src/main/resources/esr-thirdparty-sdnc.map b/dmaap-listener/src/main/resources/esr-thirdparty-sdnc.map new file mode 100644 index 000000000..603645ebe --- /dev/null +++ b/dmaap-listener/src/main/resources/esr-thirdparty-sdnc.map @@ -0,0 +1,5 @@ +# SDN-C URL +SDNC.endpoint => DataChange:data-change-notification + +# Field mapping +SDNC.template => template-esr-thirdparty-sdnc.vt diff --git a/dmaap-listener/src/main/resources/template-esr-thirdparty-sdnc.vt b/dmaap-listener/src/main/resources/template-esr-thirdparty-sdnc.vt new file mode 100644 index 000000000..225fce026 --- /dev/null +++ b/dmaap-listener/src/main/resources/template-esr-thirdparty-sdnc.vt @@ -0,0 +1,100 @@ +{ + "DataChange:input": { + "DataChange:aai-node-type": "$entitytype", + "DataChange:selflink": "$entitylink", + "DataChange:aai-event-id": "$id", + "DataChange:aai-event-trigger": "$action", + "DataChange:key-data": [{ + "DataChange:key-name": "thirdparty-sdnc-id", + "DataChange:key-value": "$thirdpartysdncid" + }, + { + "DataChange:key-name": "resource-version", + "DataChange:key-value": "$resourceversion" + }, + { + "DataChange:key-name": "location", + "DataChange:key-value": "$location" + }, + { + "DataChange:key-name": "product-name", + "DataChange:key-value": "$productname" + }, + { + "DataChange:key-name": "esr-system-info-id", + "DataChange:key-value": "$esrsysteminfoid" + }, + { + "DataChange:key-name": "system-type", + "DataChange:key-value": "$systemtype" + }, + { + "DataChange:key-name": "service-url", + "DataChange:key-value": "$serviceurl" + }, + { + "DataChange:key-name": "ssl-cacert", + "DataChange:key-value": "$sslcacert" + }, + { + "DataChange:key-name": "type", + "DataChange:key-value": "$type" + }, + { + "DataChange:key-name": "ssl-insecure", + "DataChange:key-value": "$sslinsecure" + }, + { + "DataChange:key-name": "system-status", + "DataChange:key-value": "$systemstatus" + }, + { + "DataChange:key-name": "version", + "DataChange:key-value": "$version" + }, + { + "DataChange:key-name": "passive", + "DataChange:key-value": "$passive" + }, + { + "DataChange:key-name": "password", + "DataChange:key-value": "$password" + }, + { + "DataChange:key-name": "protocol", + "DataChange:key-value": "$protocol" + }, + { + "DataChange:key-name": "ip-address", + "DataChange:key-value": "$ipaddress" + }, + { + "DataChange:key-name": "cloud-domain", + "DataChange:key-value": "$clouddomain" + }, + { + "DataChange:key-name": "user-name", + "DataChange:key-value": "$username" + }, + { + "DataChange:key-name": "system-name", + "DataChange:key-value": "$systemname" + }, + { + "DataChange:key-name": "port", + "DataChange:key-value": "$port" + }, + { + "DataChange:key-name": "vendor", + "DataChange:key-value": "$vendor" + }, + { + "DataChange:key-name": "remote-path", + "DataChange:key-value": "$remotepath" + }, + { + "DataChange:key-name": "default-tenant", + "DataChange:key-value": "$defaulttenant" + }] + } +} diff --git a/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestSdncEsrDmaapReceiver.java b/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestSdncEsrDmaapReceiver.java new file mode 100644 index 000000000..623c96426 --- /dev/null +++ b/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestSdncEsrDmaapReceiver.java @@ -0,0 +1,140 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - CCSDK + * ================================================================================ + * Copyright (C) 2018 Huawei Technologies Co., Ltd. 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.northbound.dmaapclient; + +import org.apache.commons.io.FileUtils; +import org.junit.Test; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Field; +import java.util.Map; +import java.util.Properties; + +public class TestSdncEsrDmaapReceiver { + static String aaiInput = "{\"cambria.partition\":\"AAI\",\n" + + " \"event-header\":\n" + + " {\n" + + " \"severity\":\"NORMAL\",\n" + + " \"entity-type\":\"esr-thirdparty-sdnc\",\n" + + " \"top-entity-type\":\"esr-thirdparty-sdnc\",\n" + + " \"entity-link\":\"aai/v11/external-system/esr-thirdparty-sdnc-list/esr-thirdparty-sdnc/IP-WAN-Controller-1\",\n" + + " \"event-type\":\"AAI-EVENT\",\n" + + " \"domain\":\"dev\",\n" + + " \"action\":\"UPDATE\",\n" + + " \"sequence-number\":\"0\",\n" + + " \"id\":\"bf4df797-759a-4684-a63c-393b7d40ed55\",\n" + + " \"source-name\":\"postman\",\n" + + " \"version\":\"v11\",\n" + + " \"timestamp\":\"20180104-09:57:58:721\"\n" + + " },\n" + + " \"entity\":\n" + + " {\n" + + " \"thirdparty-sdnc-id\":\"IP-WAN-Controller-1\",\n" + + " \"relationship-list\":\n" + + " {\n" + + " \"relationship\":\n" + + " [\n" + + " {\n" + + " \"related-to\":\"pnf\",\n" + + " \"relationship-data\":\n" + + " [\n" + + " {\n" + + " \"relationship-value\":\"a8098c1a-f86e-11da-bd1a-00112444be1e\",\n" + + " \"relationship-key\":\"pnf.pnf-name\"\n" + + " }\n" + + " ],\n" + + " \"related-link\":\"aai/v11/network/pnfs/pnf/a8098c1a-f86e-11da-bd1a-00112444be1e\"\n" + + " }\n" + + " ]\n" + + " },\n" + + " \"resource-version\":\"1515059878654\",\n" + + " \"location\":\"Core\",\n" + + " \"product-name\":\"AC-WAN\",\n" + + " \"esr-system-info-list\":\n" + + " {\"esr-system-info\":\n" + + " [\n" + + " {\n" + + " \"esr-system-info-id\":\"IP-WAN-Controller-ESR-1\",\n" + + " \"system-type\":\"example-system-type-val-12078\",\n" + + " \"service-url\":\"https://182.2.61.24:18002\",\n" + + " \"ssl-cacert\":\"example-ssl-cacert-val-20589\",\n" + + " \"type\":\"WAN\",\n" + + " \"ssl-insecure\":true,\n" + + " \"system-status\":\"example-system-status-val-23435\",\n" + + " \"version\":\"V3R1\",\n" + + " \"passive\":true,\n" + + " \"password\":\"Admin@12345\",\n" + + " \"protocol\":\"RESTCONF\",\n" + + " \"ip-address\":\"182.2.61.24\",\n" + + " \"cloud-domain\":\"example-cloud-domain-val-76077\",\n" + + " \"user-name\":\"admin\",\n" + + " \"system-name\":\"IP-WAN-Controller\",\n" + + " \"port\":\"18002\",\n" + + " \"vendor\":\"IP-WAN\",\n" + + " \"resource-version\":\"1515059878666\",\n" + + " \"remote-path\":\"example-remotepath-val-5833\",\n" + + " \"default-tenant\":\"example-default-tenant-val-71148\"\n" + + " }\n" + + " ]\n" + + " }\n" + + " }\n" + + " }"; + + @Test + public void testProcessMsgInvalidEventType() throws Exception { + String DMAAPLISTENERROOT = "DMAAPLISTENERROOT"; + File directory = new File("lib"); + + if (! directory.exists()){ + directory.mkdir(); + } + + File source = new File("src/main/resources"); + File dest = new File("lib/"); + try { + FileUtils.copyDirectory(source, dest); + } catch (IOException e) { + e.printStackTrace(); + } + + try { + Map env = System.getenv(); + Class cl = env.getClass(); + Field field = cl.getDeclaredField("m"); + field.setAccessible(true); + Map writableEnv = (Map) field.get(env); + writableEnv.put(DMAAPLISTENERROOT, "."); + } catch (Exception e) { + throw new IllegalStateException("Failed to set environment variable", e); + } + Properties props = new Properties(); + InputStream propStr = TestSdncEsrDmaapReceiver.class.getResourceAsStream("/dmaap-consumer-esrsysteminfo.properties"); + + props.load(propStr); + + SdncAaiDmaapConsumer consumer = new SdncAaiDmaapConsumer(); + + consumer.init(props, "src/test/resources/dmaap-consumer-esrsysteminfo.properties"); + consumer.processMsg(aaiInput); + } +} diff --git a/dmaap-listener/src/test/resources/dmaap-consumer-esrsysteminfo.properties b/dmaap-listener/src/test/resources/dmaap-consumer-esrsysteminfo.properties new file mode 100644 index 000000000..9f5cfe71f --- /dev/null +++ b/dmaap-listener/src/test/resources/dmaap-consumer-esrsysteminfo.properties @@ -0,0 +1,34 @@ +TransportType=DME2 +Latitude =47.778998 +Longitude =-122.182883 +Version =1.0 +ServiceName =dmaap-v1.dev.dmaap.dt.saat.acsi.att.com/events +Environment =TEST +Partner = +SubContextPath =/ +Protocol =https +MethodType =GET +username =test +password =test +contenttype =application/json +authKey=ABC123 +authDate=2016-05-10T13:13:50-0700 +host=localhost:3904 +topic=AAI-EVENT +group=pserver +id=1 +timeout=20000 +limit=10000 +filter={"class":"Equals","field":"event-header.entity-type","value":"pserver"} +AFT_DME2_EXCHANGE_REQUEST_HANDLERS=com.att.nsa.test.PreferredRouteRequestHandler +AFT_DME2_EXCHANGE_REPLY_HANDLERS=com.att.nsa.test.PreferredRouteReplyHandler +AFT_DME2_REQ_TRACE_ON=true +AFT_ENVIRONMENT=AFTUAT +AFT_DME2_EP_CONN_TIMEOUT=55000 +AFT_DME2_ROUNDTRIP_TIMEOUT_MS=240000 +AFT_DME2_EP_READ_TIMEOUT_MS=50000 +sessionstickinessrequired=NO +DME2preferredRouterFilePath=src/test/resources/dmaap-listener.preferredRoute.txt +sdnc.odl.user=admin +sdnc.odl.password=admin +sdnc.odl.url-base=http://localhost:8181/restconf/operations \ No newline at end of file diff --git a/dmaap-listener/src/test/resources/dmaap-listener.properties b/dmaap-listener/src/test/resources/dmaap-listener.properties index ed180e515..defef0b43 100755 --- a/dmaap-listener/src/test/resources/dmaap-listener.properties +++ b/dmaap-listener/src/test/resources/dmaap-listener.properties @@ -1 +1 @@ -subscriptions=org.onap.ccsdk.sli.northbound.dmaapclient.DummyDmaapConsumer:dmaap-consumer-1.properties \ No newline at end of file +subscriptions=org.onap.ccsdk.sli.northbound.dmaapclient.DummyDmaapConsumer:dmaap-consumer-1.properties;org.onap.ccsdk.sli.northbound.dmaapclient.SdncAaiDmaapConsumer:dmaap-consumer-esrsysteminfo.properties \ No newline at end of file -- cgit 1.2.3-korg From 3c5a179495b00b2e832d304083885aa93e8cdab7 Mon Sep 17 00:00:00 2001 From: "Smokowski, Kevin (ks6305)" Date: Tue, 7 Aug 2018 21:26:44 +0000 Subject: update configuration for onap look for properties in common folder, use java 8 Change-Id: I8a04126d8ac1db0781af9b6a015477e0fc3608dd Issue-ID: CCSDK-448 Signed-off-by: Smokowski, Kevin (ks6305) --- .../org/onap/ccsdk/sli/northbound/dmaapclient/DmaapListener.java | 2 +- dmaap-listener/src/main/scripts/start-dmaap-listener.sh | 6 +++--- dmaap-listener/src/main/scripts/stop-dmaap-listener.sh | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/DmaapListener.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/DmaapListener.java index 2be08cb8b..7e257a125 100644 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/DmaapListener.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/DmaapListener.java @@ -32,7 +32,7 @@ import org.slf4j.LoggerFactory; public class DmaapListener { private static final String DMAAP_LISTENER_PROPERTIES = "dmaap-listener.properties"; - private static final String DMAAP_LISTENER_PROPERTIES_DIR = "/opt/sdnc/data/properties"; + private static final String DMAAP_LISTENER_PROPERTIES_DIR = "/opt/onap/ccsdk/data/properties"; private static final String SDNC_CONFIG_DIR = "SDNC_CONFIG_DIR"; private static final Logger LOG = LoggerFactory.getLogger(DmaapListener.class); diff --git a/dmaap-listener/src/main/scripts/start-dmaap-listener.sh b/dmaap-listener/src/main/scripts/start-dmaap-listener.sh index 164ade332..f767d3cd1 100644 --- a/dmaap-listener/src/main/scripts/start-dmaap-listener.sh +++ b/dmaap-listener/src/main/scripts/start-dmaap-listener.sh @@ -21,15 +21,15 @@ # ============LICENSE_END========================================================= ### -PROPERTY_DIR=${PROPERTY_DIR:-/opt/sdnc/data/properties} +PROPERTY_DIR=${PROPERTY_DIR:-/opt/onap/ccsdk/data/properties} LISTENER=dmaap-listener PIDFILE=/tmp/.${LISTENER}-pid -UEBLISTENERROOT=${UEBLISTENERROOT:-/opt/app/dmaap-listener} -JAVA_HOME=${JAVA_HOME:-/usr/lib/jvm/java-7-oracle} +UEBLISTENERROOT=${UEBLISTENERROOT:-/opt/onap/dmaap-listener} +JAVA_HOME=${JAVA_HOME:-/usr/lib/jvm/java-8-oracle} JAVA_OPTS=${JAVA_OPTS:--Dhttps.protocols=TLSv1.1,TLSv1.2} JAVA=${JAVA:-${JAVA_HOME}/bin/java} diff --git a/dmaap-listener/src/main/scripts/stop-dmaap-listener.sh b/dmaap-listener/src/main/scripts/stop-dmaap-listener.sh index 61be1a141..ab242044f 100644 --- a/dmaap-listener/src/main/scripts/stop-dmaap-listener.sh +++ b/dmaap-listener/src/main/scripts/stop-dmaap-listener.sh @@ -21,13 +21,13 @@ # ============LICENSE_END========================================================= ### -PROPERTY_DIR=${PROPERTY_DIR:-/opt/sdnc/data/properties} +PROPERTY_DIR=${PROPERTY_DIR:-/opt/onap/ccsdk/data/properties} LISTENER=dmaap-listener PIDFILE=/tmp/.${LISTENER}-pid -UEBLISTENERROOT=${UEBLISTENERROOT:-/opt/app/dmaap-listener} +UEBLISTENERROOT=${UEBLISTENERROOT:-/opt/onap/dmaap-listener} if [ -f $PIDFILE ] then -- cgit 1.2.3-korg From 40ff9f9d68660a157f9ff477003fc7b359747148 Mon Sep 17 00:00:00 2001 From: "shashikanth.vh" Date: Fri, 7 Sep 2018 17:30:02 +0530 Subject: Update network topology to aai issue fix Change-Id: I72d25c8df8726430a087613544a274ca724713cb Issue-ID: SDNC-387 Signed-off-by: shashikanth.vh --- .../dmaapclient/SdncAaiDmaapConsumer.java | 29 ++++++++++++---------- 1 file changed, 16 insertions(+), 13 deletions(-) (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncAaiDmaapConsumer.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncAaiDmaapConsumer.java index be2e36c1a..fa9544f3f 100644 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncAaiDmaapConsumer.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncAaiDmaapConsumer.java @@ -132,8 +132,11 @@ public class SdncAaiDmaapConsumer extends SdncDmaapConsumerImpl { context.put(((String)key).replaceAll("-", ""), eventHeader.get((String)key)); } else { String action = (String) eventHeader.get((String) key); - context.put((String)key, action.substring(0,1).toUpperCase() - + action.substring(1).toLowerCase()); + if (action.equalsIgnoreCase("delete")) { + context.put((String) key, "Delete"); + } else { + context.put((String) key, "Update"); + } } } @@ -187,8 +190,8 @@ public class SdncAaiDmaapConsumer extends SdncDmaapConsumerImpl { aaiRootNode = oMapper.readTree(msg); } catch (Exception e) { throw new InvalidMessageException("Cannot parse json object", e); - } - + } + JsonNode eventHeaderNode = aaiRootNode.get(EVENT_HEADER); if(eventHeaderNode == null) { LOG.info("Missing Event Header node."); @@ -196,31 +199,31 @@ public class SdncAaiDmaapConsumer extends SdncDmaapConsumerImpl { } JsonNode eventTypeNode = eventHeaderNode.get(EVENT_TYPE); String eventType = eventTypeNode.textValue(); - + if(AAI_EVENT.equals(eventType) == false) { LOG.info("Unknown Event Type {}", eventType); return; } - + JsonNode entityTypeNode = eventHeaderNode.get(ENTITY_TYPE); String entityType = entityTypeNode.textValue(); - + String mapFilename = rootDir + entityType + ".map"; Map fieldMap = loadMap(mapFilename); if (fieldMap == null) { - throw new InvalidMessageException("Unable to process message - cannot load mapping file"); + return; } if (!fieldMap.containsKey(SDNC_ENDPOINT)) { - throw new InvalidMessageException("No SDNC endpoint known for message " + entityType); + return; } - String sdncEndpoint = fieldMap.get(SDNC_ENDPOINT); - + String sdncEndpoint = fieldMap.get(SDNC_ENDPOINT); + if (!fieldMap.containsKey(TEMPLATE)) { throw new InvalidMessageException("No SDNC template known for message " + entityType); } - String templateName = fieldMap.get(TEMPLATE); - + String templateName = fieldMap.get(TEMPLATE); + try { String rpcMsgbody = publish(templateName, msg); String odlUrlBase = getProperty("sdnc.odl.url-base"); -- cgit 1.2.3-korg From 481cf0c75af442dc223b803e4de8e797b931581d Mon Sep 17 00:00:00 2001 From: "shashikanth.vh" Date: Thu, 20 Sep 2018 17:59:25 +0530 Subject: integration test issues fix for sdwan and sotn On topology discovery, ESR will be updated with pnf relationship resulting in update ESR event causing topology discovery to run in loop. Change-Id: I80d98d5b11f05d395e342479352656364fe071d4 Issue-ID: SDNC-357 Signed-off-by: shashikanth.vh --- .../onap/ccsdk/sli/northbound/dmaapclient/SdncAaiDmaapConsumer.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncAaiDmaapConsumer.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncAaiDmaapConsumer.java index fa9544f3f..3733fa604 100644 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncAaiDmaapConsumer.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncAaiDmaapConsumer.java @@ -132,10 +132,12 @@ public class SdncAaiDmaapConsumer extends SdncDmaapConsumerImpl { context.put(((String)key).replaceAll("-", ""), eventHeader.get((String)key)); } else { String action = (String) eventHeader.get((String) key); - if (action.equalsIgnoreCase("delete")) { + if (action.equalsIgnoreCase("create")) { + context.put((String)key,"Update"); + } else if (action.equalsIgnoreCase("delete")) { context.put((String) key, "Delete"); } else { - context.put((String) key, "Update"); + throw new IOException("Action type not supported " + action); } } } -- cgit 1.2.3-korg From 24794310b1cc8015eb171b8a89a8072c3bcf2434 Mon Sep 17 00:00:00 2001 From: "Smokowski, Kevin (ks6305)" Date: Wed, 10 Oct 2018 20:19:50 +0000 Subject: update handling of dmaap errors Update handling of dmaap errors in MessageRouterHttpClient. Instead of calling processMessage just log the error body message because the downstream client can't handle these type of exceptions. Change-Id: I3cee7f81ecbc316226a38908fb4f07ab04c1b64e Issue-ID: CCSDK-618 Signed-off-by: Smokowski, Kevin (ks6305) --- .../sli/northbound/dmaapclient/DmaapListener.java | 6 +- .../dmaapclient/MessageRouterHttpClient.java | 89 ++++++++++++---------- 2 files changed, 55 insertions(+), 40 deletions(-) mode change 100644 => 100755 dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/DmaapListener.java mode change 100644 => 100755 dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/MessageRouterHttpClient.java (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/DmaapListener.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/DmaapListener.java old mode 100644 new mode 100755 index 7e257a125..18c00d563 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/DmaapListener.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/DmaapListener.java @@ -41,7 +41,11 @@ public class DmaapListener { Properties properties = new Properties(); String propFileName = DMAAP_LISTENER_PROPERTIES; String propPath = null; - String propDir = System.getenv(SDNC_CONFIG_DIR); + String propDir = System.getProperty(SDNC_CONFIG_DIR); + if(propDir == null) { + propDir = System.getenv(SDNC_CONFIG_DIR); + LOG.debug(SDNC_CONFIG_DIR + " read from environment variable with value " + propDir); + } List consumers = new LinkedList<>(); if (args.length > 0) { diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/MessageRouterHttpClient.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/MessageRouterHttpClient.java old mode 100644 new mode 100755 index c02ec5df3..2a9e0b145 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/MessageRouterHttpClient.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/MessageRouterHttpClient.java @@ -64,45 +64,56 @@ public class MessageRouterHttpClient implements SdncDmaapConsumer { } - @Override - public void run() { - if (isReady) { - isRunning = true; - while (isRunning) { - try { - Response response = getMessages.invoke(); - Log.info("GET " + uri + " returned http status " + response.getStatus()); - String entity = response.readEntity(String.class); - if (entity.contains("{")) { - // Get rid of opening [" - entity = entity.substring(2); - // Get rid of closing "] - entity = entity.substring(0, entity.length() - 2); - // This replacement effectively un-escapes the JSON - for (String message : entity.split("\",\"")) { - try { - processMsg(message.replace("\\\"", "\"")); - } catch (InvalidMessageException e) { - Log.error("Message could not be processed", e); - } - } - } else { - Log.info("Entity doesn't appear to contain JSON elements"); - } - } catch (Exception e) { - Log.error("GET " + uri + " failed.", e); - } finally { - Log.info("Pausing " + fetchPause + " milliseconds before fetching from " + uri + " again."); - try { - Thread.sleep(fetchPause); - } catch (InterruptedException e) { - Log.error("Could not sleep thread", e); - Thread.currentThread().interrupt(); - } - } - } - } - } + @Override + public void run() { + if (isReady) { + isRunning = true; + while (isRunning) { + try { + Response response = getMessages.invoke(); + Log.info("GET " + uri + " returned http status " + response.getStatus()); + String entity = response.readEntity(String.class); + if (response.getStatus() < 300) { + if (entity.contains("{")) { + // Get rid of opening [" + entity = entity.substring(2); + // Get rid of closing "] + entity = entity.substring(0, entity.length() - 2); + // This replacement effectively un-escapes the JSON + for (String message : entity.split("\",\"")) { + try { + processMsg(message.replace("\\\"", "\"")); + } catch (InvalidMessageException e) { + Log.error("Message could not be processed", e); + } + } + } else { + if (entity.length() < 1) { + Log.info("GET was successful, but the server returned an empty message body."); + } else { + Log.info( + "GET was successful, but entity is not valid JSON. Message body will be logged, but not processed"); + Log.info(entity); + } + } + } else { + Log.info("GET failed, message body will be logged, but not processed."); + Log.info(entity); + } + } catch (Exception e) { + Log.error("GET " + uri + " failed.", e); + } finally { + Log.info("Pausing " + fetchPause + " milliseconds before fetching from " + uri + " again."); + try { + Thread.sleep(fetchPause); + } catch (InterruptedException e) { + Log.error("Could not sleep thread", e); + Thread.currentThread().interrupt(); + } + } + } + } + } @Override public void init(Properties baseProperties, String consumerPropertiesPath) { -- cgit 1.2.3-korg From 0290fe64a150cab9b7ddfad5ae524716411d40a5 Mon Sep 17 00:00:00 2001 From: Arundathi Patil Date: Tue, 18 Dec 2018 00:35:54 +0530 Subject: Sonar Fix: SdncAaiDmaapConsumer.java Fixed sonar issues/code-smells across this file Issue-ID: CCSDK-850 Change-Id: I4f1bb7109bddfed04ffa85df174fecdaaf9a6798 Signed-off-by: Arundathi Patil --- .../ccsdk/sli/northbound/dmaapclient/SdncAaiDmaapConsumer.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncAaiDmaapConsumer.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncAaiDmaapConsumer.java index 3733fa604..5cf369403 100644 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncAaiDmaapConsumer.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncAaiDmaapConsumer.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights * reserved. + * Modifications Copyright © 2018 IBM. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -128,13 +129,13 @@ public class SdncAaiDmaapConsumer extends SdncDmaapConsumerImpl { JSONObject eventHeader = jsonObj.getJSONObject(EVENT_HEADER); for(Object key : eventHeader.keySet()) { - if (!key.equals("action")) { + if (!("action").equals(key)) { context.put(((String)key).replaceAll("-", ""), eventHeader.get((String)key)); } else { String action = (String) eventHeader.get((String) key); - if (action.equalsIgnoreCase("create")) { + if (("create").equalsIgnoreCase(action)) { context.put((String)key,"Update"); - } else if (action.equalsIgnoreCase("delete")) { + } else if (("delete").equalsIgnoreCase(action)) { context.put((String) key, "Delete"); } else { throw new IOException("Action type not supported " + action); @@ -202,7 +203,7 @@ public class SdncAaiDmaapConsumer extends SdncDmaapConsumerImpl { JsonNode eventTypeNode = eventHeaderNode.get(EVENT_TYPE); String eventType = eventTypeNode.textValue(); - if(AAI_EVENT.equals(eventType) == false) { + if(!AAI_EVENT.equals(eventType)) { LOG.info("Unknown Event Type {}", eventType); return; } -- cgit 1.2.3-korg From 5396e1b390bf7ebeccb5eba01ff563bf39e4fa62 Mon Sep 17 00:00:00 2001 From: Arundathi Patil Date: Tue, 18 Dec 2018 00:41:18 +0530 Subject: Sonar fix: SdncDmaapConsumerImpl.java Fixed sonar issues/code-smells acoss this file Issue-ID: CCSDK-851 Change-Id: Iff1156e2cafc198d00daf546699f0ff4ab34ff43 Signed-off-by: Arundathi Patil --- .../onap/ccsdk/sli/northbound/dmaapclient/SdncDmaapConsumerImpl.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncDmaapConsumerImpl.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncDmaapConsumerImpl.java index ddd871327..ee8bb4d6e 100644 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncDmaapConsumerImpl.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncDmaapConsumerImpl.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights * reserved. + * Modifications Copyright © 2018 IBM. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -155,5 +156,5 @@ public abstract class SdncDmaapConsumerImpl implements SdncDmaapConsumer { } } - abstract public void processMsg(String msg) throws InvalidMessageException; + public abstract void processMsg(String msg) throws InvalidMessageException; } -- cgit 1.2.3-korg From 2420ec6863a87e264d02dc5dd4293b5801b7e31d Mon Sep 17 00:00:00 2001 From: Arundathi Patil Date: Tue, 18 Dec 2018 15:24:11 +0530 Subject: Sonar fix: SdncLcmDmaapConsumer.java Fixed sonar issues/code-smells across this file. Issue-ID: CCSDK-854 Change-Id: I9b25a464b41ce142b6217ff0f7e40beda86eae3a Signed-off-by: Arundathi Patil --- .../onap/ccsdk/sli/northbound/dmaapclient/SdncLcmDmaapConsumer.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncLcmDmaapConsumer.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncLcmDmaapConsumer.java index 04f520bd9..f2153789f 100644 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncLcmDmaapConsumer.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncLcmDmaapConsumer.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights * reserved. + * Modifications Copyright © 2018 IBM. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,8 +32,6 @@ public class SdncLcmDmaapConsumer extends SdncDmaapConsumerImpl { private static final Logger LOG = LoggerFactory.getLogger(SdncLcmDmaapConsumer.class); - private static final String PARTITION = "cambria.partition"; - private static final String PARTITION_VALUE = "SDNC"; private static final String BODY = "body"; private static final String RPC = "rpc-name"; -- cgit 1.2.3-korg From b1cc7a21099f81395a51d63192c976bdc683e616 Mon Sep 17 00:00:00 2001 From: "Stilwell, David (stilwelld)" Date: Mon, 25 Mar 2019 17:01:04 +0000 Subject: Updated edgeRouterStatusChange.map Changes-made: Added additional entries to edgeRouterStatusChange.map Change-Id: I7e7c42d6a4b292b76758fd8cfccf7a091daa016e Issue-ID: CCSDK-1179 Signed-off-by: Stilwell, David (stilwelld) --- .../src/main/resources/edgeRouterStatusChange.map | 23 +++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/src/main/resources/edgeRouterStatusChange.map b/dmaap-listener/src/main/resources/edgeRouterStatusChange.map index 57644bbd5..fa5ff0784 100644 --- a/dmaap-listener/src/main/resources/edgeRouterStatusChange.map +++ b/dmaap-listener/src/main/resources/edgeRouterStatusChange.map @@ -20,4 +20,25 @@ inms_list => inms-list encrypted_access_flag => encrypted-access-flag sw_name => sw-name nmipaddr => nm-addr -function_code => function-code \ No newline at end of file +function_code => function-code + +EquipmentId => equip-id +PTNIIEquipmentName => equip-name +EquipmentType => equip-type +Loopback0 => loopback0 +RouterStatus => prov-status +Region => region +CountryAbbreviation => country +EquipmentNameCode => equip-name-code +ASNumber => as-number +SoftwareName => sw-name +NetworkManagementIPAddress => nm-addr +FunctionCode => function-code +Loopback1 => loopback1 +Loopback2 => loopback2 +Loopback3 => loopback3 +Loopback40 => loopback40 +Loopback65535 => loopback65535 +InmsList => inms-list +EncryptedAccessFlag => encrypted-access-flag + -- cgit 1.2.3-korg From cd1d3ffe4a39154f6bef75108635761828907dd9 Mon Sep 17 00:00:00 2001 From: Sandeep Shah Date: Wed, 10 Apr 2019 21:15:13 -0500 Subject: DMAAP Listener support for SDNR OOF PCI DMAAP Consumer JAVA files and resources (.map, .vt) Change-Id: I0027d3f092afc4b89aed1cc756a62d5eb169f5c3 Issue-ID: CCSDK-1216 Signed-off-by: SandeepLinux --- .../ANRChangesFromPolicyToSDNRDmaapConsumer.java | 343 +++++++++++++++++++++ .../PciChangesFromPolicyToSDNRDmaapConsumer.java | 314 +++++++++++++++++++ .../resources/anr-changes-from-policy-to-sdnr.map | 5 + .../anr-pci-changes-from-policy-to-sndr.vt | 8 + .../resources/pci-changes-from-policy-to-sdnr.map | 5 + 5 files changed, 675 insertions(+) create mode 100644 dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/ANRChangesFromPolicyToSDNRDmaapConsumer.java create mode 100644 dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/PciChangesFromPolicyToSDNRDmaapConsumer.java create mode 100644 dmaap-listener/src/main/resources/anr-changes-from-policy-to-sdnr.map create mode 100644 dmaap-listener/src/main/resources/anr-pci-changes-from-policy-to-sndr.vt create mode 100644 dmaap-listener/src/main/resources/pci-changes-from-policy-to-sdnr.map (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/ANRChangesFromPolicyToSDNRDmaapConsumer.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/ANRChangesFromPolicyToSDNRDmaapConsumer.java new file mode 100644 index 000000000..5bc2c6011 --- /dev/null +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/ANRChangesFromPolicyToSDNRDmaapConsumer.java @@ -0,0 +1,343 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 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.northbound.dmaapclient; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.StringWriter; +import java.io.Writer; +import java.time.Instant; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; +import org.apache.velocity.VelocityContext; +import org.apache.velocity.app.VelocityEngine; +import org.json.JSONArray; +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class ANRChangesFromPolicyToSDNRDmaapConsumer extends SdncDmaapConsumerImpl { + + private static final Logger LOG = LoggerFactory.getLogger(ANRChangesFromPolicyToSDNRDmaapConsumer.class); + private static final String SDNC_ENDPOINT = "SDNC.endpoint"; + private static final String TEMPLATE = "SDNC.template"; + private static final String DMAAPLISTENERROOT = "DMAAPLISTENERROOT"; + + private static final String PARAMETER_NAME = "parameter-name"; + private static final String STRING_VALUE = "string-value"; + private static final String GENERIC_NEIGHBOR_CONFIGURATION_INPUT = "generic-neighbor-configuration-input."; + private static final String GENERIC_NEIGHBOR_CONFIGURATION_INPUT_NEIGHBOR_LIST_IN_USE = GENERIC_NEIGHBOR_CONFIGURATION_INPUT.concat("neighbor-list-in-use"); + private static final String EVENT_HEADER = "event-header"; + private static final String ACTION = "Action"; + private static final String PAYLOAD = "Payload"; + private static final String CONFIGURATIONS = "Configurations"; + private static final String MODIFY_CONFIG_ANR = "ModifyConfigANR"; + private static final String MAP_FILE_NAME = "anr-changes-from-policy-to-sdnr"; + private static final String DATA = "data"; + private static final String FAP_SERVICE = "FAPService"; + private static final String SLI_PARAMETERS = "sli_parameters"; + private static final String RPC_NAME = "rpc-name"; + private static final String BODY = "body"; + private static final String INPUT = "input"; + + private String rootDir; + + protected VelocityEngine velocityEngine; + + public ANRChangesFromPolicyToSDNRDmaapConsumer() { + velocityEngine = new VelocityEngine(); + Properties props = new Properties(); + rootDir = System.getenv(DMAAPLISTENERROOT); + + if ((rootDir == null) || (rootDir.length() == 0)) { + rootDir = "/opt/app/dmaap-listener/lib/"; + } + else { + rootDir = rootDir + "/lib/"; + } + + props.put("file.resource.loader.path", rootDir); + velocityEngine.init(props); + } + + /* + * for testing purposes + */ + ANRChangesFromPolicyToSDNRDmaapConsumer(Properties props) { + velocityEngine = new VelocityEngine(); + velocityEngine.init(props); + } + + protected String publish(String templatePath, String jsonString, JsonNode dataNode) throws IOException, InvalidMessageException + { + if (templatePath.contains("anr-pci-changes-from-policy-to-sdnr")){ + return publishANRChangesFromPolicyToSDNR(templatePath, dataNode); + } else { + return publishFullMessage(templatePath, jsonString); + } + } + + private String publishFullMessage(String templatePath, String jsonString) throws IOException + { + JSONObject jsonObj = new JSONObject(jsonString); + VelocityContext context = new VelocityContext(); + for(Object key : jsonObj.keySet()) + { + context.put((String)key, jsonObj.get((String)key)); + } + + String id = jsonObj.getJSONObject(EVENT_HEADER).get("id").toString(); + context.put("req_id", id); + + context.put("curr_time", Instant.now()); + + ObjectMapper oMapper = new ObjectMapper(); + + String rpcMsgbody = oMapper.writeValueAsString(jsonString); + context.put("full_message", rpcMsgbody); + + Writer writer = new StringWriter(); + velocityEngine.mergeTemplate(templatePath, "UTF-8", context, writer); + writer.flush(); + + return writer.toString(); + } + + private String publishANRChangesFromPolicyToSDNR(String templatePath, JsonNode dataNode) throws IOException, InvalidMessageException + { + VelocityContext context = new VelocityContext(); + + String RPC_NAME_KEY_IN_VT = "rpc_name"; + String RPC_NAME_VALUE_IN_VT = "generic-neighbor-configuration"; + + String CELL_CONFIG = "CellConfig"; + String ALIAS_LABEL = "alias"; + String LTE = "LTE"; + String RAN = "RAN"; + String LTE_CELL = "LTECell"; + String NEIGHBOR_LIST_IN_USE = "NeighborListInUse"; + + JSONObject numberOfEntries = new JSONObject(); + JSONObject alias = new JSONObject(); + JSONArray sliParametersArray = new JSONArray(); + + String aliasValue = dataNode.get(DATA).get(FAP_SERVICE).get(ALIAS_LABEL).textValue(); + + JsonNode nbrListInUse = dataNode.get(DATA).get(FAP_SERVICE).get(CELL_CONFIG).get(LTE).get(RAN).get(NEIGHBOR_LIST_IN_USE).get(LTE_CELL); + + int entryCount = 0; + + if(nbrListInUse.isArray()) { + for(JsonNode lteCell:nbrListInUse) { + sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, GENERIC_NEIGHBOR_CONFIGURATION_INPUT_NEIGHBOR_LIST_IN_USE+"["+entryCount+"]."+"plmnid") + .put(STRING_VALUE, lteCell.get("PLMNID"))); + sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, GENERIC_NEIGHBOR_CONFIGURATION_INPUT_NEIGHBOR_LIST_IN_USE+"["+entryCount+"]."+"cid") + .put(STRING_VALUE, lteCell.get("CID"))); + sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, GENERIC_NEIGHBOR_CONFIGURATION_INPUT_NEIGHBOR_LIST_IN_USE+"["+entryCount+"]."+"phy-cell-id") + .put(STRING_VALUE, lteCell.get("PhyCellID"))); + sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, GENERIC_NEIGHBOR_CONFIGURATION_INPUT_NEIGHBOR_LIST_IN_USE+"["+entryCount+"]."+"pnf-name") + .put(STRING_VALUE, lteCell.get("PNFName"))); + sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, GENERIC_NEIGHBOR_CONFIGURATION_INPUT_NEIGHBOR_LIST_IN_USE+"["+entryCount+"]."+"blacklisted") + .put(STRING_VALUE, lteCell.get("Blacklisted"))); + + entryCount++; + } + + alias.put(PARAMETER_NAME, GENERIC_NEIGHBOR_CONFIGURATION_INPUT+ALIAS_LABEL); + alias.put(STRING_VALUE, aliasValue); + + numberOfEntries.put(PARAMETER_NAME, GENERIC_NEIGHBOR_CONFIGURATION_INPUT+"number-of-neighbor-cell-entries"); + numberOfEntries.put(STRING_VALUE, entryCount); + + sliParametersArray.put(alias); + sliParametersArray.put(numberOfEntries); + + context.put(SLI_PARAMETERS, sliParametersArray); + + context.put(RPC_NAME_KEY_IN_VT, RPC_NAME_VALUE_IN_VT); + + Writer writer = new StringWriter(); + velocityEngine.mergeTemplate(templatePath, "UTF-8", context, writer); + writer.flush(); + + return writer.toString(); + + }else { + throw new InvalidMessageException("nbrListInUse is not of Type Array. Could not read neighbor list elements"); + } + + } + + @Override + public void processMsg(String msg) throws InvalidMessageException { + + if (msg == null) { + throw new InvalidMessageException("Null message"); + } + + ObjectMapper oMapper = new ObjectMapper(); + JsonNode anrChangesRootNode; + try { + anrChangesRootNode = oMapper.readTree(msg); + } catch (Exception e) { + throw new InvalidMessageException("Cannot parse json object", e); + } + + JsonNode rpcname = anrChangesRootNode.get(RPC_NAME); + if(rpcname == null) { + LOG.info("Missing rpc-name node."); + return; + } + + if(!MODIFY_CONFIG_ANR.toLowerCase().equals(rpcname.textValue())) { + LOG.info("Unknown rpc name {}", rpcname); + return; + } + + JsonNode body = anrChangesRootNode.get(BODY); + if(body == null) { + LOG.info("Missing body node."); + return; + } + + JsonNode input = body.get(INPUT); + if(input == null) { + LOG.info("Missing input node."); + return; + } + + JsonNode action = input.get(ACTION); + if(action == null) { + LOG.info("Missing action node."); + return; + } + + if(!MODIFY_CONFIG_ANR.equals(action.textValue())) { + LOG.info("Unknown Action {}", action); + return; + } + + JsonNode payload = input.get(PAYLOAD); + if(payload == null) { + LOG.info("Missing payload node."); + return; + } + + String payloadText = payload.asText(); + + if(!payloadText.contains(CONFIGURATIONS)) { + LOG.info("Missing configurations node."); + return; + } + + JsonNode configurationsJsonNode; + try { + configurationsJsonNode = oMapper.readTree(payloadText); + } catch (Exception e) { + throw new InvalidMessageException("Cannot parse payload value", e); + } + + String mapFilename = rootDir + MAP_FILE_NAME + ".map"; + Map fieldMap = loadMap(mapFilename); + if (fieldMap == null) { + return; + } + + if (!fieldMap.containsKey(SDNC_ENDPOINT)) { + return; + } + String sdncEndpoint = fieldMap.get(SDNC_ENDPOINT); + + if (!fieldMap.containsKey(TEMPLATE)) { + throw new InvalidMessageException("No SDNC template known for message "); + } + String templateName = fieldMap.get(TEMPLATE); + + JsonNode configurations = configurationsJsonNode.get(CONFIGURATIONS); + + if(configurations.isArray()) { + for(JsonNode dataNode:configurations) { + if(dataNode.get(DATA).get(FAP_SERVICE) == null) { + LOG.info("Could not make a rpc call. Missing fapService node for dataNode element::", dataNode.textValue()); + }else { + try { + + String rpcMsgbody = publish(templateName, msg, dataNode); + String odlUrlBase = getProperty("sdnc.odl.url-base"); + String odlUser = getProperty("sdnc.odl.user"); + String odlPassword = getProperty("sdnc.odl.password"); + + if ((odlUrlBase != null) && (odlUrlBase.length() > 0)) { + SdncOdlConnection conn = SdncOdlConnection.newInstance(odlUrlBase + "/" + sdncEndpoint, odlUser, odlPassword); + + conn.send("POST", "application/json", rpcMsgbody); + } else { + LOG.info("POST message body would be:\n" + rpcMsgbody); + } + } catch (Exception e) { + LOG.error("Unable to process message", e); + } + } + } + }else { + throw new InvalidMessageException("Configurations is not of Type Array. Could not read configuration changes"); + } + } + + private Map loadMap(String mapFilename) { + File mapFile = new File(mapFilename); + + if (!mapFile.canRead()) { + LOG.error(String.format("Cannot read map file (%s)", mapFilename)); + return null; + } + + Map results = new HashMap<>(); + try (BufferedReader mapReader = new BufferedReader(new FileReader(mapFile))) { + + String curLine; + + while ((curLine = mapReader.readLine()) != null) { + curLine = curLine.trim(); + + if ((curLine.length() > 0) && (!curLine.startsWith("#")) && curLine.contains("=>")) { + String[] entry = curLine.split("=>"); + if (entry.length == 2) { + results.put(entry[0].trim(), entry[1].trim()); + } + } + } + mapReader.close(); + } catch (Exception e) { + LOG.error("Caught exception reading map " + mapFilename, e); + return null; + } + + return results; + } + +} diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/PciChangesFromPolicyToSDNRDmaapConsumer.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/PciChangesFromPolicyToSDNRDmaapConsumer.java new file mode 100644 index 000000000..8c44377f9 --- /dev/null +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/PciChangesFromPolicyToSDNRDmaapConsumer.java @@ -0,0 +1,314 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 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.northbound.dmaapclient; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.StringWriter; +import java.io.Writer; +import java.time.Instant; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; +import org.apache.velocity.VelocityContext; +import org.apache.velocity.app.VelocityEngine; +import org.json.JSONArray; +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class PciChangesFromPolicyToSDNRDmaapConsumer extends SdncDmaapConsumerImpl { + + private static final Logger LOG = LoggerFactory.getLogger(PciChangesFromPolicyToSDNRDmaapConsumer.class); + private static final String SDNC_ENDPOINT = "SDNC.endpoint"; + private static final String TEMPLATE = "SDNC.template"; + private static final String DMAAPLISTENERROOT = "DMAAPLISTENERROOT"; + + private static final String PARAMETER_NAME = "parameter-name"; + private static final String STRING_VALUE = "string-value"; + private static final String PHYSICAL_CELL_ID_INPUT_FAP_SERVICE = "configuration-phy-cell-id-input.fap-service"; + private static final String EVENT_HEADER = "event-header"; + private static final String ACTION = "Action"; + private static final String PAYLOAD = "Payload"; + private static final String CONFIGURATIONS = "Configurations"; + private static final String MODIFY_CONFIG = "ModifyConfig"; + private static final String MAP_FILE_NAME = "pci-changes-from-policy-to-sdnr"; + private static final String DATA = "data"; + private static final String FAP_SERVICE = "FAPService"; + private static final String SLI_PARAMETERS = "sli_parameters"; + private static final String RPC_NAME = "rpc-name"; + private static final String BODY = "body"; + private static final String INPUT = "input"; + + private String rootDir; + + protected VelocityEngine velocityEngine; + + public PciChangesFromPolicyToSDNRDmaapConsumer() { + velocityEngine = new VelocityEngine(); + Properties props = new Properties(); + rootDir = System.getenv(DMAAPLISTENERROOT); + + if ((rootDir == null) || (rootDir.length() == 0)) { + rootDir = "/opt/app/dmaap-listener/lib/"; + } + else { + rootDir = rootDir + "/lib/"; + } + + props.put("file.resource.loader.path", rootDir); + velocityEngine.init(props); + } + + /* + * for testing purposes + */ + PciChangesFromPolicyToSDNRDmaapConsumer(Properties props) { + velocityEngine = new VelocityEngine(); + velocityEngine.init(props); + } + + protected String publish(String templatePath, String jsonString, JsonNode configurationsJsonNode) throws IOException, InvalidMessageException + { + if (templatePath.contains("anr-pci-changes-from-policy-to-sdnr")){ + return publishPciChangesFromPolicyToSDNR(templatePath, configurationsJsonNode); + } else { + return publishFullMessage(templatePath, jsonString); + } + } + + private String publishFullMessage(String templatePath, String jsonString) throws IOException + { + JSONObject jsonObj = new JSONObject(jsonString); + VelocityContext context = new VelocityContext(); + for(Object key : jsonObj.keySet()) + { + context.put((String)key, jsonObj.get((String)key)); + } + + String id = jsonObj.getJSONObject(EVENT_HEADER).get("id").toString(); + context.put("req_id", id); + + context.put("curr_time", Instant.now()); + + ObjectMapper oMapper = new ObjectMapper(); + + String rpcMsgbody = oMapper.writeValueAsString(jsonString); + context.put("full_message", rpcMsgbody); + + Writer writer = new StringWriter(); + velocityEngine.mergeTemplate(templatePath, "UTF-8", context, writer); + writer.flush(); + + return writer.toString(); + } + + private String publishPciChangesFromPolicyToSDNR(String templatePath, JsonNode configurationsJsonNode) throws IOException, InvalidMessageException + { + String RPC_NAME_KEY_IN_VT = "rpc_name"; + String RPC_NAME_VALUE_IN_VT = "configuration-phy-cell-id"; + String ALIAS = "alias"; + String X0005b9Lte = "X0005b9Lte"; + + VelocityContext context = new VelocityContext(); + + JSONObject numberOfEntries = new JSONObject(); + JSONArray sliParametersArray = new JSONArray(); + + JsonNode configurations = configurationsJsonNode.get(CONFIGURATIONS); + + int entryCount = 0; + + if(configurations.isArray()) { + for(JsonNode dataNode:configurations) { + sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, PHYSICAL_CELL_ID_INPUT_FAP_SERVICE+"["+entryCount+"]."+ALIAS) + .put(STRING_VALUE, dataNode.get(DATA).get(FAP_SERVICE).get(ALIAS))); + sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, PHYSICAL_CELL_ID_INPUT_FAP_SERVICE+"["+entryCount+"]."+"cid") + .put(STRING_VALUE, dataNode.get(DATA).get(FAP_SERVICE).get("CellConfig").get("LTE").get("RAN").get("Common").get("CellIdentity"))); + sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, PHYSICAL_CELL_ID_INPUT_FAP_SERVICE+"["+entryCount+"]."+"phy-cell-id-in-use") + .put(STRING_VALUE, dataNode.get(DATA).get(FAP_SERVICE).get(X0005b9Lte).get("phyCellIdInUse"))); + sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, PHYSICAL_CELL_ID_INPUT_FAP_SERVICE+"["+entryCount+"]."+"pnf-name") + .put(STRING_VALUE, dataNode.get(DATA).get(FAP_SERVICE).get(X0005b9Lte).get("pnfName"))); + entryCount++; + } + + numberOfEntries.put(PARAMETER_NAME, PHYSICAL_CELL_ID_INPUT_FAP_SERVICE+"-number-of-entries"); + numberOfEntries.put(STRING_VALUE, entryCount); + + sliParametersArray.put(numberOfEntries); + + context.put(SLI_PARAMETERS, sliParametersArray); + + context.put(RPC_NAME_KEY_IN_VT, RPC_NAME_VALUE_IN_VT); + + Writer writer = new StringWriter(); + velocityEngine.mergeTemplate(templatePath, "UTF-8", context, writer); + writer.flush(); + + return writer.toString(); + + }else { + throw new InvalidMessageException("Configurations is not of Type Array. Could not read configuration changes"); + } + + } + + @Override + public void processMsg(String msg) throws InvalidMessageException { + + if (msg == null) { + throw new InvalidMessageException("Null message"); + } + + ObjectMapper oMapper = new ObjectMapper(); + JsonNode pciChangesRootNode; + try { + pciChangesRootNode = oMapper.readTree(msg); + } catch (Exception e) { + throw new InvalidMessageException("Cannot parse json object", e); + } + + JsonNode rpcname = pciChangesRootNode.get(RPC_NAME); + if(rpcname == null) { + LOG.info("Missing rpc-name node."); + return; + } + + if(!MODIFY_CONFIG.toLowerCase().equals(rpcname.textValue())) { + LOG.info("Unknown rpc name {}", rpcname); + return; + } + + JsonNode body = pciChangesRootNode.get(BODY); + if(body == null) { + LOG.info("Missing body node."); + return; + } + + JsonNode input = body.get(INPUT); + if(input == null) { + LOG.info("Missing input node."); + return; + } + + JsonNode action = input.get(ACTION); + if(action == null) { + LOG.info("Missing action node."); + return; + } + + if(!MODIFY_CONFIG.equals(action.textValue())) { + LOG.info("Unknown Action {}", action); + return; + } + + JsonNode payload = input.get(PAYLOAD); + if(payload == null) { + LOG.info("Missing payload node."); + return; + } + + String configurations = payload.asText(); + + if(!configurations.contains(CONFIGURATIONS)) { + LOG.info("Missing configurations node."); + return; + } + + JsonNode configurationsJsonNode; + try { + configurationsJsonNode = oMapper.readTree(configurations); + } catch (Exception e) { + throw new InvalidMessageException("Cannot parse payload value", e); + } + + String mapFilename = rootDir + MAP_FILE_NAME + ".map"; + Map fieldMap = loadMap(mapFilename); + if (fieldMap == null) { + return; + } + + if (!fieldMap.containsKey(SDNC_ENDPOINT)) { + return; + } + String sdncEndpoint = fieldMap.get(SDNC_ENDPOINT); + + if (!fieldMap.containsKey(TEMPLATE)) { + throw new InvalidMessageException("No SDNC template known for message "); + } + String templateName = fieldMap.get(TEMPLATE); + + try { + String rpcMsgbody = publish(templateName, msg, configurationsJsonNode); + String odlUrlBase = getProperty("sdnc.odl.url-base"); + String odlUser = getProperty("sdnc.odl.user"); + String odlPassword = getProperty("sdnc.odl.password"); + + if ((odlUrlBase != null) && (odlUrlBase.length() > 0)) { + SdncOdlConnection conn = SdncOdlConnection.newInstance(odlUrlBase + "/" + sdncEndpoint, odlUser, odlPassword); + + conn.send("POST", "application/json", rpcMsgbody); + } else { + LOG.info("POST message body would be:\n" + rpcMsgbody); + } + } catch (Exception e) { + LOG.error("Unable to process message", e); + } + } + + private Map loadMap(String mapFilename) { + File mapFile = new File(mapFilename); + + if (!mapFile.canRead()) { + LOG.error(String.format("Cannot read map file (%s)", mapFilename)); + return null; + } + + Map results = new HashMap<>(); + try (BufferedReader mapReader = new BufferedReader(new FileReader(mapFile))) { + + String curLine; + + while ((curLine = mapReader.readLine()) != null) { + curLine = curLine.trim(); + + if ((curLine.length() > 0) && (!curLine.startsWith("#")) && curLine.contains("=>")) { + String[] entry = curLine.split("=>"); + if (entry.length == 2) { + results.put(entry[0].trim(), entry[1].trim()); + } + } + } + mapReader.close(); + } catch (Exception e) { + LOG.error("Caught exception reading map " + mapFilename, e); + return null; + } + + return results; + } + +} diff --git a/dmaap-listener/src/main/resources/anr-changes-from-policy-to-sdnr.map b/dmaap-listener/src/main/resources/anr-changes-from-policy-to-sdnr.map new file mode 100644 index 000000000..e7c45b253 --- /dev/null +++ b/dmaap-listener/src/main/resources/anr-changes-from-policy-to-sdnr.map @@ -0,0 +1,5 @@ +# SDN-C URL +SDNC.endpoint => oofpcipoc-api:generic-neighbour-configuration + +# Field mapping +SDNC.template => anr-pci-changes-from-policy-to-sdnr.vt diff --git a/dmaap-listener/src/main/resources/anr-pci-changes-from-policy-to-sndr.vt b/dmaap-listener/src/main/resources/anr-pci-changes-from-policy-to-sndr.vt new file mode 100644 index 000000000..1cdd65e9c --- /dev/null +++ b/dmaap-listener/src/main/resources/anr-pci-changes-from-policy-to-sndr.vt @@ -0,0 +1,8 @@ +{ + "input": { + "module-name": "oofpcipoc-api", + "rpc-name": $rpc_name, + "mode": "sync", + "sli-parameter": $sli_parameters + } +} \ No newline at end of file diff --git a/dmaap-listener/src/main/resources/pci-changes-from-policy-to-sdnr.map b/dmaap-listener/src/main/resources/pci-changes-from-policy-to-sdnr.map new file mode 100644 index 000000000..44c34a4d4 --- /dev/null +++ b/dmaap-listener/src/main/resources/pci-changes-from-policy-to-sdnr.map @@ -0,0 +1,5 @@ +# SDN-C URL +SDNC.endpoint => oofpcipoc-api:configuration-phy-cell-id + +# Field mapping +SDNC.template => anr-pci-changes-from-policy-to-sdnr.vt -- cgit 1.2.3-korg From dc1ac454bb77359e466395a4a92891f7cebda2a2 Mon Sep 17 00:00:00 2001 From: Sandeep Shah Date: Sun, 14 Apr 2019 11:19:29 -0500 Subject: JUNIT tests for SDNR OOF PCI Dmaap Listener JUNIT test JAVA files and name change for .vt file Change-Id: I513b9abd72d4c230f57ae3f89a8fafc5f72e7cfa Issue-ID: CCSDK-1226 Signed-off-by: SandeepLinux --- .../anr-pci-changes-from-policy-to-sdnr.vt | 8 + .../anr-pci-changes-from-policy-to-sndr.vt | 8 - ...estANRChangesFromPolicyToSDNRDmaapConsumer.java | 142 ++++++++++++++++ ...estPciChangesFromPolicyToSDNRDmaapConsumer.java | 181 +++++++++++++++++++++ 4 files changed, 331 insertions(+), 8 deletions(-) create mode 100644 dmaap-listener/src/main/resources/anr-pci-changes-from-policy-to-sdnr.vt delete mode 100644 dmaap-listener/src/main/resources/anr-pci-changes-from-policy-to-sndr.vt create mode 100644 dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestANRChangesFromPolicyToSDNRDmaapConsumer.java create mode 100644 dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestPciChangesFromPolicyToSDNRDmaapConsumer.java (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/src/main/resources/anr-pci-changes-from-policy-to-sdnr.vt b/dmaap-listener/src/main/resources/anr-pci-changes-from-policy-to-sdnr.vt new file mode 100644 index 000000000..1ded88dc7 --- /dev/null +++ b/dmaap-listener/src/main/resources/anr-pci-changes-from-policy-to-sdnr.vt @@ -0,0 +1,8 @@ +{ + "input": { + "module-name": "oofpcipoc-api", + "rpc-name": "$rpc_name", + "mode": "sync", + "sli-parameter": $sli_parameters + } +} diff --git a/dmaap-listener/src/main/resources/anr-pci-changes-from-policy-to-sndr.vt b/dmaap-listener/src/main/resources/anr-pci-changes-from-policy-to-sndr.vt deleted file mode 100644 index 1cdd65e9c..000000000 --- a/dmaap-listener/src/main/resources/anr-pci-changes-from-policy-to-sndr.vt +++ /dev/null @@ -1,8 +0,0 @@ -{ - "input": { - "module-name": "oofpcipoc-api", - "rpc-name": $rpc_name, - "mode": "sync", - "sli-parameter": $sli_parameters - } -} \ No newline at end of file diff --git a/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestANRChangesFromPolicyToSDNRDmaapConsumer.java b/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestANRChangesFromPolicyToSDNRDmaapConsumer.java new file mode 100644 index 000000000..66b63a17d --- /dev/null +++ b/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestANRChangesFromPolicyToSDNRDmaapConsumer.java @@ -0,0 +1,142 @@ +package org.onap.ccsdk.sli.northbound.dmaapclient; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.Properties; + +import org.junit.Before; +import org.junit.Test; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class TestANRChangesFromPolicyToSDNRDmaapConsumer { + private static final String anrChangesFromPolicyToSDNRInput = "{\n" + + " \"body\": {\n" + + " \"input\": {\n" + + " \"CommonHeader\": {\n" + + " \"TimeStamp\": \"2018-11-30T09:13:37.368Z\",\n" + + " \"APIVer\": \"1.0\",\n" + + " \"RequestID\": \"722ee65a-8afd-48df-bf57-c152ae45bacc\",\n" + + " \"SubRequestID\": \"1\",\n" + + " \"RequestTrack\": {},\n" + + " \"Flags\": {}\n" + + " },\n" + + "\"Action\": \"ModifyConfigANR\",\n" + + " \"Payload\": \"{ \\\"Configurations\\\":[ { \\\"data\\\":{ \\\"FAPService\\\":{ \\\"alias\\\":\\\"Cell1\\\", \\\"CellConfig\\\":{ \\\"LTE\\\":{ \\\"RAN\\\":{ \\\"Common\\\":{ \\\"CellIdentity\\\":\\\"1\\\" }, \\\"NeighborListInUse\\\" : { \\\"LTECellNumberOfEntries\\\" : \\\"1\\\" , \\\"LTECell\\\" : [{ \\\"PLMNID\\\" :\\\"plmnid1\\\", \\\"CID\\\":\\\"Chn0001\\\", \\\"PhyCellID\\\":\\\"3\\\", \\\"PNFName\\\":\\\"ncserver01\\\", \\\"Blacklisted\\\":\\\"false\\\"}] } } } } } } } ] }\"\n" + + " }\n" + + " },\n" + + " \"version\": \"1.0\",\n" + + " \"rpc-name\": \"modifyconfiganr\",\n" + + " \"correlation-id\": \"722ee65a-8afd-48df-bf57-c152ae45bacc-1\",\n" + + " \"type\": \"request\"\n" + + "}\n" + + ""; + + @Before + public void setUp() throws Exception { + } + + @Test + public void testRPCMessageBodyResponse() throws Exception { + Properties props = new Properties(); + + ObjectMapper oMapper = new ObjectMapper(); + JsonNode anrChangesRootNode = oMapper.readTree(anrChangesFromPolicyToSDNRInput); + JsonNode body = anrChangesRootNode.get("body"); + JsonNode input = body.get("input"); + JsonNode payload = input.get("Payload"); + String payloadText = payload.asText(); + JsonNode configurationsJsonNode = oMapper.readTree(payloadText); + JsonNode configurations = configurationsJsonNode.get("Configurations"); + + for(JsonNode dataNode:configurations) { + String rpcMsgbody = new ANRChangesFromPolicyToSDNRDmaapConsumer(props).publish("src/main/resources/anr-pci-changes-from-policy-to-sdnr.vt", anrChangesFromPolicyToSDNRInput,dataNode); + + JsonNode rootNode; + try { + rootNode = oMapper.readTree(rpcMsgbody); + } catch (Exception e) { + throw new InvalidMessageException("Cannot parse json object", e); + } + + assertTrue(rootNode.get("input").get("module-name") != null); + assertTrue(rootNode.get("input").get("rpc-name") != null); + assertTrue(rootNode.get("input").get("mode") != null); + assertTrue(rootNode.get("input").get("sli-parameter") != null); + } + } + + @Test(expected = InvalidMessageException.class) + public void testProcessMsgNullMessage() throws Exception { + ANRChangesFromPolicyToSDNRDmaapConsumer consumer = new ANRChangesFromPolicyToSDNRDmaapConsumer(); + consumer.processMsg(null); + } + + @Test(expected = InvalidMessageException.class) + public void testProcessMsgInvalidMessage() throws Exception { + ANRChangesFromPolicyToSDNRDmaapConsumer consumer = new ANRChangesFromPolicyToSDNRDmaapConsumer(); + consumer.processMsg("test"); + } + + @Test + public void testProcessMsgMissingActionHeader() throws Exception { + ANRChangesFromPolicyToSDNRDmaapConsumer consumer = new ANRChangesFromPolicyToSDNRDmaapConsumer(); + consumer.processMsg("{\n" + + " \"body\": {\n" + + " \"input\": {\n" + + " \"CommonHeader\": {\n" + + " \"TimeStamp\": \"2018-11-30T09:13:37.368Z\",\n" + + " \"APIVer\": \"1.0\",\n" + + " \"RequestID\": \"722ee65a-8afd-48df-bf57-c152ae45bacc\",\n" + + " \"SubRequestID\": \"1\",\n" + + " \"RequestTrack\": {},\n" + + " \"Flags\": {}\n" + + " },\n" + + "\"NoAction\": \"ModifyConfigANR\",\n" + + " \"Payload\": \"{ \\\"Configurations\\\":[ { \\\"data\\\":{ \\\"FAPService\\\":{ \\\"alias\\\":\\\"Cell1\\\", \\\"CellConfig\\\":{ \\\"LTE\\\":{ \\\"RAN\\\":{ \\\"Common\\\":{ \\\"CellIdentity\\\":\\\"1\\\" }, \\\"NeighborListInUse\\\" : { \\\"LTECellNumberOfEntries\\\" : \\\"1\\\" , \\\"LTECell\\\" : [{ \\\"PLMNID\\\" :\\\"plmnid1\\\", \\\"CID\\\":\\\"Chn0001\\\", \\\"PhyCellID\\\":\\\"3\\\", \\\"PNFName\\\":\\\"ncserver01\\\", \\\"Blacklisted\\\":\\\"false\\\"}] } } } } } } } ] }\"\n" + + " }\n" + + " },\n" + + " \"version\": \"1.0\",\n" + + " \"rpc-name\": \"modifyconfiganr\",\n" + + " \"correlation-id\": \"722ee65a-8afd-48df-bf57-c152ae45bacc-1\",\n" + + " \"type\": \"request\"\n" + + "}\n" + + ""); + } + + @Test + public void testProcessMsgInvalidPayloadConfigurations() throws Exception { + String msg = "{\n" + + " \"body\": {\n" + + " \"input\": {\n" + + " \"CommonHeader\": {\n" + + " \"TimeStamp\": \"2018-11-30T09:13:37.368Z\",\n" + + " \"APIVer\": \"1.0\",\n" + + " \"RequestID\": \"722ee65a-8afd-48df-bf57-c152ae45bacc\",\n" + + " \"SubRequestID\": \"1\",\n" + + " \"RequestTrack\": {},\n" + + " \"Flags\": {}\n" + + " },\n" + + "\"Action\": \"ModifyConfigANR\",\n" + + " \"Payload\": \"{ \\\"Configurations\\\":{ { \\\"data\\\":{ \\\"FAPService\\\":{ \\\"alias\\\":\\\"Cell1\\\", \\\"CellConfig\\\":{ \\\"LTE\\\":{ \\\"RAN\\\":{ \\\"Common\\\":{ \\\"CellIdentity\\\":\\\"1\\\" }, \\\"NeighborListInUse\\\" : { \\\"LTECellNumberOfEntries\\\" : \\\"1\\\" , \\\"LTECell\\\" : [{ \\\"PLMNID\\\" :\\\"plmnid1\\\", \\\"CID\\\":\\\"Chn0001\\\", \\\"PhyCellID\\\":\\\"3\\\", \\\"PNFName\\\":\\\"ncserver01\\\", \\\"Blacklisted\\\":\\\"false\\\"}} } } } } } } } ] }\"\n" + + " }\n" + + " },\n" + + " \"version\": \"1.0\",\n" + + " \"rpc-name\": \"modifyconfiganr\",\n" + + " \"correlation-id\": \"722ee65a-8afd-48df-bf57-c152ae45bacc-1\",\n" + + " \"type\": \"request\"\n" + + "}\n" + + ""; + + try { + ANRChangesFromPolicyToSDNRDmaapConsumer consumer = new ANRChangesFromPolicyToSDNRDmaapConsumer(); + consumer.processMsg(msg); + + } catch (final InvalidMessageException e) { + final String errorMsg = "Cannot parse payload value"; + assertEquals(errorMsg, e.getMessage()); + } + } +} diff --git a/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestPciChangesFromPolicyToSDNRDmaapConsumer.java b/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestPciChangesFromPolicyToSDNRDmaapConsumer.java new file mode 100644 index 000000000..a42bc48f6 --- /dev/null +++ b/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestPciChangesFromPolicyToSDNRDmaapConsumer.java @@ -0,0 +1,181 @@ +package org.onap.ccsdk.sli.northbound.dmaapclient; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.Properties; + +import org.junit.Before; +import org.junit.Test; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class TestPciChangesFromPolicyToSDNRDmaapConsumer { + private static final String pciChangesFromPolicyToSDNRInput = "{\n" + + " \"body\": {\n" + + " \"input\": {\n" + + " \"CommonHeader\": {\n" + + " \"TimeStamp\": \"2018-11-30T09:13:37.368Z\",\n" + + " \"APIVer\": \"1.0\",\n" + + " \"RequestID\": \"9d2d790e-a5f0-11e8-98d0-529269fb1459\",\n" + + " \"SubRequestID\": \"1\",\n" + + " \"RequestTrack\": {},\n" + + " \"Flags\": {}\n" + + " },\n" + + " \"Action\": \"ModifyConfig\",\n" + + " \"Payload\": \"{\\\"Configurations\\\":[{\\\"data\\\":{\\\"FAPService\\\":{\\\"alias\\\":\\\"Chn0330\\\",\\\"X0005b9Lte\\\":{\\\"phyCellIdInUse\\\":6,\\\"pnfName\\\":\\\"ncserver23\\\"},\\\"CellConfig\\\":{\\\"LTE\\\":{\\\"RAN\\\":{\\\"Common\\\":{\\\"CellIdentity\\\":\\\"Chn0330\\\"}}}}}}},{\\\"data\\\":{\\\"FAPService\\\":{\\\"alias\\\":\\\"Chn0331\\\",\\\"X0005b9Lte\\\":{\\\"phyCellIdInUse\\\":7,\\\"pnfName\\\":\\\"ncserver23\\\"},\\\"CellConfig\\\":{\\\"LTE\\\":{\\\"RAN\\\":{\\\"Common\\\":{\\\"CellIdentity\\\":\\\"Chn0331\\\"}}}}}}}]}\"\n" + + " }\n" + + " },\n" + + " \"version\": \"1.0\",\n" + + " \"rpc-name\": \"modifyconfig\",\n" + + " \"correlation-id\": \"9d2d790e-a5f0-11e8-98d0-529269fb1459-1\",\n" + + " \"type\": \"request\"\n" + + "}"; + + @Before + public void setUp() throws Exception { + } + + @Test + public void testRPCMessageBodyResponse() throws Exception { + Properties props = new Properties(); + + ObjectMapper oMapper = new ObjectMapper(); + JsonNode pciChangesRootNode = oMapper.readTree(pciChangesFromPolicyToSDNRInput); + JsonNode body = pciChangesRootNode.get("body"); + JsonNode input = body.get("input"); + JsonNode payload = input.get("Payload"); + String payloadText = payload.asText(); + JsonNode configurationsJsonNode = oMapper.readTree(payloadText); + + String rpcMsgbody = new PciChangesFromPolicyToSDNRDmaapConsumer(props).publish("src/main/resources/anr-pci-changes-from-policy-to-sdnr.vt", pciChangesFromPolicyToSDNRInput,configurationsJsonNode); + + JsonNode rootNode; + try { + rootNode = oMapper.readTree(rpcMsgbody); + } catch (Exception e) { + throw new InvalidMessageException("Cannot parse json object", e); + } + + assertTrue(rootNode.get("input").get("module-name") != null); + assertTrue(rootNode.get("input").get("rpc-name") != null); + assertTrue(rootNode.get("input").get("mode") != null); + assertTrue(rootNode.get("input").get("sli-parameter") != null); + + } + + @Test(expected = InvalidMessageException.class) + public void testProcessMsgNullMessage() throws Exception { + PciChangesFromPolicyToSDNRDmaapConsumer consumer = new PciChangesFromPolicyToSDNRDmaapConsumer(); + consumer.processMsg(null); + } + + @Test(expected = InvalidMessageException.class) + public void testProcessMsgInvalidMessage() throws Exception { + PciChangesFromPolicyToSDNRDmaapConsumer consumer = new PciChangesFromPolicyToSDNRDmaapConsumer(); + consumer.processMsg("test"); + } + + @Test + public void testProcessMsgMissingActionHeader() throws Exception { + PciChangesFromPolicyToSDNRDmaapConsumer consumer = new PciChangesFromPolicyToSDNRDmaapConsumer(); + consumer.processMsg("{\n" + + " \"body\": {\n" + + " \"input\": {\n" + + " \"CommonHeader\": {\n" + + " \"TimeStamp\": \"2018-11-30T09:13:37.368Z\",\n" + + " \"APIVer\": \"1.0\",\n" + + " \"RequestID\": \"9d2d790e-a5f0-11e8-98d0-529269fb1459\",\n" + + " \"SubRequestID\": \"1\",\n" + + " \"RequestTrack\": {},\n" + + " \"Flags\": {}\n" + + " },\n" + + " \"RenamedAction\": \"ModifyConfig\",\n" + + " \"Payload\": {\n" + + " \"Configurations \": {\n" + + " \"data \": {\n" + + " \"FAPService \": {\n" + + " \"alias\": \"Chn0330\",\n" + + " \"X0005b9Lte\": {\n" + + " \"phyCellIdInUse\": 6,\n" + + " \"pnfName\": \"ncserver23\"\n" + + " },\n" + + " \"CellConfig\": {\n" + + " \"LTE\": {\n" + + " \"RAN\": {\n" + + " \"Common\": {\n" + + " \"CellIdentity\": \"Chn0330\"\n" + + " }\n" + + " }\n" + + " }\n" + + " }\n" + + " }\n" + + " }\n" + + " }\n" + + "\n" + + " }\n" + + " }\n" + + " },\n" + + " \"version\": \"1.0\",\n" + + " \"rpc-name\": \"modifyconfig\",\n" + + " \"correlation-id\": \"9d2d790e-a5f0-11e8-98d0-529269fb1459-1\",\n" + + " \"type\": \"request\"\n" + + "}"); + } + + @Test + public void testProcessMsgInvalidPayloadConfigurations() throws Exception { + String msg = "{\n" + + " \"body\": {\n" + + " \"input\": {\n" + + " \"CommonHeader\": {\n" + + " \"TimeStamp\": \"2018-11-30T09:13:37.368Z\",\n" + + " \"APIVer\": \"1.0\",\n" + + " \"RequestID\": \"9d2d790e-a5f0-11e8-98d0-529269fb1459\",\n" + + " \"SubRequestID\": \"1\",\n" + + " \"RequestTrack\": {},\n" + + " \"Flags\": {}\n" + + " },\n" + + " \"Action\": \"ModifyConfig\",\n" + + " \"Payload\": {\n" + + " \"Configurations \": {\n" + + " \"data \": {\n" + + " \"FAPService \": {\n" + + " \"alias\": \"Chn0330\",\n" + + " \"X0005b9Lte\": {\n" + + " \"phyCellIdInUse\": 6,\n" + + " \"pnfName\": \"ncserver23\"\n" + + " },\n" + + " \"CellConfig\": {\n" + + " \"LTE\": {\n" + + " \"RAN\": {\n" + + " \"Common\": {\n" + + " \"CellIdentity\": \"Chn0330\"\n" + + " }\n" + + " }\n" + + " }\n" + + " }\n" + + " }\n" + + " }\n" + + " }\n" + + "\n" + + " }\n" + + " }\n" + + " },\n" + + " \"version\": \"1.0\",\n" + + " \"rpc-name\": \"modifyconfig\",\n" + + " \"correlation-id\": \"9d2d790e-a5f0-11e8-98d0-529269fb1459-1\",\n" + + " \"type\": \"request\"\n" + + "}"; + + try { + PciChangesFromPolicyToSDNRDmaapConsumer consumer = new PciChangesFromPolicyToSDNRDmaapConsumer(); + consumer.processMsg(msg); + + } catch (final InvalidMessageException e) { + final String errorMsg = "Configurations is not of Type Array. Could not read configuration changes"; + assertEquals(errorMsg, e.getMessage()); + } + } +} -- cgit 1.2.3-korg From 6d6ccec6604ea2cd672bb1c453d6d1f96e9c0518 Mon Sep 17 00:00:00 2001 From: Sandeep Shah Date: Sun, 26 May 2019 10:37:21 -0500 Subject: Fix bug with DMAAP listener for SDNR OOFPCIPOC Replaced 2 dmaap consumers with one consumer for DMAAP topic SDNR-CL. Also updated corresponding JUNIT file. Issue-ID: CCSDK-1364 Signed-off-by: SandeepLinux Change-Id: I840a38d04423954102865a68b0e216c745ed161b --- .../ANRChangesFromPolicyToSDNRDmaapConsumer.java | 343 -------------- .../dmaapclient/OofPciPocDmaapConsumers.java | 504 +++++++++++++++++++++ .../PciChangesFromPolicyToSDNRDmaapConsumer.java | 314 ------------- ...estANRChangesFromPolicyToSDNRDmaapConsumer.java | 142 ------ .../dmaapclient/TestOofPciPocDmaapConsumers.java | 314 +++++++++++++ ...estPciChangesFromPolicyToSDNRDmaapConsumer.java | 181 -------- 6 files changed, 818 insertions(+), 980 deletions(-) delete mode 100644 dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/ANRChangesFromPolicyToSDNRDmaapConsumer.java create mode 100644 dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/OofPciPocDmaapConsumers.java delete mode 100644 dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/PciChangesFromPolicyToSDNRDmaapConsumer.java delete mode 100644 dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestANRChangesFromPolicyToSDNRDmaapConsumer.java create mode 100644 dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestOofPciPocDmaapConsumers.java delete mode 100644 dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestPciChangesFromPolicyToSDNRDmaapConsumer.java (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/ANRChangesFromPolicyToSDNRDmaapConsumer.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/ANRChangesFromPolicyToSDNRDmaapConsumer.java deleted file mode 100644 index 5bc2c6011..000000000 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/ANRChangesFromPolicyToSDNRDmaapConsumer.java +++ /dev/null @@ -1,343 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 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.northbound.dmaapclient; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.io.StringWriter; -import java.io.Writer; -import java.time.Instant; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; -import org.apache.velocity.VelocityContext; -import org.apache.velocity.app.VelocityEngine; -import org.json.JSONArray; -import org.json.JSONObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -public class ANRChangesFromPolicyToSDNRDmaapConsumer extends SdncDmaapConsumerImpl { - - private static final Logger LOG = LoggerFactory.getLogger(ANRChangesFromPolicyToSDNRDmaapConsumer.class); - private static final String SDNC_ENDPOINT = "SDNC.endpoint"; - private static final String TEMPLATE = "SDNC.template"; - private static final String DMAAPLISTENERROOT = "DMAAPLISTENERROOT"; - - private static final String PARAMETER_NAME = "parameter-name"; - private static final String STRING_VALUE = "string-value"; - private static final String GENERIC_NEIGHBOR_CONFIGURATION_INPUT = "generic-neighbor-configuration-input."; - private static final String GENERIC_NEIGHBOR_CONFIGURATION_INPUT_NEIGHBOR_LIST_IN_USE = GENERIC_NEIGHBOR_CONFIGURATION_INPUT.concat("neighbor-list-in-use"); - private static final String EVENT_HEADER = "event-header"; - private static final String ACTION = "Action"; - private static final String PAYLOAD = "Payload"; - private static final String CONFIGURATIONS = "Configurations"; - private static final String MODIFY_CONFIG_ANR = "ModifyConfigANR"; - private static final String MAP_FILE_NAME = "anr-changes-from-policy-to-sdnr"; - private static final String DATA = "data"; - private static final String FAP_SERVICE = "FAPService"; - private static final String SLI_PARAMETERS = "sli_parameters"; - private static final String RPC_NAME = "rpc-name"; - private static final String BODY = "body"; - private static final String INPUT = "input"; - - private String rootDir; - - protected VelocityEngine velocityEngine; - - public ANRChangesFromPolicyToSDNRDmaapConsumer() { - velocityEngine = new VelocityEngine(); - Properties props = new Properties(); - rootDir = System.getenv(DMAAPLISTENERROOT); - - if ((rootDir == null) || (rootDir.length() == 0)) { - rootDir = "/opt/app/dmaap-listener/lib/"; - } - else { - rootDir = rootDir + "/lib/"; - } - - props.put("file.resource.loader.path", rootDir); - velocityEngine.init(props); - } - - /* - * for testing purposes - */ - ANRChangesFromPolicyToSDNRDmaapConsumer(Properties props) { - velocityEngine = new VelocityEngine(); - velocityEngine.init(props); - } - - protected String publish(String templatePath, String jsonString, JsonNode dataNode) throws IOException, InvalidMessageException - { - if (templatePath.contains("anr-pci-changes-from-policy-to-sdnr")){ - return publishANRChangesFromPolicyToSDNR(templatePath, dataNode); - } else { - return publishFullMessage(templatePath, jsonString); - } - } - - private String publishFullMessage(String templatePath, String jsonString) throws IOException - { - JSONObject jsonObj = new JSONObject(jsonString); - VelocityContext context = new VelocityContext(); - for(Object key : jsonObj.keySet()) - { - context.put((String)key, jsonObj.get((String)key)); - } - - String id = jsonObj.getJSONObject(EVENT_HEADER).get("id").toString(); - context.put("req_id", id); - - context.put("curr_time", Instant.now()); - - ObjectMapper oMapper = new ObjectMapper(); - - String rpcMsgbody = oMapper.writeValueAsString(jsonString); - context.put("full_message", rpcMsgbody); - - Writer writer = new StringWriter(); - velocityEngine.mergeTemplate(templatePath, "UTF-8", context, writer); - writer.flush(); - - return writer.toString(); - } - - private String publishANRChangesFromPolicyToSDNR(String templatePath, JsonNode dataNode) throws IOException, InvalidMessageException - { - VelocityContext context = new VelocityContext(); - - String RPC_NAME_KEY_IN_VT = "rpc_name"; - String RPC_NAME_VALUE_IN_VT = "generic-neighbor-configuration"; - - String CELL_CONFIG = "CellConfig"; - String ALIAS_LABEL = "alias"; - String LTE = "LTE"; - String RAN = "RAN"; - String LTE_CELL = "LTECell"; - String NEIGHBOR_LIST_IN_USE = "NeighborListInUse"; - - JSONObject numberOfEntries = new JSONObject(); - JSONObject alias = new JSONObject(); - JSONArray sliParametersArray = new JSONArray(); - - String aliasValue = dataNode.get(DATA).get(FAP_SERVICE).get(ALIAS_LABEL).textValue(); - - JsonNode nbrListInUse = dataNode.get(DATA).get(FAP_SERVICE).get(CELL_CONFIG).get(LTE).get(RAN).get(NEIGHBOR_LIST_IN_USE).get(LTE_CELL); - - int entryCount = 0; - - if(nbrListInUse.isArray()) { - for(JsonNode lteCell:nbrListInUse) { - sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, GENERIC_NEIGHBOR_CONFIGURATION_INPUT_NEIGHBOR_LIST_IN_USE+"["+entryCount+"]."+"plmnid") - .put(STRING_VALUE, lteCell.get("PLMNID"))); - sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, GENERIC_NEIGHBOR_CONFIGURATION_INPUT_NEIGHBOR_LIST_IN_USE+"["+entryCount+"]."+"cid") - .put(STRING_VALUE, lteCell.get("CID"))); - sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, GENERIC_NEIGHBOR_CONFIGURATION_INPUT_NEIGHBOR_LIST_IN_USE+"["+entryCount+"]."+"phy-cell-id") - .put(STRING_VALUE, lteCell.get("PhyCellID"))); - sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, GENERIC_NEIGHBOR_CONFIGURATION_INPUT_NEIGHBOR_LIST_IN_USE+"["+entryCount+"]."+"pnf-name") - .put(STRING_VALUE, lteCell.get("PNFName"))); - sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, GENERIC_NEIGHBOR_CONFIGURATION_INPUT_NEIGHBOR_LIST_IN_USE+"["+entryCount+"]."+"blacklisted") - .put(STRING_VALUE, lteCell.get("Blacklisted"))); - - entryCount++; - } - - alias.put(PARAMETER_NAME, GENERIC_NEIGHBOR_CONFIGURATION_INPUT+ALIAS_LABEL); - alias.put(STRING_VALUE, aliasValue); - - numberOfEntries.put(PARAMETER_NAME, GENERIC_NEIGHBOR_CONFIGURATION_INPUT+"number-of-neighbor-cell-entries"); - numberOfEntries.put(STRING_VALUE, entryCount); - - sliParametersArray.put(alias); - sliParametersArray.put(numberOfEntries); - - context.put(SLI_PARAMETERS, sliParametersArray); - - context.put(RPC_NAME_KEY_IN_VT, RPC_NAME_VALUE_IN_VT); - - Writer writer = new StringWriter(); - velocityEngine.mergeTemplate(templatePath, "UTF-8", context, writer); - writer.flush(); - - return writer.toString(); - - }else { - throw new InvalidMessageException("nbrListInUse is not of Type Array. Could not read neighbor list elements"); - } - - } - - @Override - public void processMsg(String msg) throws InvalidMessageException { - - if (msg == null) { - throw new InvalidMessageException("Null message"); - } - - ObjectMapper oMapper = new ObjectMapper(); - JsonNode anrChangesRootNode; - try { - anrChangesRootNode = oMapper.readTree(msg); - } catch (Exception e) { - throw new InvalidMessageException("Cannot parse json object", e); - } - - JsonNode rpcname = anrChangesRootNode.get(RPC_NAME); - if(rpcname == null) { - LOG.info("Missing rpc-name node."); - return; - } - - if(!MODIFY_CONFIG_ANR.toLowerCase().equals(rpcname.textValue())) { - LOG.info("Unknown rpc name {}", rpcname); - return; - } - - JsonNode body = anrChangesRootNode.get(BODY); - if(body == null) { - LOG.info("Missing body node."); - return; - } - - JsonNode input = body.get(INPUT); - if(input == null) { - LOG.info("Missing input node."); - return; - } - - JsonNode action = input.get(ACTION); - if(action == null) { - LOG.info("Missing action node."); - return; - } - - if(!MODIFY_CONFIG_ANR.equals(action.textValue())) { - LOG.info("Unknown Action {}", action); - return; - } - - JsonNode payload = input.get(PAYLOAD); - if(payload == null) { - LOG.info("Missing payload node."); - return; - } - - String payloadText = payload.asText(); - - if(!payloadText.contains(CONFIGURATIONS)) { - LOG.info("Missing configurations node."); - return; - } - - JsonNode configurationsJsonNode; - try { - configurationsJsonNode = oMapper.readTree(payloadText); - } catch (Exception e) { - throw new InvalidMessageException("Cannot parse payload value", e); - } - - String mapFilename = rootDir + MAP_FILE_NAME + ".map"; - Map fieldMap = loadMap(mapFilename); - if (fieldMap == null) { - return; - } - - if (!fieldMap.containsKey(SDNC_ENDPOINT)) { - return; - } - String sdncEndpoint = fieldMap.get(SDNC_ENDPOINT); - - if (!fieldMap.containsKey(TEMPLATE)) { - throw new InvalidMessageException("No SDNC template known for message "); - } - String templateName = fieldMap.get(TEMPLATE); - - JsonNode configurations = configurationsJsonNode.get(CONFIGURATIONS); - - if(configurations.isArray()) { - for(JsonNode dataNode:configurations) { - if(dataNode.get(DATA).get(FAP_SERVICE) == null) { - LOG.info("Could not make a rpc call. Missing fapService node for dataNode element::", dataNode.textValue()); - }else { - try { - - String rpcMsgbody = publish(templateName, msg, dataNode); - String odlUrlBase = getProperty("sdnc.odl.url-base"); - String odlUser = getProperty("sdnc.odl.user"); - String odlPassword = getProperty("sdnc.odl.password"); - - if ((odlUrlBase != null) && (odlUrlBase.length() > 0)) { - SdncOdlConnection conn = SdncOdlConnection.newInstance(odlUrlBase + "/" + sdncEndpoint, odlUser, odlPassword); - - conn.send("POST", "application/json", rpcMsgbody); - } else { - LOG.info("POST message body would be:\n" + rpcMsgbody); - } - } catch (Exception e) { - LOG.error("Unable to process message", e); - } - } - } - }else { - throw new InvalidMessageException("Configurations is not of Type Array. Could not read configuration changes"); - } - } - - private Map loadMap(String mapFilename) { - File mapFile = new File(mapFilename); - - if (!mapFile.canRead()) { - LOG.error(String.format("Cannot read map file (%s)", mapFilename)); - return null; - } - - Map results = new HashMap<>(); - try (BufferedReader mapReader = new BufferedReader(new FileReader(mapFile))) { - - String curLine; - - while ((curLine = mapReader.readLine()) != null) { - curLine = curLine.trim(); - - if ((curLine.length() > 0) && (!curLine.startsWith("#")) && curLine.contains("=>")) { - String[] entry = curLine.split("=>"); - if (entry.length == 2) { - results.put(entry[0].trim(), entry[1].trim()); - } - } - } - mapReader.close(); - } catch (Exception e) { - LOG.error("Caught exception reading map " + mapFilename, e); - return null; - } - - return results; - } - -} diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/OofPciPocDmaapConsumers.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/OofPciPocDmaapConsumers.java new file mode 100644 index 000000000..2e6ae742b --- /dev/null +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/OofPciPocDmaapConsumers.java @@ -0,0 +1,504 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 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.northbound.dmaapclient; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.StringWriter; +import java.io.Writer; +import java.time.Instant; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; +import org.apache.velocity.VelocityContext; +import org.apache.velocity.app.VelocityEngine; +import org.json.JSONArray; +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class OofPciPocDmaapConsumers extends SdncDmaapConsumerImpl { + + private static final Logger LOG = LoggerFactory.getLogger(OofPciPocDmaapConsumers.class); + private static final String SDNC_ENDPOINT = "SDNC.endpoint"; + private static final String TEMPLATE = "SDNC.template"; + private static final String DMAAPLISTENERROOT = "DMAAPLISTENERROOT"; + private static final String UTF_8 = "UTF-8"; + + private static final String PARAMETER_NAME = "parameter-name"; + private static final String STRING_VALUE = "string-value"; + private static final String PHYSICAL_CELL_ID_INPUT_FAP_SERVICE = "configuration-phy-cell-id-input.fap-service"; + private static final String EVENT_HEADER = "event-header"; + private static final String ACTION = "Action"; + private static final String CONFIGURATIONS = "Configurations"; + private static final String MODIFY_CONFIG = "ModifyConfig"; + private static final String DATA = "data"; + private static final String FAP_SERVICE = "FAPService"; + + private static final String PAYLOAD = "Payload"; + private static final String PCI_CHANGES_MAP_FILE_NAME = "pci-changes-from-policy-to-sdnr"; + private static final String SLI_PARAMETERS = "sli_parameters"; + private static final String RPC_NAME = "rpc-name"; + private static final String BODY = "body"; + private static final String INPUT = "input"; + + private static final String GENERIC_NEIGHBOR_CONFIGURATION_INPUT = "generic-neighbor-configuration-input."; + private static final String GENERIC_NEIGHBOR_CONFIGURATION_INPUT_NEIGHBOR_LIST_IN_USE = GENERIC_NEIGHBOR_CONFIGURATION_INPUT.concat("neighbor-list-in-use"); + private static final String MODIFY_CONFIG_ANR = "ModifyConfigANR"; + private static final String ANR_CHANGES_MAP_FILE_NAME = "anr-changes-from-policy-to-sdnr"; + + private String rootDir; + + protected VelocityEngine velocityEngine; + + public OofPciPocDmaapConsumers() { + velocityEngine = new VelocityEngine(); + Properties props = new Properties(); + rootDir = System.getenv(DMAAPLISTENERROOT); + + if ((rootDir == null) || (rootDir.length() == 0)) { + rootDir = "/opt/app/dmaap-listener/lib/"; + } + else { + rootDir = rootDir + "/lib/"; + } + + props.put("file.resource.loader.path", rootDir); + velocityEngine.init(props); + } + + /* + * for testing purposes + */ + OofPciPocDmaapConsumers(Properties props) { + velocityEngine = new VelocityEngine(); + velocityEngine.init(props); + } + + protected String publish(String templatePath, String jsonString, JsonNode configurationsOrDataNode, boolean invokePciChangesPublish, boolean invokeAnrChangesPublish) throws IOException, InvalidMessageException + { + if (invokePciChangesPublish){ + return publishPciChangesFromPolicyToSDNR(templatePath, configurationsOrDataNode); + } else if (invokeAnrChangesPublish){ + return publishANRChangesFromPolicyToSDNR(templatePath, configurationsOrDataNode); + } else { + return publishFullMessage(templatePath, jsonString); + } + } + + private String publishFullMessage(String templatePath, String jsonString) throws IOException + { + JSONObject jsonObj = new JSONObject(jsonString); + VelocityContext context = new VelocityContext(); + for(Object key : jsonObj.keySet()) + { + context.put((String)key, jsonObj.get((String)key)); + } + + String id = jsonObj.getJSONObject(EVENT_HEADER).get("id").toString(); + context.put("req_id", id); + + context.put("curr_time", Instant.now()); + + ObjectMapper oMapper = new ObjectMapper(); + + String rpcMsgbody = oMapper.writeValueAsString(jsonString); + context.put("full_message", rpcMsgbody); + + Writer writer = new StringWriter(); + velocityEngine.mergeTemplate(templatePath, UTF_8, context, writer); + writer.flush(); + + return writer.toString(); + } + + private String publishANRChangesFromPolicyToSDNR(String templatePath, JsonNode dataNode) throws IOException, InvalidMessageException + { + VelocityContext context = new VelocityContext(); + + String RPC_NAME_KEY_IN_VT = "rpc_name"; + String RPC_NAME_VALUE_IN_VT = "generic-neighbor-configuration"; + + String CELL_CONFIG = "CellConfig"; + String ALIAS_LABEL = "alias"; + String LTE = "LTE"; + String RAN = "RAN"; + String LTE_CELL = "LTECell"; + String NEIGHBOR_LIST_IN_USE = "NeighborListInUse"; + + JSONObject numberOfEntries = new JSONObject(); + JSONObject alias = new JSONObject(); + JSONArray sliParametersArray = new JSONArray(); + + String aliasValue = dataNode.get(DATA).get(FAP_SERVICE).get(ALIAS_LABEL).textValue(); + + JsonNode nbrListInUse = dataNode.get(DATA).get(FAP_SERVICE).get(CELL_CONFIG).get(LTE).get(RAN).get(NEIGHBOR_LIST_IN_USE).get(LTE_CELL); + + int entryCount = 0; + + if(nbrListInUse.isArray()) { + for(JsonNode lteCell:nbrListInUse) { + sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, GENERIC_NEIGHBOR_CONFIGURATION_INPUT_NEIGHBOR_LIST_IN_USE+"["+entryCount+"]."+"plmnid") + .put(STRING_VALUE, lteCell.get("PLMNID"))); + sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, GENERIC_NEIGHBOR_CONFIGURATION_INPUT_NEIGHBOR_LIST_IN_USE+"["+entryCount+"]."+"cid") + .put(STRING_VALUE, lteCell.get("CID"))); + sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, GENERIC_NEIGHBOR_CONFIGURATION_INPUT_NEIGHBOR_LIST_IN_USE+"["+entryCount+"]."+"phy-cell-id") + .put(STRING_VALUE, lteCell.get("PhyCellID"))); + sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, GENERIC_NEIGHBOR_CONFIGURATION_INPUT_NEIGHBOR_LIST_IN_USE+"["+entryCount+"]."+"pnf-name") + .put(STRING_VALUE, lteCell.get("PNFName"))); + sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, GENERIC_NEIGHBOR_CONFIGURATION_INPUT_NEIGHBOR_LIST_IN_USE+"["+entryCount+"]."+"blacklisted") + .put(STRING_VALUE, lteCell.get("Blacklisted"))); + + entryCount++; + } + + alias.put(PARAMETER_NAME, GENERIC_NEIGHBOR_CONFIGURATION_INPUT+ALIAS_LABEL); + alias.put(STRING_VALUE, aliasValue); + + numberOfEntries.put(PARAMETER_NAME, GENERIC_NEIGHBOR_CONFIGURATION_INPUT+"number-of-neighbor-cell-entries"); + numberOfEntries.put(STRING_VALUE, entryCount); + + sliParametersArray.put(alias); + sliParametersArray.put(numberOfEntries); + + context.put(SLI_PARAMETERS, sliParametersArray); + + context.put(RPC_NAME_KEY_IN_VT, RPC_NAME_VALUE_IN_VT); + + Writer writer = new StringWriter(); + velocityEngine.mergeTemplate(templatePath, UTF_8, context, writer); + writer.flush(); + + return writer.toString(); + + }else { + throw new InvalidMessageException("nbrListInUse is not of Type Array. Could not read neighbor list elements"); + } + + } + + private String publishPciChangesFromPolicyToSDNR(String templatePath, JsonNode configurationsJsonNode) throws IOException, InvalidMessageException + { + String RPC_NAME_KEY_IN_VT = "rpc_name"; + String RPC_NAME_VALUE_IN_VT = "configuration-phy-cell-id"; + String ALIAS = "alias"; + String X0005b9Lte = "X0005b9Lte"; + + VelocityContext context = new VelocityContext(); + + JSONObject numberOfEntries = new JSONObject(); + JSONArray sliParametersArray = new JSONArray(); + + JsonNode configurations = configurationsJsonNode.get(CONFIGURATIONS); + + int entryCount = 0; + + if(configurations.isArray()) { + for(JsonNode dataNode:configurations) { + sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, PHYSICAL_CELL_ID_INPUT_FAP_SERVICE+"["+entryCount+"]."+ALIAS) + .put(STRING_VALUE, dataNode.get(DATA).get(FAP_SERVICE).get(ALIAS))); + sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, PHYSICAL_CELL_ID_INPUT_FAP_SERVICE+"["+entryCount+"]."+"cid") + .put(STRING_VALUE, dataNode.get(DATA).get(FAP_SERVICE).get("CellConfig").get("LTE").get("RAN").get("Common").get("CellIdentity"))); + sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, PHYSICAL_CELL_ID_INPUT_FAP_SERVICE+"["+entryCount+"]."+"phy-cell-id-in-use") + .put(STRING_VALUE, dataNode.get(DATA).get(FAP_SERVICE).get(X0005b9Lte).get("phyCellIdInUse"))); + sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, PHYSICAL_CELL_ID_INPUT_FAP_SERVICE+"["+entryCount+"]."+"pnf-name") + .put(STRING_VALUE, dataNode.get(DATA).get(FAP_SERVICE).get(X0005b9Lte).get("pnfName"))); + entryCount++; + } + + numberOfEntries.put(PARAMETER_NAME, PHYSICAL_CELL_ID_INPUT_FAP_SERVICE+"-number-of-entries"); + numberOfEntries.put(STRING_VALUE, entryCount); + + sliParametersArray.put(numberOfEntries); + + context.put(SLI_PARAMETERS, sliParametersArray); + + context.put(RPC_NAME_KEY_IN_VT, RPC_NAME_VALUE_IN_VT); + + Writer writer = new StringWriter(); + velocityEngine.mergeTemplate(templatePath, UTF_8, context, writer); + writer.flush(); + + return writer.toString(); + + }else { + throw new InvalidMessageException("Configurations is not of Type Array. Could not read configuration changes"); + } + + } + + @Override + public void processMsg(String msg) throws InvalidMessageException { + + if (msg == null) { + throw new InvalidMessageException("Null message"); + } + + ObjectMapper oMapper = new ObjectMapper(); + JsonNode dmaapMessageRootNode; + try { + dmaapMessageRootNode = oMapper.readTree(msg); + } catch (Exception e) { + throw new InvalidMessageException("Cannot parse json object", e); + } + + + JsonNode rpcnameNode = dmaapMessageRootNode.get(RPC_NAME); + if(rpcnameNode == null) { + LOG.info("Unable to identify the respective consumer to invoke. Please verify the dmaap message.."); + return; + } + + String rpcname = rpcnameNode.textValue(); + + if(!MODIFY_CONFIG.toLowerCase().equals(rpcname) && !MODIFY_CONFIG_ANR.toLowerCase().equals(rpcname)) { + LOG.info("Unknown rpc name {}", rpcname); + return; + } + + if(MODIFY_CONFIG.toLowerCase().equals(rpcname)) { + invokePCIChangesConsumer(dmaapMessageRootNode, oMapper, msg); + return; + } + + if(MODIFY_CONFIG_ANR.toLowerCase().equals(rpcname)) { + invokeANRChangesConsumer(dmaapMessageRootNode, oMapper, msg); + return; + } + + } + + private void invokeANRChangesConsumer(JsonNode dmaapMessageRootNode, ObjectMapper oMapper, + String msg) throws InvalidMessageException { + JsonNode body = dmaapMessageRootNode.get(BODY); + if(body == null) { + LOG.info("Missing body node."); + return; + } + + JsonNode input = body.get(INPUT); + if(input == null) { + LOG.info("Missing input node."); + return; + } + + JsonNode action = input.get(ACTION); + if(action == null) { + LOG.info("Missing action node."); + return; + } + + if(!MODIFY_CONFIG_ANR.equals(action.textValue())) { + LOG.info("Unknown Action {}", action); + return; + } + + JsonNode payload = input.get(PAYLOAD); + if(payload == null) { + LOG.info("Missing payload node."); + return; + } + + String payloadText = payload.asText(); + + if(!payloadText.contains(CONFIGURATIONS)) { + LOG.info("Missing configurations node."); + return; + } + + JsonNode configurationsJsonNode; + try { + configurationsJsonNode = oMapper.readTree(payloadText); + } catch (Exception e) { + throw new InvalidMessageException("Cannot parse payload value", e); + } + + String mapFilename = rootDir + ANR_CHANGES_MAP_FILE_NAME + ".map"; + Map fieldMap = loadMap(mapFilename); + if (fieldMap == null) { + return; + } + + if (!fieldMap.containsKey(SDNC_ENDPOINT)) { + return; + } + String sdncEndpoint = fieldMap.get(SDNC_ENDPOINT); + + if (!fieldMap.containsKey(TEMPLATE)) { + throw new InvalidMessageException("No SDNC template known for message "); + } + String templateName = fieldMap.get(TEMPLATE); + + JsonNode configurations = configurationsJsonNode.get(CONFIGURATIONS); + + if(configurations.isArray()) { + for(JsonNode dataNode:configurations) { + if(dataNode.get(DATA).get(FAP_SERVICE) == null) { + LOG.info("Could not make a rpc call. Missing fapService node for dataNode element::", dataNode.textValue()); + }else { + buildAndInvokeANRChangesRPC(sdncEndpoint, templateName,msg, dataNode); + } + } + }else { + throw new InvalidMessageException("Configurations is not of Type Array. Could not read configuration changes"); + } + } + + private void invokePCIChangesConsumer(JsonNode dmaapMessageRootNode, ObjectMapper oMapper, + String msg) throws InvalidMessageException { + JsonNode body = dmaapMessageRootNode.get(BODY); + if(body == null) { + LOG.info("Missing body node."); + return; + } + + JsonNode input = body.get(INPUT); + if(input == null) { + LOG.info("Missing input node."); + return; + } + + JsonNode action = input.get(ACTION); + if(action == null) { + LOG.info("Missing action node."); + return; + } + + if(!MODIFY_CONFIG.equals(action.textValue())) { + LOG.info("Unknown Action {}", action); + return; + } + + JsonNode payload = input.get(PAYLOAD); + if(payload == null) { + LOG.info("Missing payload node."); + return; + } + + String configurations = payload.asText(); + + if(!configurations.contains(CONFIGURATIONS)) { + LOG.info("Missing configurations node."); + return; + } + + JsonNode configurationsJsonNode; + try { + configurationsJsonNode = oMapper.readTree(configurations); + } catch (Exception e) { + throw new InvalidMessageException("Cannot parse payload value", e); + } + + String mapFilename = rootDir + PCI_CHANGES_MAP_FILE_NAME + ".map"; + Map fieldMap = loadMap(mapFilename); + if (fieldMap == null) { + return; + } + + if (!fieldMap.containsKey(SDNC_ENDPOINT)) { + return; + } + String sdncEndpoint = fieldMap.get(SDNC_ENDPOINT); + + if (!fieldMap.containsKey(TEMPLATE)) { + throw new InvalidMessageException("No SDNC template known for message "); + } + String templateName = fieldMap.get(TEMPLATE); + + buildAndInvokePCIChangesRPC(sdncEndpoint, templateName, msg, configurationsJsonNode); + } + + private void buildAndInvokePCIChangesRPC(String sdncEndpoint, String templateName, String msg, JsonNode configurationsOrDataNode) { + try { + String rpcMsgbody = publish(templateName, msg, configurationsOrDataNode, true, false); + String odlUrlBase = getProperty("sdnc.odl.url-base"); + String odlUser = getProperty("sdnc.odl.user"); + String odlPassword = getProperty("sdnc.odl.password"); + + if ((odlUrlBase != null) && (odlUrlBase.length() > 0)) { + SdncOdlConnection conn = SdncOdlConnection.newInstance(odlUrlBase + "/" + sdncEndpoint, odlUser, odlPassword); + + conn.send("POST", "application/json", rpcMsgbody); + } else { + LOG.info("POST message body would be:\n" + rpcMsgbody); + } + } catch (Exception e) { + LOG.error("Unable to process message", e); + } + } + + private void buildAndInvokeANRChangesRPC(String sdncEndpoint, String templateName, String msg, JsonNode configurationsOrDataNode) { + try { + String rpcMsgbody = publish(templateName, msg, configurationsOrDataNode, false, true); + String odlUrlBase = getProperty("sdnc.odl.url-base"); + String odlUser = getProperty("sdnc.odl.user"); + String odlPassword = getProperty("sdnc.odl.password"); + + if ((odlUrlBase != null) && (odlUrlBase.length() > 0)) { + SdncOdlConnection conn = SdncOdlConnection.newInstance(odlUrlBase + "/" + sdncEndpoint, odlUser, odlPassword); + + conn.send("POST", "application/json", rpcMsgbody); + } else { + LOG.info("POST message body would be:\n" + rpcMsgbody); + } + } catch (Exception e) { + LOG.error("Unable to process message", e); + } + } + + private Map loadMap(String mapFilename) { + File mapFile = new File(mapFilename); + + if (!mapFile.canRead()) { + LOG.error(String.format("Cannot read map file (%s)", mapFilename)); + return null; + } + + Map results = new HashMap<>(); + try (BufferedReader mapReader = new BufferedReader(new FileReader(mapFile))) { + + String curLine; + + while ((curLine = mapReader.readLine()) != null) { + curLine = curLine.trim(); + + if ((curLine.length() > 0) && (!curLine.startsWith("#")) && curLine.contains("=>")) { + String[] entry = curLine.split("=>"); + if (entry.length == 2) { + results.put(entry[0].trim(), entry[1].trim()); + } + } + } + mapReader.close(); + } catch (Exception e) { + LOG.error("Caught exception reading map " + mapFilename, e); + return null; + } + + return results; + } + +} diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/PciChangesFromPolicyToSDNRDmaapConsumer.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/PciChangesFromPolicyToSDNRDmaapConsumer.java deleted file mode 100644 index 8c44377f9..000000000 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/PciChangesFromPolicyToSDNRDmaapConsumer.java +++ /dev/null @@ -1,314 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 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.northbound.dmaapclient; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.io.StringWriter; -import java.io.Writer; -import java.time.Instant; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; -import org.apache.velocity.VelocityContext; -import org.apache.velocity.app.VelocityEngine; -import org.json.JSONArray; -import org.json.JSONObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -public class PciChangesFromPolicyToSDNRDmaapConsumer extends SdncDmaapConsumerImpl { - - private static final Logger LOG = LoggerFactory.getLogger(PciChangesFromPolicyToSDNRDmaapConsumer.class); - private static final String SDNC_ENDPOINT = "SDNC.endpoint"; - private static final String TEMPLATE = "SDNC.template"; - private static final String DMAAPLISTENERROOT = "DMAAPLISTENERROOT"; - - private static final String PARAMETER_NAME = "parameter-name"; - private static final String STRING_VALUE = "string-value"; - private static final String PHYSICAL_CELL_ID_INPUT_FAP_SERVICE = "configuration-phy-cell-id-input.fap-service"; - private static final String EVENT_HEADER = "event-header"; - private static final String ACTION = "Action"; - private static final String PAYLOAD = "Payload"; - private static final String CONFIGURATIONS = "Configurations"; - private static final String MODIFY_CONFIG = "ModifyConfig"; - private static final String MAP_FILE_NAME = "pci-changes-from-policy-to-sdnr"; - private static final String DATA = "data"; - private static final String FAP_SERVICE = "FAPService"; - private static final String SLI_PARAMETERS = "sli_parameters"; - private static final String RPC_NAME = "rpc-name"; - private static final String BODY = "body"; - private static final String INPUT = "input"; - - private String rootDir; - - protected VelocityEngine velocityEngine; - - public PciChangesFromPolicyToSDNRDmaapConsumer() { - velocityEngine = new VelocityEngine(); - Properties props = new Properties(); - rootDir = System.getenv(DMAAPLISTENERROOT); - - if ((rootDir == null) || (rootDir.length() == 0)) { - rootDir = "/opt/app/dmaap-listener/lib/"; - } - else { - rootDir = rootDir + "/lib/"; - } - - props.put("file.resource.loader.path", rootDir); - velocityEngine.init(props); - } - - /* - * for testing purposes - */ - PciChangesFromPolicyToSDNRDmaapConsumer(Properties props) { - velocityEngine = new VelocityEngine(); - velocityEngine.init(props); - } - - protected String publish(String templatePath, String jsonString, JsonNode configurationsJsonNode) throws IOException, InvalidMessageException - { - if (templatePath.contains("anr-pci-changes-from-policy-to-sdnr")){ - return publishPciChangesFromPolicyToSDNR(templatePath, configurationsJsonNode); - } else { - return publishFullMessage(templatePath, jsonString); - } - } - - private String publishFullMessage(String templatePath, String jsonString) throws IOException - { - JSONObject jsonObj = new JSONObject(jsonString); - VelocityContext context = new VelocityContext(); - for(Object key : jsonObj.keySet()) - { - context.put((String)key, jsonObj.get((String)key)); - } - - String id = jsonObj.getJSONObject(EVENT_HEADER).get("id").toString(); - context.put("req_id", id); - - context.put("curr_time", Instant.now()); - - ObjectMapper oMapper = new ObjectMapper(); - - String rpcMsgbody = oMapper.writeValueAsString(jsonString); - context.put("full_message", rpcMsgbody); - - Writer writer = new StringWriter(); - velocityEngine.mergeTemplate(templatePath, "UTF-8", context, writer); - writer.flush(); - - return writer.toString(); - } - - private String publishPciChangesFromPolicyToSDNR(String templatePath, JsonNode configurationsJsonNode) throws IOException, InvalidMessageException - { - String RPC_NAME_KEY_IN_VT = "rpc_name"; - String RPC_NAME_VALUE_IN_VT = "configuration-phy-cell-id"; - String ALIAS = "alias"; - String X0005b9Lte = "X0005b9Lte"; - - VelocityContext context = new VelocityContext(); - - JSONObject numberOfEntries = new JSONObject(); - JSONArray sliParametersArray = new JSONArray(); - - JsonNode configurations = configurationsJsonNode.get(CONFIGURATIONS); - - int entryCount = 0; - - if(configurations.isArray()) { - for(JsonNode dataNode:configurations) { - sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, PHYSICAL_CELL_ID_INPUT_FAP_SERVICE+"["+entryCount+"]."+ALIAS) - .put(STRING_VALUE, dataNode.get(DATA).get(FAP_SERVICE).get(ALIAS))); - sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, PHYSICAL_CELL_ID_INPUT_FAP_SERVICE+"["+entryCount+"]."+"cid") - .put(STRING_VALUE, dataNode.get(DATA).get(FAP_SERVICE).get("CellConfig").get("LTE").get("RAN").get("Common").get("CellIdentity"))); - sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, PHYSICAL_CELL_ID_INPUT_FAP_SERVICE+"["+entryCount+"]."+"phy-cell-id-in-use") - .put(STRING_VALUE, dataNode.get(DATA).get(FAP_SERVICE).get(X0005b9Lte).get("phyCellIdInUse"))); - sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, PHYSICAL_CELL_ID_INPUT_FAP_SERVICE+"["+entryCount+"]."+"pnf-name") - .put(STRING_VALUE, dataNode.get(DATA).get(FAP_SERVICE).get(X0005b9Lte).get("pnfName"))); - entryCount++; - } - - numberOfEntries.put(PARAMETER_NAME, PHYSICAL_CELL_ID_INPUT_FAP_SERVICE+"-number-of-entries"); - numberOfEntries.put(STRING_VALUE, entryCount); - - sliParametersArray.put(numberOfEntries); - - context.put(SLI_PARAMETERS, sliParametersArray); - - context.put(RPC_NAME_KEY_IN_VT, RPC_NAME_VALUE_IN_VT); - - Writer writer = new StringWriter(); - velocityEngine.mergeTemplate(templatePath, "UTF-8", context, writer); - writer.flush(); - - return writer.toString(); - - }else { - throw new InvalidMessageException("Configurations is not of Type Array. Could not read configuration changes"); - } - - } - - @Override - public void processMsg(String msg) throws InvalidMessageException { - - if (msg == null) { - throw new InvalidMessageException("Null message"); - } - - ObjectMapper oMapper = new ObjectMapper(); - JsonNode pciChangesRootNode; - try { - pciChangesRootNode = oMapper.readTree(msg); - } catch (Exception e) { - throw new InvalidMessageException("Cannot parse json object", e); - } - - JsonNode rpcname = pciChangesRootNode.get(RPC_NAME); - if(rpcname == null) { - LOG.info("Missing rpc-name node."); - return; - } - - if(!MODIFY_CONFIG.toLowerCase().equals(rpcname.textValue())) { - LOG.info("Unknown rpc name {}", rpcname); - return; - } - - JsonNode body = pciChangesRootNode.get(BODY); - if(body == null) { - LOG.info("Missing body node."); - return; - } - - JsonNode input = body.get(INPUT); - if(input == null) { - LOG.info("Missing input node."); - return; - } - - JsonNode action = input.get(ACTION); - if(action == null) { - LOG.info("Missing action node."); - return; - } - - if(!MODIFY_CONFIG.equals(action.textValue())) { - LOG.info("Unknown Action {}", action); - return; - } - - JsonNode payload = input.get(PAYLOAD); - if(payload == null) { - LOG.info("Missing payload node."); - return; - } - - String configurations = payload.asText(); - - if(!configurations.contains(CONFIGURATIONS)) { - LOG.info("Missing configurations node."); - return; - } - - JsonNode configurationsJsonNode; - try { - configurationsJsonNode = oMapper.readTree(configurations); - } catch (Exception e) { - throw new InvalidMessageException("Cannot parse payload value", e); - } - - String mapFilename = rootDir + MAP_FILE_NAME + ".map"; - Map fieldMap = loadMap(mapFilename); - if (fieldMap == null) { - return; - } - - if (!fieldMap.containsKey(SDNC_ENDPOINT)) { - return; - } - String sdncEndpoint = fieldMap.get(SDNC_ENDPOINT); - - if (!fieldMap.containsKey(TEMPLATE)) { - throw new InvalidMessageException("No SDNC template known for message "); - } - String templateName = fieldMap.get(TEMPLATE); - - try { - String rpcMsgbody = publish(templateName, msg, configurationsJsonNode); - String odlUrlBase = getProperty("sdnc.odl.url-base"); - String odlUser = getProperty("sdnc.odl.user"); - String odlPassword = getProperty("sdnc.odl.password"); - - if ((odlUrlBase != null) && (odlUrlBase.length() > 0)) { - SdncOdlConnection conn = SdncOdlConnection.newInstance(odlUrlBase + "/" + sdncEndpoint, odlUser, odlPassword); - - conn.send("POST", "application/json", rpcMsgbody); - } else { - LOG.info("POST message body would be:\n" + rpcMsgbody); - } - } catch (Exception e) { - LOG.error("Unable to process message", e); - } - } - - private Map loadMap(String mapFilename) { - File mapFile = new File(mapFilename); - - if (!mapFile.canRead()) { - LOG.error(String.format("Cannot read map file (%s)", mapFilename)); - return null; - } - - Map results = new HashMap<>(); - try (BufferedReader mapReader = new BufferedReader(new FileReader(mapFile))) { - - String curLine; - - while ((curLine = mapReader.readLine()) != null) { - curLine = curLine.trim(); - - if ((curLine.length() > 0) && (!curLine.startsWith("#")) && curLine.contains("=>")) { - String[] entry = curLine.split("=>"); - if (entry.length == 2) { - results.put(entry[0].trim(), entry[1].trim()); - } - } - } - mapReader.close(); - } catch (Exception e) { - LOG.error("Caught exception reading map " + mapFilename, e); - return null; - } - - return results; - } - -} diff --git a/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestANRChangesFromPolicyToSDNRDmaapConsumer.java b/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestANRChangesFromPolicyToSDNRDmaapConsumer.java deleted file mode 100644 index 66b63a17d..000000000 --- a/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestANRChangesFromPolicyToSDNRDmaapConsumer.java +++ /dev/null @@ -1,142 +0,0 @@ -package org.onap.ccsdk.sli.northbound.dmaapclient; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.util.Properties; - -import org.junit.Before; -import org.junit.Test; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -public class TestANRChangesFromPolicyToSDNRDmaapConsumer { - private static final String anrChangesFromPolicyToSDNRInput = "{\n" + - " \"body\": {\n" + - " \"input\": {\n" + - " \"CommonHeader\": {\n" + - " \"TimeStamp\": \"2018-11-30T09:13:37.368Z\",\n" + - " \"APIVer\": \"1.0\",\n" + - " \"RequestID\": \"722ee65a-8afd-48df-bf57-c152ae45bacc\",\n" + - " \"SubRequestID\": \"1\",\n" + - " \"RequestTrack\": {},\n" + - " \"Flags\": {}\n" + - " },\n" + - "\"Action\": \"ModifyConfigANR\",\n" + - " \"Payload\": \"{ \\\"Configurations\\\":[ { \\\"data\\\":{ \\\"FAPService\\\":{ \\\"alias\\\":\\\"Cell1\\\", \\\"CellConfig\\\":{ \\\"LTE\\\":{ \\\"RAN\\\":{ \\\"Common\\\":{ \\\"CellIdentity\\\":\\\"1\\\" }, \\\"NeighborListInUse\\\" : { \\\"LTECellNumberOfEntries\\\" : \\\"1\\\" , \\\"LTECell\\\" : [{ \\\"PLMNID\\\" :\\\"plmnid1\\\", \\\"CID\\\":\\\"Chn0001\\\", \\\"PhyCellID\\\":\\\"3\\\", \\\"PNFName\\\":\\\"ncserver01\\\", \\\"Blacklisted\\\":\\\"false\\\"}] } } } } } } } ] }\"\n" + - " }\n" + - " },\n" + - " \"version\": \"1.0\",\n" + - " \"rpc-name\": \"modifyconfiganr\",\n" + - " \"correlation-id\": \"722ee65a-8afd-48df-bf57-c152ae45bacc-1\",\n" + - " \"type\": \"request\"\n" + - "}\n" + - ""; - - @Before - public void setUp() throws Exception { - } - - @Test - public void testRPCMessageBodyResponse() throws Exception { - Properties props = new Properties(); - - ObjectMapper oMapper = new ObjectMapper(); - JsonNode anrChangesRootNode = oMapper.readTree(anrChangesFromPolicyToSDNRInput); - JsonNode body = anrChangesRootNode.get("body"); - JsonNode input = body.get("input"); - JsonNode payload = input.get("Payload"); - String payloadText = payload.asText(); - JsonNode configurationsJsonNode = oMapper.readTree(payloadText); - JsonNode configurations = configurationsJsonNode.get("Configurations"); - - for(JsonNode dataNode:configurations) { - String rpcMsgbody = new ANRChangesFromPolicyToSDNRDmaapConsumer(props).publish("src/main/resources/anr-pci-changes-from-policy-to-sdnr.vt", anrChangesFromPolicyToSDNRInput,dataNode); - - JsonNode rootNode; - try { - rootNode = oMapper.readTree(rpcMsgbody); - } catch (Exception e) { - throw new InvalidMessageException("Cannot parse json object", e); - } - - assertTrue(rootNode.get("input").get("module-name") != null); - assertTrue(rootNode.get("input").get("rpc-name") != null); - assertTrue(rootNode.get("input").get("mode") != null); - assertTrue(rootNode.get("input").get("sli-parameter") != null); - } - } - - @Test(expected = InvalidMessageException.class) - public void testProcessMsgNullMessage() throws Exception { - ANRChangesFromPolicyToSDNRDmaapConsumer consumer = new ANRChangesFromPolicyToSDNRDmaapConsumer(); - consumer.processMsg(null); - } - - @Test(expected = InvalidMessageException.class) - public void testProcessMsgInvalidMessage() throws Exception { - ANRChangesFromPolicyToSDNRDmaapConsumer consumer = new ANRChangesFromPolicyToSDNRDmaapConsumer(); - consumer.processMsg("test"); - } - - @Test - public void testProcessMsgMissingActionHeader() throws Exception { - ANRChangesFromPolicyToSDNRDmaapConsumer consumer = new ANRChangesFromPolicyToSDNRDmaapConsumer(); - consumer.processMsg("{\n" + - " \"body\": {\n" + - " \"input\": {\n" + - " \"CommonHeader\": {\n" + - " \"TimeStamp\": \"2018-11-30T09:13:37.368Z\",\n" + - " \"APIVer\": \"1.0\",\n" + - " \"RequestID\": \"722ee65a-8afd-48df-bf57-c152ae45bacc\",\n" + - " \"SubRequestID\": \"1\",\n" + - " \"RequestTrack\": {},\n" + - " \"Flags\": {}\n" + - " },\n" + - "\"NoAction\": \"ModifyConfigANR\",\n" + - " \"Payload\": \"{ \\\"Configurations\\\":[ { \\\"data\\\":{ \\\"FAPService\\\":{ \\\"alias\\\":\\\"Cell1\\\", \\\"CellConfig\\\":{ \\\"LTE\\\":{ \\\"RAN\\\":{ \\\"Common\\\":{ \\\"CellIdentity\\\":\\\"1\\\" }, \\\"NeighborListInUse\\\" : { \\\"LTECellNumberOfEntries\\\" : \\\"1\\\" , \\\"LTECell\\\" : [{ \\\"PLMNID\\\" :\\\"plmnid1\\\", \\\"CID\\\":\\\"Chn0001\\\", \\\"PhyCellID\\\":\\\"3\\\", \\\"PNFName\\\":\\\"ncserver01\\\", \\\"Blacklisted\\\":\\\"false\\\"}] } } } } } } } ] }\"\n" + - " }\n" + - " },\n" + - " \"version\": \"1.0\",\n" + - " \"rpc-name\": \"modifyconfiganr\",\n" + - " \"correlation-id\": \"722ee65a-8afd-48df-bf57-c152ae45bacc-1\",\n" + - " \"type\": \"request\"\n" + - "}\n" + - ""); - } - - @Test - public void testProcessMsgInvalidPayloadConfigurations() throws Exception { - String msg = "{\n" + - " \"body\": {\n" + - " \"input\": {\n" + - " \"CommonHeader\": {\n" + - " \"TimeStamp\": \"2018-11-30T09:13:37.368Z\",\n" + - " \"APIVer\": \"1.0\",\n" + - " \"RequestID\": \"722ee65a-8afd-48df-bf57-c152ae45bacc\",\n" + - " \"SubRequestID\": \"1\",\n" + - " \"RequestTrack\": {},\n" + - " \"Flags\": {}\n" + - " },\n" + - "\"Action\": \"ModifyConfigANR\",\n" + - " \"Payload\": \"{ \\\"Configurations\\\":{ { \\\"data\\\":{ \\\"FAPService\\\":{ \\\"alias\\\":\\\"Cell1\\\", \\\"CellConfig\\\":{ \\\"LTE\\\":{ \\\"RAN\\\":{ \\\"Common\\\":{ \\\"CellIdentity\\\":\\\"1\\\" }, \\\"NeighborListInUse\\\" : { \\\"LTECellNumberOfEntries\\\" : \\\"1\\\" , \\\"LTECell\\\" : [{ \\\"PLMNID\\\" :\\\"plmnid1\\\", \\\"CID\\\":\\\"Chn0001\\\", \\\"PhyCellID\\\":\\\"3\\\", \\\"PNFName\\\":\\\"ncserver01\\\", \\\"Blacklisted\\\":\\\"false\\\"}} } } } } } } } ] }\"\n" + - " }\n" + - " },\n" + - " \"version\": \"1.0\",\n" + - " \"rpc-name\": \"modifyconfiganr\",\n" + - " \"correlation-id\": \"722ee65a-8afd-48df-bf57-c152ae45bacc-1\",\n" + - " \"type\": \"request\"\n" + - "}\n" + - ""; - - try { - ANRChangesFromPolicyToSDNRDmaapConsumer consumer = new ANRChangesFromPolicyToSDNRDmaapConsumer(); - consumer.processMsg(msg); - - } catch (final InvalidMessageException e) { - final String errorMsg = "Cannot parse payload value"; - assertEquals(errorMsg, e.getMessage()); - } - } -} diff --git a/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestOofPciPocDmaapConsumers.java b/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestOofPciPocDmaapConsumers.java new file mode 100644 index 000000000..cd2ea6eb0 --- /dev/null +++ b/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestOofPciPocDmaapConsumers.java @@ -0,0 +1,314 @@ +package org.onap.ccsdk.sli.northbound.dmaapclient; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.Properties; + +import org.junit.Before; +import org.junit.Test; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class TestOofPciPocDmaapConsumers { + + private static final String pciChangesFromPolicyToSDNRInput = "{\n" + + " \"body\": {\n" + + " \"input\": {\n" + + " \"CommonHeader\": {\n" + + " \"TimeStamp\": \"2018-11-30T09:13:37.368Z\",\n" + + " \"APIVer\": \"1.0\",\n" + + " \"RequestID\": \"9d2d790e-a5f0-11e8-98d0-529269fb1459\",\n" + + " \"SubRequestID\": \"1\",\n" + + " \"RequestTrack\": {},\n" + + " \"Flags\": {}\n" + + " },\n" + + " \"Action\": \"ModifyConfig\",\n" + + " \"Payload\": \"{\\\"Configurations\\\":[{\\\"data\\\":{\\\"FAPService\\\":{\\\"alias\\\":\\\"Chn0330\\\",\\\"X0005b9Lte\\\":{\\\"phyCellIdInUse\\\":6,\\\"pnfName\\\":\\\"ncserver23\\\"},\\\"CellConfig\\\":{\\\"LTE\\\":{\\\"RAN\\\":{\\\"Common\\\":{\\\"CellIdentity\\\":\\\"Chn0330\\\"}}}}}}},{\\\"data\\\":{\\\"FAPService\\\":{\\\"alias\\\":\\\"Chn0331\\\",\\\"X0005b9Lte\\\":{\\\"phyCellIdInUse\\\":7,\\\"pnfName\\\":\\\"ncserver23\\\"},\\\"CellConfig\\\":{\\\"LTE\\\":{\\\"RAN\\\":{\\\"Common\\\":{\\\"CellIdentity\\\":\\\"Chn0331\\\"}}}}}}}]}\"\n" + + " }\n" + + " },\n" + + " \"version\": \"1.0\",\n" + + " \"rpc-name\": \"modifyconfig\",\n" + + " \"correlation-id\": \"9d2d790e-a5f0-11e8-98d0-529269fb1459-1\",\n" + + " \"type\": \"request\"\n" + + "}"; + + private static final String anrChangesFromPolicyToSDNRInput = "{\n" + + " \"body\": {\n" + + " \"input\": {\n" + + " \"CommonHeader\": {\n" + + " \"TimeStamp\": \"2018-11-30T09:13:37.368Z\",\n" + + " \"APIVer\": \"1.0\",\n" + + " \"RequestID\": \"722ee65a-8afd-48df-bf57-c152ae45bacc\",\n" + + " \"SubRequestID\": \"1\",\n" + + " \"RequestTrack\": {},\n" + + " \"Flags\": {}\n" + + " },\n" + + "\"Action\": \"ModifyConfigANR\",\n" + + " \"Payload\": \"{ \\\"Configurations\\\":[ { \\\"data\\\":{ \\\"FAPService\\\":{ \\\"alias\\\":\\\"Cell1\\\", \\\"CellConfig\\\":{ \\\"LTE\\\":{ \\\"RAN\\\":{ \\\"Common\\\":{ \\\"CellIdentity\\\":\\\"1\\\" }, \\\"NeighborListInUse\\\" : { \\\"LTECellNumberOfEntries\\\" : \\\"1\\\" , \\\"LTECell\\\" : [{ \\\"PLMNID\\\" :\\\"plmnid1\\\", \\\"CID\\\":\\\"Chn0001\\\", \\\"PhyCellID\\\":\\\"3\\\", \\\"PNFName\\\":\\\"ncserver01\\\", \\\"Blacklisted\\\":\\\"false\\\"}] } } } } } } } ] }\"\n" + + " }\n" + + " },\n" + + " \"version\": \"1.0\",\n" + + " \"rpc-name\": \"modifyconfiganr\",\n" + + " \"correlation-id\": \"722ee65a-8afd-48df-bf57-c152ae45bacc-1\",\n" + + " \"type\": \"request\"\n" + + "}\n" + + ""; + + @Before + public void setUp() throws Exception { + } + + /* ---------- PCI Changes DMAAP messages test cases ------------------- */ + + @Test + public void testPCIChangesDmaapRPCMessageBodyResponse() throws Exception { + Properties props = new Properties(); + + ObjectMapper oMapper = new ObjectMapper(); + JsonNode pciChangesRootNode = oMapper.readTree(pciChangesFromPolicyToSDNRInput); + JsonNode body = pciChangesRootNode.get("body"); + JsonNode input = body.get("input"); + JsonNode payload = input.get("Payload"); + String payloadText = payload.asText(); + JsonNode configurationsJsonNode = oMapper.readTree(payloadText); + + String rpcMsgbody = new OofPciPocDmaapConsumers(props).publish("src/main/resources/anr-pci-changes-from-policy-to-sdnr.vt", pciChangesFromPolicyToSDNRInput,configurationsJsonNode, true, false); + + JsonNode rootNode; + try { + rootNode = oMapper.readTree(rpcMsgbody); + } catch (Exception e) { + throw new InvalidMessageException("Cannot parse json object", e); + } + + assertTrue(rootNode.get("input").get("module-name") != null); + assertTrue(rootNode.get("input").get("rpc-name") != null); + assertTrue(rootNode.get("input").get("mode") != null); + assertTrue(rootNode.get("input").get("sli-parameter") != null); + + } + + @Test(expected = InvalidMessageException.class) + public void testPCIChangesDmaapProcessMsgNullMessage() throws Exception { + OofPciPocDmaapConsumers consumer = new OofPciPocDmaapConsumers(); + consumer.processMsg(null); + } + + @Test(expected = InvalidMessageException.class) + public void testPCIChangesDmaapProcessMsgInvalidMessage() throws Exception { + OofPciPocDmaapConsumers consumer = new OofPciPocDmaapConsumers(); + consumer.processMsg("test"); + } + + @Test + public void testPCIChangesDmaapProcessMsgMissingActionHeader() throws Exception { + OofPciPocDmaapConsumers consumer = new OofPciPocDmaapConsumers(); + consumer.processMsg("{\n" + + " \"body\": {\n" + + " \"input\": {\n" + + " \"CommonHeader\": {\n" + + " \"TimeStamp\": \"2018-11-30T09:13:37.368Z\",\n" + + " \"APIVer\": \"1.0\",\n" + + " \"RequestID\": \"9d2d790e-a5f0-11e8-98d0-529269fb1459\",\n" + + " \"SubRequestID\": \"1\",\n" + + " \"RequestTrack\": {},\n" + + " \"Flags\": {}\n" + + " },\n" + + " \"RenamedAction\": \"ModifyConfig\",\n" + + " \"Payload\": {\n" + + " \"Configurations \": {\n" + + " \"data \": {\n" + + " \"FAPService \": {\n" + + " \"alias\": \"Chn0330\",\n" + + " \"X0005b9Lte\": {\n" + + " \"phyCellIdInUse\": 6,\n" + + " \"pnfName\": \"ncserver23\"\n" + + " },\n" + + " \"CellConfig\": {\n" + + " \"LTE\": {\n" + + " \"RAN\": {\n" + + " \"Common\": {\n" + + " \"CellIdentity\": \"Chn0330\"\n" + + " }\n" + + " }\n" + + " }\n" + + " }\n" + + " }\n" + + " }\n" + + " }\n" + + "\n" + + " }\n" + + " }\n" + + " },\n" + + " \"version\": \"1.0\",\n" + + " \"rpc-name\": \"modifyconfig\",\n" + + " \"correlation-id\": \"9d2d790e-a5f0-11e8-98d0-529269fb1459-1\",\n" + + " \"type\": \"request\"\n" + + "}"); + } + + @Test + public void testPCIChangesDmaapProcessMsgInvalidPayloadConfigurations() throws Exception { + String msg = "{\n" + + " \"body\": {\n" + + " \"input\": {\n" + + " \"CommonHeader\": {\n" + + " \"TimeStamp\": \"2018-11-30T09:13:37.368Z\",\n" + + " \"APIVer\": \"1.0\",\n" + + " \"RequestID\": \"9d2d790e-a5f0-11e8-98d0-529269fb1459\",\n" + + " \"SubRequestID\": \"1\",\n" + + " \"RequestTrack\": {},\n" + + " \"Flags\": {}\n" + + " },\n" + + " \"Action\": \"ModifyConfig\",\n" + + " \"Payload\": {\n" + + " \"Configurations \": {\n" + + " \"data \": {\n" + + " \"FAPService \": {\n" + + " \"alias\": \"Chn0330\",\n" + + " \"X0005b9Lte\": {\n" + + " \"phyCellIdInUse\": 6,\n" + + " \"pnfName\": \"ncserver23\"\n" + + " },\n" + + " \"CellConfig\": {\n" + + " \"LTE\": {\n" + + " \"RAN\": {\n" + + " \"Common\": {\n" + + " \"CellIdentity\": \"Chn0330\"\n" + + " }\n" + + " }\n" + + " }\n" + + " }\n" + + " }\n" + + " }\n" + + " }\n" + + "\n" + + " }\n" + + " }\n" + + " },\n" + + " \"version\": \"1.0\",\n" + + " \"rpc-name\": \"modifyconfig\",\n" + + " \"correlation-id\": \"9d2d790e-a5f0-11e8-98d0-529269fb1459-1\",\n" + + " \"type\": \"request\"\n" + + "}"; + + try { + OofPciPocDmaapConsumers consumer = new OofPciPocDmaapConsumers(); + consumer.processMsg(msg); + + } catch (final InvalidMessageException e) { + final String errorMsg = "Configurations is not of Type Array. Could not read configuration changes"; + assertEquals(errorMsg, e.getMessage()); + } + } + + /* ---------- PCI Changes DMAAP messages test cases ------------------- */ + + /* ---------- ANR Changes DMAAP messages test cases ------------------- */ + + @Test + public void testANRChangesDmaapRPCMessageBodyResponse() throws Exception { + Properties props = new Properties(); + + ObjectMapper oMapper = new ObjectMapper(); + JsonNode anrChangesRootNode = oMapper.readTree(anrChangesFromPolicyToSDNRInput); + JsonNode body = anrChangesRootNode.get("body"); + JsonNode input = body.get("input"); + JsonNode payload = input.get("Payload"); + String payloadText = payload.asText(); + JsonNode configurationsJsonNode = oMapper.readTree(payloadText); + JsonNode configurations = configurationsJsonNode.get("Configurations"); + + for(JsonNode dataNode:configurations) { + String rpcMsgbody = new OofPciPocDmaapConsumers(props).publish("src/main/resources/anr-pci-changes-from-policy-to-sdnr.vt", anrChangesFromPolicyToSDNRInput,dataNode, false, true); + + JsonNode rootNode; + try { + rootNode = oMapper.readTree(rpcMsgbody); + } catch (Exception e) { + throw new InvalidMessageException("Cannot parse json object", e); + } + + assertTrue(rootNode.get("input").get("module-name") != null); + assertTrue(rootNode.get("input").get("rpc-name") != null); + assertTrue(rootNode.get("input").get("mode") != null); + assertTrue(rootNode.get("input").get("sli-parameter") != null); + } + } + + @Test(expected = InvalidMessageException.class) + public void testANRChangesDmaapProcessMsgNullMessage() throws Exception { + OofPciPocDmaapConsumers consumer = new OofPciPocDmaapConsumers(); + consumer.processMsg(null); + } + + @Test(expected = InvalidMessageException.class) + public void testANRChangesDmaapProcessMsgInvalidMessage() throws Exception { + OofPciPocDmaapConsumers consumer = new OofPciPocDmaapConsumers(); + consumer.processMsg("test"); + } + + @Test + public void testANRChangesDmaapProcessMsgMissingActionHeader() throws Exception { + OofPciPocDmaapConsumers consumer = new OofPciPocDmaapConsumers(); + consumer.processMsg("{\n" + + " \"body\": {\n" + + " \"input\": {\n" + + " \"CommonHeader\": {\n" + + " \"TimeStamp\": \"2018-11-30T09:13:37.368Z\",\n" + + " \"APIVer\": \"1.0\",\n" + + " \"RequestID\": \"722ee65a-8afd-48df-bf57-c152ae45bacc\",\n" + + " \"SubRequestID\": \"1\",\n" + + " \"RequestTrack\": {},\n" + + " \"Flags\": {}\n" + + " },\n" + + "\"NoAction\": \"ModifyConfigANR\",\n" + + " \"Payload\": \"{ \\\"Configurations\\\":[ { \\\"data\\\":{ \\\"FAPService\\\":{ \\\"alias\\\":\\\"Cell1\\\", \\\"CellConfig\\\":{ \\\"LTE\\\":{ \\\"RAN\\\":{ \\\"Common\\\":{ \\\"CellIdentity\\\":\\\"1\\\" }, \\\"NeighborListInUse\\\" : { \\\"LTECellNumberOfEntries\\\" : \\\"1\\\" , \\\"LTECell\\\" : [{ \\\"PLMNID\\\" :\\\"plmnid1\\\", \\\"CID\\\":\\\"Chn0001\\\", \\\"PhyCellID\\\":\\\"3\\\", \\\"PNFName\\\":\\\"ncserver01\\\", \\\"Blacklisted\\\":\\\"false\\\"}] } } } } } } } ] }\"\n" + + " }\n" + + " },\n" + + " \"version\": \"1.0\",\n" + + " \"rpc-name\": \"modifyconfiganr\",\n" + + " \"correlation-id\": \"722ee65a-8afd-48df-bf57-c152ae45bacc-1\",\n" + + " \"type\": \"request\"\n" + + "}\n" + + ""); + } + + @Test + public void testANRChangesDmaapProcessMsgInvalidPayloadConfigurations() throws Exception { + String msg = "{\n" + + " \"body\": {\n" + + " \"input\": {\n" + + " \"CommonHeader\": {\n" + + " \"TimeStamp\": \"2018-11-30T09:13:37.368Z\",\n" + + " \"APIVer\": \"1.0\",\n" + + " \"RequestID\": \"722ee65a-8afd-48df-bf57-c152ae45bacc\",\n" + + " \"SubRequestID\": \"1\",\n" + + " \"RequestTrack\": {},\n" + + " \"Flags\": {}\n" + + " },\n" + + "\"Action\": \"ModifyConfigANR\",\n" + + " \"Payload\": \"{ \\\"Configurations\\\":{ { \\\"data\\\":{ \\\"FAPService\\\":{ \\\"alias\\\":\\\"Cell1\\\", \\\"CellConfig\\\":{ \\\"LTE\\\":{ \\\"RAN\\\":{ \\\"Common\\\":{ \\\"CellIdentity\\\":\\\"1\\\" }, \\\"NeighborListInUse\\\" : { \\\"LTECellNumberOfEntries\\\" : \\\"1\\\" , \\\"LTECell\\\" : [{ \\\"PLMNID\\\" :\\\"plmnid1\\\", \\\"CID\\\":\\\"Chn0001\\\", \\\"PhyCellID\\\":\\\"3\\\", \\\"PNFName\\\":\\\"ncserver01\\\", \\\"Blacklisted\\\":\\\"false\\\"}} } } } } } } } ] }\"\n" + + " }\n" + + " },\n" + + " \"version\": \"1.0\",\n" + + " \"rpc-name\": \"modifyconfiganr\",\n" + + " \"correlation-id\": \"722ee65a-8afd-48df-bf57-c152ae45bacc-1\",\n" + + " \"type\": \"request\"\n" + + "}\n" + + ""; + + try { + OofPciPocDmaapConsumers consumer = new OofPciPocDmaapConsumers(); + consumer.processMsg(msg); + + } catch (final InvalidMessageException e) { + final String errorMsg = "Cannot parse payload value"; + assertEquals(errorMsg, e.getMessage()); + } + } + + /* ---------- ANR Changes DMAAP messages test cases ------------------- */ +} diff --git a/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestPciChangesFromPolicyToSDNRDmaapConsumer.java b/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestPciChangesFromPolicyToSDNRDmaapConsumer.java deleted file mode 100644 index a42bc48f6..000000000 --- a/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestPciChangesFromPolicyToSDNRDmaapConsumer.java +++ /dev/null @@ -1,181 +0,0 @@ -package org.onap.ccsdk.sli.northbound.dmaapclient; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.util.Properties; - -import org.junit.Before; -import org.junit.Test; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -public class TestPciChangesFromPolicyToSDNRDmaapConsumer { - private static final String pciChangesFromPolicyToSDNRInput = "{\n" + - " \"body\": {\n" + - " \"input\": {\n" + - " \"CommonHeader\": {\n" + - " \"TimeStamp\": \"2018-11-30T09:13:37.368Z\",\n" + - " \"APIVer\": \"1.0\",\n" + - " \"RequestID\": \"9d2d790e-a5f0-11e8-98d0-529269fb1459\",\n" + - " \"SubRequestID\": \"1\",\n" + - " \"RequestTrack\": {},\n" + - " \"Flags\": {}\n" + - " },\n" + - " \"Action\": \"ModifyConfig\",\n" + - " \"Payload\": \"{\\\"Configurations\\\":[{\\\"data\\\":{\\\"FAPService\\\":{\\\"alias\\\":\\\"Chn0330\\\",\\\"X0005b9Lte\\\":{\\\"phyCellIdInUse\\\":6,\\\"pnfName\\\":\\\"ncserver23\\\"},\\\"CellConfig\\\":{\\\"LTE\\\":{\\\"RAN\\\":{\\\"Common\\\":{\\\"CellIdentity\\\":\\\"Chn0330\\\"}}}}}}},{\\\"data\\\":{\\\"FAPService\\\":{\\\"alias\\\":\\\"Chn0331\\\",\\\"X0005b9Lte\\\":{\\\"phyCellIdInUse\\\":7,\\\"pnfName\\\":\\\"ncserver23\\\"},\\\"CellConfig\\\":{\\\"LTE\\\":{\\\"RAN\\\":{\\\"Common\\\":{\\\"CellIdentity\\\":\\\"Chn0331\\\"}}}}}}}]}\"\n" + - " }\n" + - " },\n" + - " \"version\": \"1.0\",\n" + - " \"rpc-name\": \"modifyconfig\",\n" + - " \"correlation-id\": \"9d2d790e-a5f0-11e8-98d0-529269fb1459-1\",\n" + - " \"type\": \"request\"\n" + - "}"; - - @Before - public void setUp() throws Exception { - } - - @Test - public void testRPCMessageBodyResponse() throws Exception { - Properties props = new Properties(); - - ObjectMapper oMapper = new ObjectMapper(); - JsonNode pciChangesRootNode = oMapper.readTree(pciChangesFromPolicyToSDNRInput); - JsonNode body = pciChangesRootNode.get("body"); - JsonNode input = body.get("input"); - JsonNode payload = input.get("Payload"); - String payloadText = payload.asText(); - JsonNode configurationsJsonNode = oMapper.readTree(payloadText); - - String rpcMsgbody = new PciChangesFromPolicyToSDNRDmaapConsumer(props).publish("src/main/resources/anr-pci-changes-from-policy-to-sdnr.vt", pciChangesFromPolicyToSDNRInput,configurationsJsonNode); - - JsonNode rootNode; - try { - rootNode = oMapper.readTree(rpcMsgbody); - } catch (Exception e) { - throw new InvalidMessageException("Cannot parse json object", e); - } - - assertTrue(rootNode.get("input").get("module-name") != null); - assertTrue(rootNode.get("input").get("rpc-name") != null); - assertTrue(rootNode.get("input").get("mode") != null); - assertTrue(rootNode.get("input").get("sli-parameter") != null); - - } - - @Test(expected = InvalidMessageException.class) - public void testProcessMsgNullMessage() throws Exception { - PciChangesFromPolicyToSDNRDmaapConsumer consumer = new PciChangesFromPolicyToSDNRDmaapConsumer(); - consumer.processMsg(null); - } - - @Test(expected = InvalidMessageException.class) - public void testProcessMsgInvalidMessage() throws Exception { - PciChangesFromPolicyToSDNRDmaapConsumer consumer = new PciChangesFromPolicyToSDNRDmaapConsumer(); - consumer.processMsg("test"); - } - - @Test - public void testProcessMsgMissingActionHeader() throws Exception { - PciChangesFromPolicyToSDNRDmaapConsumer consumer = new PciChangesFromPolicyToSDNRDmaapConsumer(); - consumer.processMsg("{\n" + - " \"body\": {\n" + - " \"input\": {\n" + - " \"CommonHeader\": {\n" + - " \"TimeStamp\": \"2018-11-30T09:13:37.368Z\",\n" + - " \"APIVer\": \"1.0\",\n" + - " \"RequestID\": \"9d2d790e-a5f0-11e8-98d0-529269fb1459\",\n" + - " \"SubRequestID\": \"1\",\n" + - " \"RequestTrack\": {},\n" + - " \"Flags\": {}\n" + - " },\n" + - " \"RenamedAction\": \"ModifyConfig\",\n" + - " \"Payload\": {\n" + - " \"Configurations \": {\n" + - " \"data \": {\n" + - " \"FAPService \": {\n" + - " \"alias\": \"Chn0330\",\n" + - " \"X0005b9Lte\": {\n" + - " \"phyCellIdInUse\": 6,\n" + - " \"pnfName\": \"ncserver23\"\n" + - " },\n" + - " \"CellConfig\": {\n" + - " \"LTE\": {\n" + - " \"RAN\": {\n" + - " \"Common\": {\n" + - " \"CellIdentity\": \"Chn0330\"\n" + - " }\n" + - " }\n" + - " }\n" + - " }\n" + - " }\n" + - " }\n" + - " }\n" + - "\n" + - " }\n" + - " }\n" + - " },\n" + - " \"version\": \"1.0\",\n" + - " \"rpc-name\": \"modifyconfig\",\n" + - " \"correlation-id\": \"9d2d790e-a5f0-11e8-98d0-529269fb1459-1\",\n" + - " \"type\": \"request\"\n" + - "}"); - } - - @Test - public void testProcessMsgInvalidPayloadConfigurations() throws Exception { - String msg = "{\n" + - " \"body\": {\n" + - " \"input\": {\n" + - " \"CommonHeader\": {\n" + - " \"TimeStamp\": \"2018-11-30T09:13:37.368Z\",\n" + - " \"APIVer\": \"1.0\",\n" + - " \"RequestID\": \"9d2d790e-a5f0-11e8-98d0-529269fb1459\",\n" + - " \"SubRequestID\": \"1\",\n" + - " \"RequestTrack\": {},\n" + - " \"Flags\": {}\n" + - " },\n" + - " \"Action\": \"ModifyConfig\",\n" + - " \"Payload\": {\n" + - " \"Configurations \": {\n" + - " \"data \": {\n" + - " \"FAPService \": {\n" + - " \"alias\": \"Chn0330\",\n" + - " \"X0005b9Lte\": {\n" + - " \"phyCellIdInUse\": 6,\n" + - " \"pnfName\": \"ncserver23\"\n" + - " },\n" + - " \"CellConfig\": {\n" + - " \"LTE\": {\n" + - " \"RAN\": {\n" + - " \"Common\": {\n" + - " \"CellIdentity\": \"Chn0330\"\n" + - " }\n" + - " }\n" + - " }\n" + - " }\n" + - " }\n" + - " }\n" + - " }\n" + - "\n" + - " }\n" + - " }\n" + - " },\n" + - " \"version\": \"1.0\",\n" + - " \"rpc-name\": \"modifyconfig\",\n" + - " \"correlation-id\": \"9d2d790e-a5f0-11e8-98d0-529269fb1459-1\",\n" + - " \"type\": \"request\"\n" + - "}"; - - try { - PciChangesFromPolicyToSDNRDmaapConsumer consumer = new PciChangesFromPolicyToSDNRDmaapConsumer(); - consumer.processMsg(msg); - - } catch (final InvalidMessageException e) { - final String errorMsg = "Configurations is not of Type Array. Could not read configuration changes"; - assertEquals(errorMsg, e.getMessage()); - } - } -} -- cgit 1.2.3-korg From 9b5c8a76bf6a75d5d82df56a1db0a09651596f82 Mon Sep 17 00:00:00 2001 From: Sandeep Shah Date: Thu, 13 Jun 2019 05:50:38 -0500 Subject: Bug fixes/mods to dmaap-listener for SDNR OOF PCI Bug fixes to support payload with escape characters and modifications to velocity template map files to point to correct SDNC end point Issue-ID: CCSDK-1399 Signed-off-by: SandeepLinux Change-Id: I38a0a3f19379ea20b7055e9581318f54b93dca6d --- .../dmaapclient/OofPciPocDmaapConsumers.java | 21 ++++++++++++--------- .../resources/anr-changes-from-policy-to-sdnr.map | 4 ++-- .../resources/pci-changes-from-policy-to-sdnr.map | 4 ++-- 3 files changed, 16 insertions(+), 13 deletions(-) (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/OofPciPocDmaapConsumers.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/OofPciPocDmaapConsumers.java index 2e6ae742b..7037d8848 100644 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/OofPciPocDmaapConsumers.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/OofPciPocDmaapConsumers.java @@ -65,6 +65,9 @@ public class OofPciPocDmaapConsumers extends SdncDmaapConsumerImpl { private static final String BODY = "body"; private static final String INPUT = "input"; + private static final String EMPTY = ""; + private static final String ESCAPE_SEQUENCE_QUOTES = "\""; + private static final String GENERIC_NEIGHBOR_CONFIGURATION_INPUT = "generic-neighbor-configuration-input."; private static final String GENERIC_NEIGHBOR_CONFIGURATION_INPUT_NEIGHBOR_LIST_IN_USE = GENERIC_NEIGHBOR_CONFIGURATION_INPUT.concat("neighbor-list-in-use"); private static final String MODIFY_CONFIG_ANR = "ModifyConfigANR"; @@ -162,15 +165,15 @@ public class OofPciPocDmaapConsumers extends SdncDmaapConsumerImpl { if(nbrListInUse.isArray()) { for(JsonNode lteCell:nbrListInUse) { sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, GENERIC_NEIGHBOR_CONFIGURATION_INPUT_NEIGHBOR_LIST_IN_USE+"["+entryCount+"]."+"plmnid") - .put(STRING_VALUE, lteCell.get("PLMNID"))); + .put(STRING_VALUE, lteCell.get("PLMNID").toString().replace(ESCAPE_SEQUENCE_QUOTES, EMPTY))); sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, GENERIC_NEIGHBOR_CONFIGURATION_INPUT_NEIGHBOR_LIST_IN_USE+"["+entryCount+"]."+"cid") - .put(STRING_VALUE, lteCell.get("CID"))); + .put(STRING_VALUE, lteCell.get("CID").toString().replace(ESCAPE_SEQUENCE_QUOTES, EMPTY))); sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, GENERIC_NEIGHBOR_CONFIGURATION_INPUT_NEIGHBOR_LIST_IN_USE+"["+entryCount+"]."+"phy-cell-id") - .put(STRING_VALUE, lteCell.get("PhyCellID"))); + .put(STRING_VALUE, lteCell.get("PhyCellID").toString().replace(ESCAPE_SEQUENCE_QUOTES, EMPTY))); sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, GENERIC_NEIGHBOR_CONFIGURATION_INPUT_NEIGHBOR_LIST_IN_USE+"["+entryCount+"]."+"pnf-name") - .put(STRING_VALUE, lteCell.get("PNFName"))); + .put(STRING_VALUE, lteCell.get("PNFName").toString().replace(ESCAPE_SEQUENCE_QUOTES, EMPTY))); sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, GENERIC_NEIGHBOR_CONFIGURATION_INPUT_NEIGHBOR_LIST_IN_USE+"["+entryCount+"]."+"blacklisted") - .put(STRING_VALUE, lteCell.get("Blacklisted"))); + .put(STRING_VALUE, lteCell.get("Blacklisted").toString().replace(ESCAPE_SEQUENCE_QUOTES, EMPTY))); entryCount++; } @@ -219,13 +222,13 @@ public class OofPciPocDmaapConsumers extends SdncDmaapConsumerImpl { if(configurations.isArray()) { for(JsonNode dataNode:configurations) { sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, PHYSICAL_CELL_ID_INPUT_FAP_SERVICE+"["+entryCount+"]."+ALIAS) - .put(STRING_VALUE, dataNode.get(DATA).get(FAP_SERVICE).get(ALIAS))); + .put(STRING_VALUE, dataNode.get(DATA).get(FAP_SERVICE).get(ALIAS).toString().replace(ESCAPE_SEQUENCE_QUOTES, EMPTY))); sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, PHYSICAL_CELL_ID_INPUT_FAP_SERVICE+"["+entryCount+"]."+"cid") - .put(STRING_VALUE, dataNode.get(DATA).get(FAP_SERVICE).get("CellConfig").get("LTE").get("RAN").get("Common").get("CellIdentity"))); + .put(STRING_VALUE, dataNode.get(DATA).get(FAP_SERVICE).get("CellConfig").get("LTE").get("RAN").get("Common").get("CellIdentity").toString().replace(ESCAPE_SEQUENCE_QUOTES, EMPTY))); sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, PHYSICAL_CELL_ID_INPUT_FAP_SERVICE+"["+entryCount+"]."+"phy-cell-id-in-use") - .put(STRING_VALUE, dataNode.get(DATA).get(FAP_SERVICE).get(X0005b9Lte).get("phyCellIdInUse"))); + .put(STRING_VALUE, dataNode.get(DATA).get(FAP_SERVICE).get(X0005b9Lte).get("phyCellIdInUse").toString().replace(ESCAPE_SEQUENCE_QUOTES, EMPTY))); sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, PHYSICAL_CELL_ID_INPUT_FAP_SERVICE+"["+entryCount+"]."+"pnf-name") - .put(STRING_VALUE, dataNode.get(DATA).get(FAP_SERVICE).get(X0005b9Lte).get("pnfName"))); + .put(STRING_VALUE, dataNode.get(DATA).get(FAP_SERVICE).get(X0005b9Lte).get("pnfName").toString().replace(ESCAPE_SEQUENCE_QUOTES, EMPTY))); entryCount++; } diff --git a/dmaap-listener/src/main/resources/anr-changes-from-policy-to-sdnr.map b/dmaap-listener/src/main/resources/anr-changes-from-policy-to-sdnr.map index e7c45b253..5cd2b8371 100644 --- a/dmaap-listener/src/main/resources/anr-changes-from-policy-to-sdnr.map +++ b/dmaap-listener/src/main/resources/anr-changes-from-policy-to-sdnr.map @@ -1,5 +1,5 @@ # SDN-C URL -SDNC.endpoint => oofpcipoc-api:generic-neighbour-configuration +SDNC.endpoint => SLI-API:execute-graph -# Field mapping +# Field mapping SDNC.template => anr-pci-changes-from-policy-to-sdnr.vt diff --git a/dmaap-listener/src/main/resources/pci-changes-from-policy-to-sdnr.map b/dmaap-listener/src/main/resources/pci-changes-from-policy-to-sdnr.map index 44c34a4d4..5cd2b8371 100644 --- a/dmaap-listener/src/main/resources/pci-changes-from-policy-to-sdnr.map +++ b/dmaap-listener/src/main/resources/pci-changes-from-policy-to-sdnr.map @@ -1,5 +1,5 @@ # SDN-C URL -SDNC.endpoint => oofpcipoc-api:configuration-phy-cell-id +SDNC.endpoint => SLI-API:execute-graph -# Field mapping +# Field mapping SDNC.template => anr-pci-changes-from-policy-to-sdnr.vt -- cgit 1.2.3-korg From 47a2c99bdeeefd34172d2b4a2cb7170b1c81bd67 Mon Sep 17 00:00:00 2001 From: Sandeep Shah Date: Thu, 1 Aug 2019 09:13:34 -0500 Subject: OOFPCIPPOC DMAAP listener bug fix DMAAP listener code change to refer to the correct YANG RPC leaf node Issue-ID: CCSDK-1565 Signed-off-by: SandeepLinux Change-Id: Id8afb807bf281125e522f86079a877184271ca51 --- .../dmaapclient/OofPciPocDmaapConsumers.java | 108 ++++++++++----------- 1 file changed, 54 insertions(+), 54 deletions(-) (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/OofPciPocDmaapConsumers.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/OofPciPocDmaapConsumers.java index 7037d8848..9d78e8acf 100644 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/OofPciPocDmaapConsumers.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/OofPciPocDmaapConsumers.java @@ -57,17 +57,17 @@ public class OofPciPocDmaapConsumers extends SdncDmaapConsumerImpl { private static final String MODIFY_CONFIG = "ModifyConfig"; private static final String DATA = "data"; private static final String FAP_SERVICE = "FAPService"; - + private static final String PAYLOAD = "Payload"; private static final String PCI_CHANGES_MAP_FILE_NAME = "pci-changes-from-policy-to-sdnr"; private static final String SLI_PARAMETERS = "sli_parameters"; private static final String RPC_NAME = "rpc-name"; private static final String BODY = "body"; private static final String INPUT = "input"; - + private static final String EMPTY = ""; private static final String ESCAPE_SEQUENCE_QUOTES = "\""; - + private static final String GENERIC_NEIGHBOR_CONFIGURATION_INPUT = "generic-neighbor-configuration-input."; private static final String GENERIC_NEIGHBOR_CONFIGURATION_INPUT_NEIGHBOR_LIST_IN_USE = GENERIC_NEIGHBOR_CONFIGURATION_INPUT.concat("neighbor-list-in-use"); private static final String MODIFY_CONFIG_ANR = "ModifyConfigANR"; @@ -137,31 +137,31 @@ public class OofPciPocDmaapConsumers extends SdncDmaapConsumerImpl { return writer.toString(); } - + private String publishANRChangesFromPolicyToSDNR(String templatePath, JsonNode dataNode) throws IOException, InvalidMessageException { VelocityContext context = new VelocityContext(); - + String RPC_NAME_KEY_IN_VT = "rpc_name"; String RPC_NAME_VALUE_IN_VT = "generic-neighbor-configuration"; - + String CELL_CONFIG = "CellConfig"; String ALIAS_LABEL = "alias"; String LTE = "LTE"; String RAN = "RAN"; String LTE_CELL = "LTECell"; String NEIGHBOR_LIST_IN_USE = "NeighborListInUse"; - + JSONObject numberOfEntries = new JSONObject(); JSONObject alias = new JSONObject(); JSONArray sliParametersArray = new JSONArray(); - + String aliasValue = dataNode.get(DATA).get(FAP_SERVICE).get(ALIAS_LABEL).textValue(); - + JsonNode nbrListInUse = dataNode.get(DATA).get(FAP_SERVICE).get(CELL_CONFIG).get(LTE).get(RAN).get(NEIGHBOR_LIST_IN_USE).get(LTE_CELL); - + int entryCount = 0; - + if(nbrListInUse.isArray()) { for(JsonNode lteCell:nbrListInUse) { sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, GENERIC_NEIGHBOR_CONFIGURATION_INPUT_NEIGHBOR_LIST_IN_USE+"["+entryCount+"]."+"plmnid") @@ -174,21 +174,21 @@ public class OofPciPocDmaapConsumers extends SdncDmaapConsumerImpl { .put(STRING_VALUE, lteCell.get("PNFName").toString().replace(ESCAPE_SEQUENCE_QUOTES, EMPTY))); sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, GENERIC_NEIGHBOR_CONFIGURATION_INPUT_NEIGHBOR_LIST_IN_USE+"["+entryCount+"]."+"blacklisted") .put(STRING_VALUE, lteCell.get("Blacklisted").toString().replace(ESCAPE_SEQUENCE_QUOTES, EMPTY))); - + entryCount++; } - + alias.put(PARAMETER_NAME, GENERIC_NEIGHBOR_CONFIGURATION_INPUT+ALIAS_LABEL); alias.put(STRING_VALUE, aliasValue); - - numberOfEntries.put(PARAMETER_NAME, GENERIC_NEIGHBOR_CONFIGURATION_INPUT+"number-of-neighbor-cell-entries"); + + numberOfEntries.put(PARAMETER_NAME, GENERIC_NEIGHBOR_CONFIGURATION_INPUT+"lte-cell-number-of-entries"); numberOfEntries.put(STRING_VALUE, entryCount); - + sliParametersArray.put(alias); sliParametersArray.put(numberOfEntries); - + context.put(SLI_PARAMETERS, sliParametersArray); - + context.put(RPC_NAME_KEY_IN_VT, RPC_NAME_VALUE_IN_VT); Writer writer = new StringWriter(); @@ -196,29 +196,29 @@ public class OofPciPocDmaapConsumers extends SdncDmaapConsumerImpl { writer.flush(); return writer.toString(); - + }else { throw new InvalidMessageException("nbrListInUse is not of Type Array. Could not read neighbor list elements"); } - + } - + private String publishPciChangesFromPolicyToSDNR(String templatePath, JsonNode configurationsJsonNode) throws IOException, InvalidMessageException { String RPC_NAME_KEY_IN_VT = "rpc_name"; String RPC_NAME_VALUE_IN_VT = "configuration-phy-cell-id"; String ALIAS = "alias"; String X0005b9Lte = "X0005b9Lte"; - + VelocityContext context = new VelocityContext(); - + JSONObject numberOfEntries = new JSONObject(); JSONArray sliParametersArray = new JSONArray(); - + JsonNode configurations = configurationsJsonNode.get(CONFIGURATIONS); - + int entryCount = 0; - + if(configurations.isArray()) { for(JsonNode dataNode:configurations) { sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, PHYSICAL_CELL_ID_INPUT_FAP_SERVICE+"["+entryCount+"]."+ALIAS) @@ -231,14 +231,14 @@ public class OofPciPocDmaapConsumers extends SdncDmaapConsumerImpl { .put(STRING_VALUE, dataNode.get(DATA).get(FAP_SERVICE).get(X0005b9Lte).get("pnfName").toString().replace(ESCAPE_SEQUENCE_QUOTES, EMPTY))); entryCount++; } - + numberOfEntries.put(PARAMETER_NAME, PHYSICAL_CELL_ID_INPUT_FAP_SERVICE+"-number-of-entries"); numberOfEntries.put(STRING_VALUE, entryCount); - + sliParametersArray.put(numberOfEntries); - + context.put(SLI_PARAMETERS, sliParametersArray); - + context.put(RPC_NAME_KEY_IN_VT, RPC_NAME_VALUE_IN_VT); Writer writer = new StringWriter(); @@ -246,11 +246,11 @@ public class OofPciPocDmaapConsumers extends SdncDmaapConsumerImpl { writer.flush(); return writer.toString(); - + }else { throw new InvalidMessageException("Configurations is not of Type Array. Could not read configuration changes"); } - + } @Override @@ -267,31 +267,31 @@ public class OofPciPocDmaapConsumers extends SdncDmaapConsumerImpl { } catch (Exception e) { throw new InvalidMessageException("Cannot parse json object", e); } - + JsonNode rpcnameNode = dmaapMessageRootNode.get(RPC_NAME); if(rpcnameNode == null) { LOG.info("Unable to identify the respective consumer to invoke. Please verify the dmaap message.."); return; } - + String rpcname = rpcnameNode.textValue(); - + if(!MODIFY_CONFIG.toLowerCase().equals(rpcname) && !MODIFY_CONFIG_ANR.toLowerCase().equals(rpcname)) { LOG.info("Unknown rpc name {}", rpcname); return; } - + if(MODIFY_CONFIG.toLowerCase().equals(rpcname)) { invokePCIChangesConsumer(dmaapMessageRootNode, oMapper, msg); return; } - + if(MODIFY_CONFIG_ANR.toLowerCase().equals(rpcname)) { invokeANRChangesConsumer(dmaapMessageRootNode, oMapper, msg); return; } - + } private void invokeANRChangesConsumer(JsonNode dmaapMessageRootNode, ObjectMapper oMapper, @@ -301,24 +301,24 @@ public class OofPciPocDmaapConsumers extends SdncDmaapConsumerImpl { LOG.info("Missing body node."); return; } - + JsonNode input = body.get(INPUT); if(input == null) { LOG.info("Missing input node."); return; } - + JsonNode action = input.get(ACTION); if(action == null) { LOG.info("Missing action node."); return; } - + if(!MODIFY_CONFIG_ANR.equals(action.textValue())) { LOG.info("Unknown Action {}", action); return; } - + JsonNode payload = input.get(PAYLOAD); if(payload == null) { LOG.info("Missing payload node."); @@ -326,12 +326,12 @@ public class OofPciPocDmaapConsumers extends SdncDmaapConsumerImpl { } String payloadText = payload.asText(); - + if(!payloadText.contains(CONFIGURATIONS)) { LOG.info("Missing configurations node."); return; } - + JsonNode configurationsJsonNode; try { configurationsJsonNode = oMapper.readTree(payloadText); @@ -354,9 +354,9 @@ public class OofPciPocDmaapConsumers extends SdncDmaapConsumerImpl { throw new InvalidMessageException("No SDNC template known for message "); } String templateName = fieldMap.get(TEMPLATE); - + JsonNode configurations = configurationsJsonNode.get(CONFIGURATIONS); - + if(configurations.isArray()) { for(JsonNode dataNode:configurations) { if(dataNode.get(DATA).get(FAP_SERVICE) == null) { @@ -377,24 +377,24 @@ public class OofPciPocDmaapConsumers extends SdncDmaapConsumerImpl { LOG.info("Missing body node."); return; } - + JsonNode input = body.get(INPUT); if(input == null) { LOG.info("Missing input node."); return; } - + JsonNode action = input.get(ACTION); if(action == null) { LOG.info("Missing action node."); return; } - + if(!MODIFY_CONFIG.equals(action.textValue())) { LOG.info("Unknown Action {}", action); return; } - + JsonNode payload = input.get(PAYLOAD); if(payload == null) { LOG.info("Missing payload node."); @@ -402,12 +402,12 @@ public class OofPciPocDmaapConsumers extends SdncDmaapConsumerImpl { } String configurations = payload.asText(); - + if(!configurations.contains(CONFIGURATIONS)) { LOG.info("Missing configurations node."); return; } - + JsonNode configurationsJsonNode; try { configurationsJsonNode = oMapper.readTree(configurations); @@ -430,7 +430,7 @@ public class OofPciPocDmaapConsumers extends SdncDmaapConsumerImpl { throw new InvalidMessageException("No SDNC template known for message "); } String templateName = fieldMap.get(TEMPLATE); - + buildAndInvokePCIChangesRPC(sdncEndpoint, templateName, msg, configurationsJsonNode); } @@ -452,7 +452,7 @@ public class OofPciPocDmaapConsumers extends SdncDmaapConsumerImpl { LOG.error("Unable to process message", e); } } - + private void buildAndInvokeANRChangesRPC(String sdncEndpoint, String templateName, String msg, JsonNode configurationsOrDataNode) { try { String rpcMsgbody = publish(templateName, msg, configurationsOrDataNode, false, true); -- cgit 1.2.3-korg From 4852d3577447aa8790b63442b6d5c48412e2eb21 Mon Sep 17 00:00:00 2001 From: Sandeep Shah Date: Mon, 19 Aug 2019 21:40:44 -0500 Subject: Bug fix to address DMAAPLISTENERROOT Modified rootDir to /opt/onap/sdnc/...where map and vt template files are transferred in the docker Issue-ID: CCSDK-1400 Signed-off-by: SandeepLinux Change-Id: Ie634ff60cf439be5f5136275f2ea19abf40949de --- .../onap/ccsdk/sli/northbound/dmaapclient/OofPciPocDmaapConsumers.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/OofPciPocDmaapConsumers.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/OofPciPocDmaapConsumers.java index 9d78e8acf..e8dacb959 100644 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/OofPciPocDmaapConsumers.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/OofPciPocDmaapConsumers.java @@ -83,7 +83,7 @@ public class OofPciPocDmaapConsumers extends SdncDmaapConsumerImpl { rootDir = System.getenv(DMAAPLISTENERROOT); if ((rootDir == null) || (rootDir.length() == 0)) { - rootDir = "/opt/app/dmaap-listener/lib/"; + rootDir = "/opt/onap/sdnc/dmaap-listener/lib/"; } else { rootDir = rootDir + "/lib/"; -- cgit 1.2.3-korg From fc2a8c873189ee8d46e5973176777a4dad1e353f Mon Sep 17 00:00:00 2001 From: Sandeep Shah Date: Fri, 22 Nov 2019 11:14:57 -0600 Subject: DMAAP Listener for ORAN A1 Adapter Policy Mgmt Support DMAAP listener for A1 Adapter related DMAAP messages for policy management. Also included are JUNIT test files. DMAAP topic is A1-P. Issue-ID: CCSDK-1964 Signed-off-by: SandeepLinux Change-Id: Ied78e8c14538136fede0f420804232770bcbdf3b --- .../dmaapclient/A1AdapterPolicyDmaapConsumer.java | 92 ++++++++++++++ .../TestA1AdapterPolicyDmaapConsumer.java | 136 +++++++++++++++++++++ .../dmaap-consumer-a1Adapter-policy-1.properties | 35 ++++++ 3 files changed, 263 insertions(+) create mode 100644 dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/A1AdapterPolicyDmaapConsumer.java create mode 100644 dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestA1AdapterPolicyDmaapConsumer.java create mode 100644 dmaap-listener/src/test/resources/dmaap-consumer-a1Adapter-policy-1.properties (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/A1AdapterPolicyDmaapConsumer.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/A1AdapterPolicyDmaapConsumer.java new file mode 100644 index 000000000..778a77b80 --- /dev/null +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/A1AdapterPolicyDmaapConsumer.java @@ -0,0 +1,92 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * Modifications Copyright © 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.northbound.dmaapclient; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class A1AdapterPolicyDmaapConsumer extends SdncDmaapConsumerImpl { + + private static final Logger LOG = LoggerFactory.getLogger(A1AdapterPolicyDmaapConsumer.class); + + private static final String BODY = "body"; + private static final String RPC = "rpc-name"; + + @Override + public void processMsg(String msg) throws InvalidMessageException { + + if (msg == null) { + throw new InvalidMessageException("Null A1-ADAPTER-DMAAP message"); + } + + ObjectMapper oMapper = new ObjectMapper(); + JsonNode a1AdapterRootNode; + try { + a1AdapterRootNode = oMapper.readTree(msg); + } catch (Exception e) { + throw new InvalidMessageException("Cannot parse A1-ADAPTER-DMAAP json input", e); + } + + JsonNode bodyNode = a1AdapterRootNode.get(BODY); + if(bodyNode == null) { + LOG.warn("Missing body in A1-ADAPTER-DMAAP message"); + return; + } + String rpcMsgbody; + try { + ObjectMapper mapper = new ObjectMapper(); + rpcMsgbody = mapper.writeValueAsString(bodyNode); + + } catch (Exception e) { + LOG.error("Unable to parse body in A1-ADAPTER-DMAAP message", e); + return; + } + + JsonNode rpcNode = a1AdapterRootNode.get(RPC); + if(rpcNode == null) { + LOG.warn("Missing node in A1-ADAPTER-DMAAP message- " + RPC); + return; + } + String rpc = rpcNode.textValue(); + String sdncEndpoint = "A1-ADAPTER-API:" + rpc; + + try { + String odlUrlBase = getProperty("sdnc.odl.url-base"); + String odlUser = getProperty("sdnc.odl.user"); + String odlPassword = getProperty("sdnc.odl.password"); + LOG.info("POST A1-ADAPTER-API Request " + rpcMsgbody); + if ((odlUrlBase != null) && (odlUrlBase.length() > 0)) { + SdncOdlConnection conn = SdncOdlConnection.newInstance(odlUrlBase + "/" + sdncEndpoint, odlUser, odlPassword); + + conn.send("POST", "application/json", rpcMsgbody); + } else { + LOG.warn("Unable to POST A1-ADAPTER-API message. SDNC URL not available. body:\n" + rpcMsgbody); + } + } catch (Exception e) { + LOG.error("Unable to process message", e); + } + } +} diff --git a/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestA1AdapterPolicyDmaapConsumer.java b/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestA1AdapterPolicyDmaapConsumer.java new file mode 100644 index 000000000..8b7044f69 --- /dev/null +++ b/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestA1AdapterPolicyDmaapConsumer.java @@ -0,0 +1,136 @@ +/* + * Copyright (c) 2017. Lorem ipsum dolor sit amet, consectetur adipiscing elit. + * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan. + * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna. + * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus. + * Vestibulum commodo. Ut rhoncus gravida arcu. + */ + +package org.onap.ccsdk.sli.northbound.dmaapclient; + +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Field; +import java.util.Map; +import java.util.Properties; + +import org.apache.commons.io.FileUtils; + +import org.junit.Before; +import org.junit.Test; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class TestA1AdapterPolicyDmaapConsumer { + private static final String a1AdapterInput = "{\n" + + " \"body\": {\n" + + " \"input\": {\n" + + " \"CommonHeader\": {\n" + + " \"TimeStamp\": \"2018-11-30T09:13:37.368Z\",\n" + + " \"APIver\": \"1.0\",\n" + + " \"RequestID\": \"9d2d790e-a5f0-11e8-98d0-529269fb1459\",\n" + + " \"SubRequestID\": \"1\",\n" + + " \"RequestTrack\": {},\n" + + " \"Flags\": {}\n },\n" + + " \"Action\": \"getHealthCheck\",\n" + + " \"Payload\": {\n" + + " \"near-rt-ric-id\": \"near-RT-ric1\",\n" + + " \"policy-type-id\": \"20000\",\n" + + " \"description\": \"parameters to control policy \",\n" + + " \"name\": \"admission_control_policy\",\n" + + " \"policy-type\": \"object\"\n" + + " }\n" + + " },\n" + + " \"version\": \"1.0\",\n" + + " \"rpc-name\": \"getHealthCheck\",\n" + + " \"correlation-id\": \"9d2d790e-a5f0-11e8-98d0-529269fb1459-1\",\n" + + " \"type\": \"request\"\n" + + " }\n" + + "}"; + + @Test + public void test() throws Exception { + Properties props = new Properties(); + + A1AdapterPolicyDmaapConsumer consumer = new A1AdapterPolicyDmaapConsumer(); + InputStream propStr = TestA1AdapterPolicyDmaapConsumer.class.getResourceAsStream("/dmaap-consumer-a1Adapter-policy-1.properties"); + props.load(propStr); + consumer.init(props, "src/test/resources/dmaap-consumer-1.properties"); + consumer.processMsg(a1AdapterInput); + } + + @Test(expected = InvalidMessageException.class) + public void testProcessMsgNullMessage() throws Exception { + A1AdapterPolicyDmaapConsumer consumer = new A1AdapterPolicyDmaapConsumer(); + consumer.processMsg(null); + } + + @Test + public void testProcessMsgMissingBody() throws Exception { + String msg = "{\n" + + " \"body1\": {\n" + + " \"input\": {\n" + + " \"CommonHeader\": {\n" + + " \"TimeStamp\": \"2018-11-30T09:13:37.368Z\",\n" + + " \"APIver\": \"1.0\",\n" + + " \"RequestID\": \"9d2d790e-a5f0-11e8-98d0-529269fb1459\",\n" + + " \"SubRequestID\": \"1\",\n" + + " \"RequestTrack\": {},\n" + + " \"Flags\": {}\n },\n" + + " \"Action\": \"getHealthCheck\",\n" + + " \"Payload\": {\n" + + " \"near-rt-ric-id\": \"near-RT-ric1\",\n" + + " \"policy-type-id\": \"20000\",\n" + + " \"description\": \"parameters to control policy \",\n" + + " \"name\": \"admission_control_policy\",\n" + + " \"policy-type\": \"object\"\n" + + " }\n" + + " },\n" + + " \"version\": \"1.0\",\n" + + " \"rpc-name\": \"getHealthCheck\",\n" + + " \"correlation-id\": \"9d2d790e-a5f0-11e8-98d0-529269fb1459-1\",\n" + + " \"type\": \"request\"\n" + + " }\n" + + "}"; + + A1AdapterPolicyDmaapConsumer consumer = new A1AdapterPolicyDmaapConsumer(); + consumer.processMsg(msg); + } + + @Test + public void testProcessMsgInvalidRPC() throws Exception { + String msg = "{\n" + + " \"body\": {\n" + + " \"input\": {\n" + + " \"CommonHeader\": {\n" + + " \"TimeStamp\": \"2018-11-30T09:13:37.368Z\",\n" + + " \"APIver\": \"1.0\",\n" + + " \"RequestID\": \"9d2d790e-a5f0-11e8-98d0-529269fb1459\",\n" + + " \"SubRequestID\": \"1\",\n" + + " \"RequestTrack\": {},\n" + + " \"Flags\": {}\n },\n" + + " \"Action\": \"getHealthCheck\",\n" + + " \"Payload\": {\n" + + " \"near-rt-ric-id\": \"near-RT-ric1\",\n" + + " \"policy-type-id\": \"20000\",\n" + + " \"description\": \"parameters to control policy \",\n" + + " \"name\": \"admission_control_policy\",\n" + + " \"policy-type\": \"object\"\n" + + " }\n" + + " },\n" + + " \"version\": \"1.0\",\n" + + " \"rpc-name1\": \"getHealthCheck\",\n" + + " \"correlation-id\": \"9d2d790e-a5f0-11e8-98d0-529269fb1459-1\",\n" + + " \"type\": \"request\"\n" + + " }\n" + + "}"; + + A1AdapterPolicyDmaapConsumer consumer = new A1AdapterPolicyDmaapConsumer(); + consumer.processMsg(msg); + } + +} diff --git a/dmaap-listener/src/test/resources/dmaap-consumer-a1Adapter-policy-1.properties b/dmaap-listener/src/test/resources/dmaap-consumer-a1Adapter-policy-1.properties new file mode 100644 index 000000000..edb7c453e --- /dev/null +++ b/dmaap-listener/src/test/resources/dmaap-consumer-a1Adapter-policy-1.properties @@ -0,0 +1,35 @@ +TransportType=HTTPNOAUTH +Latitude =50.000000 +Longitude =-100.000000 +Version =1.0 +ServiceName =message-router.onap:3904/events +Environment =TEST +Partner = +routeOffer=MR1 +SubContextPath =/ +Protocol =http +MethodType =GET +username =admin +password =admin +contenttype =application/json +authKey=fs20cKwalJ6ry4kX:7Hqm6BDZK47IKxGRkOPFk33qMYs= +authDate=2019-04-09T04:28:40-05:00 +host=message-router.onap:3904 +topic=A1-P +group=users +id=sdnc1 +timeout=15000 +limit=1000 +filter= +AFT_DME2_EXCHANGE_REQUEST_HANDLERS=com.att.nsa.test.PreferredRouteRequestHandler +AFT_DME2_EXCHANGE_REPLY_HANDLERS=com.att.nsa.test.PreferredRouteReplyHandler +AFT_DME2_REQ_TRACE_ON=true +AFT_ENVIRONMENT=AFTUAT +AFT_DME2_EP_CONN_TIMEOUT=15000 +AFT_DME2_ROUNDTRIP_TIMEOUT_MS=240000 +AFT_DME2_EP_READ_TIMEOUT_MS=50000 +sessionstickinessrequired=NO +DME2preferredRouterFilePath=/opt/onap/sdnc/data/properties/dmaap-listener.preferredRoute.txt +sdnc.odl.user=admin +sdnc.odl.password=Kp8bJ4SXszM0WXlhak3eHlcse2gAw84vaoGGmJvUy2U +sdnc.odl.url-base=http://sdnc.onap:8282/restconf/operations -- cgit 1.2.3-korg From fff922790262500c1cced5e674179bf8873acb83 Mon Sep 17 00:00:00 2001 From: Sandeep Shah Date: Tue, 17 Dec 2019 00:22:14 -0600 Subject: Bug fix in DMAAP listener for A1 Adapter Modification to use the payload node to be sent as an RPC message to stay in alignment with YANG model for A1 adapter Issue-ID: CCSDK-2001 Signed-off-by: SandeepLinux Change-Id: I023cf27ec9ac0305f1bc23bc9762603192c09e27 --- .../dmaapclient/A1AdapterPolicyDmaapConsumer.java | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/A1AdapterPolicyDmaapConsumer.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/A1AdapterPolicyDmaapConsumer.java index 778a77b80..dd59f5868 100644 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/A1AdapterPolicyDmaapConsumer.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/A1AdapterPolicyDmaapConsumer.java @@ -34,6 +34,9 @@ public class A1AdapterPolicyDmaapConsumer extends SdncDmaapConsumerImpl { private static final String BODY = "body"; private static final String RPC = "rpc-name"; + private static final String INPUT = "input"; + private static final String PAYLOAD = "Payload"; + @Override public void processMsg(String msg) throws InvalidMessageException { @@ -55,13 +58,26 @@ public class A1AdapterPolicyDmaapConsumer extends SdncDmaapConsumerImpl { LOG.warn("Missing body in A1-ADAPTER-DMAAP message"); return; } + + JsonNode input = bodyNode.get(INPUT); + if(input == null) { + LOG.info("Missing input node."); + return; + } + + JsonNode payloadNode = input.get(PAYLOAD); + if(payloadNode == null) { + LOG.info("Missing payload node."); + return; + } + String rpcMsgbody; try { ObjectMapper mapper = new ObjectMapper(); - rpcMsgbody = mapper.writeValueAsString(bodyNode); + rpcMsgbody = mapper.writeValueAsString(payloadNode); } catch (Exception e) { - LOG.error("Unable to parse body in A1-ADAPTER-DMAAP message", e); + LOG.error("Unable to parse payload in A1-ADAPTER-DMAAP message", e); return; } -- cgit 1.2.3-korg From 66ce8b86e11159bc833a64685333f7676055e38d Mon Sep 17 00:00:00 2001 From: Sandeep Shah Date: Tue, 3 Mar 2020 10:10:48 -0600 Subject: DMAAP Listener for ORAN CMNotify VES events DMAAP listener for VES events originating from ORAN. Will invoke RPC/DG for updating RuntimeDB Issue-ID: CCSDK-2133 Signed-off-by: SandeepLinux Change-Id: Ia17a7b2da1c58f5624c1d331aac56ce566d097bf --- .../dmaapclient/CMNotifyDmaapConsumer.java | 112 +++++++++++++++++ .../dmaapclient/TestCMNotifyDmaapConsumer.java | 140 +++++++++++++++++++++ .../resources/dmaap-consumer-cMNotify-1.properties | 35 ++++++ 3 files changed, 287 insertions(+) create mode 100644 dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/CMNotifyDmaapConsumer.java create mode 100644 dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestCMNotifyDmaapConsumer.java create mode 100644 dmaap-listener/src/test/resources/dmaap-consumer-cMNotify-1.properties (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/CMNotifyDmaapConsumer.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/CMNotifyDmaapConsumer.java new file mode 100644 index 000000000..e49e77ea8 --- /dev/null +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/CMNotifyDmaapConsumer.java @@ -0,0 +1,112 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * Modifications Copyright © 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.northbound.dmaapclient; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.json.JSONObject; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class CMNotifyDmaapConsumer extends SdncDmaapConsumerImpl { + + private static final Logger LOG = LoggerFactory.getLogger(CMNotifyDmaapConsumer.class); + + private static final String BODY = "body"; + private static final String RPC = "rpc-name"; + private static final String INPUT = "input"; + private static final String PAYLOAD = "Payload"; + + @Override + public void processMsg(String msg) throws InvalidMessageException { + + if (msg == null) { + throw new InvalidMessageException("Null CMNotify-DMAAP message"); + } + + ObjectMapper oMapper = new ObjectMapper(); + JsonNode CMNotifyRootNode; + try { + CMNotifyRootNode = oMapper.readTree(msg); + } catch (Exception e) { + throw new InvalidMessageException("Cannot parse CMNotify-DMAAP json input", e); + } + + JsonNode bodyNode = CMNotifyRootNode.get(BODY); + if(bodyNode == null) { + LOG.warn("Missing body in CMNotify-DMAAP message"); + return; + } + + JsonNode input = bodyNode.get(INPUT); + if(input == null) { + LOG.info("Missing input node."); + return; + } + + JsonNode payloadNode = input.get(PAYLOAD); + if(payloadNode == null) { + LOG.info("Missing payload node."); + return; + } + + JSONObject rpcMsgBodyNode = new JSONObject(); + + rpcMsgBodyNode.put(INPUT,payloadNode); + + String rpcMsgbody; + try { + ObjectMapper mapper = new ObjectMapper(); + rpcMsgbody = mapper.writeValueAsString(rpcMsgBodyNode); + + } catch (Exception e) { + LOG.error("Unable to parse payload in CMNotify-DMAAP message", e); + return; + } + + JsonNode rpcNode = CMNotifyRootNode.get(RPC); + if(rpcNode == null) { + LOG.warn("Missing node in CMNotify-DMAAP message- " + RPC); + return; + } + String rpc = rpcNode.textValue(); + String sdncEndpoint = "CM-NOTIFY-API:" + rpc; + + try { + String odlUrlBase = getProperty("sdnc.odl.url-base"); + String odlUser = getProperty("sdnc.odl.user"); + String odlPassword = getProperty("sdnc.odl.password"); + LOG.info("POST CM-NOTIFY-API Request " + rpcMsgbody); + if ((odlUrlBase != null) && (odlUrlBase.length() > 0)) { + SdncOdlConnection conn = SdncOdlConnection.newInstance(odlUrlBase + "/" + sdncEndpoint, odlUser, odlPassword); + + conn.send("POST", "application/json", rpcMsgbody); + } else { + LOG.warn("Unable to POST CM-NOTIFY-API message. SDNC URL not available. body:\n" + rpcMsgbody); + } + } catch (Exception e) { + LOG.error("Unable to process message", e); + } + } +} diff --git a/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestCMNotifyDmaapConsumer.java b/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestCMNotifyDmaapConsumer.java new file mode 100644 index 000000000..122a6d40b --- /dev/null +++ b/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestCMNotifyDmaapConsumer.java @@ -0,0 +1,140 @@ +/* + * Copyright (c) 2017. Lorem ipsum dolor sit amet, consectetur adipiscing elit. + * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan. + * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna. + * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus. + * Vestibulum commodo. Ut rhoncus gravida arcu. + */ + +package org.onap.ccsdk.sli.northbound.dmaapclient; + +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Field; +import java.util.Map; +import java.util.Properties; + +import org.apache.commons.io.FileUtils; + +import org.junit.Before; +import org.junit.Test; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + + +public class TestCMNotifyDmaapConsumer { + private static final String cMNotifyInput = "{\n" + + " \"body\": {\n" + + " \"input\": {\n" + + " \"CommonHeader\": {\n" + + " \"TimeStamp\": \"2018-11-30T09:13:37.368Z\",\n" + + " \"APIver\": \"1.0\",\n" + + " \"RequestID\": \"9d2d790e-a5f0-11e8-98d0-529269fb1459\",\n" + + " \"SubRequestID\": \"1\",\n" + + " \"RequestTrack\": {},\n" + + " \"Flags\": {}\n },\n" + + " \"Action\": \"nbrlist-change-notification\",\n" + + " \"Payload\": {\n" + + " \"fap-service-number-of-entries-changed\": 1,\n" + + " \"fap-service\": [{ \"alias\": \n" + + " \"Chn0001\", \"cid\": \"Chn0001\", \"lte-cell-number-of-entries\": 1,\n" + + " \"lte-ran-neighbor-list-in-use-lte-cell-changed\": \n" + + " [{ \"plmnid\": \"ran-1\", \"cid\": \"Chn0002\", \"phy-cell-id\": 4,\n" + + " \"pnf-name\": \"ncserver1\",\n" + + " \"blacklisted\": false }] }] }\n" + + " }\n" + + " },\n" + + " \"version\": \"1.0\",\n" + + " \"rpc-name\": \"nbrlist-change-notification\",\n" + + " \"correlation-id\": \"9d2d790e-a5f0-11e8-98d0-529269fb1459-1\",\n" + + " \"type\": \"request\"\n" + + "}"; + + + @Test + public void test() throws Exception { + Properties props = new Properties(); + + CMNotifyDmaapConsumer consumer = new CMNotifyDmaapConsumer(); + InputStream propStr = TestCMNotifyDmaapConsumer.class.getResourceAsStream("/dmaap-consumer-cMNotify-1.properties"); + props.load(propStr); + consumer.init(props, "src/test/resources/dmaap-consumer-1.properties"); + consumer.processMsg(cMNotifyInput); + } + + @Test(expected = InvalidMessageException.class) + public void testProcessMsgNullMessage() throws Exception { + CMNotifyDmaapConsumer consumer = new CMNotifyDmaapConsumer(); + consumer.processMsg(null); + } + + @Test + public void testProcessMsgMissingBody() throws Exception { + String msg = "{\n" + + " \"bodyTest\": {\n" + + " \"input\": {\n" + + " \"CommonHeader\": {\n" + + " \"TimeStamp\": \"2018-11-30T09:13:37.368Z\",\n" + + " \"APIver\": \"1.0\",\n" + + " \"RequestID\": \"9d2d790e-a5f0-11e8-98d0-529269fb1459\",\n" + + " \"SubRequestID\": \"1\",\n" + + " \"RequestTrack\": {},\n" + + " \"Flags\": {}\n },\n" + + " \"Action\": \"nbrlist-change-notification\",\n" + + " \"Payload\": {\n" + + " \"fap-service-number-of-entries-changed\": 1,\n" + + " \"fap-service\": [{ \"alias\": \n" + + " \"Chn0001\", \"cid\": \"Chn0001\", \"lte-cell-number-of-entries\": 1,\n" + + " \"lte-ran-neighbor-list-in-use-lte-cell-changed\": \n" + + " [{ \"plmnid\": \"ran-1\", \"cid\": \"Chn0002\", \"phy-cell-id\": 4,\n" + + " \"pnf-name\": \"ncserver1\",\n" + + " \"blacklisted\": false }] }] }\n" + + " }\n" + + " },\n" + + " \"version\": \"1.0\",\n" + + " \"rpc-name\": \"nbrlist-change-notification\",\n" + + " \"correlation-id\": \"9d2d790e-a5f0-11e8-98d0-529269fb1459-1\",\n" + + " \"type\": \"request\"\n" + + "}"; + CMNotifyDmaapConsumer consumer = new CMNotifyDmaapConsumer(); + consumer.processMsg(msg); + } + + @Test + public void testProcessMsgInvalidRPC() throws Exception { + String msg = "{\n" + + " \"body\": {\n" + + " \"input\": {\n" + + " \"CommonHeader\": {\n" + + " \"TimeStamp\": \"2018-11-30T09:13:37.368Z\",\n" + + " \"APIver\": \"1.0\",\n" + + " \"RequestID\": \"9d2d790e-a5f0-11e8-98d0-529269fb1459\",\n" + + " \"SubRequestID\": \"1\",\n" + + " \"RequestTrack\": {},\n" + + " \"Flags\": {}\n },\n" + + " \"Action\": \"nbrlist-change-notification\",\n" + + " \"Payload\": {\n" + + " \"fap-service-number-of-entries-changed\": 1,\n" + + " \"fap-service\": [{ \"alias\": \n" + + " \"Chn0001\", \"cid\": \"Chn0001\", \"lte-cell-number-of-entries\": 1,\n" + + " \"lte-ran-neighbor-list-in-use-lte-cell-changed\": \n" + + " [{ \"plmnid\": \"ran-1\", \"cid\": \"Chn0002\", \"phy-cell-id\": 4,\n" + + " \"pnf-name\": \"ncserver1\",\n" + + " \"blacklisted\": false }] }] }\n" + + " }\n" + + " },\n" + + " \"version\": \"1.0\",\n" + + " \"rpc-nameTest\": \"nbrlist-change-notification\",\n" + + " \"correlation-id\": \"9d2d790e-a5f0-11e8-98d0-529269fb1459-1\",\n" + + " \"type\": \"request\"\n" + + "}"; + + CMNotifyDmaapConsumer consumer = new CMNotifyDmaapConsumer(); + consumer.processMsg(msg); + } + +} diff --git a/dmaap-listener/src/test/resources/dmaap-consumer-cMNotify-1.properties b/dmaap-listener/src/test/resources/dmaap-consumer-cMNotify-1.properties new file mode 100644 index 000000000..aae34a26f --- /dev/null +++ b/dmaap-listener/src/test/resources/dmaap-consumer-cMNotify-1.properties @@ -0,0 +1,35 @@ +TransportType=HTTPNOAUTH +Latitude =50.000000 +Longitude =-100.000000 +Version =1.0 +ServiceName =message-router.onap:3904/events +Environment =TEST +Partner = +routeOffer=MR1 +SubContextPath =/ +Protocol =http +MethodType =GET +username =admin +password =admin +contenttype =application/json +authKey=fs20cKwalJ6ry4kX:7Hqm6BDZK47IKxGRkOPFk33qMYs= +authDate=2019-04-09T04:28:40-05:00 +host=message-router.onap:3904 +topic=CM-NOTIFICATION +group=users +id=sdnc1 +timeout=15000 +limit=1000 +filter= +AFT_DME2_EXCHANGE_REQUEST_HANDLERS=com.att.nsa.test.PreferredRouteRequestHandler +AFT_DME2_EXCHANGE_REPLY_HANDLERS=com.att.nsa.test.PreferredRouteReplyHandler +AFT_DME2_REQ_TRACE_ON=true +AFT_ENVIRONMENT=AFTUAT +AFT_DME2_EP_CONN_TIMEOUT=15000 +AFT_DME2_ROUNDTRIP_TIMEOUT_MS=240000 +AFT_DME2_EP_READ_TIMEOUT_MS=50000 +sessionstickinessrequired=NO +DME2preferredRouterFilePath=/opt/onap/sdnc/data/properties/dmaap-listener.preferredRoute.txt +sdnc.odl.user=admin +sdnc.odl.password=Kp8bJ4SXszM0WXlhak3eHlcse2gAw84vaoGGmJvUy2U +sdnc.odl.url-base=http://sdnc.onap:8282/restconf/operations -- cgit 1.2.3-korg From b39dc2b5bc842824b6bc2b85bc4f92eedb6d454b Mon Sep 17 00:00:00 2001 From: Dan Timoney Date: Fri, 15 May 2020 10:10:57 -0400 Subject: Change log4j2 configuration Changed log4j2 configuration from using properties files to using XML, which corrected the issue we were seeing with log files being created but empty. Also updated sdc.client.version to use released version 1.4.2 instead of 1.4.2-SNAPSHOT, which no longer exists - causing a compile error. Change-Id: I7040453ccbc3b3fd246a07fa3287c7d4d331fb34 Issue-ID: SDNC-1167 Signed-off-by: Dan Timoney --- dmaap-listener/src/main/resources/log4j.properties | 37 ---------------------- dmaap-listener/src/main/resources/log4j2.xml | 26 +++++++++++++++ ueb-listener/pom.xml | 4 +-- ueb-listener/src/main/resources/log4j.properties | 37 ---------------------- ueb-listener/src/main/resources/log4j2.xml | 26 +++++++++++++++ 5 files changed, 54 insertions(+), 76 deletions(-) delete mode 100644 dmaap-listener/src/main/resources/log4j.properties create mode 100644 dmaap-listener/src/main/resources/log4j2.xml delete mode 100644 ueb-listener/src/main/resources/log4j.properties create mode 100644 ueb-listener/src/main/resources/log4j2.xml (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/src/main/resources/log4j.properties b/dmaap-listener/src/main/resources/log4j.properties deleted file mode 100644 index 8db00762b..000000000 --- a/dmaap-listener/src/main/resources/log4j.properties +++ /dev/null @@ -1,37 +0,0 @@ -### -# ============LICENSE_START======================================================= -# openECOMP : SDN-C -# ================================================================================ -# Copyright (C) 2017 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========================================================= -### - -log4j.rootLogger=DEBUG,CONSOLE,LOGFILE - -# CONSOLE is set to be a ConsoleAppender using a PatternLayout. -log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender -log4j.appender.CONSOLE.Threshold=ERROR -log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout -log4j.appender.CONSOLE.layout.ConversionPattern=%p %d{yyyy-MM-dd HH:mm:ss.SSS Z} %c{1} - %m%n - -# LOGFILE is set to be a File appender using a PatternLayout. -log4j.appender.LOGFILE=org.apache.log4j.RollingFileAppender -log4j.appender.LOGFILE.File=/opt/app/dmaap-listener/logs/dmaap-listener.log -log4j.appender.LOGFILE.Append=true -log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout -log4j.appender.LOGFILE.layout.ConversionPattern=%p %d{yyyy-MM-dd HH:mm:ss.SSS Z} %c{1} - %m%n -log4j.appender.LOGFILE.MaxFileSize=10MB -log4j.appender.LOGFILE.MaxBackupIndex=10 diff --git a/dmaap-listener/src/main/resources/log4j2.xml b/dmaap-listener/src/main/resources/log4j2.xml new file mode 100644 index 000000000..01ee93714 --- /dev/null +++ b/dmaap-listener/src/main/resources/log4j2.xml @@ -0,0 +1,26 @@ + + + + + $${env:LOGDIR:-logs} + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ueb-listener/pom.xml b/ueb-listener/pom.xml index 42546fd7b..1df9f35b2 100755 --- a/ueb-listener/pom.xml +++ b/ueb-listener/pom.xml @@ -24,8 +24,8 @@ ${project.version}-${build.number} ${project.version} ${project.version} - 1.4.1-SNAPSHOT - 1.6.5 + 1.4.1 + 1.6.5 diff --git a/ueb-listener/src/main/resources/log4j.properties b/ueb-listener/src/main/resources/log4j.properties deleted file mode 100644 index f2f4ed26b..000000000 --- a/ueb-listener/src/main/resources/log4j.properties +++ /dev/null @@ -1,37 +0,0 @@ -### -# ============LICENSE_START======================================================= -# openECOMP : SDN-C -# ================================================================================ -# Copyright (C) 2017 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========================================================= -### - -log4j.rootLogger=DEBUG,CONSOLE,LOGFILE - -# CONSOLE is set to be a ConsoleAppender using a PatternLayout. -log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender -log4j.appender.CONSOLE.Threshold=ERROR -log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout -log4j.appender.CONSOLE.layout.ConversionPattern=%p %d{yyyy-MM-dd HH:mm:ss.SSS Z} %c{1} - %m%n - -# LOGFILE is set to be a File appender using a PatternLayout. -log4j.appender.LOGFILE=org.apache.log4j.RollingFileAppender -log4j.appender.LOGFILE.File=/opt/app/ueb-listener/logs/ueb-listener.log -log4j.appender.LOGFILE.Append=true -log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout -log4j.appender.LOGFILE.layout.ConversionPattern=%p %d{yyyy-MM-dd HH:mm:ss.SSS Z} %c{1} - %m%n -log4j.appender.LOGFILE.MaxFileSize=10MB -log4j.appender.LOGFILE.MaxBackupIndex=10 diff --git a/ueb-listener/src/main/resources/log4j2.xml b/ueb-listener/src/main/resources/log4j2.xml new file mode 100644 index 000000000..23ab908a5 --- /dev/null +++ b/ueb-listener/src/main/resources/log4j2.xml @@ -0,0 +1,26 @@ + + + + + $${env:LOGDIR:-logs} + + + + + + + + + + + + + + + + + + + + \ No newline at end of file -- cgit 1.2.3-korg From b1f7ad239ed681f473970538d17849281692578c Mon Sep 17 00:00:00 2001 From: Sandeep Shah Date: Fri, 22 May 2020 23:06:07 -0500 Subject: Bug fix in DMAAP message parsing for CMNotify Minor bug fix in the DMAAP message for CMNotify Issue-ID: CCSDK-2383 Signed-off-by: SandeepLinux Change-Id: Ia080adafecf6d6b3a12682aaab3f244a33a16de5 --- .../ccsdk/sli/northbound/dmaapclient/CMNotifyDmaapConsumer.java | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/CMNotifyDmaapConsumer.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/CMNotifyDmaapConsumer.java index e49e77ea8..fa14fbb24 100644 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/CMNotifyDmaapConsumer.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/CMNotifyDmaapConsumer.java @@ -71,14 +71,10 @@ public class CMNotifyDmaapConsumer extends SdncDmaapConsumerImpl { return; } - JSONObject rpcMsgBodyNode = new JSONObject(); - - rpcMsgBodyNode.put(INPUT,payloadNode); - String rpcMsgbody; try { ObjectMapper mapper = new ObjectMapper(); - rpcMsgbody = mapper.writeValueAsString(rpcMsgBodyNode); + rpcMsgbody = "{\"input\":" + mapper.writeValueAsString(payloadNode) + "}"; } catch (Exception e) { LOG.error("Unable to parse payload in CMNotify-DMAAP message", e); -- cgit 1.2.3-korg From 9bfbca954ba6fe021e1c166990b86ab0d9830d79 Mon Sep 17 00:00:00 2001 From: Franklin Dsilva Date: Tue, 26 May 2020 09:10:33 +0000 Subject: Path-/opt/app/dmaap-listener/lib does not exist in sdnc-dmaap-listener pod Change-Id: I21a1f00adef418d29e68cf7cdd1939761b87750f Issue-ID: CCSDK-2388 Signed-off-by: Franklin Dsilva --- .../org/onap/ccsdk/sli/northbound/dmaapclient/SdncAaiDmaapConsumer.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncAaiDmaapConsumer.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncAaiDmaapConsumer.java index 5cf369403..f35e6f1e3 100644 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncAaiDmaapConsumer.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncAaiDmaapConsumer.java @@ -68,7 +68,7 @@ public class SdncAaiDmaapConsumer extends SdncDmaapConsumerImpl { rootDir = System.getenv(DMAAPLISTENERROOT); if ((rootDir == null) || (rootDir.length() == 0)) { - rootDir = "/opt/app/dmaap-listener/lib/"; + rootDir = "/opt/onap/sdnc/dmaap-listener/lib/"; } else { rootDir = rootDir + "/lib/"; -- cgit 1.2.3-korg From 1ed8346da11ee15694246c432a8ac3b27bce2468 Mon Sep 17 00:00:00 2001 From: Sandeep Shah Date: Thu, 4 Jun 2020 19:02:10 -0500 Subject: Aiign requestID, subrequestID for DMAAP msgs Updated DMAAP listener to keep track of requestID and subRequestID for DMAAP message publication. These values are sent to DG as part of SLI parms Issue-ID: CCSDK-2413 Signed-off-by: SandeepLinux Change-Id: I207a7d1223416475de0b44ba80944ed2f4f57305 --- .../dmaapclient/OofPciPocDmaapConsumers.java | 65 ++++++++++++++++++++-- 1 file changed, 61 insertions(+), 4 deletions(-) (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/OofPciPocDmaapConsumers.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/OofPciPocDmaapConsumers.java index e8dacb959..9ff6fd616 100644 --- a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/OofPciPocDmaapConsumers.java +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/OofPciPocDmaapConsumers.java @@ -64,6 +64,16 @@ public class OofPciPocDmaapConsumers extends SdncDmaapConsumerImpl { private static final String RPC_NAME = "rpc-name"; private static final String BODY = "body"; private static final String INPUT = "input"; + private static final String COMMON_HEADER = "CommonHeader"; + private static final String TIME_STAMP = "TimeStamp"; + private static final String REQUEST_ID = "RequestID"; + private static final String SUB_REQUEST_ID = "SubRequestID"; + + private static final String TIME_STAMP_FOR_SLI = "timeStamp"; + private static final String REQUEST_ID_FOR_SLI = "requestID"; + private static final String SUB_REQUEST_ID_FOR_SLI = "subRequestID"; + + private static final String CONFIGURATION_PHY_CELL_ID_INPUT = "configuration-phy-cell-id-input."; private static final String EMPTY = ""; private static final String ESCAPE_SEQUENCE_QUOTES = "\""; @@ -104,9 +114,9 @@ public class OofPciPocDmaapConsumers extends SdncDmaapConsumerImpl { protected String publish(String templatePath, String jsonString, JsonNode configurationsOrDataNode, boolean invokePciChangesPublish, boolean invokeAnrChangesPublish) throws IOException, InvalidMessageException { if (invokePciChangesPublish){ - return publishPciChangesFromPolicyToSDNR(templatePath, configurationsOrDataNode); + return publishPciChangesFromPolicyToSDNR(templatePath, configurationsOrDataNode, jsonString); } else if (invokeAnrChangesPublish){ - return publishANRChangesFromPolicyToSDNR(templatePath, configurationsOrDataNode); + return publishANRChangesFromPolicyToSDNR(templatePath, configurationsOrDataNode, jsonString); } else { return publishFullMessage(templatePath, jsonString); } @@ -138,7 +148,7 @@ public class OofPciPocDmaapConsumers extends SdncDmaapConsumerImpl { return writer.toString(); } - private String publishANRChangesFromPolicyToSDNR(String templatePath, JsonNode dataNode) throws IOException, InvalidMessageException + private String publishANRChangesFromPolicyToSDNR(String templatePath, JsonNode dataNode, String msg) throws IOException, InvalidMessageException { VelocityContext context = new VelocityContext(); @@ -156,6 +166,29 @@ public class OofPciPocDmaapConsumers extends SdncDmaapConsumerImpl { JSONObject alias = new JSONObject(); JSONArray sliParametersArray = new JSONArray(); + ObjectMapper oMapper = new ObjectMapper(); + + JsonNode dmaapMessageRootNode; + try { + dmaapMessageRootNode = oMapper.readTree(msg); + } catch (Exception e) { + throw new InvalidMessageException("Cannot parse json object", e); + } + + JsonNode commonHeader = dmaapMessageRootNode.get(BODY).get(INPUT).get(COMMON_HEADER); + + JsonNode timeStamp = commonHeader.get(TIME_STAMP); + + JsonNode requestID = commonHeader.get(REQUEST_ID); + + JsonNode subRequestID = commonHeader.get(SUB_REQUEST_ID); + + sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, GENERIC_NEIGHBOR_CONFIGURATION_INPUT+TIME_STAMP_FOR_SLI).put(STRING_VALUE,timeStamp)); + + sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, GENERIC_NEIGHBOR_CONFIGURATION_INPUT+REQUEST_ID_FOR_SLI).put(STRING_VALUE,requestID)); + + sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, GENERIC_NEIGHBOR_CONFIGURATION_INPUT+SUB_REQUEST_ID_FOR_SLI).put(STRING_VALUE,subRequestID)); + String aliasValue = dataNode.get(DATA).get(FAP_SERVICE).get(ALIAS_LABEL).textValue(); JsonNode nbrListInUse = dataNode.get(DATA).get(FAP_SERVICE).get(CELL_CONFIG).get(LTE).get(RAN).get(NEIGHBOR_LIST_IN_USE).get(LTE_CELL); @@ -203,7 +236,7 @@ public class OofPciPocDmaapConsumers extends SdncDmaapConsumerImpl { } - private String publishPciChangesFromPolicyToSDNR(String templatePath, JsonNode configurationsJsonNode) throws IOException, InvalidMessageException + private String publishPciChangesFromPolicyToSDNR(String templatePath, JsonNode configurationsJsonNode, String msg) throws IOException, InvalidMessageException { String RPC_NAME_KEY_IN_VT = "rpc_name"; String RPC_NAME_VALUE_IN_VT = "configuration-phy-cell-id"; @@ -217,6 +250,29 @@ public class OofPciPocDmaapConsumers extends SdncDmaapConsumerImpl { JsonNode configurations = configurationsJsonNode.get(CONFIGURATIONS); + ObjectMapper oMapper = new ObjectMapper(); + + JsonNode dmaapMessageRootNode; + try { + dmaapMessageRootNode = oMapper.readTree(msg); + } catch (Exception e) { + throw new InvalidMessageException("Cannot parse json object", e); + } + + JsonNode commonHeader = dmaapMessageRootNode.get(BODY).get(INPUT).get(COMMON_HEADER); + + JsonNode timeStamp = commonHeader.get(TIME_STAMP); + + JsonNode requestID = commonHeader.get(REQUEST_ID); + + JsonNode subRequestID = commonHeader.get(SUB_REQUEST_ID); + + sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, CONFIGURATION_PHY_CELL_ID_INPUT+TIME_STAMP_FOR_SLI).put(STRING_VALUE,timeStamp)); + + sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, CONFIGURATION_PHY_CELL_ID_INPUT+REQUEST_ID_FOR_SLI).put(STRING_VALUE,requestID)); + + sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, CONFIGURATION_PHY_CELL_ID_INPUT+SUB_REQUEST_ID_FOR_SLI).put(STRING_VALUE,subRequestID)); + int entryCount = 0; if(configurations.isArray()) { @@ -390,6 +446,7 @@ public class OofPciPocDmaapConsumers extends SdncDmaapConsumerImpl { return; } + if(!MODIFY_CONFIG.equals(action.textValue())) { LOG.info("Unknown Action {}", action); return; -- cgit 1.2.3-korg From e73281177c4d6069d410a47d152cdaf598d09dac Mon Sep 17 00:00:00 2001 From: Sandeep Shah Date: Wed, 2 Sep 2020 17:50:30 -0500 Subject: DMAAP Listener for ranSlice Feature support DMAAP listener for ranSlide related DMAAP messages from Policy and other ONAP components Issue-ID: CCSDK-2722 Signed-off-by: SandeepLinux Change-Id: I14267bc5247a383039ab11ada82d67b0f3f3c13c --- .../dmaapclient/SdncRANSliceDmaapConsumer.java | 92 ++++++++++++ .../dmaapclient/TestSdncRANSliceDmaapConsumer.java | 166 +++++++++++++++++++++ 2 files changed, 258 insertions(+) create mode 100644 dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncRANSliceDmaapConsumer.java create mode 100644 dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestSdncRANSliceDmaapConsumer.java (limited to 'dmaap-listener/src') diff --git a/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncRANSliceDmaapConsumer.java b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncRANSliceDmaapConsumer.java new file mode 100644 index 000000000..f1749f99b --- /dev/null +++ b/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/SdncRANSliceDmaapConsumer.java @@ -0,0 +1,92 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * Modifications Copyright © 2018 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.northbound.dmaapclient; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SdncRANSliceDmaapConsumer extends SdncDmaapConsumerImpl { + + private static final Logger LOG = LoggerFactory.getLogger(SdncRANSliceDmaapConsumer.class); + + private static final String BODY = "body"; + private static final String RPC = "rpc-name"; + + @Override + public void processMsg(String msg) throws InvalidMessageException { + + if (msg == null) { + throw new InvalidMessageException("Null RANSlice message"); + } + + ObjectMapper oMapper = new ObjectMapper(); + JsonNode ranSliceRootNode; + try { + ranSliceRootNode = oMapper.readTree(msg); + } catch (Exception e) { + throw new InvalidMessageException("Cannot parse RANSlice json input", e); + } + + JsonNode bodyNode = ranSliceRootNode.get(BODY); + if(bodyNode == null) { + LOG.warn("Missing body in RANSlice message"); + return; + } + String rpcMsgbody; + try { + ObjectMapper mapper = new ObjectMapper(); + rpcMsgbody = mapper.writeValueAsString(bodyNode); + + } catch (Exception e) { + LOG.error("Unable to parse body in RANSlice message", e); + return; + } + + JsonNode rpcNode = ranSliceRootNode.get(RPC); + if(rpcNode == null) { + LOG.warn("Missing node in RANSlice message- " + RPC); + return; + } + String rpc = rpcNode.textValue(); + String sdncEndpoint = "ran-slice-api:" + rpc; + + try { + String odlUrlBase = getProperty("sdnc.odl.url-base"); + String odlUser = getProperty("sdnc.odl.user"); + String odlPassword = getProperty("sdnc.odl.password"); + LOG.info("POST RANSlice Request " + rpcMsgbody); + if ((odlUrlBase != null) && (odlUrlBase.length() > 0)) { + SdncOdlConnection conn = SdncOdlConnection.newInstance(odlUrlBase + "/" + sdncEndpoint, odlUser, odlPassword); + + conn.send("POST", "application/json", rpcMsgbody); + } else { + LOG.warn("Unable to POST RANSlice message. SDNC URL not available. body:\n" + rpcMsgbody); + } + } catch (Exception e) { + LOG.error("Unable to process message", e); + } + } +} diff --git a/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestSdncRANSliceDmaapConsumer.java b/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestSdncRANSliceDmaapConsumer.java new file mode 100644 index 000000000..50c427ec1 --- /dev/null +++ b/dmaap-listener/src/test/java/org/onap/ccsdk/sli/northbound/dmaapclient/TestSdncRANSliceDmaapConsumer.java @@ -0,0 +1,166 @@ +/* + * Copyright (c) 2017. Lorem ipsum dolor sit amet, consectetur adipiscing elit. + * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan. + * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna. + * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus. + * Vestibulum commodo. Ut rhoncus gravida arcu. + */ + +package org.onap.ccsdk.sli.northbound.dmaapclient; + +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Field; +import java.util.Map; +import java.util.Properties; + +import org.apache.commons.io.FileUtils; + +import org.junit.Before; +import org.junit.Test; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class TestSdncRANSliceDmaapConsumer { + private static final String ranSliceInput = + "{\r\n" + + " \"version\": \"ranSlice-dmaap.version\",\r\n" + + " \"cambria.partition\": \"SDNC\",\r\n" + + " \"correlation-id\": \"ranSlice-dmaap.correlation-id\",\r\n" + + " \"rpc-name\": \"upgrade-software\",\r\n" + + " \"type\": \"ranSlice-dmaap.type\",\r\n" + + " \"body\": {\r\n" + + " \"input\": {\r\n" + + " \"common-header\": {\r\n" + + " \"api-ver\": \"ranSlice-dmaap.api-ver\",\r\n" + + " \"flags\": {\r\n" + + " \"ttl\": \"ranSlice-dmaap.flags.mode\",\r\n" + + " \"force\": \"ranSlice-dmaap.flags.force\",\r\n" + + " \"mode\": \"ranSlice-dmaap.flags.mode\"\r\n" + + " },\r\n" + + " \"originator-id\": \"ranSlice-dmaap.originator-id\",\r\n" + + " \"request-id\": \"ranSlice-dmaap.request-id\",\r\n" + + " \"sub-request-id\": \"ranSlice-dmaap.sub-request-id\",\r\n" + + " \"timestamp\": \"ranSlice-dmaap.timestamp\"\r\n" + + " },\r\n" + + " \"payload\": \"ranSlice-dmaap.payload\"\r\n" + + " }\r\n" + + " }\r\n" + + "}"; + + + @Test + public void test() throws Exception { + Properties props = new Properties(); + + SdncRANSliceDmaapConsumer consumer = new SdncRANSliceDmaapConsumer(); + InputStream propStr = TestSdncRANSliceDmaapConsumer.class.getResourceAsStream("/dmaap-consumer-1.properties"); + props.load(propStr); + consumer.init(props, "src/test/resources/dmaap-consumer-1.properties"); + consumer.processMsg(ranSliceInput); + } + + @Test(expected = InvalidMessageException.class) + public void testProcessMsgNullMessage() throws Exception { + SdncRANSliceDmaapConsumer consumer = new SdncRANSliceDmaapConsumer(); + consumer.processMsg(null); + } + + @Test + public void testProcessMsgMissingBody() throws Exception { + String msg = "{\r\n" + + " \"version\": \"ranSlice-dmaap.version\",\r\n" + + " \"cambria.partition\": \"SDNC\",\r\n" + + " \"correlation-id\": \"ranSlice-dmaap.correlation-id\",\r\n" + + " \"rpc-name\": \"upgrade-software\",\r\n" + + " \"type\": \"ranSlice-dmaap.type\",\r\n" + + " \"body1\": {\r\n" + + " \"input\": {\r\n" + + " \"common-header\": {\r\n" + + " \"api-ver\": \"ranSlice-dmaap.api-ver\",\r\n" + + " \"flags\": {\r\n" + + " \"ttl\": \"ranSlice-dmaap.flags.mode\",\r\n" + + " \"force\": \"ranSlice-dmaap.flags.force\",\r\n" + + " \"mode\": \"ranSlice-dmaap.flags.mode\"\r\n" + + " },\r\n" + + " \"originator-id\": \"ranSlice-dmaap.originator-id\",\r\n" + + " \"request-id\": \"ranSlice-dmaap.request-id\",\r\n" + + " \"sub-request-id\": \"ranSlice-dmaap.sub-request-id\",\r\n" + + " \"timestamp\": \"ranSlice-dmaap.timestamp\"\r\n" + + " },\r\n" + + " \"payload\": \"ranSlice-dmaap.payload\"\r\n" + + " }\r\n" + + " }\r\n" + + "}"; + + SdncRANSliceDmaapConsumer consumer = new SdncRANSliceDmaapConsumer(); + consumer.processMsg(msg); + } + + @Test + public void testProcessMsgInvalidRPC() throws Exception { + String msg = "{\r\n" + + " \"version\": \"ranSlice-dmaap.version\",\r\n" + + " \"cambria.partition\": \"SDNC\",\r\n" + + " \"correlation-id\": \"ranSlice-dmaap.correlation-id\",\r\n" + + " \"rpc-name1\": \"upgrade-software\",\r\n" + + " \"type\": \"ranSlice-dmaap.type\",\r\n" + + " \"body\": {\r\n" + + " \"input\": {\r\n" + + " \"common-header\": {\r\n" + + " \"api-ver\": \"ranSlice-dmaap.api-ver\",\r\n" + + " \"flags\": {\r\n" + + " \"ttl\": \"ranSlice-dmaap.flags.mode\",\r\n" + + " \"force\": \"ranSlice-dmaap.flags.force\",\r\n" + + " \"mode\": \"ranSlice-dmaap.flags.mode\"\r\n" + + " },\r\n" + + " \"originator-id\": \"ranSlice-dmaap.originator-id\",\r\n" + + " \"request-id\": \"ranSlice-dmaap.request-id\",\r\n" + + " \"sub-request-id\": \"ranSlice-dmaap.sub-request-id\",\r\n" + + " \"timestamp\": \"ranSlice-dmaap.timestamp\"\r\n" + + " },\r\n" + + " \"payload\": \"ranSlice-dmaap.payload\"\r\n" + + " }\r\n" + + " }\r\n" + + "}"; + + SdncRANSliceDmaapConsumer consumer = new SdncRANSliceDmaapConsumer(); + consumer.processMsg(msg); + } + + @Test + public void testProcessMsgInvalidPartition() throws Exception { + String msg = "{\r\n" + + " \"version\": \"ranSlice-dmaap.version\",\r\n" + + " \"cambria.partition\": \"BAD\",\r\n" + + " \"correlation-id\": \"ranSlice-dmaap.correlation-id\",\r\n" + + " \"rpc-name\": \"upgrade-software\",\r\n" + + " \"type\": \"ranSlice-dmaap.type\",\r\n" + + " \"body\": {\r\n" + + " \"input\": {\r\n" + + " \"common-header\": {\r\n" + + " \"api-ver\": \"ranSlice-dmaap.api-ver\",\r\n" + + " \"flags\": {\r\n" + + " \"ttl\": \"ranSlice-dmaap.flags.mode\",\r\n" + + " \"force\": \"ranSlice-dmaap.flags.force\",\r\n" + + " \"mode\": \"ranSlice-dmaap.flags.mode\"\r\n" + + " },\r\n" + + " \"originator-id\": \"ranSlice-dmaap.originator-id\",\r\n" + + " \"request-id\": \"ranSlice-dmaap.request-id\",\r\n" + + " \"sub-request-id\": \"ranSlice-dmaap.sub-request-id\",\r\n" + + " \"timestamp\": \"ranSlice-dmaap.timestamp\"\r\n" + + " },\r\n" + + " \"payload\": \"ranSlice-dmaap.payload\"\r\n" + + " }\r\n" + + " }\r\n" + + "}"; + + + SdncRANSliceDmaapConsumer consumer = new SdncRANSliceDmaapConsumer(); + consumer.processMsg(msg); + } +} -- cgit 1.2.3-korg