Skip to main content
summaryrefslogtreecommitdiffstats
blob: d25fe98fceb54f8d02155fcb7dbbee15bda780f3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
/*******************************************************************************
 * Copyright (c) 2009 Boeing.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Boeing - initial API and implementation
 *******************************************************************************/
package org.eclipse.osee.framework.core.model.cache;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import org.eclipse.osee.framework.core.data.Identity;
import org.eclipse.osee.framework.core.enums.OseeCacheEnum;
import org.eclipse.osee.framework.core.enums.StorageState;
import org.eclipse.osee.framework.core.exception.OseeArgumentException;
import org.eclipse.osee.framework.core.exception.OseeCoreException;
import org.eclipse.osee.framework.core.exception.OseeStateException;
import org.eclipse.osee.framework.core.exception.OseeTypeDoesNotExist;
import org.eclipse.osee.framework.core.model.AbstractOseeType;
import org.eclipse.osee.framework.core.model.IOseeStorable;
import org.eclipse.osee.framework.core.util.Conditions;
import org.eclipse.osee.framework.jdk.core.type.HashCollection;
import org.eclipse.osee.framework.jdk.core.util.GUID;
import org.eclipse.osee.framework.logging.OseeLog;

/**
 * @author Roberto E. Escobar
 */
public abstract class AbstractOseeCache<K, T extends AbstractOseeType<K>> implements IOseeCache<K, T> {
   private final HashCollection<String, T> nameToTypeMap = new HashCollection<String, T>(true,
      CopyOnWriteArrayList.class);
   private final Map<Integer, T> idToTypeMap = new ConcurrentHashMap<Integer, T>();
   private final Map<K, T> guidToTypeMap = new ConcurrentHashMap<K, T>();

   private final IOseeDataAccessor<K, T> dataAccessor;
   private final OseeCacheEnum cacheId;
   private final boolean uniqueName;
   private final AtomicBoolean wasLoaded;
   private long lastLoaded;
   private boolean ignoreEnsurePopulateException;
   private boolean isEnsurePopulateSynchronized;

   protected AbstractOseeCache(OseeCacheEnum cacheId, IOseeDataAccessor<K, T> dataAccessor, boolean uniqueName) {
      this.lastLoaded = 0;
      this.cacheId = cacheId;
      this.wasLoaded = new AtomicBoolean(false);
      this.ignoreEnsurePopulateException = false;
      this.dataAccessor = dataAccessor;
      this.uniqueName = uniqueName;
      this.isEnsurePopulateSynchronized = true;
   }

   // Temporary fix to avoid deadlock on server types cache loading 
   public void setSynchronizedEnsurePopulate(boolean isSynchronized) {
      this.isEnsurePopulateSynchronized = isSynchronized;
   }

   public boolean isSynchronizedEnsurePopulate() {
      return isEnsurePopulateSynchronized;
   }

   public void invalidate() {
      wasLoaded.set(false);
   }

   @Override
   public final synchronized void decacheAll() {
      clearAdditionalData();
      nameToTypeMap.clear();
      idToTypeMap.clear();
      guidToTypeMap.clear();
      wasLoaded.set(false);
   }

   protected void clearAdditionalData() {
      // for subclass overriding
   }

   public void setIgnoreEnsurePopulateException(boolean isIgnored) {
      this.ignoreEnsurePopulateException = isIgnored;
   }

   public boolean isEnsurePopulateExceptionIgnored() {
      return ignoreEnsurePopulateException;
   }

   @Override
   public OseeCacheEnum getCacheId() {
      return cacheId;
   }

   @Override
   public int size() {
      return guidToTypeMap.size();
   }

   protected IOseeDataAccessor<K, T> getDataAccessor() {
      return dataAccessor;
   }

   public boolean existsByGuid(K guid) throws OseeCoreException {
      ensurePopulated();
      return guidToTypeMap.containsKey(guid);
   }

   @Override
   public void decache(T... types) throws OseeCoreException {
      Conditions.checkNotNull(types, "types to de-cache");
      for (T type : types) {
         decache(type);
      }
   }

   @Override
   public void decache(T type) throws OseeCoreException {
      Conditions.checkNotNull(type, "type to de-cache");
      ensurePopulated();
      guidToTypeMap.remove(type.getGuid());
      decacheByName(type);
      if (type.isIdValid()) {
         idToTypeMap.remove(type.getId());
      }
   }

   /**
    * this method is intended for use by subclasses only. The calling method must synchronize the use of this view of
    * the views because it is not a copy. This method exists to improve performance for subclasses
    */
   protected synchronized Collection<T> getRawValues() throws OseeCoreException {
      ensurePopulated();
      return guidToTypeMap.values();
   }

   private void decacheByName(T type) {
      Set<String> keysToRemove = new HashSet<String>();

      for (String name : nameToTypeMap.keySet()) {
         Collection<T> items = nameToTypeMap.getValues(name);
         if (items != null && items.contains(type)) {
            keysToRemove.add(name);
         }
      }

      for (String key : keysToRemove) {
         nameToTypeMap.removeValue(key, type);
      }
   }

   @Override
   public void cache(T... types) throws OseeCoreException {
      Conditions.checkNotNull(types, "types to cache");
      for (T type : types) {
         cache(type);
      }
   }

   @Override
   public void cache(T type) throws OseeCoreException {
      Conditions.checkNotNull(type, "type to cache");
      ensurePopulated();
      nameToTypeMap.put(type.getName(), type);
      guidToTypeMap.put(type.getGuid(), type);
      cacheById(type);
      if (isNameUniquenessEnforced()) {
         checkNameUnique(type);
      }
   }

   public boolean isNameUniquenessEnforced() {
      return uniqueName;
   }

   private void checkNameUnique(T type) throws OseeCoreException {
      ensurePopulated();
      Collection<T> cachedTypes = getByName(type.getName());
      Set<String> itemsFound = new HashSet<String>();
      // TODO Need to revisit this based on deleted types
      //      for (T cachedType : cachedTypes) {
      //         if (!cachedType.getGuid().equals(type.getGuid()) && !cachedType.getModificationType().isDeleted()) {
      //            itemsFound.add(String.format("[%s:%s]", cachedType.getName(), cachedType.getGuid()));
      //         }
      //      }
      if (cachedTypes.size() > 1) {
         throw new OseeStateException("Item [%s:%s] does not have a unique name. Matching types [%s]", type.getName(),
            type.getGuid(), itemsFound);
      }
   }

   private void cacheById(T type) throws OseeCoreException {
      Conditions.checkNotNull(type, "type to cache");
      ensurePopulated();
      if (type.isIdValid()) {
         idToTypeMap.put(type.getId(), type);
      }
   }

   @Override
   public Collection<T> getAll() throws OseeCoreException {
      ensurePopulated();
      return new ArrayList<T>(guidToTypeMap.values());
   }

   @Override
   public T getById(int typeId) throws OseeCoreException {
      ensurePopulated();
      return idToTypeMap.get(typeId);
   }

   public T getUniqueByName(String typeName) throws OseeCoreException {
      ensurePopulated();
      Collection<T> values = getByName(typeName);
      if (values.size() > 1) {
         throw new OseeStateException("Multiple items matching [%s] name exist", typeName);
      }
      return values.isEmpty() ? null : values.iterator().next();
   }

   public Collection<T> getByName(String typeName) throws OseeCoreException {
      ensurePopulated();
      Collection<T> types = new ArrayList<T>();
      Collection<T> values = nameToTypeMap.getValues(typeName);
      if (values != null) {
         types.addAll(values);
      }
      return types;
   }

   public T getBySoleName(String typeName) throws OseeCoreException {
      ensurePopulated();
      Collection<T> types = getByName(typeName);
      if (types.size() != 1) {
         throw new OseeArgumentException("AbstractOseeCache expected 1 type but found [%d] types for [%s]",
            types.size(), typeName);
      }
      return types.iterator().next();
   }

   @Override
   public T getByGuid(K guid) throws OseeCoreException {
      ensurePopulated();
      if (guid instanceof String) {
         if (!GUID.isValid((String) guid)) {
            throw new OseeArgumentException("[%s] is not a valid guid", guid);
         }
      }
      return guidToTypeMap.get(guid);
   }

   public T get(Identity<K> token) throws OseeCoreException {
      ensurePopulated();
      return getByGuid(token.getGuid());
   }

   @Override
   public Collection<T> getAllDirty() throws OseeCoreException {
      ensurePopulated();
      Collection<T> dirtyItems = new HashSet<T>();
      for (T type : guidToTypeMap.values()) {
         if (type.isDirty()) {
            dirtyItems.add(type);
         }
      }
      return dirtyItems;
   }

   @Override
   public void storeAllModified() throws OseeCoreException {
      storeItems(getAllDirty());
   }

   private void populate() throws OseeCoreException {
      if (wasLoaded.compareAndSet(false, true)) {
         try {
            reloadCache();
         } catch (OseeCoreException ex) {
            if (!isEnsurePopulateExceptionIgnored()) {
               throw ex;
            }
         }
      }
   }

   @Override
   public void ensurePopulated() throws OseeCoreException {
      if (isSynchronizedEnsurePopulate()) {
         synchronized (this) {
            populate();
         }
      } else {
         populate();
      }
   }

   public void storeByGuid(Collection<K> guids) throws OseeCoreException {
      ensurePopulated();
      Conditions.checkNotNull(guids, "guids to store");
      Collection<T> items = new HashSet<T>();
      for (K guid : guids) {
         T type = getByGuid(guid);
         if (type == null) {
            throw new OseeTypeDoesNotExist(String.format("Item was not found [%s]", guid));
         }
         items.add(type);
      }
      storeItems(items);
   }

   @Override
   public long getLastLoaded() {
      return lastLoaded;
   }

   private void setLastLoaded(long lastLoaded) {
      this.lastLoaded = lastLoaded;
   }

   @Override
   public synchronized boolean reloadCache() throws OseeCoreException {
      getDataAccessor().load(this);
      OseeLog.log(this.getClass(), Level.INFO, "Loaded " + getCacheId().toString().toLowerCase());
      setLastLoaded(System.currentTimeMillis());
      wasLoaded.set(true);
      return true;
   }

   @Override
   public void storeItems(T... items) throws OseeCoreException {
      Conditions.checkNotNull(items, "items to store");
      storeItems(Arrays.asList(items));
   }

   @Override
   public void storeItems(Collection<T> toStore) throws OseeCoreException {
      Conditions.checkNotNull(toStore, "items to store");
      if (!toStore.isEmpty()) {
         getDataAccessor().store(toStore);
         synchronized (this) {
            for (T type : toStore) {
               decache(type);
               if (StorageState.PURGED != type.getStorageState()) {
                  cache(type);
               }
            }
         }
      }
   }

   public int getLocalId(Identity<K> token) throws OseeCoreException {
      T type = get(token);
      return type != null ? type.getId() : IOseeStorable.UNPERSISTED_VALUE;
   }

   public void cacheFrom(AbstractOseeCache<K, T> source) throws OseeCoreException {
      for (T type : source.getAll()) {
         cache(type);
      }
   }
}

Back to the top