Exemplo n.º 1
0
 /**
  * 保存到缓存中
  *
  * @param cacheKey
  * @param value
  */
 public void putObect(CacheKey ckey, Object value) {
   if (ckey == null) return;
   if (cache.contain(ckey.getKey())) return;
   cache.put(ckey.getKey(), new CacheableWrapper(ckey.getDataKey(), value));
   Debug.logVerbose(
       "[JdonFramework]<-cache->save cache: " + ckey.getKey() + ", cache size:" + cache.size(),
       module);
 }
Exemplo n.º 2
0
 /**
  * Selects a faction from the salvage list and generates a table using the same parameters as this
  * table, but from five years earlier. Generated tables are cached for later use. If the generated
  * table contains no units, it is discarded and the selected entry is deleted. This continues
  * until either a unit is generated or there are no remaining entries.
  *
  * @param filter - passed to generateUnit() in the generated table.
  * @return - a unit generated from another faction, or null if none of the factions in the salvage
  *     list contain any units that meet the parameters.
  */
 private MechSummary generateSalvage(UnitFilter filter) {
   while (salvageTotal > 0) {
     int roll = Compute.randomInt(salvageTotal);
     TableEntry salvageEntry = null;
     for (TableEntry te : salvageTable) {
       if (roll < te.weight) {
         salvageEntry = te;
         break;
       }
       roll -= te.weight;
     }
     if (salvageEntry != null) {
       UnitTable salvage =
           UnitTable.findTable(
               salvageEntry.getSalvageFaction(),
               key.getUnitType(),
               key.getYear() - 5,
               key.getRating(),
               key.getWeightClasses(),
               key.getNetworkMask(),
               key.getMovementModes(),
               key.getRoles(),
               key.getRoleStrictness(),
               key.getFaction());
       if (salvage.hasUnits()) {
         return salvage.generateUnit(filter);
       } else {
         salvageTotal -= salvageEntry.weight;
         salvageTable.remove(salvageEntry);
       }
     }
   }
   assert (salvageTable.isEmpty() && salvageTotal == 0);
   return null;
 }
Exemplo n.º 3
0
 /**
  * @param index
  * @return - a string representing the entry at the indicated index for use in the table
  */
 public String getEntryText(int index) {
   if (index >= salvageTable.size()) {
     return unitTable.get(index - salvageTable.size()).getUnitEntry().getName();
   } else {
     if (key.getFaction().isClan()) {
       return "Isorla: " + salvageTable.get(index).getSalvageFaction().getName(key.getYear() - 5);
     } else {
       return "Salvage: " + salvageTable.get(index).getSalvageFaction().getName(key.getYear() - 5);
     }
   }
 }
Exemplo n.º 4
0
    public String toString() {
      StrWriter out = new StrWriter();

      out.print("address=" + address.get() + " dirty=" + dirty);

      return out.toString();
    }
Exemplo n.º 5
0
 /**
  * 如果该cache已经存在,则不再创建并返回已有cache
  *
  * @param groupId 如果cache和账号无关,置为null,创建全局cache
  * @param expireTime 小于0(比如-1)则忽略超时
  */
 public <K, V> Cache<K, V> createPersistedLruExpireCache(
     String groupId, CacheKey cacheID, int capacity, long expireTime) {
   if (groupId == null) {
     groupId = GLOBAL_CACHE_GROUP_ID;
   }
   Map<CacheKey, Cache> caches;
   synchronized (cacheMap) {
     caches = cacheMap.get(groupId);
     if (caches == null) {
       caches = new ConcurrentHashMap<>();
       cacheMap.put(groupId, caches);
       LogUtil.w(sTAG, groupId + " caches not exist, warning.");
     }
   }
   Cache<K, V> cache = caches.get(cacheID);
   if (cache == null) {
     try {
       cache = new PersistedLruExpireCache(cacheID.getKey(), groupId, capacity, 1, expireTime);
       caches.put(cacheID, cache);
     } catch (IOException e) {
       LogUtil.e(sTAG, e.getMessage(), e);
     }
   } else {
     cache.setCapacity(capacity);
   }
   return cache;
 }
Exemplo n.º 6
0
  /**
   * Look-up the value through the cache. This always evaluates the {@code subKeyFactory} function
   * and optionally evaluates {@code valueFactory} function if there is no entry in the cache for
   * given pair of (key, subKey) or the entry has already been cleared.
   *
   * @param key possibly null key
   * @param parameter parameter used together with key to create sub-key and value (should not be
   *     null)
   * @return the cached value (never null)
   * @throws NullPointerException if {@code parameter} passed in or {@code sub-key} calculated by
   *     {@code subKeyFactory} or {@code value} calculated by {@code valueFactory} is null.
   */
  public V get(K key, P parameter) {
    Objects.requireNonNull(parameter);

    expungeStaleEntries();

    Object cacheKey = CacheKey.valueOf(key, refQueue);

    // lazily install the 2nd level valuesMap for the particular cacheKey
    ConcurrentMap<Object, Supplier<V>> valuesMap = map.get(cacheKey);
    if (valuesMap == null) {
      ConcurrentMap<Object, Supplier<V>> oldValuesMap =
          map.putIfAbsent(cacheKey, valuesMap = new ConcurrentHashMap<>());
      if (oldValuesMap != null) {
        valuesMap = oldValuesMap;
      }
    }

    // create subKey and retrieve the possible Supplier<V> stored by that
    // subKey from valuesMap
    Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));
    Supplier<V> supplier = valuesMap.get(subKey);
    Factory factory = null;

    while (true) {
      if (supplier != null) {
        // supplier might be a Factory or a CacheValue<V> instance
        V value = supplier.get();
        if (value != null) {
          return value;
        }
      }
      // else no supplier in cache
      // or a supplier that returned null (could be a cleared CacheValue
      // or a Factory that wasn't successful in installing the CacheValue)

      // lazily construct a Factory
      if (factory == null) {
        factory = new Factory(key, parameter, subKey, valuesMap);
      }

      if (supplier == null) {
        supplier = valuesMap.putIfAbsent(subKey, factory);
        if (supplier == null) {
          // successfully installed Factory
          supplier = factory;
        }
        // else retry with winning supplier
      } else {
        if (valuesMap.replace(subKey, supplier, factory)) {
          // successfully replaced
          // cleared CacheEntry / unsuccessful Factory
          // with our Factory
          supplier = factory;
        } else {
          // retry with current supplier
          supplier = valuesMap.get(subKey);
        }
      }
    }
  }
 private void cacheMarkDirty(CacheKey key) {
   if (cache != null) {
     int index = key.ordinal();
     cache[index] = null;
     cacheState[index] = STATE_NOT_CACHED;
   }
 }
Exemplo n.º 8
0
 @Test
 public void shouldTestCacheKeysEqual() {
   Date date = new Date();
   CacheKey key1 = new CacheKey(new Object[] {1, "hello", null, new Date(date.getTime())});
   CacheKey key2 = new CacheKey(new Object[] {1, "hello", null, new Date(date.getTime())});
   assertTrue(key1.equals(key2));
   assertTrue(key2.equals(key1));
   assertTrue(key1.hashCode() == key2.hashCode());
   assertTrue(key1.toString().equals(key2.toString()));
 }
Exemplo n.º 9
0
 @Test
 public void shouldTestCacheKeysNotEqualDueToOrder() throws Exception {
   CacheKey key1 = new CacheKey(new Object[] {1, "hello", null});
   Thread.sleep(1000);
   CacheKey key2 = new CacheKey(new Object[] {1, null, "hello"});
   assertFalse(key1.equals(key2));
   assertFalse(key2.equals(key1));
   assertFalse(key1.hashCode() == key2.hashCode());
   assertFalse(key1.toString().equals(key2.toString()));
 }
Exemplo n.º 10
0
  private void populateCache(int index) {
    if (cache == null) {
      int size = CacheKey.values().length;
      cache = new Object[size];
      cacheState = new byte[size];
    }

    if (cacheState[index] == STATE_NOT_CACHED) {
      CacheKey key = CacheKey.values()[index];

      if (getJSONObject().has(key.name())) {
        cache[index] = key.extractValue(this);
        cacheState[index] = STATE_CACHED_VALUE;
      } else {
        cacheState[index] = STATE_CACHED_NO_VALUE;
      }
    }
  }
Exemplo n.º 11
0
    private void write() throws IOException {
      if (isFree()) throw new IllegalArgumentException("cannot write a free element");

      elem.clear();

      long addr = address.get() * elementSize;

      for (int i = 0; i < nrfats; i++) {
        api.write(addr, elem);
        addr += fatsize;
        elem.clear();
      }
    }
  public void test() {
    Vector primaryKeys = new Vector();
    primaryKeys.add(new java.math.BigDecimal(4));
    CacheKey cacheKey =
        getAbstractSession()
            .getIdentityMapAccessorInstance()
            .acquireDeferredLock(
                primaryKeys, Employee.class, getSession().getDescriptor(Employee.class), false);
    CacheKey cacheKey2 =
        getAbstractSession()
            .getIdentityMapAccessorInstance()
            .acquireDeferredLock(
                primaryKeys, Employee.class, getSession().getDescriptor(Employee.class), false);
    if (cacheKey != cacheKey2) {
      throw new TestErrorException(
          "WeakIdentityMap failed to return same cachkey for successive calls for same primary key and class");
    }

    // must release because the deferred lock is not removed on an initialize identity map
    cacheKey.releaseDeferredLock();
    cacheKey2.releaseDeferredLock();
  }
Exemplo n.º 13
0
  private static void evaluateAccessor(
      Object request, CachableValueAccessor node, CacheKey key, boolean isRoot)
      throws ServiceException {
    try {
      Object value = null;
      if (!isRoot) {
        if (node.m_accessor != null) {
          if (request != null) {
            value = node.m_accessor.invoke(request, (Object[]) null);
          } else {
            value = null;
          }
        }
      } else {
        value = request;
      }

      // walk down the accessor structure and apply the method.
      if (node.m_elementAccessors.size() != 0) {
        Iterator i = node.m_elementAccessors.keySet().iterator();
        while (i.hasNext()) {
          CachableValueAccessor childAccessor = node.m_elementAccessors.get(i.next());
          evaluateAccessor(value, childAccessor, key, false);
        }
      } else {
        // we've reached the leaf. Insert to cache key
        key.add(node.m_fullPath, value);
      }
    } catch (IllegalAccessException e) {
      throw new ServiceException(
          ErrorDataFactory.createErrorData(
              ErrorConstants.SVC_CLIENT_CACHE_NOT_SUPPORTED, ErrorConstants.ERRORDOMAIN),
          e);
    } catch (IllegalArgumentException e) {
      throw new ServiceException(
          ErrorDataFactory.createErrorData(
              ErrorConstants.SVC_CLIENT_CACHE_NOT_SUPPORTED, ErrorConstants.ERRORDOMAIN),
          e);
    } catch (InvocationTargetException e) {
      throw new ServiceException(
          ErrorDataFactory.createErrorData(
              ErrorConstants.SVC_CLIENT_CACHE_NOT_SUPPORTED, ErrorConstants.ERRORDOMAIN),
          e);
    }
  }
Exemplo n.º 14
0
 @Test
 public void shouldDemonstrateEmptyAndNullKeysAreEqual() {
   CacheKey key1 = new CacheKey();
   CacheKey key2 = new CacheKey();
   assertEquals(key1, key2);
   assertEquals(key2, key1);
   key1.update(null);
   key2.update(null);
   assertEquals(key1, key2);
   assertEquals(key2, key1);
   key1.update(null);
   key2.update(null);
   assertEquals(key1, key2);
   assertEquals(key2, key1);
 }
Exemplo n.º 15
0
  private boolean deleteTokenCacheItem(
      String authority,
      String itemAuthority,
      String resource,
      String clientId,
      String userId,
      boolean isMultipleResourceRefreshToken) {

    final AuthenticationContext authContext;
    try {
      authContext = getOrCreateContext(authority);
    } catch (Exception e) {
      callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, e.getMessage()));
      return true;
    }

    String key =
        CacheKey.createCacheKey(
            itemAuthority, resource, clientId, isMultipleResourceRefreshToken, userId);
    authContext.getCache().removeItem(key);

    callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK));
    return true;
  }
Exemplo n.º 16
0
 private CacheElement get(long address) {
   key.set(address);
   return get(key);
 }
Exemplo n.º 17
0
 private void expungeStaleEntries() {
   CacheKey<K> cacheKey;
   while ((cacheKey = (CacheKey<K>) refQueue.poll()) != null) {
     cacheKey.expungeFrom(map, reverseMap);
   }
 }
Exemplo n.º 18
0
  /**
   * Initializes table based on values provided by key
   *
   * @param key - a structure providing the parameters for generating the table
   */
  protected UnitTable(CacheKey key) {
    this.key = key;
    /**
     * Generate the RAT, then go through it to build the NavigableMaps that will be used for random
     * selection.
     */
    if (key.getFaction().isActiveInYear(key.getYear())) {
      List<TableEntry> table =
          RATGenerator.getInstance()
              .generateTable(
                  key.getFaction(),
                  key.getUnitType(),
                  key.getYear(),
                  key.getRating(),
                  key.getWeightClasses(),
                  key.getNetworkMask(),
                  key.getMovementModes(),
                  key.getRoles(),
                  key.getRoleStrictness(),
                  key.getDeployingFaction());
      Collections.sort(table);

      table.forEach(
          te -> {
            if (te.isUnit()) {
              unitTotal += te.weight;
              unitTable.add(te);
            } else {
              salvageTotal += te.weight;
              salvageTable.add(te);
            }
          });
      if (salvageTotal + unitTotal > 0) {
        salvagePct = salvageTotal * 100 / (salvageTotal + unitTotal);
      }
    }
  }
Exemplo n.º 19
0
 private boolean cacheHasKey(CacheKey key) {
   int index = key.ordinal();
   populateCache(index);
   return cacheState[index] == STATE_CACHED_VALUE;
 }
Exemplo n.º 20
0
 private void cacheRemoveValue(CacheKey key) {
   int index = key.ordinal();
   populateCache(index);
   cache[index] = null;
   cacheState[index] = STATE_CACHED_NO_VALUE;
 }
Exemplo n.º 21
0
 private boolean cacheValueIsNotNull(CacheKey key) {
   int index = key.ordinal();
   populateCache(index);
   return cache[index] != null;
 }
Exemplo n.º 22
0
 private <T> T cacheGet(CacheKey key) {
   int index = key.ordinal();
   populateCache(index);
   return (T) cache[index];
 }
Exemplo n.º 23
0
 private Object peekCache(String key, int userId) {
   synchronized (mCache) {
     // Safe to reuse mCacheKey, because it is not stored in the map.
     return mCache.get(mCacheKey.set(key, userId));
   }
 }
Exemplo n.º 24
0
 private void free() throws IOException {
   if (isFree()) throw new IllegalArgumentException("cannot free a free element");
   flush();
   address.free();
 }
Exemplo n.º 25
0
 private boolean isFree() {
   return address.isFree();
 }
Exemplo n.º 26
0
 private void invalidateCache(String key, int userId) {
   synchronized (mCache) {
     // Safe to reuse mCacheKey, because it is not stored in the map.
     mCache.remove(mCacheKey.set(key, userId));
   }
 }
Exemplo n.º 27
0
 /**
  * Static utility for creating the cacheKey.
  *
  * @param opName An operation name.
  * @param request A request object of this operation.
  * @param accessorCache A CachableValueAccessor for accessing the Cached value.
  * @return A CacheKey for the given request object.
  * @throws ServiceException Exception during CacheKey generation.
  */
 public static CacheKey generateCacheKey(
     String opName, Object request, CachableValueAccessor accessorCache) throws ServiceException {
   CacheKey key = CacheKey.createCacheKey(opName);
   evaluateAccessor(request, accessorCache, key, true);
   return key;
 }