Fix bugs and formatting issues
[dcaegen2/services/son-handler.git] / src / main / java / org / onap / dcaegen2 / services / sonhms / child / ChildThreadUtils.java
1 /*******************************************************************************
2  *  ============LICENSE_START=======================================================
3  *  son-handler
4  *  ================================================================================
5  *   Copyright (C) 2019 Wipro Limited.
6  *   ==============================================================================
7  *     Licensed under the Apache License, Version 2.0 (the "License");
8  *     you may not use this file except in compliance with the License.
9  *     You may obtain a copy of the License at
10  *  
11  *          http://www.apache.org/licenses/LICENSE-2.0
12  *  
13  *     Unless required by applicable law or agreed to in writing, software
14  *     distributed under the License is distributed on an "AS IS" BASIS,
15  *     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  *     See the License for the specific language governing permissions and
17  *     limitations under the License.
18  *     ============LICENSE_END=========================================================
19  *  
20  *******************************************************************************/
21
22 package org.onap.dcaegen2.services.sonhms.child;
23
24 import com.fasterxml.jackson.annotation.JsonInclude.Include;
25 import com.fasterxml.jackson.core.JsonProcessingException;
26 import com.fasterxml.jackson.databind.ObjectMapper;
27
28 import java.util.ArrayList;
29 import java.util.List;
30 import java.util.Map;
31 import java.util.UUID;
32
33 import org.onap.dcaegen2.services.sonhms.ConfigPolicy;
34 import org.onap.dcaegen2.services.sonhms.Configuration;
35 import org.onap.dcaegen2.services.sonhms.dao.SonRequestsRepository;
36 import org.onap.dcaegen2.services.sonhms.dmaap.PolicyDmaapClient;
37 import org.onap.dcaegen2.services.sonhms.entity.SonRequests;
38 import org.onap.dcaegen2.services.sonhms.exceptions.ConfigDbNotFoundException;
39 import org.onap.dcaegen2.services.sonhms.model.CellConfig;
40 import org.onap.dcaegen2.services.sonhms.model.CellPciPair;
41 import org.onap.dcaegen2.services.sonhms.model.Common;
42 import org.onap.dcaegen2.services.sonhms.model.Configurations;
43 import org.onap.dcaegen2.services.sonhms.model.Data;
44 import org.onap.dcaegen2.services.sonhms.model.FapService;
45 import org.onap.dcaegen2.services.sonhms.model.Lte;
46 import org.onap.dcaegen2.services.sonhms.model.LteCell;
47 import org.onap.dcaegen2.services.sonhms.model.NeighborListInUse;
48 import org.onap.dcaegen2.services.sonhms.model.Payload;
49 import org.onap.dcaegen2.services.sonhms.model.PolicyNotification;
50 import org.onap.dcaegen2.services.sonhms.model.Ran;
51 import org.onap.dcaegen2.services.sonhms.model.X0005b9Lte;
52 import org.onap.dcaegen2.services.sonhms.restclient.AsyncResponseBody;
53 import org.onap.dcaegen2.services.sonhms.restclient.SdnrRestClient;
54 import org.onap.dcaegen2.services.sonhms.restclient.Solutions;
55 import org.onap.dcaegen2.services.sonhms.utils.BeanUtil;
56 import org.slf4j.Logger;
57
58 public class ChildThreadUtils {
59
60     private static final Logger log = org.slf4j.LoggerFactory.getLogger(ChildThreadUtils.class);
61     private ConfigPolicy configPolicy;
62     private PnfUtils pnfUtils;
63     private PolicyDmaapClient policyDmaapClient;
64
65     /**
66      * Parameterized constructor.
67      */
68     public ChildThreadUtils(ConfigPolicy configPolicy, PnfUtils pnfUtils, PolicyDmaapClient policyDmaapClient) {
69         this.configPolicy = configPolicy;
70         this.pnfUtils = pnfUtils;
71         this.policyDmaapClient = policyDmaapClient;
72     }
73
74     /**
75      * Save request.
76      */
77     public void saveRequest(String transactionId, long childThreadId) {
78         SonRequestsRepository sonRequestsRepository = BeanUtil.getBean(SonRequestsRepository.class);
79
80         SonRequests sonRequest = new SonRequests();
81         sonRequest.setTransactionId(transactionId);
82         sonRequest.setChildThreadId(childThreadId);
83         sonRequestsRepository.save(sonRequest);
84     }
85
86     /**
87      * Determines whether to trigger Oof or wait for notifications.
88      */
89     public Boolean triggerOrWait(Map<String, ArrayList<Integer>> collisionConfusionResult) {
90         // determine collision or confusion
91
92         Configuration configuration = Configuration.getInstance();
93         int collisionSum = 0;
94         int confusionSum = 0;
95
96         for (Map.Entry<String, ArrayList<Integer>> entry : collisionConfusionResult.entrySet()) {
97
98             ArrayList<Integer> arr;
99             arr = entry.getValue();
100             // check for 0 collision and confusion
101             if (!arr.isEmpty()) {
102                 collisionSum = collisionSum + arr.get(0);
103                 confusionSum = confusionSum + arr.get(1);
104             }
105         }
106         return ((collisionSum >= configuration.getMinCollision()) && (confusionSum >= configuration.getMinConfusion()));
107
108     }
109
110     /**
111      * get policy notification string from oof result.
112      *
113      */
114     public String getNotificationString(String pnfName, String requestId, String payloadString,
115             Long alarmStartTime, String action) {
116         
117         String closedLoopControlName = "ControlLoop-vPCI-fb41f388-a5f2-11e8-98d0-529269fb1459";
118         try {
119             closedLoopControlName = (String) configPolicy.getConfig().get("PCI_MODCONFIG_POLICY_NAME");
120         } catch (NullPointerException e) {
121             log.error("Config policy not found, Using default");
122         }
123
124         PolicyNotification policyNotification = new PolicyNotification(closedLoopControlName, requestId, alarmStartTime,
125                 pnfName, action);
126
127         policyNotification.setClosedLoopControlName(closedLoopControlName);
128         policyNotification.setPayload(payloadString);
129         ObjectMapper mapper = new ObjectMapper();
130
131         String notification = "";
132         try {
133             notification = mapper.writeValueAsString(policyNotification);
134         } catch (JsonProcessingException e1) {
135             log.debug("JSON processing exception: {}", e1);
136         }
137         return notification;
138     }
139
140     /**
141      * Sends Dmaap notification to Policy.
142      *
143      * @throws ConfigDbNotFoundException
144      *             when config db is unreachable
145      */
146     public Boolean sendToPolicy(AsyncResponseBody async) throws ConfigDbNotFoundException {
147
148         if (log.isDebugEnabled()) {
149             log.debug(async.toString());
150         }
151
152         Solutions solutions;
153         solutions = async.getSolutions();
154         if (!solutions.getPciSolutions().isEmpty()) {
155             Map<String, List<CellPciPair>> pnfs = pnfUtils.getPnfs(solutions);
156             for (Map.Entry<String, List<CellPciPair>> entry : pnfs.entrySet()) {
157                 String pnfName = entry.getKey();
158                 List<CellPciPair> cellPciPairs = entry.getValue();
159                 ArrayList<Configurations> configurations = new ArrayList<>();
160                 for (CellPciPair cellPciPair : cellPciPairs) {
161                     String cellId = cellPciPair.getCellId();
162                     int pci = cellPciPair.getPhysicalCellId();
163                     Configurations configuration = new Configurations(new Data(new FapService(cellId,
164                             new X0005b9Lte(pci, pnfName), new CellConfig(new Lte(new Ran(new Common(cellId), null))))));
165                     configurations.add(configuration);
166                 }
167
168                 Payload payload = new Payload(configurations);
169                 ObjectMapper mapper = new ObjectMapper();
170                 mapper.setSerializationInclusion(Include.NON_NULL);
171                 String payloadString = "";
172                 try {
173                     payloadString = mapper.writeValueAsString(payload);
174                 } catch (JsonProcessingException e) {
175                     log.debug("JSON processing exception: {}", e);
176                 }
177
178                 String notification = getNotificationString(pnfName, UUID.randomUUID().toString(), payloadString,
179                         System.currentTimeMillis(), "ModifyConfig");
180                 log.info("Policy Notification: {}", notification);
181                 boolean status = policyDmaapClient.sendNotificationToPolicy(notification);
182                 log.debug("sent Message: {}", status);
183                 if (status) {
184                     log.debug("Message sent to policy");
185                 } else {
186                     log.debug("Sending notification to policy failed");
187                 }
188
189             }
190         }
191         if (!solutions.getAnrSolutions().isEmpty()) {
192             Map<String, List<Map<String,List<String>>>> anrPnfs;
193             List<Configurations> configurations = new ArrayList<>();
194             anrPnfs = pnfUtils.getPnfsForAnrSolutions(solutions.getAnrSolutions());
195             for(Map.Entry<String, List<Map<String,List<String>>>> entry : anrPnfs.entrySet()) {
196                 String pnfName = entry.getKey();
197                 for(Map<String,List<String>> cellRemNeighborsPair : anrPnfs.get(pnfName)) {
198                   for(Map.Entry<String, List<String>> entry1 : cellRemNeighborsPair.entrySet()) {
199                       String cellId = entry1.getKey();
200                       List<LteCell> lteCellList = new ArrayList<>();
201                       for(String removeableNeighbor : entry1.getValue()) {
202                           LteCell lteCell = new LteCell();
203                           lteCell.setBlacklisted("true");
204                           lteCell.setPlmnId(solutions.getNetworkId());
205                           lteCell.setCid(removeableNeighbor);
206                           int pci = SdnrRestClient.getPci(cellId);
207                           lteCell.setPhyCellId(pci);
208                           lteCell.setPnfName(pnfName);
209                           lteCellList.add(lteCell);
210                       }
211                       Configurations configuration = new Configurations(
212                               new Data(new FapService(cellId, null, new CellConfig(new Lte(new Ran(new Common(cellId),
213                                       new NeighborListInUse(null, lteCellList, String.valueOf(lteCellList.size()))))))));
214                       configurations.add(configuration); 
215                   }
216                 }
217                 Payload payload = new Payload(configurations);
218                 ObjectMapper mapper = new ObjectMapper();
219                 mapper.setSerializationInclusion(Include.NON_NULL);
220                 String payloadString = null;
221                 try {
222                     payloadString = mapper.writeValueAsString(payload);
223                 } catch (JsonProcessingException e) {
224                     log.error("Exception in writing anrupdate string", e);
225                 }
226                 String notification = getNotificationString(pnfName, UUID.randomUUID().toString(), payloadString,
227                         System.currentTimeMillis(), "ModifyConfigANR");
228                 log.info("Policy Notification: {}", notification);
229                 Boolean result = policyDmaapClient.sendNotificationToPolicy(notification);
230                 log.info("send notification to policy result {} ", result);
231             }
232             
233         }
234         return true;
235     }
236
237 }