Port champ-microservice project restructure
[aai/champ.git] / champ-service / src / main / java / org / onap / champ / service / ChampTransactionCache.java
1
2 package org.onap.champ.service;
3
4 import java.util.concurrent.TimeUnit;
5
6 import org.onap.aai.champcore.ChampGraph;
7 import org.onap.aai.champcore.ChampTransaction;
8 import org.onap.aai.champcore.exceptions.ChampTransactionException;
9 import org.onap.champ.service.logging.ChampMsgs;
10 import org.onap.aai.cl.api.Logger;
11 import org.onap.aai.cl.eelf.LoggerFactory;
12
13 import com.google.common.cache.Cache;
14 import com.google.common.cache.CacheBuilder;
15 import com.google.common.cache.RemovalCause;
16 import com.google.common.cache.RemovalListener;
17 import com.google.common.cache.RemovalNotification;
18
19 /**
20  * Self expiring Cache to hold request transactionIds . Events are expired
21  * automatically after configured interval
22  */
23 public class ChampTransactionCache {
24   private static Logger logger = LoggerFactory.getInstance().getLogger(ChampTransactionCache
25       .class.getName());
26
27   
28   private ChampGraph graphImpl;
29   private Cache<String, ChampTransaction> cache;
30
31
32
33   public ChampTransactionCache(long txTimeOutInSec,ChampGraph graphImpl) {
34     CacheBuilder builder = CacheBuilder.newBuilder().expireAfterWrite(txTimeOutInSec, TimeUnit.SECONDS)
35         .removalListener(new RemovalListener() {
36
37           public void onRemoval(RemovalNotification notification) {
38             if(notification.getCause()==RemovalCause.EXPIRED){
39             logger.info(ChampMsgs.CHAMP_TX_CACHE, "Following transaction: "+notification.getKey()+" is being evicted from cache due to timeout of " + txTimeOutInSec+" seconds");
40             try {
41               graphImpl.rollbackTransaction((ChampTransaction) notification.getValue());
42               logger.info(ChampMsgs.CHAMP_TX_CACHE, "Transaction rolledback successfully :" + notification.getKey());
43             } catch (ChampTransactionException e) {
44               // TODO Auto-generated catch block
45               e.printStackTrace();
46             }
47             }
48           }
49         });
50     cache = builder.build();
51
52     this.graphImpl = graphImpl;
53     
54   }
55
56   public  void put(String txId, ChampTransaction tx) {
57     cache.put(txId, tx);
58
59   }
60
61   public  ChampTransaction get(String txId) {
62     if (txId==null)
63       return null;
64     if(cache.getIfPresent(txId)==null){
65       //cleanup cache so that removalListener is called
66       cache.cleanUp();
67     }
68     return cache.getIfPresent(txId);
69   }
70
71   public  void invalidate(String txId) {
72     cache.invalidate(txId);
73   }
74   
75
76
77 }