[AAF-21] Updated Copyright Headers for AAF
[aaf/authz.git] / authz-core / src / main / java / com / att / cache / Cache.java
1 /*******************************************************************************\r
2  * ============LICENSE_START====================================================\r
3  * * org.onap.aaf\r
4  * * ===========================================================================\r
5  * * Copyright © 2017 AT&T Intellectual Property. All rights reserved.\r
6  * * ===========================================================================\r
7  * * Licensed under the Apache License, Version 2.0 (the "License");\r
8  * * you may not use this file except in compliance with the License.\r
9  * * You may obtain a copy of the License at\r
10  * * \r
11  *  *      http://www.apache.org/licenses/LICENSE-2.0\r
12  * * \r
13  *  * Unless required by applicable law or agreed to in writing, software\r
14  * * distributed under the License is distributed on an "AS IS" BASIS,\r
15  * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
16  * * See the License for the specific language governing permissions and\r
17  * * limitations under the License.\r
18  * * ============LICENSE_END====================================================\r
19  * *\r
20  * * ECOMP is a trademark and service mark of AT&T Intellectual Property.\r
21  * *\r
22  ******************************************************************************/\r
23 package com.att.cache;\r
24 \r
25 import java.util.ArrayList;\r
26 import java.util.Date;\r
27 import java.util.HashMap;\r
28 import java.util.HashSet;\r
29 import java.util.List;\r
30 import java.util.Map;\r
31 import java.util.Set;\r
32 import java.util.Timer;\r
33 import java.util.TimerTask;\r
34 import java.util.concurrent.ConcurrentHashMap;\r
35 import java.util.logging.Level;\r
36 \r
37 import com.att.inno.env.Env;\r
38 import com.att.inno.env.Trans;\r
39 \r
40 /**\r
41  * Create and maintain a Map of Maps used for Caching\r
42  * \r
43  *\r
44  * @param <TRANS>\r
45  * @param <DATA>\r
46  */\r
47 public class Cache<TRANS extends Trans, DATA> {\r
48         private static Clean clean;\r
49         private static Timer cleanseTimer;\r
50 \r
51         public static final String CACHE_HIGH_COUNT = "CACHE_HIGH_COUNT";\r
52         public static final String CACHE_CLEAN_INTERVAL = "CACHE_CLEAN_INTERVAL";\r
53 //      public static final String CACHE_MIN_REFRESH_INTERVAL = "CACHE_MIN_REFRESH_INTERVAL";\r
54 \r
55         private static final Map<String,Map<String,Dated>> cacheMap;\r
56 \r
57         static {\r
58                 cacheMap = new HashMap<String,Map<String,Dated>>();\r
59         }\r
60 \r
61         /**\r
62          * Dated Class - store any Data with timestamp\r
63          * \r
64          *\r
65          */\r
66         public final static class Dated { \r
67                 public Date timestamp;\r
68                 public List<?> data;\r
69                 \r
70                 public Dated(List<?> data) {\r
71                         timestamp = new Date();\r
72                         this.data = data;\r
73                 }\r
74 \r
75                 public <T> Dated(T t) {\r
76                         timestamp = new Date();\r
77                         ArrayList<T> al = new ArrayList<T>(1);\r
78                         al.add(t);\r
79                         data = al;\r
80                 }\r
81 \r
82                 public void touch() {\r
83                         timestamp = new Date();\r
84                 }\r
85         }\r
86         \r
87         public static Map<String,Dated> obtain(String key) {\r
88                 Map<String, Dated> m = cacheMap.get(key);\r
89                 if(m==null) {\r
90                         m = new ConcurrentHashMap<String, Dated>();\r
91                         synchronized(cacheMap) {\r
92                                 cacheMap.put(key, m);\r
93                         }\r
94                 }\r
95                 return m;\r
96         }\r
97 \r
98         /**\r
99          * Clean will examine resources, and remove those that have expired.\r
100          * \r
101          * If "highs" have been exceeded, then we'll expire 10% more the next time.  This will adjust after each run\r
102          * without checking contents more than once, making a good average "high" in the minimum speed.\r
103          * \r
104          *\r
105          */\r
106         private final static class Clean extends TimerTask {\r
107                 private final Env env;\r
108                 private Set<String> set;\r
109                 \r
110                 // The idea here is to not be too restrictive on a high, but to Expire more items by \r
111                 // shortening the time to expire.  This is done by judiciously incrementing "advance"\r
112                 // when the "highs" are exceeded.  This effectively reduces numbers of cached items quickly.\r
113                 private final int high;\r
114                 private long advance;\r
115                 private final long timeInterval;\r
116                 \r
117                 public Clean(Env env, long cleanInterval, int highCount) {\r
118                         this.env = env;\r
119                         high = highCount;\r
120                         timeInterval = cleanInterval;\r
121                         advance = 0;\r
122                         set = new HashSet<String>();\r
123                 }\r
124                 \r
125                 public synchronized void add(String key) {\r
126                         set.add(key);\r
127                 }\r
128 \r
129                 public void run() {\r
130                         int count = 0;\r
131                         int total = 0;\r
132                         // look at now.  If we need to expire more by increasing "now" by "advance"\r
133                         Date now = new Date(System.currentTimeMillis() + advance);\r
134                         \r
135                         \r
136                         for(String name : set) {\r
137                                 Map<String,Dated> map = cacheMap.get(name);\r
138                                 if(map!=null) for(Map.Entry<String,Dated> me : map.entrySet()) {\r
139                                         ++total;\r
140                                         if(me.getValue().timestamp.before(now)) {\r
141                                                 map.remove(me.getKey());\r
142                                                 ++count;\r
143                                         }\r
144                                 }\r
145 //                              if(count>0) {\r
146 //                                      env.info().log(Level.INFO, "Cache removed",count,"expired",name,"Elements");\r
147 //                              }\r
148                         }\r
149                         \r
150                         if(count>0) {\r
151                                 env.info().log(Level.INFO, "Cache removed",count,"expired Cached Elements out of", total);\r
152                         }\r
153 \r
154                         // If High (total) is reached during this period, increase the number of expired services removed for next time.\r
155                         // There's no point doing it again here, as there should have been cleaned items.\r
156                         if(total>high) {\r
157                                 // advance cleanup by 10%, without getting greater than timeInterval.\r
158                                 advance = Math.min(timeInterval, advance+(timeInterval/10));\r
159                         } else {\r
160                                 // reduce advance by 10%, without getting lower than 0.\r
161                                 advance = Math.max(0, advance-(timeInterval/10));\r
162                         }\r
163                 }\r
164         }\r
165 \r
166         public static synchronized void startCleansing(Env env, String ... keys) {\r
167                 if(cleanseTimer==null) {\r
168                         cleanseTimer = new Timer("Cache Cleanup Timer");\r
169                         int cleanInterval = Integer.parseInt(env.getProperty(CACHE_CLEAN_INTERVAL,"60000")); // 1 minute clean cycles \r
170                         int highCount = Integer.parseInt(env.getProperty(CACHE_HIGH_COUNT,"5000"));\r
171                         cleanseTimer.schedule(clean = new Clean(env, cleanInterval, highCount), cleanInterval, cleanInterval);\r
172                 }\r
173                 \r
174                 for(String key : keys) {\r
175                         clean.add(key);\r
176                 }\r
177         }\r
178 \r
179         public static void stopTimer() {\r
180                 if(cleanseTimer!=null) {\r
181                         cleanseTimer.cancel();\r
182                         cleanseTimer = null;\r
183                 }\r
184         }\r
185 \r
186         public static void addShutdownHook() {\r
187                 Runtime.getRuntime().addShutdownHook(new Thread() {\r
188                         @Override\r
189                         public void run() {\r
190                                 Cache.stopTimer();\r
191                         }\r
192                 }); \r
193         }\r
194 \r
195 }\r