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