NONRTRIC - ECS Persistent storage of EI Jobs
[nonrtric.git] / enrichment-coordinator-service / src / main / java / org / oransc / enrichment / repository / InfoTypes.java
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  * %%
5  * Copyright (C) 2019 Nordix Foundation
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.oransc.enrichment.repository;
22
23 import com.google.gson.Gson;
24 import com.google.gson.GsonBuilder;
25 import com.google.gson.TypeAdapterFactory;
26
27 import java.io.File;
28 import java.io.FileOutputStream;
29 import java.io.IOException;
30 import java.io.PrintStream;
31 import java.lang.invoke.MethodHandles;
32 import java.nio.file.Files;
33 import java.nio.file.Path;
34 import java.nio.file.Paths;
35 import java.util.Collection;
36 import java.util.HashMap;
37 import java.util.Map;
38 import java.util.ServiceLoader;
39 import java.util.Vector;
40
41 import org.oransc.enrichment.configuration.ApplicationConfig;
42 import org.oransc.enrichment.exceptions.ServiceException;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45 import org.springframework.util.FileSystemUtils;
46
47 /**
48  * Dynamic representation of all Information Types in the system.
49  */
50 @SuppressWarnings("squid:S2629") // Invoke method(s) only conditionally
51 public class InfoTypes {
52     private final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
53     private final Map<String, InfoType> allEiTypes = new HashMap<>();
54     private final ApplicationConfig config;
55     private final Gson gson;
56
57     public InfoTypes(ApplicationConfig config) {
58         this.config = config;
59         GsonBuilder gsonBuilder = new GsonBuilder();
60         ServiceLoader.load(TypeAdapterFactory.class).forEach(gsonBuilder::registerTypeAdapterFactory);
61         this.gson = gsonBuilder.create();
62     }
63
64     public synchronized void restoreTypesFromDatabase() throws IOException {
65         Files.createDirectories(Paths.get(getDatabaseDirectory()));
66         File dbDir = new File(getDatabaseDirectory());
67
68         for (File file : dbDir.listFiles()) {
69             String json = Files.readString(file.toPath());
70             InfoType type = gson.fromJson(json, InfoType.class);
71             allEiTypes.put(type.getId(), type);
72         }
73     }
74
75     public synchronized void put(InfoType type) {
76         allEiTypes.put(type.getId(), type);
77         storeInFile(type);
78     }
79
80     public synchronized Collection<InfoType> getAllInfoTypes() {
81         return new Vector<>(allEiTypes.values());
82     }
83
84     public synchronized InfoType getType(String id) throws ServiceException {
85         InfoType type = allEiTypes.get(id);
86         if (type == null) {
87             throw new ServiceException("Information type not found: " + id);
88         }
89         return type;
90     }
91
92     public synchronized InfoType get(String id) {
93         return allEiTypes.get(id);
94     }
95
96     public synchronized void remove(InfoType type) {
97         allEiTypes.remove(type.getId());
98         try {
99             Files.delete(getPath(type));
100         } catch (IOException e) {
101             logger.warn("Could not remove file: {} {}", type.getId(), e.getMessage());
102         }
103     }
104
105     public synchronized int size() {
106         return allEiTypes.size();
107     }
108
109     public synchronized void clear() {
110         this.allEiTypes.clear();
111         clearDatabase();
112     }
113
114     private void clearDatabase() {
115         try {
116             FileSystemUtils.deleteRecursively(Path.of(getDatabaseDirectory()));
117             Files.createDirectories(Paths.get(getDatabaseDirectory()));
118         } catch (IOException e) {
119             logger.warn("Could not delete database : {}", e.getMessage());
120         }
121     }
122
123     private void storeInFile(InfoType type) {
124         try {
125             try (PrintStream out = new PrintStream(new FileOutputStream(getFile(type)))) {
126                 out.print(gson.toJson(type));
127             }
128         } catch (Exception e) {
129             logger.warn("Could not save job: {} {}", type.getId(), e.getMessage());
130         }
131     }
132
133     private File getFile(InfoType type) {
134         return getPath(type).toFile();
135     }
136
137     private Path getPath(InfoType type) {
138         return getPath(type.getId());
139     }
140
141     private Path getPath(String typeId) {
142         return Path.of(getDatabaseDirectory(), typeId);
143     }
144
145     private String getDatabaseDirectory() {
146         return config.getVardataDirectory() + "/database/eitypes";
147     }
148 }