@BeforeClass
  public static void beforeEachClass() throws Exception {

    context = mock(ExecutionContext.class);

    final DefaultCacheManager container =
        new DefaultCacheManager("./src/test/resources/infinispan_persistent_config.xml", true);

    TradesCacheSource.loadCache(container.getCache(TradesCacheSource.TRADES_CACHE_NAME));

    factory =
        new InfinispanManagedConnectionFactory() {

          /** */
          private static final long serialVersionUID = 6241061876834919893L;

          @Override
          protected Object performJNDICacheLookup(String jnidName) throws Exception {
            return container;
          }
        };

    factory.setCacheJndiName(JNDI_NAME);
    factory.setCacheTypeMap(
        RemoteInfinispanTestHelper.TRADE_CACHE_NAME + ":" + Trade.class.getName());

    tfactory = new InfinispanCacheExecutionFactory();

    tfactory.start();
  }
Пример #2
0
  public void testMemoryConsumption() throws InterruptedException {
    DefaultCacheManager cm = new DefaultCacheManager(true);

    Cache<Object, Object> cache = cm.getCache();

    long freeMemBefore = freeMemKb();
    System.out.println("freeMemBefore = " + freeMemBefore);

    for (int i = 0; i < 1024 * 300; i++) {
      cache.put(i, i);
    }
    System.out.println("Free meme after: " + freeMemKb());
    System.out.println("Consumed memory: " + (freeMemBefore - freeMemKb()));
    cm.stop();
    for (int i = 0; i < 10; i++) {
      System.gc();
      if (isOkay(freeMemBefore)) {
        break;
      } else {
        Thread.sleep(1000);
      }
    }
    System.out.println("Free memory at the end:" + freeMemKb());
    assert isOkay(freeMemBefore);
  }
Пример #3
0
 @PostConstruct
 public void generateCache() {
   m = new DefaultCacheManager();
   Configuration c = new Configuration();
   m.defineConfiguration("defaultCache", c);
   cache = m.getCache("defaultCache");
 }
Пример #4
0
  public void testRun() throws Exception {
    String wsName = "test";
    DefaultCacheManager dcm = new DefaultCacheManager();
    Cache<String, Metadata> metaCache = dcm.getCache("meta");
    Cache<String, byte[]> dataCache = dcm.getCache("data");

    GridFilesystem gfs = new GridFilesystem(dataCache, metaCache);

    BuildContext bcontext =
        DirectoryBuilder.newDirectoryInstance(metaCache, dataCache, metaCache, wsName);
    bcontext.chunkSize(1024 * 1024);
    Directory directory = bcontext.create();
    Central central = CentralConfig.oldFromDir(directory).build();

    central.newIndexer().index(IndexJobs.create("/bleujin", 10));

    central.newSearcher().createRequest("").find().debugPrint();

    OutputStream output = gfs.getOutput("/test.data");
    IOUtil.copyNClose(new StringInputStream("hello bleujin"), output);

    Debug.line(IOUtil.toStringWithClose(gfs.getInput("/test.data")));

    central.newSearcher().createRequest("").find().debugPrint();

    File root = gfs.getFile("/");
    viewFile(root);

    dcm.stop();
  }
Пример #5
0
 @Test
 public void testDummyTMGetCache() {
   ConfigurationBuilder cb = new ConfigurationBuilder();
   cb.transaction()
       .use1PcForAutoCommitTransactions(true)
       .transactionManagerLookup(new DummyTransactionManagerLookup());
   DefaultCacheManager cm = new DefaultCacheManager(cb.build());
   cm.getCache();
 }
Пример #6
0
  @Test
  public void testGetAndPut() {
    // new configuration
    DefaultCacheManager cacheManager = new DefaultCacheManager(new ConfigurationBuilder().build());

    Cache<String, String> cache = cacheManager.getCache();
    cache.put("Foo", "2");
    cache.put("Bar", "4");

    Assert.assertEquals(cache.get("Foo"), "2");
    Assert.assertEquals(cache.get("Bar"), "4");
  }
Пример #7
0
 public static void main(String[] args) throws IOException {
   DefaultCacheManager cacheManager =
       new DefaultCacheManager("config-samples/lucene-demo-cache-config.xml");
   cacheManager.start();
   try {
     Cache<?, ?> cache = cacheManager.getCache();
     InfinispanDirectory directory = new InfinispanDirectory(cache);
     DemoDriver driver = new DemoDriver(directory, cache);
     driver.run();
   } finally {
     cacheManager.stop();
   }
 }
  @Override
  public Object removeObject(Object key) {
    // TODO Auto-generated method stub
    Cache cache = cacheManager.getCache(this.id);

    return cache.remove((String) key.toString());
  }
 @Test(expected = CacheException.class)
 public void testTimestampValidation() {
   Properties p = createProperties();
   final DefaultCacheManager manager =
       new DefaultCacheManager(GlobalConfigurationBuilder.defaultClusteredBuilder().build());
   try {
     InfinispanRegionFactory factory = createRegionFactory(manager, p);
     ConfigurationBuilder builder = new ConfigurationBuilder();
     builder.clustering().cacheMode(CacheMode.INVALIDATION_SYNC);
     manager.defineConfiguration("timestamps", builder.build());
     factory.start(null, p);
     fail("Should have failed saying that invalidation is not allowed for timestamp caches.");
   } finally {
     TestingUtil.killCacheManagers(manager);
   }
 }
Пример #10
0
  public static synchronized HotRodServer createServer() throws IOException {
    count++;
    if (server == null) {
      CACHEMANAGER = new DefaultCacheManager(CONFIG_FILE);

      CACHEMANAGER.start();
      // This doesn't work on IPv6, because the util assumes "127.0.0.1" ...
      // server = HotRodTestingUtil.startHotRodServer(cacheManager, HOST, PORT);

      server = new HotRodServer();
      String hostAddress = hostAddress();
      String hostPort = Integer.toString(hostPort());
      String timeoutStr = Integer.toString(TIMEOUT);
      Properties props = new Properties();
      props.setProperty(Main.PROP_KEY_HOST(), hostAddress);
      props.setProperty(Main.PROP_KEY_PORT(), hostPort);
      props.setProperty(Main.PROP_KEY_IDLE_TIMEOUT(), timeoutStr);
      props.setProperty(Main.PROP_KEY_PROXY_HOST(), hostAddress);
      props.setProperty(Main.PROP_KEY_PROXY_PORT(), hostPort);
      // System.out.println("Starting HotRot Server at " + hostAddress + ":" + hostPort);
      server.start(props, CACHEMANAGER);

      server.cacheManager().startCaches(CACHE_NAME);

      server
          .getCacheManager()
          .getCache(CACHE_NAME)
          .put("1", new String("value1")); // $NON-NLS-1$  //$NON-NLS-2$
      server
          .getCacheManager()
          .getCache(CACHE_NAME)
          .put("2", new String("value2")); // $NON-NLS-1$  //$NON-NLS-2$
    }
    return server;
  }
  private static ObjectConnection createConnection(DefaultCacheManager container) {
    TradesCacheSource.loadCache(container.getCache(TradesCacheSource.TRADES_CACHE_NAME));

    CacheContainerWrapper wrapper = new TestInfinispanCacheWrapper(container);

    ObjectConnection conn = new TestInfinispanConnection(wrapper, container);

    return conn;
  }
 @Override
 public int getSize() {
   // TODO Auto-generated method stub
   Cache<String, Object> cache = cacheManager.getCache(this.id);
   if (cache == null) {
     return 0;
   }
   return cache.size();
 }
  public void add() {
    Cache<Long, Product> cache = cacheManager.getCache();

    Product product = new Product(id, name, description, pieces, price);

    cache.put(id, product);

    message = "Product successfully added.";
    logger.info("Added product: " + product);
  }
  @Override
  public synchronized void deleted(String pid) {
    ServiceRegistration<EmbeddedCacheManager> serviceRegistration =
        managedRegistrations.remove(pid);
    if (serviceRegistration != null) {
      try {
        serviceRegistration.unregister();
      } catch (Exception e) {
      }
    }

    DefaultCacheManager cacheManager = cacheManagers.remove(pid);
    if (cacheManager != null) {
      try {
        cacheManager.stop();
      } catch (Exception e) {
      }
    }
  }
  @Override
  public synchronized void updated(String pid, @SuppressWarnings("rawtypes") Dictionary properties)
      throws ConfigurationException {
    String config = (String) properties.get(PROP_CONFIG);
    if (config == null) {
      throw new ConfigurationException(PROP_CONFIG, "Property must be set");
    }

    String instanceId = (String) properties.get(PROP_INSTANCE_ID);
    if (instanceId == null) {
      throw new ConfigurationException(PROP_INSTANCE_ID, "Property must be set");
    }

    try {
      URL configURL =
          new FileLookup()
              .lookupFileLocation(config, Thread.currentThread().getContextClassLoader());
      if (configURL == null) {
        throw new ConfigurationException(
            PROP_CONFIG, String.format("Failed to find the specified config '%s'.", config));
      }

      /* Unregister and destroy the old object. */
      deleted(pid);

      InputStream configStream = configURL.openStream();
      DefaultCacheManager cacheManager = new DefaultCacheManager(configStream);

      cacheManager.start();

      Hashtable<String, String> ht = new Hashtable<String, String>();
      ht.put(PROP_INSTANCE_ID, instanceId);
      ht.put(PROP_CONFIG, config);

      ServiceRegistration<EmbeddedCacheManager> serviceRegistration =
          bundleContext.registerService(EmbeddedCacheManager.class, cacheManager, ht);

      managedRegistrations.put(pid, serviceRegistration);
      cacheManagers.put(pid, cacheManager);
    } catch (Exception e) {
      throw new ConfigurationException(null, "Cannot start the CacheManager", e);
    }
  }
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    log.info("putting hello");
    Cache<String, String> c = m.getCache();
    String x = (String) c.get("hello");

    PrintWriter writer = resp.getWriter();
    writer.println(PAGE_HEADER);
    writer.println("<h1>" + "Get Infinispan: " + x + "</h1>");
    writer.println(PAGE_FOOTER);
    writer.close();
  }
Пример #17
0
  /**
   * Extract the BinaryStore out of Modeshape (infinspan, jdbc, file, transient, etc)
   *
   * @return
   */
  @Override
  public Map<String, String> apply(final Repository input) {
    checkNotNull(input, "null cannot have a BinaryStore!");

    final Map<String, String> result = new LinkedHashMap<>();
    final BinaryStore store = getBinaryStore.apply(input);

    if (!(store instanceof InfinispanBinaryStore)) {
      return result;
    }

    final InfinispanBinaryStore ispnStore = (InfinispanBinaryStore) store;

    final List<Cache<?, ?>> caches = ispnStore.getCaches();
    final DefaultCacheManager cm = (DefaultCacheManager) caches.get(0).getCacheManager();

    if (cm == null) {
      LOGGER.debug("Could not get cluster configuration information");
      return result;
    }

    final int nodeView;

    if (cm.getTransport() != null) {
      nodeView = cm.getTransport().getViewId() + 1;
    } else {
      nodeView = UNKNOWN_NODE_VIEW;
    }

    result.put(CLUSTER_NAME, cm.getClusterName());
    result.put(
        CACHE_MODE, cm.getCache().getCacheConfiguration().clustering().cacheMode().toString());
    result.put(NODE_ADDRESS, cm.getNodeAddress());
    result.put(PHYSICAL_ADDRESS, cm.getPhysicalAddresses());
    result.put(NODE_VIEW, nodeView == UNKNOWN_NODE_VIEW ? "Unknown" : String.valueOf(nodeView));
    result.put(CLUSTER_SIZE, String.valueOf(cm.getClusterSize()));
    result.put(CLUSTER_MEMBERS, cm.getClusterMembers());
    return result;
  }
 /**
  * 만료시간이 설정되어있을 때 Flag값을 주어 0.5초 전이라면 다시 cache에 put해줄 수 있도록 체크
  *
  * @param map
  * @param key
  * @return true/false
  */
 private boolean checkLt(Map<String, Object> map, String key) {
   if (null == map.get("lifeTime")) {
     return false;
   }
   Cache<String, Object> cache = cacheManager.getCache(this.id);
   Long lifeTime = (Long) map.get("lifeTime");
   Long currTime = System.currentTimeMillis();
   if (null != lifeTime && (lifeTime - 500) < currTime && currTime < lifeTime) {
     if ((Boolean) map.get("cacheFlag")) {
       // 캐시를 다시 put하는 동안 다른 Thread가 캐시에서 읽어가도록 flag를 false로 세팅
       map.put("cacheFlag", false);
       // cache.put(key.toString(), map);
       // sonar에서 스트링객체에 toString을 호출하는 것이 불필요하다고 하여 다음과 같이 수정
       cache.put(key, map);
       return true;
     }
   }
   return false;
 }
  @Override
  public void putObject(Object key, Object value) {

    // Cache<String, Object> cache = cacheManager.getCache(this.id);
    // cache.put(key.toString(), value);
    Cache<String, Object> cache = cacheManager.getCache(this.id);

    Map<String, Object> map = new HashMap<String, Object>();
    map.put("data", value);
    // 만료 시간을 설정한 경우 현재시간에 만료시간을 더한 값을 map에 put해준다.
    Long lifeTime = cache.getCacheConfiguration().expiration().lifespan();
    if (-1 != lifeTime) {
      map.put("lifeTime", lifeTime + System.currentTimeMillis());
      map.put("cacheFlag", true);
    }
    cache.put(key.toString(), map);

    if (LOG.isDebugEnabled()) {
      LOG.debug("Cache Key(putObject) : " + key);
      LOG.debug("Cache Key(size) : " + getSize());
    }
  }
Пример #20
0
  public static synchronized void releaseServer() {
    --count;
    if (count <= 0) {

      try {
        if (CACHEMANAGER != null) {
          CACHEMANAGER.stop();
        }
      } finally {
        CACHEMANAGER = null;
      }

      try {
        // System.out.println("Stopping HotRot Server at " + hostAddress() + ":" + hostPort());
        if (server != null) {
          server.stop();
        }
      } finally {
        server = null;
      }
    }
  }
  @Override
  public Object getObject(Object key) {

    Cache<String, Object> cache = cacheManager.getCache(this.id);

    // Object result = cache.get(key.toString());
    Map<String, Object> result = (Map<String, Object>) cache.get(key.toString());
    Object value = cache.get(key.toString());
    if (null != result) {
      value = result.get("data");
      if (checkLt(result, key.toString())) {
        // 만료시간0.5초 전이라면 cache에 값을 put
        return null;
      }
    }
    if (LOG.isDebugEnabled()) {
      LOG.debug("Cache Key(getObject) : " + key);
      LOG.debug("Cache Key(size) : " + getSize());
      //			LOG.debug("Cache result : " + result); 결과 값 클 때 디버그 출력하다가 멈춤
    }

    return value;
  }
 @Override
 protected long getSavedSessionsCount() {
   return cm.getCache("jbpm-configured-cache").size();
 }
 @AfterClass
 public static void stopCacheManagers() {
   PRECONFIGURED_DEFAULT_CACHE_MANAGER.stop();
   DEFAULT_CACHE_MANAGER.stop();
 }
 @BeforeClass
 public static void startCacheManagers() {
   DEFAULT_CACHE_MANAGER.start();
   PRECONFIGURED_DEFAULT_CACHE_MANAGER.start();
 }
 @Override
 public BasicCache getCache(String cacheName) {
   return dcm.getCache(cacheName);
 }
Пример #26
0
 @PreDestroy
 public void cleanUp() {
   manager.stop();
   manager = null;
 }
Пример #27
0
 @Test
 public void testDefineNamedCache() {
   DefaultCacheManager cacheManager = new DefaultCacheManager(new ConfigurationBuilder().build());
   cacheManager.defineConfiguration("foo", new ConfigurationBuilder().build());
 }
 @Override
 public void clear() {
   // TODO Auto-generated method stub
   Cache<String, Object> cache = cacheManager.getCache(this.id);
   cache.clear();
 }
Пример #29
0
 private void initProtobufMetadataManager(
     DefaultCacheManager cacheManager, GlobalComponentRegistry gcr) {
   ProtobufMetadataManagerImpl protobufMetadataManager = new ProtobufMetadataManagerImpl();
   gcr.registerComponent(protobufMetadataManager, ProtobufMetadataManager.class);
   registerProtobufMetadataManagerMBean(protobufMetadataManager, gcr, cacheManager.getName());
 }