2  * ============LICENSE_START=======================================================
 
   4  * ================================================================================
 
   5  * Copyright (C) 2017 AT&T Intellectual Property. All rights
 
   7  * ================================================================================
 
   8  * Licensed under the Apache License, Version 2.0 (the "License");
 
   9  * you may not use this file except in compliance with the License.
 
  10  * You may obtain a copy of the License at
 
  12  *      http://www.apache.org/licenses/LICENSE-2.0
 
  14  * Unless required by applicable law or agreed to in writing, software
 
  15  * distributed under the License is distributed on an "AS IS" BASIS,
 
  16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 
  17  * See the License for the specific language governing permissions and
 
  18  * limitations under the License.
 
  19  * ============LICENSE_END=========================================================
 
  22 package org.onap.ccsdk.sli.northbound.dmaapclient;
 
  24 import java.io.BufferedReader;
 
  26 import java.io.FileReader;
 
  27 import java.io.IOException;
 
  28 import java.io.StringWriter;
 
  29 import java.io.Writer;
 
  30 import java.time.Instant;
 
  31 import java.util.HashMap;
 
  33 import java.util.Properties;
 
  34 import org.apache.velocity.VelocityContext;
 
  35 import org.apache.velocity.app.VelocityEngine;
 
  36 import org.json.JSONArray;
 
  37 import org.json.JSONObject;
 
  38 import org.slf4j.Logger;
 
  39 import org.slf4j.LoggerFactory;
 
  40 import com.fasterxml.jackson.databind.JsonNode;
 
  41 import com.fasterxml.jackson.databind.ObjectMapper;
 
  43 public class ANRChangesFromPolicyToSDNRDmaapConsumer extends SdncDmaapConsumerImpl {
 
  45     private static final Logger LOG = LoggerFactory.getLogger(ANRChangesFromPolicyToSDNRDmaapConsumer.class);
 
  46     private static final String SDNC_ENDPOINT = "SDNC.endpoint";
 
  47     private static final String TEMPLATE = "SDNC.template";
 
  48     private static final String DMAAPLISTENERROOT = "DMAAPLISTENERROOT";
 
  50     private static final String PARAMETER_NAME = "parameter-name";
 
  51     private static final String STRING_VALUE = "string-value";
 
  52     private static final String GENERIC_NEIGHBOR_CONFIGURATION_INPUT = "generic-neighbor-configuration-input.";
 
  53     private static final String GENERIC_NEIGHBOR_CONFIGURATION_INPUT_NEIGHBOR_LIST_IN_USE = GENERIC_NEIGHBOR_CONFIGURATION_INPUT.concat("neighbor-list-in-use");
 
  54     private static final String EVENT_HEADER = "event-header";
 
  55         private static final String ACTION = "Action";
 
  56         private static final String PAYLOAD = "Payload";
 
  57         private static final String CONFIGURATIONS = "Configurations";
 
  58         private static final String MODIFY_CONFIG_ANR = "ModifyConfigANR";
 
  59         private static final String MAP_FILE_NAME = "anr-changes-from-policy-to-sdnr";
 
  60         private static final String DATA = "data";
 
  61         private static final String FAP_SERVICE = "FAPService";
 
  62         private static final String SLI_PARAMETERS = "sli_parameters";
 
  63         private static final String RPC_NAME = "rpc-name";
 
  64         private static final String BODY = "body";
 
  65         private static final String INPUT = "input";
 
  67     private String rootDir;
 
  69     protected VelocityEngine velocityEngine;
 
  71     public ANRChangesFromPolicyToSDNRDmaapConsumer() {
 
  72         velocityEngine = new VelocityEngine();
 
  73         Properties props = new Properties();
 
  74         rootDir = System.getenv(DMAAPLISTENERROOT);
 
  76         if ((rootDir == null) || (rootDir.length() == 0)) {
 
  77             rootDir = "/opt/app/dmaap-listener/lib/";
 
  80             rootDir = rootDir + "/lib/";
 
  83         props.put("file.resource.loader.path", rootDir);
 
  84         velocityEngine.init(props);
 
  88      * for testing purposes
 
  90     ANRChangesFromPolicyToSDNRDmaapConsumer(Properties props) {
 
  91         velocityEngine = new VelocityEngine();
 
  92         velocityEngine.init(props);
 
  95     protected String publish(String templatePath, String jsonString, JsonNode dataNode) throws IOException, InvalidMessageException
 
  97         if (templatePath.contains("anr-pci-changes-from-policy-to-sdnr")){
 
  98             return publishANRChangesFromPolicyToSDNR(templatePath, dataNode);
 
 100             return publishFullMessage(templatePath, jsonString);
 
 104     private String publishFullMessage(String templatePath, String jsonString) throws IOException
 
 106         JSONObject jsonObj = new JSONObject(jsonString);
 
 107         VelocityContext context = new VelocityContext();
 
 108         for(Object key : jsonObj.keySet())
 
 110             context.put((String)key, jsonObj.get((String)key));
 
 113         String id = jsonObj.getJSONObject(EVENT_HEADER).get("id").toString();
 
 114         context.put("req_id", id);
 
 116         context.put("curr_time", Instant.now());
 
 118         ObjectMapper oMapper = new ObjectMapper();
 
 120         String rpcMsgbody = oMapper.writeValueAsString(jsonString);
 
 121         context.put("full_message", rpcMsgbody);
 
 123         Writer writer = new StringWriter();
 
 124         velocityEngine.mergeTemplate(templatePath, "UTF-8", context, writer);
 
 127         return writer.toString();
 
 130     private String publishANRChangesFromPolicyToSDNR(String templatePath, JsonNode dataNode) throws IOException, InvalidMessageException
 
 132         VelocityContext context = new VelocityContext();
 
 134                 String RPC_NAME_KEY_IN_VT = "rpc_name";
 
 135         String RPC_NAME_VALUE_IN_VT = "generic-neighbor-configuration";
 
 137         String CELL_CONFIG = "CellConfig";
 
 138         String ALIAS_LABEL = "alias";
 
 141         String LTE_CELL = "LTECell";
 
 142         String NEIGHBOR_LIST_IN_USE = "NeighborListInUse";
 
 144         JSONObject numberOfEntries = new JSONObject();
 
 145         JSONObject alias = new JSONObject();
 
 146         JSONArray sliParametersArray = new JSONArray();
 
 148         String aliasValue =  dataNode.get(DATA).get(FAP_SERVICE).get(ALIAS_LABEL).textValue();
 
 150         JsonNode nbrListInUse = dataNode.get(DATA).get(FAP_SERVICE).get(CELL_CONFIG).get(LTE).get(RAN).get(NEIGHBOR_LIST_IN_USE).get(LTE_CELL);
 
 154         if(nbrListInUse.isArray()) {
 
 155                 for(JsonNode lteCell:nbrListInUse) {
 
 156                         sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, GENERIC_NEIGHBOR_CONFIGURATION_INPUT_NEIGHBOR_LIST_IN_USE+"["+entryCount+"]."+"plmnid")
 
 157                                 .put(STRING_VALUE, lteCell.get("PLMNID")));
 
 158                         sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, GENERIC_NEIGHBOR_CONFIGURATION_INPUT_NEIGHBOR_LIST_IN_USE+"["+entryCount+"]."+"cid")
 
 159                                 .put(STRING_VALUE, lteCell.get("CID")));
 
 160                         sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, GENERIC_NEIGHBOR_CONFIGURATION_INPUT_NEIGHBOR_LIST_IN_USE+"["+entryCount+"]."+"phy-cell-id")
 
 161                                 .put(STRING_VALUE, lteCell.get("PhyCellID")));
 
 162                         sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, GENERIC_NEIGHBOR_CONFIGURATION_INPUT_NEIGHBOR_LIST_IN_USE+"["+entryCount+"]."+"pnf-name")
 
 163                                 .put(STRING_VALUE, lteCell.get("PNFName")));
 
 164                         sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, GENERIC_NEIGHBOR_CONFIGURATION_INPUT_NEIGHBOR_LIST_IN_USE+"["+entryCount+"]."+"blacklisted")
 
 165                                 .put(STRING_VALUE, lteCell.get("Blacklisted")));
 
 170                 alias.put(PARAMETER_NAME, GENERIC_NEIGHBOR_CONFIGURATION_INPUT+ALIAS_LABEL);
 
 171             alias.put(STRING_VALUE, aliasValue);
 
 173             numberOfEntries.put(PARAMETER_NAME, GENERIC_NEIGHBOR_CONFIGURATION_INPUT+"number-of-neighbor-cell-entries");
 
 174             numberOfEntries.put(STRING_VALUE, entryCount);
 
 176             sliParametersArray.put(alias);
 
 177             sliParametersArray.put(numberOfEntries);
 
 179             context.put(SLI_PARAMETERS, sliParametersArray);
 
 181             context.put(RPC_NAME_KEY_IN_VT, RPC_NAME_VALUE_IN_VT);
 
 183             Writer writer = new StringWriter();
 
 184             velocityEngine.mergeTemplate(templatePath, "UTF-8", context, writer);
 
 187             return writer.toString();
 
 190                 throw new InvalidMessageException("nbrListInUse is not of Type Array. Could not read neighbor list elements");
 
 196     public void processMsg(String msg) throws InvalidMessageException {
 
 199             throw new InvalidMessageException("Null message");
 
 202         ObjectMapper oMapper = new ObjectMapper();
 
 203         JsonNode anrChangesRootNode;
 
 205                 anrChangesRootNode = oMapper.readTree(msg);
 
 206         } catch (Exception e) {
 
 207             throw new InvalidMessageException("Cannot parse json object", e);
 
 210         JsonNode rpcname = anrChangesRootNode.get(RPC_NAME);
 
 211         if(rpcname == null) {
 
 212                  LOG.info("Missing rpc-name node.");
 
 216         if(!MODIFY_CONFIG_ANR.toLowerCase().equals(rpcname.textValue())) {
 
 217             LOG.info("Unknown rpc name {}", rpcname);
 
 221         JsonNode body = anrChangesRootNode.get(BODY);
 
 223                  LOG.info("Missing body node.");
 
 227         JsonNode input = body.get(INPUT);
 
 229                  LOG.info("Missing input node.");
 
 233         JsonNode action = input.get(ACTION);
 
 235                  LOG.info("Missing action node.");
 
 239         if(!MODIFY_CONFIG_ANR.equals(action.textValue())) {
 
 240             LOG.info("Unknown Action {}", action);
 
 244         JsonNode payload = input.get(PAYLOAD);
 
 245         if(payload == null) {
 
 246             LOG.info("Missing payload node.");
 
 250         String payloadText = payload.asText();
 
 252         if(!payloadText.contains(CONFIGURATIONS)) {
 
 253          LOG.info("Missing configurations node.");
 
 257        JsonNode configurationsJsonNode;
 
 259                 configurationsJsonNode = oMapper.readTree(payloadText);
 
 260             } catch (Exception e) {
 
 261                 throw new InvalidMessageException("Cannot parse payload value", e);
 
 264         String mapFilename = rootDir + MAP_FILE_NAME + ".map";
 
 265         Map<String, String> fieldMap = loadMap(mapFilename);
 
 266         if (fieldMap == null) {
 
 270         if (!fieldMap.containsKey(SDNC_ENDPOINT)) {
 
 273         String sdncEndpoint = fieldMap.get(SDNC_ENDPOINT);
 
 275         if (!fieldMap.containsKey(TEMPLATE)) {
 
 276             throw new InvalidMessageException("No SDNC template known for message ");
 
 278         String templateName = fieldMap.get(TEMPLATE);
 
 280         JsonNode configurations = configurationsJsonNode.get(CONFIGURATIONS);
 
 282         if(configurations.isArray()) {
 
 283                 for(JsonNode dataNode:configurations) {
 
 284                 if(dataNode.get(DATA).get(FAP_SERVICE) == null) {
 
 285                     LOG.info("Could not make a rpc call. Missing fapService node for dataNode element::", dataNode.textValue());
 
 289                         String rpcMsgbody = publish(templateName, msg, dataNode);
 
 290                         String odlUrlBase = getProperty("sdnc.odl.url-base");
 
 291                         String odlUser = getProperty("sdnc.odl.user");
 
 292                         String odlPassword = getProperty("sdnc.odl.password");
 
 294                         if ((odlUrlBase != null) && (odlUrlBase.length() > 0)) {
 
 295                             SdncOdlConnection conn = SdncOdlConnection.newInstance(odlUrlBase + "/" + sdncEndpoint, odlUser, odlPassword);
 
 297                             conn.send("POST", "application/json", rpcMsgbody);
 
 299                             LOG.info("POST message body would be:\n" + rpcMsgbody);
 
 301                     } catch (Exception e) {
 
 302                         LOG.error("Unable to process message", e);
 
 307                 throw new InvalidMessageException("Configurations is not of Type Array. Could not read configuration changes");
 
 311     private Map<String, String> loadMap(String mapFilename) {
 
 312         File mapFile = new File(mapFilename);
 
 314         if (!mapFile.canRead()) {
 
 315             LOG.error(String.format("Cannot read map file (%s)", mapFilename));
 
 319         Map<String, String> results = new HashMap<>();
 
 320         try (BufferedReader mapReader = new BufferedReader(new FileReader(mapFile))) {
 
 324             while ((curLine = mapReader.readLine()) != null) {
 
 325                 curLine = curLine.trim();
 
 327                 if ((curLine.length() > 0) && (!curLine.startsWith("#")) && curLine.contains("=>")) {
 
 328                     String[] entry = curLine.split("=>");
 
 329                     if (entry.length == 2) {
 
 330                         results.put(entry[0].trim(), entry[1].trim());
 
 335         } catch (Exception e) {
 
 336             LOG.error("Caught exception reading map " + mapFilename, e);