738d3b922bbefec65875d20716541646e46de32b
[policy/drools-applications.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2019 AT&T Intellectual Property. 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.policy.controlloop.eventmanager;
22
23 import lombok.Getter;
24 import org.drools.core.WorkingMemory;
25 import org.kie.api.runtime.rule.FactHandle;
26 import org.onap.policy.drools.core.lock.Lock;
27 import org.onap.policy.drools.core.lock.LockCallback;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30
31 /**
32  * Lock call-back that updates working memory.
33  */
34 @Getter
35 public class LockCallbackWorkingMemory implements LockCallback {
36     private static final Logger logger = LoggerFactory.getLogger(LockCallbackWorkingMemory.class);
37
38     /**
39      * Name to be logged when the lock is updated.
40      */
41     private final String name;
42
43     /**
44      * Working memory to be updated when the lock is notified.
45      */
46     private final WorkingMemory workingMemory;
47
48
49     /**
50      * Constructs the object.
51      *
52      * @param name name to be logged when the lock is updated
53      * @param workingMemory working memory to be updated when the lock is notified
54      */
55     public LockCallbackWorkingMemory(String name, WorkingMemory workingMemory) {
56         this.name = name;
57         this.workingMemory = workingMemory;
58     }
59
60     @Override
61     public void lockAvailable(Lock lock) {
62         notifySession(lock);
63     }
64
65     @Override
66     public void lockUnavailable(Lock lock) {
67         notifySession(lock);
68     }
69
70     /**
71      * Notifies the session that the lock has been updated.
72      */
73     private void notifySession(Lock lock) {
74         FactHandle fact = workingMemory.getFactHandle(lock);
75         if (fact != null) {
76             logger.debug("{}: updating lock={}", name, lock);
77             workingMemory.update(fact, lock);
78         }
79     }
80 }