Merge "Bump parent version to 2.5.4-SNAPSHOT"
[ccsdk/features.git] / sdnr / wt / devicemanager-onap / openroadm / provider / src / main / java / org / onap / ccsdk / features / sdnr / wt / devicemanager / openroadm / impl / PmDataBuilderOpenRoadm.java
1 /*
2  * ============LICENSE_START=======================================================
3  * ONAP : ccsdk features
4  * ================================================================================
5  * Copyright (C) 2020 highstreet technologies GmbH Intellectual Property.
6  * All rights reserved.
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
11  *
12  *     http://www.apache.org/licenses/LICENSE-2.0
13  *
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=========================================================
20  *
21  */
22 package org.onap.ccsdk.features.sdnr.wt.devicemanager.openroadm.impl;
23
24 import java.net.URL;
25 import java.util.ArrayList;
26 import java.util.Collection;
27 import java.util.Enumeration;
28 import java.util.HashMap;
29 import java.util.List;
30 import java.util.Map;
31
32 import org.onap.ccsdk.features.sdnr.wt.common.YangHelper;
33 import org.onap.ccsdk.features.sdnr.wt.netconfnodestateservice.NetconfBindingAccessor;
34 import org.onap.ccsdk.features.sdnr.wt.yang.mapper.YangToolsMapperHelper;
35 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
36 import org.opendaylight.yang.gen.v1.http.org.openroadm.pm.rev191129.HistoricalPmList;
37 import org.opendaylight.yang.gen.v1.http.org.openroadm.pm.rev191129.historical.pm.group.HistoricalPm;
38 import org.opendaylight.yang.gen.v1.http.org.openroadm.pm.rev191129.historical.pm.list.HistoricalPmEntry;
39 import org.opendaylight.yang.gen.v1.http.org.openroadm.pm.rev191129.historical.pm.val.group.Measurement;
40 import org.opendaylight.yang.gen.v1.http.org.openroadm.pm.types.rev191129.PmDataType;
41 import org.opendaylight.yang.gen.v1.http.org.openroadm.pm.types.rev191129.PmGranularity;
42 import org.opendaylight.yang.gen.v1.http.org.openroadm.pm.types.rev191129.PmNamesEnum;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.g836.pm.types.rev200413.ErroredSecond;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.g836.pm.types.rev200413.SeverelyErroredSecond;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.openroadm.pm.types.rev200413.PerformanceMeasurementTypeId;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.GranularityPeriodType;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.PmdataEntity;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.PmdataEntityBuilder;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.pmdata.entity.PerformanceDataBuilder;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.pmdata.grp.MeasurementBuilder;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.pmdata.grp.MeasurementKey;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.units.rev200413.Celsius;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.units.rev200413.DB;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.units.rev200413.DBm;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.units.rev200413.Fahrenheit;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.units.rev200413.KHz;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.units.rev200413.MW;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.units.rev200413.PerformanceMeasurementUnitId;
59 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
60 import org.osgi.framework.Bundle;
61 import org.osgi.framework.BundleContext;
62 import org.osgi.framework.FrameworkUtil;
63 import org.slf4j.Logger;
64 import org.slf4j.LoggerFactory;
65
66 /**
67  * @author shabnam
68  * <p>
69  * Reading Openroadm PM data and returning as PmDataEntitiy data
70  */
71 public class PmDataBuilderOpenRoadm {
72     // variables
73     private static final Logger log = LoggerFactory.getLogger(PmDataBuilderOpenRoadm.class);
74     private PmdataEntityBuilder pmDataBuilder;
75     private Bundle b = FrameworkUtil.getBundle(this.getClass());
76
77     // end of variables
78     // constructors
79     public PmDataBuilderOpenRoadm(NetconfBindingAccessor accessor) {
80         this.pmDataBuilder = new PmdataEntityBuilder();
81         this.pmDataBuilder.setNodeName(accessor.getNodeId().getValue());
82     }
83
84     // end of constructors
85     // public methods
86     // Read PM data
87     public HistoricalPmList getPmData(NetconfBindingAccessor accessor) {
88         final Class<HistoricalPmList> pmDataClass = HistoricalPmList.class;
89         log.debug("Get PM data for element {}", accessor.getNodeId().getValue());
90         InstanceIdentifier<HistoricalPmList> pmDataIid = InstanceIdentifier.builder(pmDataClass).build();
91         return accessor.getTransactionUtils().readData(accessor.getDataBroker(), LogicalDatastoreType.OPERATIONAL,
92                 pmDataIid);
93
94     }
95
96     // Build PM entity for writing into the database
97     public List<PmdataEntity> buildPmDataEntity(HistoricalPmList historicalPmEnitityList) {
98         List<PmdataEntity> pmEntitiyList = new ArrayList<>();
99         if (historicalPmEnitityList == null) {
100             return pmEntitiyList;
101         }
102         Collection<HistoricalPmEntry> pmDataEntryList =
103                 YangHelper.getCollection(historicalPmEnitityList.getHistoricalPmEntry());
104         for (HistoricalPmEntry pmDataEntry : pmDataEntryList) {
105             pmDataBuilder.setUuidInterface(pmDataEntry.getPmResourceType().getName());
106             Collection<HistoricalPm> historicalPmList = YangHelper.getCollection(pmDataEntry.getHistoricalPm());
107             for (HistoricalPm historicalPm : historicalPmList) {
108                 log.debug("PmName:{}", historicalPm.getType());
109                 //              pmDataBuilder.setPerformanceData(value)
110
111                 try {
112                     writeperformanceData(historicalPm);
113                 } catch (ClassNotFoundException e) {
114                     log.debug("No relevant data found");
115                 }
116                 pmEntitiyList.add(this.pmDataBuilder.build());
117
118                 log.debug("PmListSize before db writing: {}", pmEntitiyList.size());
119             }
120             log.debug("PmListSize before db writing: {}", pmEntitiyList.size());
121         }
122         return pmEntitiyList;
123     }
124     // end of public methods
125
126     // private methods
127     private void writeperformanceData(HistoricalPm historicalPm) throws ClassNotFoundException {
128         Collection<Measurement> measurementList = YangHelper.getCollection(historicalPm.getMeasurement());
129         Map<MeasurementKey, org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.pmdata.grp.Measurement>
130                 measurementMap = new HashMap<>();
131         // Map Performance data of PmDataEntity with MeasurmentData-HistoricalPm
132         PerformanceDataBuilder performanceDataBuilder = new PerformanceDataBuilder();
133         for (Measurement measurementData : measurementList) {
134             this.pmDataBuilder.setGranularityPeriod(mapGranularityPeriod(measurementData.getGranularity()))
135                     .setTimeStamp(measurementData.getCompletionTime());
136             if (measurementData.getValidity().getName().equals("suspect")) {
137                 this.pmDataBuilder.setSuspectIntervalFlag(true);
138             }
139             measurementMap.put(
140                     new MeasurementKey(measurementBuilder(historicalPm.getType(), measurementData.getPmParameterUnit(),
141                             measurementData.getPmParameterValue()).getPmKey()),
142                     measurementBuilder(historicalPm.getType(), measurementData.getPmParameterUnit(),
143                             measurementData.getPmParameterValue()));
144
145
146         }
147
148         pmDataBuilder.setPerformanceData(performanceDataBuilder.setMeasurement(measurementMap).build());
149     }
150
151
152     // Mapping Granularity period of PmDataEntity with PmGranularity of MeasurmentData-HistoricalPm
153     private GranularityPeriodType mapGranularityPeriod(PmGranularity pmGranularity) {
154
155         GranularityPeriodType granPeriod = null;
156         switch (pmGranularity.getName()) {
157             case ("notApplicable"):
158                 granPeriod = GranularityPeriodType.Unknown;
159                 break;
160             case ("15min"):
161                 granPeriod = GranularityPeriodType.Period15Min;
162                 break;
163             case ("24Hour"):
164                 granPeriod = GranularityPeriodType.Period24Hours;
165                 break;
166             default:
167                 granPeriod = GranularityPeriodType.Period15Min;
168                 break;
169         }
170         return granPeriod;
171     }
172
173     private List<Class<? extends PerformanceMeasurementTypeId>> setMeasurementTypeId() {
174         String packageName =
175                 "org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.openroadm.pm.types.rev200413";
176         String packageName1 =
177                 "/org/opendaylight/yang/gen/v1/urn/opendaylight/params/xml/ns/yang/data/provider/openroadm/pm/types/rev200413/";
178         List<Class<? extends PerformanceMeasurementTypeId>> measTypeObjList =
179                 new ArrayList<>();
180         URL root = Thread.currentThread().getContextClassLoader().getResource(packageName1);
181
182         log.debug("path for type package: {}", root);
183
184         Enumeration<URL> results = getFileURL(b, packageName);
185         log.debug("Found Packages {}", results);
186         if (results != null) {
187             while (results.hasMoreElements()) {
188                 URL path = results.nextElement();
189
190                 Class<?> cls1 = loadClass(b, path.getFile());
191
192                 if (PerformanceMeasurementTypeId.class.isAssignableFrom(cls1)) {
193                     measTypeObjList.add((Class<? extends PerformanceMeasurementTypeId>) cls1);
194
195                     log.debug("Class Added {}", cls1.getSimpleName());
196                 }
197             }
198         }
199
200         return measTypeObjList;
201     }
202
203     private PerformanceMeasurementUnitId setMeasurementUnit(String unitName) {
204
205         switch (unitName) {
206             case ("celsius"):
207                 return Celsius.VALUE;
208             case ("dB"):
209                 return DB.VALUE;
210             case ("dBm"):
211                 return DBm.VALUE;
212             case ("fahrenheit"):
213                 return Fahrenheit.VALUE;
214             case ("kHz"):
215                 return KHz.VALUE;
216             case ("mW"):
217                 return MW.VALUE;
218             default:
219                 break;
220         }
221         return null;
222     }
223
224     private org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.pmdata.grp.Measurement measurementBuilder(
225             PmNamesEnum pmType, String pmUnit, PmDataType pmDataType) {
226
227         MeasurementBuilder measBuilder = new MeasurementBuilder();
228         if (pmType.getName().equals("erroredSeconds")) {
229             measBuilder.setPmKey(ErroredSecond.VALUE);
230         } else if (pmType.getName().equals("severelyErroredSeconds")) {
231             measBuilder.setPmKey(SeverelyErroredSecond.VALUE);
232         } else {
233             for (Class<? extends PerformanceMeasurementTypeId> obj : setMeasurementTypeId()) {
234                 if (obj.toString().contains(pmType.name())) {
235                     measBuilder.setPmKey(YangToolsMapperHelper.getIdentityValueFromClass(obj) );
236                 }
237             }
238         }
239         measBuilder.setPmUnit(setMeasurementUnit(pmUnit));
240         measBuilder.setPmValue(pmDataType);
241         return measBuilder.build();
242
243     }
244
245     private Class<?> loadClass(Bundle bundle, String classFilePath) {
246         String className = classFilePath.replaceFirst("^/", "").replace('/', '.').replaceFirst(".class$", "");
247         try {
248             return bundle.loadClass(className);
249         } catch (Exception e) {
250             log.debug(String.format("Class [%s] could not be loaded. Message: [%s].", className, e.getMessage()));
251         }
252         return null;
253     }
254
255     private static Enumeration<URL> getFileURL(Bundle b, String classPath) {
256
257         BundleContext context = b == null ? null : b.getBundleContext();
258         if (context == null) {
259             log.debug("no bundle context available");
260             return null;
261         }
262         Bundle[] bundles = context.getBundles();
263         if (bundles == null || bundles.length <= 0) {
264             log.debug("no bundles found");
265             return null;
266         }
267         log.debug("found {} bundles", bundles.length);
268         Enumeration<URL> resultUrl = null;
269
270         for (Bundle bundle : bundles) {
271             resultUrl = bundle.findEntries("/" + classPath.replace(".", "/"), "*.class", false);
272             if (resultUrl != null) {
273                 break;
274
275             }
276
277         }
278
279         return resultUrl;
280     }
281
282
283     // end of private methods
284 }
285