com.googlecode.concurrentlinkedhashmap.ConcurrentLinkedHashMap Java Examples

The following examples show how to use com.googlecode.concurrentlinkedhashmap.ConcurrentLinkedHashMap. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: InMemoryMetricsRepository.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized List<MetricEntity> queryByAppAndResourceBetween(String app, String resource,
                                                                    long startTime, long endTime) {
    List<MetricEntity> results = new ArrayList<>();
    if (StringUtil.isBlank(app)) {
        return results;
    }
    Map<String, ConcurrentLinkedHashMap<Long, MetricEntity>> resourceMap = allMetrics.get(app);
    if (resourceMap == null) {
        return results;
    }
    ConcurrentLinkedHashMap<Long, MetricEntity> metricsMap = resourceMap.get(resource);
    if (metricsMap == null) {
        return results;
    }
    for (Entry<Long, MetricEntity> entry : metricsMap.entrySet()) {
        if (entry.getKey() >= startTime && entry.getKey() <= endTime) {
            results.add(entry.getValue());
        }
    }
    return results;
}
 
Example #2
Source File: SerializingCache.java    From stratio-cassandra with Apache License 2.0 6 votes vote down vote up
private SerializingCache(long capacity, Weigher<RefCountedMemory> weigher, ISerializer<V> serializer)
{
    this.serializer = serializer;

    EvictionListener<K,RefCountedMemory> listener = new EvictionListener<K, RefCountedMemory>()
    {
        public void onEviction(K k, RefCountedMemory mem)
        {
            mem.unreference();
        }
    };

    this.map = new ConcurrentLinkedHashMap.Builder<K, RefCountedMemory>()
               .weigher(weigher)
               .maximumWeightedCapacity(capacity)
               .concurrencyLevel(DEFAULT_CONCURENCY_LEVEL)
               .listener(listener)
               .build();
}
 
Example #3
Source File: DeepPagingCache.java    From incubator-retired-blur with Apache License 2.0 6 votes vote down vote up
public DeepPagingCache(long maxEntriesForDeepPaging) {
  _hits = Metrics.newMeter(new MetricName(ORG_APACHE_BLUR, DEEP_PAGING_CACHE, HIT), HIT, TimeUnit.SECONDS);
  _misses = Metrics.newMeter(new MetricName(ORG_APACHE_BLUR, DEEP_PAGING_CACHE, MISS), MISS, TimeUnit.SECONDS);
  _evictions = Metrics.newMeter(new MetricName(ORG_APACHE_BLUR, DEEP_PAGING_CACHE, EVICTION), EVICTION,
      TimeUnit.SECONDS);
  _lruCache = new ConcurrentLinkedHashMap.Builder<DeepPageKeyPlusPosition, DeepPageContainer>()
      .maximumWeightedCapacity(maxEntriesForDeepPaging)
      .listener(new EvictionListener<DeepPageKeyPlusPosition, DeepPageContainer>() {
        @Override
        public void onEviction(DeepPageKeyPlusPosition key, DeepPageContainer value) {
          _positionCache.remove(key);
          _evictions.mark();
        }
      }).build();
  Metrics.newGauge(new MetricName(ORG_APACHE_BLUR, DEEP_PAGING_CACHE, SIZE), new Gauge<Long>() {
    @Override
    public Long value() {
      return _lruCache.weightedSize();
    }
  });
  _positionCache = new ConcurrentSkipListMap<DeepPageKeyPlusPosition, DeepPageContainer>();
}
 
Example #4
Source File: PerfHashBenchmark.java    From concurrentlinkedhashmap with Apache License 2.0 6 votes vote down vote up
public int run_normal( ConcurrentLinkedHashMap<String,String> hm ) {
  SimpleRandom R = new SimpleRandom();

  int get_ops = 0;
  int put_ops = 0;
  int del_ops = 0;
  while( !_stop ) {
    int x = R.nextInt()&((1<<20)-1);
    String key = KEYS[R.nextInt()&(KEYS.length-1)];
    if( x < _gr ) {
      get_ops++;
      String val = hm.get(key);
      if( val != null && !val.equals(key) ) {
        throw new IllegalArgumentException("Mismatched key="+key+" and val="+val);
      }
    } else if( x < _pr ) {
      put_ops++;
  hm.putIfAbsent( key, key );
    } else {
      del_ops++;
      hm.remove( key );
    }
  }
  // We stopped; report results into shared result structure
  return get_ops+put_ops+del_ops;
}
 
Example #5
Source File: AbstractBfnRule.java    From light with Apache License 2.0 6 votes vote down vote up
protected List<String> getCategoryEntityList(String categoryRid, String sortedBy, String sortDir) throws Exception {
    List<String> list = null;
    // get list from cache
    Map<String, Object> categoryMap = ServiceLocator.getInstance().getMemoryImage("categoryMap");
    ConcurrentMap<Object, Object> listCache = (ConcurrentMap<Object, Object>)categoryMap.get("listCache");
    if(listCache == null) {
        listCache = new ConcurrentLinkedHashMap.Builder<Object, Object>()
                .maximumWeightedCapacity(200)
                .build();
        categoryMap.put("listCache", listCache);
    } else {
        list = (List<String>)listCache.get(categoryRid + sortedBy + sortDir);
    }
    if(list == null) {
        // not in cache, get from db
        list = getCategoryEntityListDb(categoryRid, sortedBy, sortDir);
        if(list != null) {
            listCache.put(categoryRid + sortedBy + sortDir, list);
        }
    }
    return list;
}
 
Example #6
Source File: AbstractBfnRule.java    From light with Apache License 2.0 6 votes vote down vote up
public Map<String, Object> getCategoryEntity(String entityRid) {
    Map<String, Object> entity = null;
    Map<String, Object> categoryMap = ServiceLocator.getInstance().getMemoryImage("categoryMap");
    ConcurrentMap<Object, Object> entityCache = (ConcurrentMap<Object, Object>)categoryMap.get("entityCache");
    if(entityCache == null) {
        entityCache = new ConcurrentLinkedHashMap.Builder<Object, Object>()
                .maximumWeightedCapacity(10000)
                .build();
        categoryMap.put("entityCache", entityCache);
    } else {
        entity = (Map<String, Object>)entityCache.get(entityRid);
    }
    if(entity == null) {
        entity = getCategoryEntityDb(entityRid);
        if(entity != null) {
            entityCache.put(entityRid, entity);
        }
    }
    return entity;
}
 
Example #7
Source File: AbstractBfnRule.java    From light with Apache License 2.0 6 votes vote down vote up
protected List<String> getRecentEntityList(String host, String categoryType, String sortedBy, String sortDir) {
    List<String> list = null;
    // get list from cache
    Map<String, Object> categoryMap = ServiceLocator.getInstance().getMemoryImage("categoryMap");
    ConcurrentMap<Object, Object> listCache = (ConcurrentMap<Object, Object>)categoryMap.get("listCache");
    if(listCache == null) {
        listCache = new ConcurrentLinkedHashMap.Builder<Object, Object>()
                .maximumWeightedCapacity(200)
                .build();
        categoryMap.put("listCache", listCache);
    } else {
        list = (List<String>)listCache.get(host + categoryType);
    }
    if(list == null) {
        // not in cache, get from db
        list = getRecentEntityListDb(host, categoryType, sortedBy, sortDir);
        if(list != null) {
            listCache.put(host + categoryType, list);
        }
    }
    return list;
}
 
Example #8
Source File: AbstractTagRule.java    From light with Apache License 2.0 6 votes vote down vote up
protected Map<String, Object> getTagEntity(String entityRid) {
    Map<String, Object> entity = null;
    Map<String, Object> categoryMap = ServiceLocator.getInstance().getMemoryImage("categoryMap");
    ConcurrentMap<Object, Object> entityCache = (ConcurrentMap<Object, Object>)categoryMap.get("entityCache");
    if(entityCache == null) {
        entityCache = new ConcurrentLinkedHashMap.Builder<Object, Object>()
                .maximumWeightedCapacity(10000)
                .build();
        categoryMap.put("entityCache", entityCache);
    } else {
        entity = (Map<String, Object>)entityCache.get(entityRid);
    }
    if(entity == null) {
        entity = getCategoryEntityDb(entityRid);
        if(entity != null) {
            entityCache.put(entityRid, entity);
        }
    }
    return entity;
}
 
Example #9
Source File: AbstractTagRule.java    From light with Apache License 2.0 6 votes vote down vote up
protected List<String> getTagEntityList(String host, String tagId) {
    List<String> list = null;
    Map<String, Object> categoryMap = ServiceLocator.getInstance().getMemoryImage("categoryMap");
    ConcurrentMap<Object, Object> listCache = (ConcurrentMap<Object, Object>)categoryMap.get("listCache");
    if(listCache == null) {
        listCache = new ConcurrentLinkedHashMap.Builder<Object, Object>()
                .maximumWeightedCapacity(200)
                .build();
        categoryMap.put("listCache", listCache);
    } else {
        list = (List<String>)listCache.get(host + tagId);
    }
    if(list == null) {
        list = getTagEntityListDb(host, tagId);
        if(list != null) {
            listCache.put(host + tagId, list);
        }
    }
    return list;
}
 
Example #10
Source File: AbstractRuleRule.java    From light with Apache License 2.0 6 votes vote down vote up
public static void loadCompileCache() {
    String sql = "SELECT FROM Rule";
    Map<String, Object> compileMap = ServiceLocator.getInstance().getMemoryImage("compileMap");
    ConcurrentMap<String, String> cache = (ConcurrentMap<String, String>)compileMap.get("cache");
    if(cache == null) {
        cache = new ConcurrentLinkedHashMap.Builder<String, String>()
                .maximumWeightedCapacity(10000)
                .build();
        compileMap.put("cache", cache);
    }
    OrientGraph graph = ServiceLocator.getInstance().getGraph();
    try {
        for (Vertex rule : (Iterable<Vertex>) graph.command(new OCommandSQL(sql)).execute()) {
            cache.put((String) rule.getProperty("ruleClass"), (String) rule.getProperty("sourceCode"));
        }
    } catch (Exception e) {
        logger.error("Exception:", e);
        throw e;
    } finally {
        graph.shutdown();
    }
}
 
Example #11
Source File: AbstractRule.java    From light with Apache License 2.0 6 votes vote down vote up
public Map<String, Object> getAccessByRuleClass(OrientGraph graph, String ruleClass) throws Exception {
    Map<String, Object> access = null;
    Map<String, Object> accessMap = ServiceLocator.getInstance().getMemoryImage("accessMap");
    ConcurrentMap<Object, Object> cache = (ConcurrentMap<Object, Object>)accessMap.get("cache");
    if(cache == null) {
        cache = new ConcurrentLinkedHashMap.Builder<Object, Object>()
                .maximumWeightedCapacity(1000)
                .build();
        accessMap.put("cache", cache);
    } else {
        access = (Map<String, Object>)cache.get(ruleClass);
    }
    if(access == null) {
        OrientVertex accessVertex = (OrientVertex)graph.getVertexByKey("Access.ruleClass", ruleClass);
        if(accessVertex != null) {
            String json = accessVertex.getRecord().toJSON();
            access = mapper.readValue(json,
                    new TypeReference<HashMap<String, Object>>() {
                    });
            cache.put(ruleClass, access);
        }
    }
    return access;
}
 
Example #12
Source File: AbstractMenuRule.java    From light with Apache License 2.0 6 votes vote down vote up
protected String getJsonByRid(String rid) {
    String json = null;
    Map<String, Object> menuMap = (Map<String, Object>)ServiceLocator.getInstance().getMemoryImage("menuMap");
    ConcurrentMap<Object, Object> cache = (ConcurrentMap<Object, Object>)menuMap.get("cache");
    if(cache != null) {
        json = (String)cache.get("rid");
    }
    if(json == null) {
        json = DbService.getJsonByRid(rid);
        // put it into the blog cache.
        if(json != null) {
            if(cache == null) {
                cache = new ConcurrentLinkedHashMap.Builder<Object, Object>()
                        .maximumWeightedCapacity(1000)
                        .build();
                menuMap.put("cache", cache);
            }
            cache.put(rid, json);
        }
    }
    return json;
}
 
Example #13
Source File: AbstractMenuRule.java    From light with Apache License 2.0 6 votes vote down vote up
protected String getMenu(OrientGraph graph, String host) {
    String json = null;
    Map<String, Object> menuMap = (Map<String, Object>)ServiceLocator.getInstance().getMemoryImage("menuMap");
    ConcurrentMap<Object, Object> cache = (ConcurrentMap<Object, Object>)menuMap.get("cache");
    if(cache != null) {
        json = (String)cache.get(host);
    }
    if(json == null) {
        Vertex menu = graph.getVertexByKey("Menu.host", host);
        if(menu != null) {
            json = ((OrientVertex)menu).getRecord().toJSON("rid,fetchPlan:[*]in_Create:-2 [*]out_Create:-2 [*]in_Update:-2 [*]out_Update:-2 [*]in_Own:-2 [*]out_Own:4");
        }
        if(json != null) {
            if(cache == null) {
                cache = new ConcurrentLinkedHashMap.Builder<Object, Object>()
                        .maximumWeightedCapacity(1000)
                        .build();
                menuMap.put("cache", cache);
            }
            cache.put(host, json);
        }
    }
    return json;
}
 
Example #14
Source File: UtilCache.java    From scipio-erp with Apache License 2.0 6 votes vote down vote up
public void setMaxInMemory(int newInMemory) {
    this.maxInMemory = newInMemory;
    Map<Object, CacheLine<V>> oldmap = this.memoryTable;

    if (newInMemory > 0) {
        if (this.memoryTable instanceof ConcurrentLinkedHashMap<?, ?>) {
            ((ConcurrentLinkedHashMap<?, ?>) this.memoryTable).setCapacity(newInMemory);
            return;
        }
        this.memoryTable =new Builder<Object, CacheLine<V>>()
                .maximumWeightedCapacity(newInMemory)
                .build();
    } else {
        this.memoryTable = new ConcurrentHashMap<>();
    }

    this.memoryTable.putAll(oldmap);
}
 
Example #15
Source File: AbstractPageRule.java    From light with Apache License 2.0 6 votes vote down vote up
protected CacheObject getPageById(OrientGraph graph, String pageId) {
    CacheObject co = null;
    Map<String, Object> pageMap = ServiceLocator.getInstance().getMemoryImage("pageMap");
    ConcurrentMap<Object, Object> cache = (ConcurrentMap<Object, Object>)pageMap.get("cache");
    if(cache == null) {
        cache = new ConcurrentLinkedHashMap.Builder<Object, Object>()
                .maximumWeightedCapacity(1000)
                .build();
        pageMap.put("cache", cache);
    } else {
        co = (CacheObject)cache.get(pageId);
    }
    if(co == null) {
        OrientVertex page = (OrientVertex)graph.getVertexByKey("Page.pageId", pageId);
        if(page != null) {
            String json = page.getRecord().toJSON();
            co = new CacheObject(page.getProperty("@version").toString(), json);
            cache.put(pageId, co);
        }
    }
    return co;
}
 
Example #16
Source File: AbstractPageRule.java    From light with Apache License 2.0 6 votes vote down vote up
protected void addPage(Map<String, Object> data) throws Exception {
    OrientGraph graph = ServiceLocator.getInstance().getGraph();
    try {
        graph.begin();
        Vertex createUser = graph.getVertexByKey("User.userId", data.remove("createUserId"));
        OrientVertex page = graph.addVertex("class:Page", data);
        createUser.addEdge("Create", page);
        graph.commit();
        String json = page.getRecord().toJSON();
        Map<String, Object> pageMap = ServiceLocator.getInstance().getMemoryImage("pageMap");
        ConcurrentMap<Object, Object> cache = (ConcurrentMap<Object, Object>)pageMap.get("cache");
        if(cache == null) {
            cache = new ConcurrentLinkedHashMap.Builder<Object, Object>()
                    .maximumWeightedCapacity(1000)
                    .build();
            pageMap.put("cache", cache);
        }
        cache.put(data.get("pageId"), new CacheObject(page.getProperty("@version").toString(), json));
    } catch (Exception e) {
        logger.error("Exception:", e);
        graph.rollback();
        throw e;
    } finally {
        graph.shutdown();
    }
}
 
Example #17
Source File: AbstractDependencyRule.java    From light with Apache License 2.0 5 votes vote down vote up
protected void addDependency(Map<String, Object> data) throws Exception {
    String json = null;
    OrientGraph graph = ServiceLocator.getInstance().getGraph();
    try {
        graph.begin();
        Vertex sourceRule = graph.getVertexByKey("Rule.ruleClass", data.get("sourceRuleClass"));
        Vertex destRule = graph.getVertexByKey("Rule.ruleClass", data.get("destRuleClass"));
        Edge edge = sourceRule.addEdge("Depend", destRule);
        edge.setProperty("content", data.get("content"));
        graph.commit();
        //json = edge.getRecord().toJSON();
    } catch (Exception e) {
        logger.error("Exception:", e);
        graph.rollback();
        throw e;
    } finally {
        graph.shutdown();
    }
    Map<String, Object> pageMap = ServiceLocator.getInstance().getMemoryImage("pageMap");
    ConcurrentMap<Object, Object> cache = (ConcurrentMap<Object, Object>)pageMap.get("cache");
    if(cache == null) {
        cache = new ConcurrentLinkedHashMap.Builder<Object, Object>()
                .maximumWeightedCapacity(1000)
                .build();
        pageMap.put("cache", cache);
    }
    cache.put(data.get("pageId"), json);
}
 
Example #18
Source File: AliasBlurFilterCache.java    From incubator-retired-blur with Apache License 2.0 5 votes vote down vote up
public AliasBlurFilterCache(BlurConfiguration configuration) {
  super(configuration);
  long _cacheEntries = 100;
  _preFilterCacheMap = new ConcurrentLinkedHashMap.Builder<FilterKey, Filter>()
      .maximumWeightedCapacity(_cacheEntries).build();
  _postFilterCacheMap = new ConcurrentLinkedHashMap.Builder<FilterKey, Filter>().maximumWeightedCapacity(
      _cacheEntries).build();
  Map<String, String> properties = configuration.getProperties();
  for (Entry<String, String> entry : properties.entrySet()) {
    if (isFilterAlias(entry.getKey())) {
      String value = entry.getValue();
      if (value == null || value.isEmpty()) {
        continue;
      }
      String name = getFilterAlias(entry.getKey());
      int index = name.indexOf('.');
      String table = name.substring(0, index);
      String alias = name.substring(index + 1);
      ConcurrentMap<String, String> aliasFilterMap = _tableAliasFilterMap.get(table);
      if (aliasFilterMap == null) {
        aliasFilterMap = new ConcurrentHashMap<String, String>();
        _tableAliasFilterMap.put(table, aliasFilterMap);
      }

      aliasFilterMap.put(alias, value);
    }
  }
}
 
Example #19
Source File: InMemoryMetricsRepository.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized void save(MetricEntity entity) {
    if (entity == null || StringUtil.isBlank(entity.getApp())) {
        return;
    }
    allMetrics.computeIfAbsent(entity.getApp(), e -> new ConcurrentHashMap<>(16))
        .computeIfAbsent(entity.getResource(), e -> new ConcurrentLinkedHashMap.Builder<Long, MetricEntity>()
            .maximumWeightedCapacity(MAX_METRIC_LIVE_TIME_MS).weigher((key, value) -> {
                // Metric older than {@link #MAX_METRIC_LIVE_TIME_MS} will be removed.
                int weight = (int)(System.currentTimeMillis() - key);
                // weight must be a number greater than or equal to one
                return Math.max(weight, 1);
            }).build()).put(entity.getTimestamp().getTime(), entity);
}
 
Example #20
Source File: TableBlockCache.java    From heftydb with Apache License 2.0 5 votes vote down vote up
public TableBlockCache(long maxSize, Weigher<T> weigher) {
    cache = new ConcurrentLinkedHashMap.Builder<Entry, T>().concurrencyLevel(CONCURRENCY_LEVEL).weigher(weigher)
            .listener(new EvictionListener<Entry, T>() {
        @Override
        public void onEviction(Entry key, T value) {
            totalSize.addAndGet(-(value.memory().size()));
            value.memory().release();
        }
    }).maximumWeightedCapacity(maxSize).build();
    this.maxSize = maxSize;
}
 
Example #21
Source File: AbstractPageRule.java    From light with Apache License 2.0 5 votes vote down vote up
protected void impPage(Map<String, Object> data) throws Exception {
    OrientGraph graph = ServiceLocator.getInstance().getGraph();
    String pageId = (String)data.get("pageId");
    try {
        graph.begin();
        OrientVertex page = (OrientVertex)graph.getVertexByKey("Page.pageId", pageId);
        if(page != null) {
            graph.removeVertex(page);
        }
        Vertex createUser = graph.getVertexByKey("User.userId", data.remove("createUserId"));
        page = graph.addVertex("class:Page", data);
        createUser.addEdge("Create", page);
        graph.commit();
        String json = page.getRecord().toJSON();
        Map<String, Object> pageMap = ServiceLocator.getInstance().getMemoryImage("pageMap");
        ConcurrentMap<Object, Object> cache = (ConcurrentMap<Object, Object>)pageMap.get("cache");
        if(cache == null) {
            cache = new ConcurrentLinkedHashMap.Builder<Object, Object>()
                    .maximumWeightedCapacity(1000)
                    .build();
            pageMap.put("cache", cache);
        }
        CacheObject co = (CacheObject)cache.get(pageId);
        if(co != null) {
            co.setEtag(page.getProperty("@version").toString());
            co.setData(json);
        } else {
            cache.put(pageId, new CacheObject(page.getProperty("@version").toString(), json));
        }
    } catch (Exception e) {
        logger.error("Exception:", e);
        graph.rollback();
        throw e;
    } finally {
        graph.shutdown();
    }
}
 
Example #22
Source File: AbstractFormRule.java    From light with Apache License 2.0 5 votes vote down vote up
protected String getFormById(Map<String, Object> inputMap) throws Exception {
    Map<String, Object> data = (Map<String, Object>)inputMap.get("data");
    String formId = (String)data.get("formId");
    String json  = null;
    Map<String, Object> formMap = ServiceLocator.getInstance().getMemoryImage("formMap");
    ConcurrentMap<Object, Object> cache = (ConcurrentMap<Object, Object>)formMap.get("cache");
    if(cache == null) {
        cache = new ConcurrentLinkedHashMap.Builder<Object, Object>()
                .maximumWeightedCapacity(100)
                .build();
        formMap.put("cache", cache);
    } else {
        json = (String)cache.get(formId);
    }
    if(json == null) {
        OrientGraph graph = ServiceLocator.getInstance().getGraph();
        try {
            OrientVertex form = (OrientVertex)graph.getVertexByKey("Form.formId", formId);
            if(form != null) {
                json = form.getRecord().toJSON();
                if(formId.endsWith("_d")) {
                    // enrich the form with dynamicOptions for drop down values
                    json = enrichForm(json, inputMap);
                }
                cache.put(formId, json);
            }
        } catch (Exception e) {
            logger.error("Exception:", e);
            throw e;
        } finally {
            graph.shutdown();
        }
    }
    return json;
}
 
Example #23
Source File: AbstractPageRule.java    From light with Apache License 2.0 5 votes vote down vote up
protected void updPage(Map<String, Object> data) {
    String pageId = (String)data.get("pageId");
    OrientGraph graph = ServiceLocator.getInstance().getGraph();
    try {
        graph.begin();
        OrientVertex page = (OrientVertex)graph.getVertexByKey("Page.pageId", pageId);
        if(page != null) {
            page.setProperty("content", data.get("content"));
            page.setProperty("updateDate", data.get("updateDate"));
            Vertex updateUser = graph.getVertexByKey("User.userId", data.get("updateUserId"));
            updateUser.addEdge("Update", page);
        }
        graph.commit();
        String json = page.getRecord().toJSON();
        Map<String, Object> pageMap = ServiceLocator.getInstance().getMemoryImage("pageMap");
        ConcurrentMap<Object, Object> cache = (ConcurrentMap<Object, Object>)pageMap.get("cache");
        if(cache == null) {
            cache = new ConcurrentLinkedHashMap.Builder<Object, Object>()
                    .maximumWeightedCapacity(1000)
                    .build();
            pageMap.put("cache", cache);
        }
        CacheObject co = (CacheObject)cache.get(pageId);
        if(co != null) {
            co.setEtag(page.getProperty("@version").toString());
            co.setData(json);
        } else {
            cache.put(pageId, new CacheObject(page.getProperty("@version").toString(), json));
        }
    } catch (Exception e) {
        logger.error("Exception:", e);
        graph.rollback();
        throw e;
    } finally {
        graph.shutdown();
    }
}
 
Example #24
Source File: BranchRule.java    From light with Apache License 2.0 5 votes vote down vote up
/**
 * Only this method needs to be cached as it is called by the site home rendering. Other get methods
 * are for admin only and no need to be cached.
 * @param branchType
 * @param objects
 * @return
 * @throws Exception
 */
public boolean getBranchTree(String branchType, Object ...objects) throws Exception {
    Map<String, Object> inputMap = (Map<String, Object>) objects[0];
    Map<String, Object> data = (Map<String, Object>)inputMap.get("data");
    String host = (String)data.get("host");
    String json = null;
    Map<String, Object> branchMap = ServiceLocator.getInstance().getMemoryImage("branchMap");
    ConcurrentMap<Object, Object> cache = (ConcurrentMap<Object, Object>)branchMap.get("treeCache");
    if(cache == null) {
        cache = new ConcurrentLinkedHashMap.Builder<Object, Object>()
                .maximumWeightedCapacity(100)
                .build();
        branchMap.put("treeCache", cache);
    } else {
        json = (String)cache.get(host + branchType);
    }
    if(json == null) {
        json = getBranchTreeDb(branchType, host);
        if(json != null) cache.put(host + branchType, json);
    }
    if(json != null) {
        inputMap.put("result", json);
        return true;
    } else {
        inputMap.put("result", "No document can be found");
        inputMap.put("responseCode", 404);
        return false;
    }
}
 
Example #25
Source File: AbstractMenuRule.java    From light with Apache License 2.0 5 votes vote down vote up
protected String addMenu( Map<String, Object> data) throws Exception {
    String json = null;
    OrientGraph graph = ServiceLocator.getInstance().getGraph();
    try {
        graph.begin();
        OrientVertex menu = graph.addVertex("class:Menu", "host", data.get("host"), "createDate", data.get("createDate"));
        List<String> addMenuItems = (List<String>)data.get("addMenuItems");
        if(addMenuItems != null && addMenuItems.size() > 0) {
            // find vertex for each menuItem id and create edge to it.
            for(String menuItemId: addMenuItems) {
                Vertex menuItem = graph.getVertexByKey("MenuItem.menuItemId", menuItemId);
                menu.addEdge("Own", menuItem);
            }
        }
        Vertex user = graph.getVertexByKey("User.userId", data.get("createUserId"));
        user.addEdge("Create", menu);
        graph.commit();
        json = menu.getRecord().toJSON("fetchPlan:menuItems:2");
    } catch (Exception e) {
        logger.error("Exception:", e);
        graph.rollback();
        throw e;
    } finally {
        graph.shutdown();
    }
    Map<String, Object> menuMap = (Map<String, Object>)ServiceLocator.getInstance().getMemoryImage("menuMap");
    ConcurrentMap<Object, Object> cache = (ConcurrentMap<Object, Object>)menuMap.get("cache");
    if(cache == null) {
        cache = new ConcurrentLinkedHashMap.Builder<Object, Object>()
                .maximumWeightedCapacity(100)
                .build();
        menuMap.put("cache", cache);
    }
    cache.put(data.get("host"), json);
    return json;
}
 
Example #26
Source File: AbstractRule.java    From light with Apache License 2.0 5 votes vote down vote up
public static Map<String, Object> getRuleByRuleClass(String ruleClass) throws Exception {
    Map<String, Object> map = null;
    Map<String, Object> ruleMap = ServiceLocator.getInstance().getMemoryImage("ruleMap");
    ConcurrentMap<String, Map<String, Object>> cache = (ConcurrentMap<String, Map<String, Object>>)ruleMap.get("cache");
    if(cache == null) {
        cache = new ConcurrentLinkedHashMap.Builder<String, Map<String, Object>>()
                .maximumWeightedCapacity(1000)
                .build();
        ruleMap.put("cache", cache);
    } else {
        map = cache.get(ruleClass);
    }
    if(map == null) {
        OrientGraph graph = ServiceLocator.getInstance().getGraph();
        try {
            OrientVertex rule = (OrientVertex)graph.getVertexByKey("Rule.ruleClass", ruleClass);
            if(rule != null) {
                map = rule.getRecord().toMap();
                // remove sourceCode as we don't need it and it is big
                map.remove("sourceCode");

                // convert schema to JsonSchema in order to speed up validation.
                if(map.get("schema") != null) {
                    JsonNode schemaNode = ServiceLocator.getInstance().getMapper().valueToTree(map.get("schema"));
                    JsonSchema schema = schemaFactory.getJsonSchema(schemaNode);
                    map.put("schema", schema);
                }

                logger.debug("map = " + map);
                cache.put(ruleClass, map);
            }
        } catch (Exception e) {
            logger.error("Exception:", e);
            throw e;
        } finally {
            graph.shutdown();
        }
    }
    return map;
}
 
Example #27
Source File: AbstractRule.java    From light with Apache License 2.0 5 votes vote down vote up
public Map<String, Object> getAccessByRuleClass(String ruleClass) throws Exception {
    Map<String, Object> access = null;
    Map<String, Object> accessMap = ServiceLocator.getInstance().getMemoryImage("accessMap");
    ConcurrentMap<Object, Object> cache = (ConcurrentMap<Object, Object>)accessMap.get("cache");
    if(cache == null) {
        cache = new ConcurrentLinkedHashMap.Builder<Object, Object>()
                .maximumWeightedCapacity(1000)
                .build();
        accessMap.put("cache", cache);
    } else {
        access = (Map<String, Object>)cache.get(ruleClass);
    }
    if(access == null) {
        OrientGraph graph = ServiceLocator.getInstance().getGraph();
        try {
            OrientVertex accessVertex = (OrientVertex)graph.getVertexByKey("Access.ruleClass", ruleClass);
            if(accessVertex != null) {
                String json = accessVertex.getRecord().toJSON();
                access = mapper.readValue(json,
                        new TypeReference<HashMap<String, Object>>() {
                        });
                cache.put(ruleClass, access);
            }
        } catch (Exception e) {
            logger.error("Exception:", e);
            throw e;
        } finally {
            graph.shutdown();
        }
    }
    return access;
}
 
Example #28
Source File: GetContentRule.java    From light with Apache License 2.0 5 votes vote down vote up
public boolean execute(Object ...objects) throws Exception {
    Map<String, Object> inputMap = (Map<String, Object>) objects[0];
    Map<String, Object> data = (Map<String, Object>) inputMap.get("data");
    // here we get user's host to decide which domain he/she can access
    Map<String, Object> user = (Map<String, Object>) inputMap.get("user");
    String host = (String) user.get("host");
    if(host == null) {
        host = (String)data.get("host");
    }
    String path = (String) data.get("path");
    String root = getRootPath(host);
    String absPath = getAbsPath(root, path);
    // now save this absPath into the in memory cache and return a uuid key to the client in order to
    // download the file.
    Map<String, Object> fileMap = ServiceLocator.getInstance().getMemoryImage("fileMap");
    ConcurrentMap<Object, Object> cache = (ConcurrentMap<Object, Object>)fileMap.get("cache");
    if(cache == null) {
        cache = new ConcurrentLinkedHashMap.Builder<Object, Object>()
                .maximumWeightedCapacity(100)
                .build();
        fileMap.put("cache", cache);
    }
    String token = HashUtil.generateUUID();
    cache.put(token, absPath);
    Map<String, Object> result = new HashMap<String,Object>();
    result.put("token", token);
    inputMap.put("result", mapper.writeValueAsString(result));
    return true;
}
 
Example #29
Source File: PerfHashBenchmark.java    From concurrentlinkedhashmap with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
  while( !_start ) {
    try { Thread.sleep(1); } catch( Exception e ){}
  }

  long nano1 = System.nanoTime();

  int total = 0;
  if( _read_ratio == 0 ) {
    total = run_churn();
  } else {
    if( _hash instanceof ConcurrentLinkedHashMap) {
      total = run_normal( (ConcurrentLinkedHashMap<String,String>) _hash);
    } else if( _hash instanceof NonBlockingHashMap ) {
      total = run_normal( (NonBlockingHashMap<String,String>) _hash);
    } else if( _hash instanceof ConcurrentHashMap ) {
      total = run_normal( (ConcurrentHashMap<String,String>) _hash);
    } else {
      total = run_normal(_hash);
    }
  }

  _ops[_tnum] = total;
  long nano2 = System.nanoTime();
  _nanos[_tnum] = (nano2-nano1);
}
 
Example #30
Source File: PersistableCache.java    From ServerCore with Apache License 2.0 5 votes vote down vote up
public PersistableCache(JdbcTemplate template, int size) {
    dataMap = new ConcurrentLinkedHashMap.Builder<Long, Persistable>().maximumWeightedCapacity(size).weigher(Weighers.singleton())
            .listener((id, data) -> {
                if (data.isDirty()) {
                    //如果发现数据是脏的,那么重新put一次,保证及时入库
                    LOGGER.error("脏数据从缓存中移除了:" + id);
                }
            }).build();
}