ICS sample producer and consumer
[nonrtric.git] / sample-services / ics-producer-consumer / producer / src / main / java / com / demo / producer / repository / Jobs.java
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  *
5  * Copyright (C) 2024: OpenInfra Foundation Europe
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 com.demo.producer.repository;
22
23 import java.util.HashMap;
24 import java.util.Map;
25 import java.util.Vector;
26
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
29 import org.springframework.stereotype.Component;
30
31 import com.demo.producer.repository.Job.Parameters;
32 import com.google.gson.Gson;
33 import com.google.gson.GsonBuilder;
34
35 @Component
36 public class Jobs {
37     private static final Logger logger = LoggerFactory.getLogger(Jobs.class);
38
39     private Map<String, Job> allJobs = new HashMap<>();
40
41     public Jobs() {
42     }
43
44     public synchronized Job getJob(String id) throws Exception {
45         Job job = allJobs.get(id);
46         if (job == null) {
47             throw new Exception("Could not find job: " + id);
48         }
49         return job;
50     }
51
52     public synchronized Job get(String id) {
53         return allJobs.get(id);
54     }
55
56     public void addJob(String id, InfoType type, String owner, Parameters parameters) {
57         Job job = new Job(id, type, owner, parameters);
58         this.put(job);
59     }
60
61     private synchronized void put(Job job) {
62         logger.debug("Put job: {}", job.getId());
63         allJobs.put(job.getId(), job);
64     }
65
66     public synchronized Iterable<Job> getAll() {
67         return new Vector<>(allJobs.values());
68     }
69
70     public synchronized int size() {
71         return allJobs.size();
72     }
73
74     public synchronized Job delete(String id) {
75         return allJobs.remove(id);
76     }
77
78     @Override
79     public String toString() {
80         Gson gson = new GsonBuilder().create();
81         return gson.toJson(allJobs);
82     }
83 }