Some changes in status notifications
[nonrtric.git] / enrichment-coordinator-service / src / main / java / org / oransc / enrichment / repository / EiJobs.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 existing EI jobs.
49  */
50 public class EiJobs {
51     private Map<String, EiJob> allEiJobs = new HashMap<>();
52
53     private MultiMap<EiJob> jobsByType = new MultiMap<>();
54     private MultiMap<EiJob> jobsByOwner = new MultiMap<>();
55     private final Gson gson;
56
57     private final ApplicationConfig config;
58     private final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
59
60     public EiJobs(ApplicationConfig config) {
61         this.config = config;
62         GsonBuilder gsonBuilder = new GsonBuilder();
63         ServiceLoader.load(TypeAdapterFactory.class).forEach(gsonBuilder::registerTypeAdapterFactory);
64         this.gson = gsonBuilder.create();
65     }
66
67     public synchronized void restoreJobsFromDatabase() throws IOException {
68         Files.createDirectories(Paths.get(getDatabaseDirectory()));
69         File dbDir = new File(getDatabaseDirectory());
70
71         for (File file : dbDir.listFiles()) {
72             String json = Files.readString(file.toPath());
73             EiJob job = gson.fromJson(json, EiJob.class);
74             this.put(job, false);
75         }
76
77     }
78
79     public synchronized void put(EiJob job) {
80         this.put(job, true);
81     }
82
83     public synchronized Collection<EiJob> getJobs() {
84         return new Vector<>(allEiJobs.values());
85     }
86
87     public synchronized EiJob getJob(String id) throws ServiceException {
88         EiJob ric = allEiJobs.get(id);
89         if (ric == null) {
90             throw new ServiceException("Could not find EI job: " + id);
91         }
92         return ric;
93     }
94
95     public synchronized Collection<EiJob> getJobsForType(String typeId) {
96         return jobsByType.get(typeId);
97     }
98
99     public synchronized Collection<EiJob> getJobsForType(EiType type) {
100         return jobsByType.get(type.getId());
101     }
102
103     public synchronized Collection<EiJob> getJobsForOwner(String owner) {
104         return jobsByOwner.get(owner);
105     }
106
107     public synchronized EiJob get(String id) {
108         return allEiJobs.get(id);
109     }
110
111     public synchronized EiJob remove(String id) {
112         EiJob job = allEiJobs.get(id);
113         if (job != null) {
114             remove(job);
115         }
116         return job;
117     }
118
119     public synchronized void remove(EiJob job) {
120         this.allEiJobs.remove(job.getId());
121         jobsByType.remove(job.getTypeId(), job.getId());
122         jobsByOwner.remove(job.getOwner(), job.getId());
123
124         try {
125             Files.delete(getPath(job));
126         } catch (IOException e) {
127             logger.warn("Could not remove file: {}", e.getMessage());
128         }
129
130     }
131
132     public synchronized int size() {
133         return allEiJobs.size();
134     }
135
136     public synchronized void clear() {
137         this.allEiJobs.clear();
138         this.jobsByType.clear();
139         jobsByOwner.clear();
140         try {
141             FileSystemUtils.deleteRecursively(Path.of(getDatabaseDirectory()));
142             Files.createDirectories(Paths.get(getDatabaseDirectory()));
143         } catch (IOException e) {
144             logger.warn("Could not delete database : {}", e.getMessage());
145         }
146     }
147
148     private void put(EiJob job, boolean storePersistently) {
149         allEiJobs.put(job.getId(), job);
150         jobsByType.put(job.getTypeId(), job.getId(), job);
151         jobsByOwner.put(job.getOwner(), job.getId(), job);
152         if (storePersistently) {
153             storeJobInFile(job);
154         }
155     }
156
157     private void storeJobInFile(EiJob job) {
158         try {
159             try (PrintStream out = new PrintStream(new FileOutputStream(getFile(job)))) {
160                 out.print(gson.toJson(job));
161             }
162         } catch (Exception e) {
163             logger.warn("Could not save job: {} {}", job.getId(), e.getMessage());
164         }
165     }
166
167     private File getFile(EiJob job) {
168         return getPath(job).toFile();
169     }
170
171     private Path getPath(EiJob job) {
172         return Path.of(getDatabaseDirectory(), job.getId());
173     }
174
175     private String getDatabaseDirectory() {
176         return config.getVardataDirectory() + "/database";
177     }
178
179 }