53dc55db887ede1413700058b56a282b94f3694d
[ccsdk/oran.git] /
1 /*-
2  * ========================LICENSE_START=================================
3  * ONAP : ccsdk oran
4  * ======================================================================
5  * Copyright (C) 2019-2020 Nordix Foundation. 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.ccsdk.oran.a1policymanagementservice.repository;
22
23 import com.google.gson.Gson;
24 import com.google.gson.GsonBuilder;
25
26 import java.io.File;
27 import java.io.FileOutputStream;
28 import java.io.IOException;
29 import java.io.PrintStream;
30 import java.lang.invoke.MethodHandles;
31 import java.nio.file.Files;
32 import java.nio.file.Path;
33 import java.util.ArrayList;
34 import java.util.Collection;
35 import java.util.HashMap;
36 import java.util.Map;
37 import java.util.Vector;
38
39 import org.jetbrains.annotations.Nullable;
40 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ApplicationConfig;
41 import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.EntityNotFoundException;
42 import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.ServiceException;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45 import org.springframework.beans.factory.annotation.Autowired;
46 import org.springframework.context.annotation.Configuration;
47 import org.springframework.util.FileSystemUtils;
48
49 @Configuration
50 public class PolicyTypes {
51     private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
52     private Map<String, PolicyType> types = new HashMap<>();
53     private final ApplicationConfig appConfig;
54     private static Gson gson = new GsonBuilder().create();
55
56     public PolicyTypes(@Autowired ApplicationConfig appConfig) {
57         this.appConfig = appConfig;
58         restoreFromDatabase();
59     }
60
61     public synchronized PolicyType getType(String name) throws EntityNotFoundException {
62         PolicyType t = types.get(name);
63         if (t == null) {
64             throw new EntityNotFoundException("Could not find type: " + name);
65         }
66         return t;
67     }
68
69     public synchronized PolicyType get(String name) {
70         return types.get(name);
71     }
72
73     public synchronized void put(PolicyType type) {
74         types.put(type.getId(), type);
75         store(type);
76     }
77
78     public synchronized boolean contains(String policyType) {
79         return types.containsKey(policyType);
80     }
81
82     public synchronized Collection<PolicyType> getAll() {
83         return new Vector<>(types.values());
84     }
85
86     /**
87      * Filter out types matching criterias
88      *
89      * @param types the types to select from
90      * @param typeName select types with given type name
91      * @param compatibleWithVersion select types that are compatible with given
92      *        version string (major.minor.patch)
93      * @return the types that matches given criterias
94      * @throws ServiceException if there are errors in the given input
95      */
96     public static Collection<PolicyType> filterTypes(Collection<PolicyType> types, @Nullable String typeName,
97             @Nullable String compatibleWithVersion) throws ServiceException {
98         if (typeName != null) {
99             types = filterTypeName(types, typeName);
100         }
101         if (compatibleWithVersion != null) {
102             types = filterCompatibleWithVersion(types, compatibleWithVersion);
103         }
104         return types;
105     }
106
107     public synchronized int size() {
108         return types.size();
109     }
110
111     public synchronized void clear() {
112         this.types.clear();
113         try {
114             FileSystemUtils.deleteRecursively(getDatabasePath());
115         } catch (IOException | ServiceException e) {
116             logger.warn("Could not delete policy type database : {}", e.getMessage());
117         }
118     }
119
120     public void store(PolicyType type) {
121         try {
122             Files.createDirectories(getDatabasePath());
123             try (PrintStream out = new PrintStream(new FileOutputStream(getFile(type)))) {
124                 out.print(gson.toJson(type));
125             }
126         } catch (ServiceException e) {
127             logger.debug("Could not store policy type: {} {}", type.getId(), e.getMessage());
128         } catch (IOException e) {
129             logger.warn("Could not store policy type: {} {}", type.getId(), e.getMessage());
130         }
131     }
132
133     private File getFile(PolicyType type) throws ServiceException {
134         return Path.of(getDatabaseDirectory(), type.getId() + ".json").toFile();
135     }
136
137     void restoreFromDatabase() {
138         try {
139             Files.createDirectories(getDatabasePath());
140             for (File file : getDatabasePath().toFile().listFiles()) {
141                 String json = Files.readString(file.toPath());
142                 PolicyType type = gson.fromJson(json, PolicyType.class);
143                 this.types.put(type.getId(), type);
144             }
145             logger.debug("Restored type database,no of types: {}", this.types.size());
146         } catch (ServiceException e) {
147             logger.debug("Could not restore policy type database : {}", e.getMessage());
148         } catch (Exception e) {
149             logger.warn("Could not restore policy type database : {}", e.getMessage());
150         }
151     }
152
153     private String getDatabaseDirectory() throws ServiceException {
154         if (appConfig.getVardataDirectory() == null) {
155             throw new ServiceException("No policy type storage provided");
156         }
157         return appConfig.getVardataDirectory() + "/database/policyTypes";
158     }
159
160     private Path getDatabasePath() throws ServiceException {
161         return Path.of(getDatabaseDirectory());
162     }
163
164     private static Collection<PolicyType> filterTypeName(Collection<PolicyType> types, String typeName) {
165         Collection<PolicyType> result = new ArrayList<>();
166         for (PolicyType type : types) {
167             PolicyType.TypeId nameVersion = type.getTypeId();
168             if (nameVersion.getName().equals(typeName)) {
169                 result.add(type);
170             }
171         }
172         return result;
173     }
174
175     private static boolean isTypeCompatibleWithVersion(PolicyType type, PolicyType.Version version) {
176         try {
177             PolicyType.TypeId typeId = type.getTypeId();
178             PolicyType.Version typeVersion = PolicyType.Version.ofString(typeId.getVersion());
179             return (typeVersion.major == version.major && typeVersion.minor >= version.minor);
180         } catch (Exception e) {
181             logger.warn("Ignoring type with syntactically incorrect type ID: {}", type.getId());
182             return false;
183         }
184     }
185
186     private static Collection<PolicyType> filterCompatibleWithVersion(Collection<PolicyType> types, String versionStr)
187             throws ServiceException {
188         Collection<PolicyType> result = new ArrayList<>();
189         PolicyType.Version otherVersion = PolicyType.Version.ofString(versionStr);
190         for (PolicyType type : types) {
191             if (isTypeCompatibleWithVersion(type, otherVersion)) {
192                 result.add(type);
193             }
194         }
195         return result;
196     }
197
198 }