Sonar/Checkstyle in model/context/core
[policy/apex-pdp.git] / context / context-management / src / main / java / org / onap / policy / apex / context / impl / distribution / AbstractDistributor.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.apex.context.impl.distribution;
22
23 import java.util.Collections;
24 import java.util.HashMap;
25 import java.util.Map;
26 import java.util.Map.Entry;
27
28 import org.onap.policy.apex.context.ContextAlbum;
29 import org.onap.policy.apex.context.ContextException;
30 import org.onap.policy.apex.context.Distributor;
31 import org.onap.policy.apex.context.LockManager;
32 import org.onap.policy.apex.context.Persistor;
33 import org.onap.policy.apex.context.impl.ContextAlbumImpl;
34 import org.onap.policy.apex.context.impl.locking.LockManagerFactory;
35 import org.onap.policy.apex.context.impl.persistence.PersistorFactory;
36 import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
37 import org.onap.policy.apex.model.basicmodel.concepts.AxKeyInformation;
38 import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult;
39 import org.onap.policy.apex.model.basicmodel.service.ModelService;
40 import org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbum;
41 import org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbums;
42 import org.onap.policy.apex.model.contextmodel.concepts.AxContextModel;
43 import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchema;
44 import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchemas;
45 import org.slf4j.ext.XLogger;
46 import org.slf4j.ext.XLoggerFactory;
47
48 /**
49  * This context distributor implements the mechanism-neutral parts of a context distributor.
50  *
51  * @author Liam Fallon (liam.fallon@ericsson.com)
52  */
53 public abstract class AbstractDistributor implements Distributor {
54
55     // Logger for this class
56     private static final XLogger LOGGER = XLoggerFactory.getXLogger(AbstractDistributor.class);
57
58     // The key of this distributor
59     private AxArtifactKey key = null;
60
61     // The context albums for this context set indexed by their keys
62     private static Map<AxArtifactKey, ContextAlbum> albumMaps =
63             Collections.synchronizedMap(new HashMap<AxArtifactKey, ContextAlbum>());
64
65     // Lock manager for this distributor
66     private static LockManager lockManager = null;
67
68     // Hold a persistor for this distributor
69     private Persistor persistor = null;
70
71     // Hold a flush timer for this context distributor
72     private static DistributorFlushTimerTask flushTimer = null;
73
74     /**
75      * Create an instance of an abstract Context Distributor.
76      */
77     public AbstractDistributor() {
78         LOGGER.entry("AbstractContextDistributor()");
79         LOGGER.exit("AbstractContextDistributor()");
80     }
81
82     /*
83      * (non-Javadoc)
84      *
85      * @see org.onap.policy.apex.context.ContextDistributor#init(org.onap.policy.apex.model.basicmodel.concepts.
86      * AxArtifactKey)
87      */
88     @Override
89     public void init(final AxArtifactKey distributorKey) throws ContextException {
90         LOGGER.entry("init(" + distributorKey + ")");
91
92         // Record parameters and key
93         this.key = distributorKey;
94
95         // Create the lock manager if it doesn't already exist
96         if (lockManager == null) {
97             setLockManager(new LockManagerFactory().createLockManager(key));
98         }
99
100         // Set up flushing on the context distributor if its not set up already
101         if (flushTimer == null) {
102             setFlushTimer(new DistributorFlushTimerTask(this));
103         }
104
105         // Create a new persistor for this key
106         persistor = new PersistorFactory().createPersistor(key);
107         LOGGER.exit("init(" + key + ")");
108     }
109
110     /**
111      * Set the static lock manager
112      * @param incomingLockManager the lock manager value
113      */
114     private static void setLockManager(final LockManager incomingLockManager) {
115         lockManager = incomingLockManager;
116     }
117
118     /**
119      * Set the static flush timer
120      * @param incomingFlushTimer the flush timer value
121      */
122     private static void setFlushTimer(final DistributorFlushTimerTask incomingFlushTimer) {
123         flushTimer = incomingFlushTimer;
124     }
125
126     /*
127      * (non-Javadoc)
128      *
129      * @see org.onap.policy.apex.context.ContextDistributor#shutdown()
130      */
131     @Override
132     public abstract void shutdown();
133
134     /*
135      * (non-Javadoc)
136      *
137      * @see org.onap.policy.apex.context.ContextDistributor#getKey()
138      */
139     @Override
140     public AxArtifactKey getKey() {
141         return key;
142     }
143
144     /**
145      * Create a context album using whatever underlying mechanism we are using for albums.
146      *
147      * @param contextAlbumKey The key of the album
148      * @return The album as a string-object map
149      */
150     public abstract Map<String, Object> getContextAlbumMap(AxArtifactKey contextAlbumKey);
151
152
153     /*
154      * (non-Javadoc)
155      *
156      * @see org.onap.policy.apex.context.Distributor#registerModel(org.onap.policy.apex.model.contextmodel.concepts.
157      * AxContextModel)
158      */
159     @Override
160     public void registerModel(final AxContextModel contextModel) throws ContextException {
161         ModelService.registerModel(AxKeyInformation.class, contextModel.getKeyInformation());
162         ModelService.registerModel(AxContextSchemas.class, contextModel.getSchemas());
163         ModelService.registerModel(AxContextAlbums.class, contextModel.getAlbums());
164     }
165
166     /*
167      * (non-Javadoc)
168      *
169      * @see
170      * org.onap.policy.apex.core.context.ContextDistributor#createContextAlbum(org.onap.policy.apex.core.basicmodel.
171      * concepts. AxArtifactKey)
172      */
173     @Override
174     public synchronized ContextAlbum createContextAlbum(final AxArtifactKey axContextAlbumKey) throws ContextException {
175         // Get the context album definition
176         final AxContextAlbum album = ModelService.getModel(AxContextAlbums.class).get(axContextAlbumKey);
177         if (album == null) {
178             final String resultString = "context album " + axContextAlbumKey.getId() + " does not exist";
179             LOGGER.warn(resultString);
180             throw new ContextException(resultString);
181         }
182
183         // Check if the context album is valid
184         final AxValidationResult result = album.validate(new AxValidationResult());
185         if (!result.isValid()) {
186             final String resultString =
187                     "context album definition for " + album.getKey().getId() + " is invalid" + result;
188             LOGGER.warn(resultString);
189             throw new ContextException(resultString);
190         }
191
192         // Get the schema of the context album
193         final AxContextSchema schema = ModelService.getModel(AxContextSchemas.class).get(album.getItemSchema());
194         if (schema == null) {
195             final String resultString = "schema \"" + album.getItemSchema().getId() + "\" for context album "
196                     + album.getKey().getId() + " does not exist";
197             LOGGER.warn(resultString);
198             throw new ContextException(resultString);
199         }
200
201         // Check if the map has already been instantiated
202         if (!albumMaps.containsKey(album.getKey())) {
203             // Instantiate the album map for this context album that we'll distribute using the distribution mechanism
204             final Map<String, Object> newContextAlbumMap = getContextAlbumMap(album.getKey());
205
206             // The distributed context album will have content from another process instance if the album exists in
207             // another process,
208             // if not, we have to try to read the content from persistence
209             if (newContextAlbumMap.isEmpty()) {
210                 // Read entries from persistence, (Not implemented yet)
211             }
212
213             // Create the context album and put the context album object onto the distributor
214             albumMaps.put(album.getKey(), new ContextAlbumImpl(album, this, newContextAlbumMap));
215         }
216
217         return albumMaps.get(album.getKey());
218     }
219
220     /*
221      * (non-Javadoc)
222      *
223      * @see
224      * org.onap.policy.apex.core.context.ContextDistributor#removeContextAlbum(org.onap.policy.apex.core.basicmodel.
225      * concepts. AxArtifactKey)
226      */
227     @Override
228     public void removeContextAlbum(final AxContextAlbum contextAlbum) throws ContextException {
229         // Check if the map already exists, if not return
230         if (!albumMaps.containsKey(contextAlbum.getKey())) {
231             LOGGER.warn("map remove failed, supplied map is null");
232             throw new ContextException("map update failed, supplied map is null");
233         }
234
235         // Remove the map from the distributor
236         albumMaps.remove(contextAlbum.getKey());
237     }
238
239     /*
240      * (non-Javadoc)
241      *
242      * @see org.onap.policy.apex.core.context.ContextDistributor#flush()
243      */
244     @Override
245     public void flush() throws ContextException {
246         // Flush all the maps
247         for (final Entry<AxArtifactKey, ContextAlbum> distributorMapEntry : albumMaps.entrySet()) {
248             // Let the persistor write each of the entries
249             for (final Object contextItem : distributorMapEntry.getValue().values()) {
250                 persistor.writeContextItem((AxContextSchema) contextItem);
251             }
252         }
253     }
254
255     /*
256      * (non-Javadoc)
257      *
258      * @see org.onap.policy.apex.core.context.ContextDistributor#flushContextAlbum(org.onap.policy.apex.core.context.
259      * ContextAlbum)
260      */
261     @Override
262     public void flushContextAlbum(final ContextAlbum contextAlbum) throws ContextException {
263         // Check if the map already exists, if not return
264         if (!albumMaps.containsKey(contextAlbum.getKey())) {
265             LOGGER.warn("map flush failed, supplied map is null");
266             throw new ContextException("map flush failed, supplied map is null");
267         }
268
269         // Let the persistor flush the items on the map
270         for (final Object contextItem : albumMaps.get(contextAlbum.getKey()).values()) {
271             persistor.writeContextItem(contextItem);
272         }
273     }
274
275     /*
276      * (non-Javadoc)
277      *
278      * @see org.onap.policy.apex.core.context.ContextDistributor#lockForReading(java.lang.String)
279      */
280     @Override
281     public synchronized void lockForReading(final AxArtifactKey mapKey, final String itemKey) throws ContextException {
282         // Lock using the lock manager
283         lockManager.lockForReading(mapKey.getId(), itemKey);
284     }
285
286     /*
287      * (non-Javadoc)
288      *
289      * @see org.onap.policy.apex.core.context.ContextDistributor#lockForWriting(java.lang.String)
290      */
291     @Override
292     public synchronized void lockForWriting(final AxArtifactKey mapKey, final String itemKey) throws ContextException {
293         // Lock using the lock manager
294         lockManager.lockForWriting(mapKey.getId(), itemKey);
295     }
296
297     /*
298      * (non-Javadoc)
299      *
300      * @see org.onap.policy.apex.core.context.ContextDistributor#unlockForReading(java.lang.String)
301      */
302     @Override
303     public void unlockForReading(final AxArtifactKey mapKey, final String itemKey) throws ContextException {
304         // Unlock using the lock manager
305         lockManager.unlockForReading(mapKey.getId(), itemKey);
306     }
307
308     /*
309      * (non-Javadoc)
310      *
311      * @see org.onap.policy.apex.core.context.ContextDistributor#unlockForWriting(java.lang.String)
312      */
313     @Override
314     public void unlockForWriting(final AxArtifactKey mapKey, final String itemKey) throws ContextException {
315         // Unlock using the lock manager
316         lockManager.unlockForWriting(mapKey.getId(), itemKey);
317     }
318
319     /*
320      * (non-Javadoc)
321      *
322      * @see org.onap.policy.apex.core.context.ContextDistributor#clear()
323      */
324     @Override
325     public void clear() {
326         // Shut down the lock manager
327         if (lockManager != null) {
328             lockManager.shutdown();
329             setLockManager(null);
330         }
331
332         albumMaps.clear();
333
334         // Turn off the flush timer
335         flushTimer.cancel();
336
337         // Shut down the specialization of the context distributor
338         shutdown();
339     }
340 }