1 /*******************************************************************************
\r
2 * ============LICENSE_START====================================================
\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
11 * * http://www.apache.org/licenses/LICENSE-2.0
\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
20 * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
\r
22 ******************************************************************************/
\r
23 package com.att.dao;
\r
25 import java.util.Date;
\r
26 import java.util.List;
\r
27 import java.util.Map;
\r
28 import java.util.Timer;
\r
29 import java.util.TimerTask;
\r
31 import com.att.authz.env.AuthzEnv;
\r
32 import com.att.authz.env.AuthzTrans;
\r
33 import com.att.authz.layer.Result;
\r
34 import com.att.cache.Cache;
\r
35 import com.att.dao.aaf.cass.Status;
\r
36 import com.att.inno.env.Env;
\r
37 import com.att.inno.env.Trans;
\r
39 public class Cached<TRANS extends Trans, DATA extends Cacheable> extends Cache<TRANS,DATA> {
\r
40 // Java does not allow creation of Arrays with Generics in them...
\r
41 // private Map<String,Dated> cache[];
\r
42 protected final CIDAO<TRANS> info;
\r
44 private static Timer infoTimer;
\r
45 private Object cache[];
\r
46 public final int segSize;
\r
48 protected final String name;
\r
52 // Taken from String Hash, but coded, to ensure consistent across Java versions. Also covers negative case;
\r
53 public int cacheIdx(String key) {
\r
55 for (int i = 0; i < key.length(); i++) {
\r
56 h = 31*h + key.charAt(i);
\r
62 public Cached(CIDAO<TRANS> info, String name, int segSize) {
\r
64 this.segSize = segSize;
\r
66 cache = new Object[segSize];
\r
67 // Create a new Map for each Segment, and store locally
\r
68 for(int i=0;i<segSize;++i) {
\r
69 cache[i]=obtain(name+i);
\r
73 public void add(String key, List<DATA> data) {
\r
74 @SuppressWarnings("unchecked")
\r
75 Map<String,Dated> map = ((Map<String,Dated>)cache[cacheIdx(key)]);
\r
76 map.put(key, new Dated(data));
\r
80 public int invalidate(String key) {
\r
81 int cacheIdx = cacheIdx(key);
\r
82 @SuppressWarnings("unchecked")
\r
83 Map<String,Dated> map = ((Map<String,Dated>)cache[cacheIdx]);
\r
84 // if(map.remove(key)!=null) // Not seeming to remove all the time
\r
85 if(map!=null)map.clear();
\r
86 // System.err.println("Remove " + name + " " + key);
\r
90 public Result<Void> invalidate(int segment) {
\r
91 if(segment<0 || segment>=cache.length) return Result.err(Status.ERR_BadData,"Cache Segment %s is out of range",Integer.toString(segment));
\r
92 @SuppressWarnings("unchecked")
\r
93 Map<String,Dated> map = ((Map<String,Dated>)cache[segment]);
\r
100 protected interface Getter<D> {
\r
101 public abstract Result<List<D>> get();
\r
104 // TODO utilize Segmented Caches, and fold "get" into "reads"
\r
105 @SuppressWarnings("unchecked")
\r
106 public Result<List<DATA>> get(TRANS trans, String key, Getter<DATA> getter) {
\r
107 List<DATA> ld = null;
\r
108 Result<List<DATA>> rld = null;
\r
110 int cacheIdx = cacheIdx(key);
\r
111 Map<String, Dated> map = ((Map<String,Dated>)cache[cacheIdx]);
\r
113 // Check for saved element in cache
\r
114 Dated cached = map.get(key);
\r
115 // Note: These Segment Timestamps are kept up to date with DB
\r
116 Date dbStamp = info.get(trans, name,cacheIdx);
\r
118 // Check for cache Entry and whether it is still good (a good Cache Entry is same or after DBEntry, so we use "before" syntax)
\r
119 if(cached!=null && dbStamp.before(cached.timestamp)) {
\r
120 ld = (List<DATA>)cached.data;
\r
121 rld = Result.ok(ld);
\r
123 rld = getter.get();
\r
124 if(rld.isOK()) { // only store valid lists
\r
125 map.put(key, new Dated(rld.value)); // successful item found gets put in cache
\r
126 // } else if(rld.status == Result.ERR_Backend){
\r
127 // map.remove(key);
\r
134 * Each Cached object has multiple Segments that need cleaning. Derive each, and add to Cleansing Thread
\r
138 public static void startCleansing(AuthzEnv env, CachedDAO<?,?,?> ... dao) {
\r
139 for(CachedDAO<?,?,?> d : dao) {
\r
140 for(int i=0;i<d.segSize;++i) {
\r
141 startCleansing(env, d.table()+i);
\r
147 public static<T extends Trans> void startRefresh(AuthzEnv env, CIDAO<AuthzTrans> cidao) {
\r
148 if(infoTimer==null) {
\r
149 infoTimer = new Timer("CachedDAO Info Refresh Timer");
\r
150 int minRefresh = 10*1000*60; // 10 mins Integer.parseInt(env.getProperty(CACHE_MIN_REFRESH_INTERVAL,"2000")); // 2 second minimum refresh
\r
151 infoTimer.schedule(new Refresh(env,cidao, minRefresh), 1000, minRefresh); // note: Refresh from DB immediately
\r
155 public static void stopTimer() {
\r
157 if(infoTimer!=null) {
\r
158 infoTimer.cancel();
\r
163 private final static class Refresh extends TimerTask {
\r
164 private static final int maxRefresh = 2*60*10000; // 20 mins
\r
165 private AuthzEnv env;
\r
166 private CIDAO<AuthzTrans> cidao;
\r
167 private int minRefresh;
\r
168 private long lastRun;
\r
170 public Refresh(AuthzEnv env, CIDAO<AuthzTrans> cidao, int minRefresh) {
\r
172 this.cidao = cidao;
\r
173 this.minRefresh = minRefresh;
\r
174 lastRun = System.currentTimeMillis()-maxRefresh-1000;
\r
178 public void run() {
\r
179 // Evaluate whether to refresh based on transaction rate
\r
180 long now = System.currentTimeMillis();
\r
181 long interval = now-lastRun;
\r
183 if(interval < minRefresh || interval < Math.min(env.transRate(),maxRefresh)) return;
\r
185 AuthzTrans trans = env.newTransNoAvg();
\r
186 Result<Void> rv = cidao.check(trans);
\r
187 if(rv.status!=Result.OK) {
\r
188 env.error().log("Error in CacheInfo Refresh",rv.details);
\r
190 if(env.debug().isLoggable()) {
\r
191 StringBuilder sb = new StringBuilder("Cache Info Refresh: ");
\r
192 trans.auditTrail(0, sb, Env.REMOTE);
\r
193 env.debug().log(sb);
\r