2 * ============LICENSE_START====================================================
4 * ===========================================================================
5 * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
7 * Modification Copyright (c) 2019 IBM
8 * ===========================================================================
9 * Licensed under the Apache License, Version 2.0 (the "License");
10 * you may not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
20 * ============LICENSE_END====================================================
24 package org.onap.aaf.auth.dao;
26 import java.util.Date;
27 import java.util.List;
29 import java.util.Timer;
30 import java.util.TimerTask;
32 import org.onap.aaf.auth.cache.Cache;
33 import org.onap.aaf.auth.dao.cass.Status;
34 import org.onap.aaf.auth.env.AuthzEnv;
35 import org.onap.aaf.auth.env.AuthzTrans;
36 import org.onap.aaf.auth.layer.Result;
37 import org.onap.aaf.misc.env.Env;
38 import org.onap.aaf.misc.env.Trans;
40 public class Cached<TRANS extends Trans, DATA extends Cacheable> extends Cache<TRANS,DATA> {
41 // Java does not allow creation of Arrays with Generics in them...
42 protected final CIDAO<TRANS> info;
44 private static Timer infoTimer;
45 private Object cache[];
46 public final int segSize;
48 protected final String name;
50 private final long expireIn;
53 public Cached(CIDAO<TRANS> info, String name, int segSize, long expireIn) {
55 this.segSize = segSize;
57 this.expireIn = expireIn;
58 cache = new Object[segSize];
59 // Create a new Map for each Segment, and store locally
60 for (int i=0;i<segSize;++i) {
61 cache[i]=obtain(name+i);
65 // Taken from String Hash, but coded, to ensure consistent across Java versions. Also covers negative case;
66 public int cacheIdx(String key) {
68 for (int i = 0; i < key.length(); i++) {
69 h = 31*h + key.charAt(i);
77 public void add(String key, List<DATA> data) {
78 @SuppressWarnings("unchecked")
79 Map<String,Dated> map = ((Map<String,Dated>)cache[cacheIdx(key)]);
80 map.put(key, new Dated(data, expireIn));
84 public int invalidate(String key) {
85 int cacheIdx = cacheIdx(key);
86 @SuppressWarnings("unchecked")
87 Map<String,Dated> map = ((Map<String,Dated>)cache[cacheIdx]);
88 if (map!=null)map.clear();
92 public Result<Void> invalidate(int segment) {
93 if (segment<0 || segment>=cache.length) {
94 return Result.err(Status.ERR_BadData,"Cache Segment %s is out of range",Integer.toString(segment));
96 @SuppressWarnings("unchecked")
97 Map<String,Dated> map = ((Map<String,Dated>)cache[segment]);
105 public interface Getter<D> {
106 public abstract Result<List<D>> get();
109 // TODO utilize Segmented Caches, and fold "get" into "reads"
110 @SuppressWarnings("unchecked")
111 public Result<List<DATA>> get(TRANS trans, String key, Getter<DATA> getter) {
112 List<DATA> ld = null;
113 Result<List<DATA>> rld = null;
115 int cacheIdx = cacheIdx(key);
116 Map<String, Dated> map = ((Map<String,Dated>)cache[cacheIdx]);
118 // Check for saved element in cache
119 Dated cached = map.get(key);
120 // Note: These Segment Timestamps are kept up to date with DB
121 Date dbStamp = info.get(trans, name,cacheIdx);
123 // Check for cache Entry and whether it is still good (a good Cache Entry is same or after DBEntry, so we use "before" syntax)
124 if (cached!=null && dbStamp!=null && dbStamp.before(cached.timestamp)) {
125 ld = (List<DATA>)cached.data;
129 if (rld.isOK()) { // only store valid lists
130 map.put(key, new Dated(rld.value,expireIn)); // successful item found gets put in cache
137 * Each Cached object has multiple Segments that need cleaning. Derive each, and add to Cleansing Thread
141 public static void startCleansing(AuthzEnv env, CachedDAO<?,?,?> ... dao) {
142 for (CachedDAO<?,?,?> d : dao) {
143 for (int i=0;i<d.segSize;++i) {
144 startCleansing(env, d.table()+i);
150 public static<T extends Trans> void startRefresh(AuthzEnv env, CIDAO<AuthzTrans> cidao) {
151 if (infoTimer==null) {
152 infoTimer = new Timer("CachedDAO Info Refresh Timer");
153 int minRefresh = 10*1000*60; // 10 mins Integer.parseInt(env.getProperty(CACHE_MIN_REFRESH_INTERVAL,"2000")); // 2 second minimum refresh
154 infoTimer.schedule(new Refresh(env,cidao, minRefresh), 1000, minRefresh); // note: Refresh from DB immediately
158 public static void stopTimer() {
160 if (infoTimer!=null) {
166 private static final class Refresh extends TimerTask {
167 private static final int MAXREFRESH = 2*60*10000; // 20 mins
168 private AuthzEnv env;
169 private CIDAO<AuthzTrans> cidao;
170 private int minRefresh;
171 private long lastRun;
173 public Refresh(AuthzEnv env, CIDAO<AuthzTrans> cidao, int minRefresh) {
176 this.minRefresh = minRefresh;
177 lastRun = System.currentTimeMillis()-MAXREFRESH-1000;
182 // Evaluate whether to refresh based on transaction rate
183 long now = System.currentTimeMillis();
184 long interval = now-lastRun;
186 if (interval < minRefresh || interval < Math.min(env.transRate(),MAXREFRESH)) {
190 AuthzTrans trans = env.newTransNoAvg();
191 Result<Void> rv = cidao.check(trans);
192 if (rv.status!=Result.OK) {
193 env.error().log("Error in CacheInfo Refresh",rv.details);
195 if (env.debug().isLoggable()) {
196 StringBuilder sb = new StringBuilder("Cache Info Refresh: ");
197 trans.auditTrail(0, sb, Env.REMOTE);