Added unit tests fo MappingRulesValidator
[sdc/dcae-d/dt-be-main.git] / dcaedt_be / src / main / java / org / onap / sdc / dcae / ves / VesStructureLoader.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
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 package org.onap.sdc.dcae.ves;
22
23 import com.google.gson.Gson;
24 import com.google.gson.GsonBuilder;
25 import com.google.gson.JsonIOException;
26 import com.google.gson.JsonSyntaxException;
27 import com.google.gson.reflect.TypeToken;
28 import org.apache.commons.lang.ArrayUtils;
29 import org.apache.commons.lang.StringUtils;
30 import org.onap.sdc.common.onaplog.OnapLoggerDebug;
31 import org.onap.sdc.common.onaplog.OnapLoggerError;
32 import org.onap.sdc.common.onaplog.enums.LogLevel;
33 import org.springframework.stereotype.Service;
34
35 import javax.annotation.PostConstruct;
36 import javax.annotation.PreDestroy;
37 import java.io.*;
38 import java.lang.reflect.Type;
39 import java.util.HashMap;
40 import java.util.Map;
41 import java.util.Set;
42 import java.util.stream.Collectors;
43
44 @Service("vesstructureloader")
45 public class VesStructureLoader {
46
47
48
49     private static OnapLoggerError errLogger = OnapLoggerError.getInstance();
50     private static OnapLoggerDebug debugLogger = OnapLoggerDebug.getInstance();
51
52     private static Map<String, EventListenerDefinition> eventListeners = new HashMap<>();
53     private static final Type type = new TypeToken<VesDataItemsDefinition>(){}.getType();
54     private static final Gson gson = new GsonBuilder().registerTypeAdapter(type, new VesJsonDeserializer()).create();
55     private static final String SCHEMA_NAME_PREFIX = "CommonEventFormat_v";
56     private static final String SCHEMA_NAME_SUFFIX = ".json";
57
58     private VesStructureLoader() {
59     }
60
61     @PostConstruct
62     public void init() {
63
64         debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "VesStructureLoader: Trying to load json schemas");
65         String jettyBase = System.getProperty("jetty.base");
66         if (jettyBase == null) {
67             String msg = "Couldn't resolve jetty.base environmental variable";
68             errLogger.log(LogLevel.ERROR, this.getClass().getName(), msg);
69             throw new IllegalArgumentException(msg + ". Failed to load VES schema files... aborting");
70         }
71         debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "jetty.base={}", jettyBase);
72
73         File dir = new File(jettyBase + "/config/dcae-be/ves-schema");
74         File[] files = dir.listFiles((dir1, name) -> name.startsWith(SCHEMA_NAME_PREFIX) && name.endsWith(SCHEMA_NAME_SUFFIX));
75
76         if (ArrayUtils.isEmpty(files)) {
77             errLogger.log(LogLevel.ERROR, this.getClass().getName(), "Error – Failed to find VES Schema definitions.");
78         } else {
79
80             for (File f : files) {
81                 debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Loading VES schema file: {}", f.getName());
82                 parseJsonFileAndSaveToMap(f);
83             }
84         }
85
86     }
87
88     private void parseJsonFileAndSaveToMap(File file) {
89
90         try {
91             EventListenerDefinition eventListener = gson.fromJson(new FileReader(file), EventListenerDefinition.class);
92             debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), gson.toJson(eventListener));
93             String validationError = getValidatorMessage(eventListener);
94             if (StringUtils.isEmpty(validationError)) {
95                 eventListeners.put(getVersionFromFileName(file.getName()), eventListener);
96             } else {
97                 errLogger.log(LogLevel.ERROR, this.getClass().getName(), "Error: Failed to parse VES schema file {}. [{}]", file.getName(), validationError);
98             }
99         } catch (FileNotFoundException | JsonIOException | JsonSyntaxException e) {
100             errLogger.log(LogLevel.ERROR, this.getClass().getName(), "Error: Failed to parse VES schema file {}. [{}]", file.getName(), e);
101         }
102     }
103
104     public static Map<String, VesDataTypeDefinition> getEventListenerDefinitionByVersion(String version) {
105         return eventListeners.get(version).getProperties().get(EventListenerDefinition.EVENT_ROOT).getProperties();
106     }
107
108     public static Set<String> getAvailableVersionsList() {
109         return eventListeners.keySet();
110     }
111
112     public static Map<String, Set<String>> getAvailableVersionsAndEventTypes() {
113         return eventListeners.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> getEventListenerDefinitionByVersion(e.getKey()).keySet()));
114     }
115
116     public static Set<String> getEventTypeListByVersion(String version) {
117         return getEventListenerDefinitionByVersion(version).keySet();
118     }
119
120     private String getValidatorMessage(EventListenerDefinition eventListenerDefinition) {
121         String validationError = eventListenerDefinition.validate();
122         if (StringUtils.isBlank(validationError)) {
123             validationError = eventListenerDefinition.resolveRefTypes();
124         }
125         return validationError;
126     }
127
128     private String getVersionFromFileName(String fileName) {
129         return fileName.replace(SCHEMA_NAME_PREFIX, "").replace(SCHEMA_NAME_SUFFIX, "");
130     }
131
132     @PreDestroy
133     public void preDestroy() {
134         // why is this method empty?
135     }
136 }