Java Code Examples for org.infinispan.Cache

The following are top voted examples for showing how to use org.infinispan.Cache. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: hacep   File: ClusterTest.java   View source code 6 votes vote down vote up
@Test
public void testClusterSize() {
    System.setProperty("grid.buffer", "10");

    RulesConfigurationTestImpl rulesConfigurationTest = RulesTestBuilder.buildV1();
    RulesManager rulesManager = new RulesManager(rulesConfigurationTest);
    rulesManager.start(null, null, null);

    LOGGER.info("Start test cluster size");
    Cache<Key, HAKieSession> cache1 = startNodes(2, rulesManager).getCache();
    Cache<Key, HAKieSession> cache2 = startNodes(2, rulesManager).getCache();

    assertEquals(2, ((DefaultCacheManager) cache1.getCacheManager()).getClusterSize());
    assertEquals(2, ((DefaultCacheManager) cache2.getCacheManager()).getClusterSize());
    LOGGER.info("End test cluster size");
    rulesManager.stop();
}
 
Example 2
Project: hacep   File: PrimaryConsoleCommand.java   View source code 6 votes vote down vote up
@Override
public boolean execute(UI console, Iterator<String> args) throws IllegalParametersException {

    String cacheName = args.next();
    Cache<Key, Object> cache = application.getCacheManager().getCache(cacheName, false);

    if (cache != null) {
        Set<String> primaryVals = jdgUtility.primaryValuesFromKeys(cache);
        primaryVals.forEach(console::println);
        console.println("Cache Size: " + cache.size() + "\n");
        console.println("Primary Size: " + primaryVals.size() + "\n");
    } else {
        console.println("Cache " + cacheName + " not existent");
    }
    return true;
}
 
Example 3
Project: hacep   File: ReplicaConsoleCommand.java   View source code 6 votes vote down vote up
@Override
public boolean execute(UI console, Iterator<String> args) throws IllegalParametersException {

    String cacheName = args.next();
    Cache<Key, Object> cache = application.getCacheManager().getCache(cacheName, false);

    if (cache != null) {
        Set<String> replicas = jdgUtility.replicaValuesFromKeys(cache);
        replicas.forEach(console::println);
        console.println("Cache Size: " + cache.size() + "\n");
        console.println("Replica Size: " + replicas.size() + "\n");
    } else {
        console.println("Cache " + cacheName + " not existent");
    }
    return true;
}
 
Example 4
Project: hacep   File: InfoConsoleCommand.java   View source code 6 votes vote down vote up
@Override
public boolean execute(UI console, Iterator<String> args) throws IllegalParametersException {
    try {
        String cacheName = args.next();
        Cache<Key, Object> cache = application.getCacheManager().getCache(cacheName, false);

        if (cache != null) {
            console.println(buildInfo(cache));
        } else {
            console.println("Cache " + cacheName + " not existent");
        }

    } catch (NoSuchElementException e) {
        console.println(application.info());
    }
    return true;

}
 
Example 5
Project: jdg7-example   File: WordCountAp.java   View source code 6 votes vote down vote up
@GET
@Path("/put")
public String put(@QueryParam("num") int num) {
    log.debugf("PUT START num=%d", num);
    
    int putNum = num == 0 ? 1 : num;
    
    Cache<Long, String> cache = jdg.getManager().getCache("default");
    
    IntStream.rangeClosed(1, putNum).parallel().forEach(i -> {
        cache.put(
                uid.incrementAndGet(),
                kokoro.getRandom(),      // 夏目漱石「こころ」からランダムに1行取得してput
                1,                       // LifeSapn = 1分(putしてから1分後に自動削除)
                TimeUnit.MINUTES );
        });
    
    int cacheSize = cache.size();
    log.debugf("PUT END cacheSize=%,d", cacheSize);
    return "" + cacheSize;
}
 
Example 6
Project: syndesis-rest   File: DataManager.java   View source code 6 votes vote down vote up
public <T extends WithId<T>> ListResult<T> fetchAll(Class<T> model, Function<ListResult<T>, ListResult<T>>... operators) {

        ListResult<T> result;
        if( getDataAccessObject(model)!=null ) {
            result = doWithDataAccessObject(model, d -> d.fetchAll());
        } else {
            Kind kind = Kind.from(model);
            Cache<String, T> cache = caches.getCache(kind.getModelName());
            result = ListResult.of(cache.values());
        }

        for (Function<ListResult<T>, ListResult<T>> operator : operators) {
            result = operator.apply(result);
        }
        return result;
    }
 
Example 7
Project: syndesis-rest   File: DataManager.java   View source code 6 votes vote down vote up
public <T extends WithId<T>> T create(final T entity) {
    Kind kind = entity.getKind();
    Cache<String, T> cache = caches.getCache(kind.getModelName());
    Optional<String> id = entity.getId();
    String idVal;

    final T entityToCreate;
    if (!id.isPresent()) {
        idVal = KeyGenerator.createKey();
        entityToCreate = entity.withId(idVal);
    } else {
        idVal = id.get();
        if (cache.keySet().contains(idVal)) {
            throw new EntityExistsException("There already exists a "
                + kind + " with id " + idVal);
        }
        entityToCreate = entity;
    }

    this.<T, T>doWithDataAccessObject(kind.getModelClass(), d -> d.create(entityToCreate));
    cache.put(idVal, entityToCreate);
    broadcast("created", kind.getModelName(), idVal);
    return entityToCreate;
}
 
Example 8
Project: playground   File: ProcessingNode.java   View source code 6 votes vote down vote up
/**
 * The first argument is the name of the node.
 */
public ProcessingNode(String name, String configurationFileName) throws Exception
{
    if (name == null)
    {
        this.name = "ANONYMOUS";
    }
    else
    {
        this.name = name;
    }

    this.configurationFileName = configurationFileName;

    caches = new HashMap<String, Cache>();
}
 
Example 9
Project: playground   File: AccessServlet.java   View source code 6 votes vote down vote up
@Override
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
    {

        ServiceContainer sc = CurrentServiceContainer.getServiceContainer();

//        for(ServiceName sn: sc.getServiceNames()) {
//            log.info("" + sn);
//        }

        ServiceName sn = ServiceName.of("jboss", "infinispan", "web", "repl");
        ServiceController scon = sc.getService(sn);
        Cache cache = (Cache)scon.getValue();
        log.info("" + cache);


        String path = req.getPathInfo();

        Object o = null;

        if ("/put".equals(path)) {
            cache.put("test", "blah");
        }
        else if ("/get".equals(path)) {

            o = cache.get("test");
        }

        res.setContentType("text/html");
        PrintWriter out = res.getWriter();

        if (o != null) {
            out.println(o);
        }
    }
 
Example 10
Project: Camel   File: InfinispanConsumerEmbeddedHandler.java   View source code 6 votes vote down vote up
@Override
public InfinispanEventListener start(InfinispanConsumer consumer) {
    Cache<?, ?> embeddedCache = InfinispanUtil.asEmbedded(consumer.getCache());
    InfinispanConfiguration configuration = consumer.getConfiguration();
    InfinispanEventListener listener;
    if (configuration.hasCustomListener()) {
        listener = configuration.getCustomListener();
        listener.setInfinispanConsumer(consumer);
    } else if (configuration.isClusteredListener()) {
        if (configuration.isSync()) {
            listener = new InfinispanSyncClusteredEventListener(consumer, configuration.getEventTypes());
        } else {
            listener = new InfinispanAsyncClusteredEventListener(consumer, configuration.getEventTypes());
        }
    } else {
        if (configuration.isSync()) {
            listener = new InfinispanSyncLocalEventListener(consumer, configuration.getEventTypes());
        } else {
            listener = new InfinispanAsyncLocalEventListener(consumer, configuration.getEventTypes());
        }
    }
    embeddedCache.addListener(listener);
    return listener;
}
 
Example 11
Project: infinispan-simple-tutorials   File: InfinispanQuery.java   View source code 6 votes vote down vote up
public static void main(String[] args) {
   ConfigurationBuilder builder = new ConfigurationBuilder();
   builder.indexing().index(Index.ALL)
      .addProperty("default.directory_provider", "ram")
      .addProperty("lucene_version", "LUCENE_CURRENT");
   // Construct a simple local cache manager with default configuration
   DefaultCacheManager cacheManager = new DefaultCacheManager(builder.build());
   // Obtain the default cache
   Cache<String, Person> cache = cacheManager.getCache();
   // Store some entries
   cache.put("person1", new Person("William", "Shakespeare"));
   cache.put("person2", new Person("William", "Wordsworth"));
   cache.put("person3", new Person("John", "Milton"));
   // Obtain a query factory for the cache
   QueryFactory queryFactory = Search.getQueryFactory(cache);
   // Construct a query
   Query query = queryFactory.from(Person.class).having("name").eq("William").toBuilder().build();
   // Execute the query
   List<Person> matches = query.list();
   // List the results
   matches.forEach(person -> System.out.printf("Match: %s", person));
   // Stop the cache manager and release all resources
   cacheManager.stop();
}
 
Example 12
Project: infinispan-simple-tutorials   File: InfinispanReplicated.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws Exception {
   // Setup up a clustered cache manager
   GlobalConfigurationBuilder global = GlobalConfigurationBuilder.defaultClusteredBuilder();
   // Make the default cache a replicated synchronous one
   ConfigurationBuilder builder = new ConfigurationBuilder();
   builder.clustering().cacheMode(CacheMode.REPL_SYNC);
   // Initialize the cache manager
   DefaultCacheManager cacheManager = new DefaultCacheManager(global.build(), builder.build());
   // Obtain the default cache
   Cache<String, String> cache = cacheManager.getCache();
   // Store the current node address in some random keys
   for(int i=0; i < 10; i++) {
      cache.put(UUID.randomUUID().toString(), cacheManager.getNodeAddress());
   }
   // Display the current cache contents for the whole cluster
   cache.entrySet().forEach(entry -> System.out.printf("%s = %s\n", entry.getKey(), entry.getValue()));
   // Display the current cache contents for this node
   cache.getAdvancedCache().withFlags(Flag.SKIP_REMOTE_LOOKUP)
      .entrySet().forEach(entry -> System.out.printf("%s = %s\n", entry.getKey(), entry.getValue()));
   // Stop the cache manager and release all resources
   cacheManager.stop();
}
 
Example 13
Project: infinispan-simple-tutorials   File: InfinispanStreams.java   View source code 6 votes vote down vote up
public static void main(String[] args) {
   // Construct a simple local cache manager with default configuration
   DefaultCacheManager cacheManager = new DefaultCacheManager();
   // Define local cache configuration
   cacheManager.defineConfiguration("local", new ConfigurationBuilder().build());
   // Obtain the local cache
   Cache<String, String> cache = cacheManager.getCache("local");
   // Store some values
   int range = 10;
   IntStream.range(0, range).boxed().forEach(i -> cache.put(i + "-key", i + "-value"));
   // Map and reduce the keys
   int result = cache.keySet().stream()
      .map((Serializable & Function<String, Integer>) e -> Integer.valueOf(e.substring(0, e.indexOf("-"))))
           .collect(CacheCollectors.serializableCollector(() -> Collectors.summingInt(i -> i.intValue())));
   System.out.printf("Result = %d\n", result);
   // Stop the cache manager and release all resources
   cacheManager.stop();
}
 
Example 14
Project: infinispan-simple-tutorials   File: InfinispanListen.java   View source code 6 votes vote down vote up
public static void main(String[] args) {
   // Construct a simple local cache manager with default configuration
   DefaultCacheManager cacheManager = new DefaultCacheManager();
   // Define local cache configuration
   cacheManager.defineConfiguration("local", new ConfigurationBuilder().build());
   // Obtain the local cache
   Cache<String, String> cache = cacheManager.getCache("local");
   // Register a listener
   cache.addListener(new MyListener());
   // Store some values
   cache.put("key1", "value1");
   cache.put("key2", "value2");
   cache.put("key1", "newValue");
   // Stop the cache manager and release all resources
   cacheManager.stop();
}
 
Example 15
Project: infinispan-simple-tutorials   File: InfinispanDistExec.java   View source code 6 votes vote down vote up
public static void main(String[] args) {
   // Setup up a clustered cache manager
   GlobalConfigurationBuilder global = GlobalConfigurationBuilder.defaultClusteredBuilder();
   // Make the default cache a distributed one
   ConfigurationBuilder builder = new ConfigurationBuilder();
   builder.clustering().cacheMode(CacheMode.DIST_SYNC);
   // Initialize the cache manager
   DefaultCacheManager cacheManager = new DefaultCacheManager(global.build(), builder.build());
   // Obtain the default cache
   Cache<String, String> cache = cacheManager.getCache();
   // Create a distributed executor service using the distributed cache to determine the nodes on which to run
   DefaultExecutorService executorService = new DefaultExecutorService(cache);
   // Submit a job to all nodes
   List<Future<Integer>> results = executorService.submitEverywhere((Callable & Serializable) () -> new Random().nextInt());
   // Print out the results
   results.forEach(s -> {
      try {
         System.out.printf("%s\n", s.get(100, TimeUnit.MILLISECONDS));
      } catch (Exception e) {
      }
   });
   // Shuts down the cache manager and all associated resources
   cacheManager.stop();
   System.exit(0);
}
 
Example 16
Project: infinispan-simple-tutorials   File: InfinispanDistributed.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws Exception {
   // Setup up a clustered cache manager
   GlobalConfigurationBuilder global = GlobalConfigurationBuilder.defaultClusteredBuilder();
   // Make the default cache a distributed synchronous one
   ConfigurationBuilder builder = new ConfigurationBuilder();
   builder.clustering().cacheMode(CacheMode.DIST_SYNC);
   // Initialize the cache manager
   DefaultCacheManager cacheManager = new DefaultCacheManager(global.build(), builder.build());
   // Obtain the default cache
   Cache<String, String> cache = cacheManager.getCache();
   // Store the current node address in some random keys
   for(int i=0; i < 10; i++) {
      cache.put(UUID.randomUUID().toString(), cacheManager.getNodeAddress());
   }
   // Display the current cache contents for the whole cluster
   cache.entrySet().forEach(entry -> System.out.printf("%s = %s\n", entry.getKey(), entry.getValue()));
   // Display the current cache contents for this node
   cache.getAdvancedCache().withFlags(Flag.SKIP_REMOTE_LOOKUP)
      .entrySet().forEach(entry -> System.out.printf("%s = %s\n", entry.getKey(), entry.getValue()));
   // Stop the cache manager and release all resources
   cacheManager.stop();
}
 
Example 17
Project: owsi-core-parent   File: InfinispanClusterServiceImpl.java   View source code 6 votes vote down vote up
private void filterPriorityQueue(IPriorityQueue priorityQueue, Predicate<IAttribution> attributionPredicate) {
	Cache<IPriorityQueue, List<IAttribution>> cache = getPriorityQueuesCache();
	boolean commit = false;
	if (!cache.getAdvancedCache().startBatch()) {
		LOGGER.error("Batch attempt on {} failed", priorityQueue);
	}
	try {
		// get lock values
		if (!cache.getAdvancedCache().lock(priorityQueue)) {
			LOGGER.error("Lock attempt on {} failed", priorityQueue);
			commit = false;
			return;
		}
		List<IAttribution> values = cache.getOrDefault(priorityQueue, Lists.<IAttribution> newArrayList());
		List<IAttribution> newValues = Lists.newArrayList(Collections2.filter(values, attributionPredicate));
		cache.put(priorityQueue, newValues);
		commit = true;
	} finally {
		cache.endBatch(commit);
	}
}
 
Example 18
Project: hawkular-commons   File: InventoryServiceIspnTest.java   View source code 6 votes vote down vote up
public InventoryServiceIspnTest() throws IOException {
    Cache<String, Object> resource = CACHE_MANAGER.getCache("resource");
    Cache<String, Object> resourceType = CACHE_MANAGER.getCache("resource_type");
    resource.clear();
    resourceType.clear();
    inventoryStats = new InventoryStats(resource,
            resourceType,
            new File(((SingleFileStoreConfiguration) resource.getAdvancedCache()
                    .getCacheConfiguration()
                    .persistence()
                    .stores()
                    .iterator()
                    .next()).location()));
    inventoryStats.init();
    ScrapeConfig scrapeConfig = null;
    try {
        scrapeConfig = JsonUtil.getYamlMapper().readValue(InventoryServiceIspn.class.getResourceAsStream(SCRAPE_CONFIG_LOCAL), ScrapeConfig.class);
    } catch (IOException e) {
        e.printStackTrace();
    }
    File scrapeLocation = new File(PROMETHEUS_SCRAPE_CONFIG);
    scrapeLocation.mkdirs();
    service = new InventoryServiceIspn(resource, resourceType, getClass().getClassLoader().getResource("").getPath(), inventoryStats, scrapeConfig, scrapeLocation);
}
 
Example 19
Project: elytron-web   File: FormAuthenticationWithClusteredSSOTest.java   View source code 6 votes vote down vote up
@Override
protected HttpServerAuthenticationMechanismFactory doCreateHttpServerMechanismFactory(Map<String, ?> properties) {
    HttpServerAuthenticationMechanismFactory delegate = super.doCreateHttpServerMechanismFactory(properties);

    String cacheManagerName = UUID.randomUUID().toString();
    EmbeddedCacheManager cacheManager = new DefaultCacheManager(
            GlobalConfigurationBuilder.defaultClusteredBuilder()
                    .globalJmxStatistics().cacheManagerName(cacheManagerName)
                    .transport().nodeName(cacheManagerName).addProperty(JGroupsTransport.CONFIGURATION_FILE, "fast.xml")
                    .build(),
            new ConfigurationBuilder()
                    .clustering()
                    .cacheMode(CacheMode.REPL_SYNC)
                    .build()
    );

    Cache<String, SingleSignOnEntry> cache = cacheManager.getCache();
    SingleSignOnManager manager = new DefaultSingleSignOnManager(cache, new DefaultSingleSignOnSessionIdentifierFactory(), (id, entry) -> cache.put(id, entry));
    SingleSignOnServerMechanismFactory.SingleSignOnConfiguration signOnConfiguration = new SingleSignOnServerMechanismFactory.SingleSignOnConfiguration("JSESSIONSSOID", null, "/", false, false);

    SingleSignOnSessionFactory singleSignOnSessionFactory = new DefaultSingleSignOnSessionFactory(manager, this.keyPairSupplier.get());

    return new SingleSignOnServerMechanismFactory(delegate, singleSignOnSessionFactory, signOnConfiguration);
}
 
Example 20
Project: siebog   File: ECTimerServiceImpl.java   View source code 6 votes vote down vote up
@Timeout
public void timeout(Timer timer) {
	final Cache<String, ExecutionControl> cache = GlobalCache.get().getExecutionControls();
	String info = (String) timer.getInfo();
	try {
		int n = info.indexOf(' ');
		String execCtrlName = info.substring(0, n);
		int cycleNum = Integer.parseInt(info.substring(n + 1));
		ExecutionControl execCtrl = cache.get(execCtrlName);
		if (execCtrl != null)
			execCtrl.onTimeout(cycleNum);
		else
			logger.log(Level.WARNING, "ExecutionControl " + execCtrlName + " not found.");
	} catch (ConcurrentAccessTimeoutException ex) {
		logger.warning(ex.getMessage());
	}
}
 
Example 21
Project: marmotta   File: InfinispanEmbeddedCacheManager.java   View source code 6 votes vote down vote up
/**
 * Clear all caches managed by this cache manager.
 */
public void clear() {
    Set<String> set =  cacheManager.getCacheNames();
    Iterator<String> iterator =  set.iterator();
    while(iterator.hasNext()){
        String cacheName = iterator.next();
        Cache<String,Object> cache = cacheManager.getCache(cacheName);
        cache.clear();
    }

    nodeCache     = null;
    tripleCache   = null;
    uriCache      = null;
    literalCache  = null;
    bnodeCache    = null;
    nsPrefixCache = null;
    nsUriCache    = null;
    registryCache = null;
}
 
Example 22
Project: infinispan-queue   File: InfinispanQueue.java   View source code 6 votes vote down vote up
/**
 * Queue에 들어있는 데이터 출력
 * 
 * @param cache
 */
public void printInfo(Cache<String, Object> cache) {
	System.out.println("========= Queue Info =========");
	System.out.println("Queue Size=" + (Integer) cache.get(QUEUE_SIZE));
	String headKey = (String) cache.get(QUEUE_HEAD);
	System.out.println("Queue Head=" + headKey);
	System.out.println("Queue Tail=" + cache.get(QUEUE_TAIL));
	
	InfinispanQueueElement element = new InfinispanQueueElement();
	while(true) {
		element = (InfinispanQueueElement) cache.get(headKey);
		if( element == null ) {
			break;
		}
		System.out.println("Queue> " + element);
		headKey = element.getNextId();
	}
	System.out.println("========= Queue END =========");
	
}
 
Example 23
Project: infinispan-cachestore-cloud   File: CloudCacheStoreFunctionalIT.java   View source code 6 votes vote down vote up
@AfterMethod(alwaysRun = true)
private void nukeBuckets() throws Exception {
   for (String name : cacheManager.getCacheNames()) {
      CloudStore ccs = new CloudStore();
      Cache cache = cacheManager.getCache(name);
      ccs.init(new InitializationContextImpl(
                  cache.getAdvancedCache().getCacheConfiguration().persistence().stores().get(0), 
                  cache, 
                  TestingUtil.extractGlobalMarshaller(cacheManager),
                  cache.getAdvancedCache().getComponentRegistry().getTimeService(),
                  new ByteBufferFactoryImpl(),
                  new MarshalledEntryFactoryImpl()
                  ));
      ccs.start();
      ccs.removeContainer();
      ccs.stop();
   }
}
 
Example 24
Project: hat-vldb2014-code   File: InfinispanClient.java   View source code 6 votes vote down vote up
public int read(String table, String key, Set<String> fields, HashMap<String, ByteIterator> result) {
    try {
       Map<String, String> row;
       if (clustered) {
          row = AtomicMapLookup.getAtomicMap(infinispanManager.getCache(table), key, false);
       } else {
          Cache<String, Map<String, String>> cache = infinispanManager.getCache(table);
          row = cache.get(key);
       }
       if (row != null) {
          result.clear();
          if (fields == null || fields.isEmpty()) {
StringByteIterator.putAllAsByteIterators(result, row);
          } else {
      for (String field : fields) result.put(field, new StringByteIterator(row.get(field)));
          }
       }
       return OK;
    } catch (Exception e) {
       return ERROR;
    }
 }
 
Example 25
Project: cache2k-benchmark   File: InfinispanCacheFactory.java   View source code 6 votes vote down vote up
@Override
public BenchmarkCache<Integer, Integer> create(int _maxElements) {
  EmbeddedCacheManager m = getCacheMangaer();
  ConfigurationBuilder cb = new ConfigurationBuilder();

  cb.eviction().maxEntries(_maxElements);
  cb.storeAsBinary().disable();
  if (!withExpiry) {
    cb.expiration().disableReaper().lifespan(-1);
  } else {
    cb.expiration().lifespan(5 * 60, TimeUnit.SECONDS);
  }
  switch (algorithm) {
    case LRU: cb.eviction().strategy(EvictionStrategy.LRU); break;
    case LIRS: cb.eviction().strategy(EvictionStrategy.LIRS); break;
    case UNORDERED: cb.eviction().strategy(EvictionStrategy.UNORDERED); break;
  }
  m.defineConfiguration(CACHE_NAME, cb.build());
  Cache<Integer, Integer> _cache = m.getCache(CACHE_NAME);
  return new MyBenchmarkCache(_cache);
}
 
Example 26
Project: infinispan-cachestore-leveldb   File: ConfigurationTest.java   View source code 6 votes vote down vote up
public void testConfigBuilder() {
   GlobalConfiguration globalConfig = new GlobalConfigurationBuilder().globalJmxStatistics().transport().defaultTransport().build();

   Configuration cacheConfig = new ConfigurationBuilder().persistence().addStore(LevelDBStoreConfigurationBuilder.class).location(tmpDataDirectory)
         .expiredLocation(tmpExpiredDirectory).implementationType(LevelDBStoreConfiguration.ImplementationType.AUTO).build();

   StoreConfiguration cacheLoaderConfig = cacheConfig.persistence().stores().get(0);
   assertTrue(cacheLoaderConfig instanceof LevelDBStoreConfiguration);
   LevelDBStoreConfiguration leveldbConfig = (LevelDBStoreConfiguration) cacheLoaderConfig;
   assertEquals(tmpDataDirectory, leveldbConfig.location());
   assertEquals(tmpExpiredDirectory, leveldbConfig.expiredLocation());

   EmbeddedCacheManager cacheManager = new DefaultCacheManager(globalConfig);

   cacheManager.defineConfiguration("testCache", cacheConfig);

   cacheManager.start();
   Cache<String, String> cache = cacheManager.getCache("testCache");

   cache.put("hello", "there");
   cache.stop();
   cacheManager.stop();
}
 
Example 27
Project: infinispan-cachestore-leveldb   File: ConfigurationTest.java   View source code 6 votes vote down vote up
@Test(enabled = false, description = "ISPN-3388")
public void testLegacyJavaConfig() {
   GlobalConfiguration globalConfig = new GlobalConfigurationBuilder().globalJmxStatistics().transport().defaultTransport().build();

   Configuration cacheConfig = new ConfigurationBuilder().persistence().addStore(LevelDBStoreConfigurationBuilder.class).addProperty("location", tmpDataDirectory)
         .addProperty("expiredLocation", tmpExpiredDirectory).addProperty("implementationType", LevelDBStoreConfiguration.ImplementationType.AUTO.toString()).build();

   EmbeddedCacheManager cacheManager = new DefaultCacheManager(globalConfig);

   cacheManager.defineConfiguration("testCache", cacheConfig);

   cacheManager.start();
   Cache<String, String> cache = cacheManager.getCache("testCache");

   cache.put("hello", "there legacy java");
   cache.stop();
   cacheManager.stop();
}
 
Example 28
Project: infinispan-cachestore-mapdb   File: ConfigurationTest.java   View source code 6 votes vote down vote up
public void testConfigBuilder() {
   GlobalConfiguration globalConfig = new GlobalConfigurationBuilder().globalJmxStatistics().transport().defaultTransport().build();

   Configuration cacheConfig = new ConfigurationBuilder().persistence().addStore(MapDBStoreConfigurationBuilder.class)
         .location(tmpDirectory)
         .compression(true)
         .build();

   StoreConfiguration cacheLoaderConfig = cacheConfig.persistence().stores().get(0);
   assertTrue(cacheLoaderConfig instanceof MapDBStoreConfiguration);
   MapDBStoreConfiguration config = (MapDBStoreConfiguration) cacheLoaderConfig;
   assertEquals(true, config.compression());
   
   EmbeddedCacheManager cacheManager = new DefaultCacheManager(globalConfig);

   cacheManager.defineConfiguration("testCache", cacheConfig);

   cacheManager.start();
   Cache<String, String> cache = cacheManager.getCache("testCache");

   cache.put("hello", "there");
   cache.stop();
   cacheManager.stop();
}
 
Example 29
Project: ODL   File: ClusterManager.java   View source code 6 votes vote down vote up
@Override
public void addListener(String containerName, String cacheName,
        IGetUpdates<?, ?> u) throws CacheListenerAddException {
    EmbeddedCacheManager manager = this.cm;
    Cache<Object,Object> c;
    String realCacheName = "{" + containerName + "}_{" + cacheName + "}";
    if (manager == null) {
        return;
    }

    if (!manager.cacheExists(realCacheName)) {
        throw new CacheListenerAddException();
    }
    c = manager.getCache(realCacheName);
    CacheListenerContainer cl = new CacheListenerContainer(u,
            containerName, cacheName);
    c.addListener(cl);
}
 
Example 30
Project: ODL   File: ClusterManager.java   View source code 6 votes vote down vote up
@Override
public Set<IGetUpdates<?, ?>> getListeners(String containerName,
        String cacheName) {
    EmbeddedCacheManager manager = this.cm;
    Cache<Object,Object> c;
    String realCacheName = "{" + containerName + "}_{" + cacheName + "}";
    if (manager == null) {
        return null;
    }

    if (!manager.cacheExists(realCacheName)) {
        return null;
    }
    c = manager.getCache(realCacheName);

    Set<IGetUpdates<?, ?>> res = new HashSet<IGetUpdates<?, ?>>();
    Set<Object> listeners = c.getListeners();
    for (Object listener : listeners) {
        if (listener instanceof CacheListenerContainer) {
            CacheListenerContainer cl = (CacheListenerContainer) listener;
            res.add(cl.whichListener());
        }
    }

    return res;
}
 
Example 31
Project: ODL   File: ClusterManager.java   View source code 6 votes vote down vote up
@Override
public void removeListener(String containerName, String cacheName,
        IGetUpdates<?, ?> u) {
    EmbeddedCacheManager manager = this.cm;
    Cache<Object,Object> c;
    String realCacheName = "{" + containerName + "}_{" + cacheName + "}";
    if (manager == null) {
        return;
    }

    if (!manager.cacheExists(realCacheName)) {
        return;
    }
    c = manager.getCache(realCacheName);

    Set<Object> listeners = c.getListeners();
    for (Object listener : listeners) {
        if (listener instanceof CacheListenerContainer) {
            CacheListenerContainer cl = (CacheListenerContainer) listener;
            if (cl.whichListener() == u) {
                c.removeListener(listener);
                return;
            }
        }
    }
}
 
Example 32
Project: bolton-sigmod2013-code   File: InfinispanClient.java   View source code 6 votes vote down vote up
public int read(String table, String key, Set<String> fields, HashMap<String, ByteIterator> result) {
    try {
       Map<String, String> row;
       if (clustered) {
          row = AtomicMapLookup.getAtomicMap(infinispanManager.getCache(table), key, false);
       } else {
          Cache<String, Map<String, String>> cache = infinispanManager.getCache(table);
          row = cache.get(key);
       }
       if (row != null) {
          result.clear();
          if (fields == null || fields.isEmpty()) {
StringByteIterator.putAllAsByteIterators(result, row);
          } else {
      for (String field : fields) result.put(field, new StringByteIterator(row.get(field)));
          }
       }
       return OK;
    } catch (Exception e) {
       return ERROR;
    }
 }
 
Example 33
Project: infinispan-cachestore-offheap   File: ConfigurationTest.java   View source code 6 votes vote down vote up
public void testConfigBuilder() {
   GlobalConfiguration globalConfig = new GlobalConfigurationBuilder().globalJmxStatistics().transport().defaultTransport().build();

   Configuration cacheConfig = new ConfigurationBuilder().persistence().addStore(OffheapStoreConfigurationBuilder.class)
         .compression(true)
         .build();

   StoreConfiguration cacheLoaderConfig = cacheConfig.persistence().stores().get(0);
   assertTrue(cacheLoaderConfig instanceof OffheapStoreConfiguration);
   OffheapStoreConfiguration config = (OffheapStoreConfiguration) cacheLoaderConfig;
   assertEquals(true, config.compression());
   
   EmbeddedCacheManager cacheManager = new DefaultCacheManager(globalConfig);

   cacheManager.defineConfiguration("testCache", cacheConfig);

   cacheManager.start();
   Cache<String, String> cache = cacheManager.getCache("testCache");

   cache.put("hello", "there");
   cache.stop();
   cacheManager.stop();
}
 
Example 34
Project: infinispan-odata-server   File: InfinispanProducer.java   View source code 6 votes vote down vote up
/**
 *
 * Get embedded Infinispan cache which acts as an underlying store for JSON documents.
 *
 * Look into global map for registered cache. Avoiding multiple asking CacheManager.
 * <p/>
 * If there is no cache with the given name, get it from CacheManager and put.
 *
 * @param cacheName -- name of cache, AdvancedCache is returned.
 * @return AdvancedCache instance in dependence on a given name.
 */
private AdvancedCache getCache(String cacheName) {
    if (caches.get(cacheName) != null) {
        return this.caches.get(cacheName);
    } else {
        try {
            defaultCacheManager.startCache(cacheName);
            Cache cache = defaultCacheManager.getCache(cacheName);
            this.caches.put(cacheName, cache.getAdvancedCache());
            return cache.getAdvancedCache();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("ERROR DURING STARTING CACHE " + cacheName, e);
        }
    }
    return this.caches.get(cacheName);
}
 
Example 35
Project: cas-5.1.0   File: InfinispanTicketRegistryConfiguration.java   View source code 5 votes vote down vote up
private Cache<String, Ticket> getCache(final InfinispanProperties span) {
    final String cacheName = span.getCacheName();
    if (StringUtils.isBlank(cacheName)) {
        return cacheManager().getCache();
    }
    return cacheManager().getCache(cacheName);
}
 
Example 36
Project: JBoss-Developers-Guide   File: ExpirationXmlConfiguration.java   View source code 5 votes vote down vote up
public static void main(String[] args) throws IOException, InterruptedException {
	
     
      // Initialize the cache manager
	DefaultCacheManager cacheManager = new DefaultCacheManager("config/beosbank-infinispan.xml");
      // Obtain the default cache
      Cache<Long, MoneyTransfert> cache = cacheManager.getCache("beosbank-dist");
      
      
	// Obtain the remote cache
	cache.addListener(new DatagridListener());
	// Create a Money Transfer Object from XML Message using BeaoIO API
	try {
		BeosBankCacheUtils.loadEntries(cache,inputFileNames);
		// Inspect the cache .
		System.out.println(cache.size());
		Thread.sleep(2000);
		cache.get(5l);
		System.out.println("Cache content after 2 sec");
		//Current node content
		printCacheContent(cache);
		
		Thread.sleep(1000);
		System.out.println("Cache content after 3 sec");
		printCacheContent(cache);
		
		Thread.sleep(3000);
		System.out.println("Cache content after 6 sec");
		printCacheContent(cache);
		
		// Stop the cache
		cache.stop();

	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

}
 
Example 37
Project: JBoss-Developers-Guide   File: EvictionDemo.java   View source code 5 votes vote down vote up
public static void main(String[] args) throws IOException, InterruptedException {
	
      //Configuration
	ConfigurationBuilder builder = new ConfigurationBuilder();
	builder
		.eviction()
		.strategy(EvictionStrategy.LRU)
		.type(EvictionType.COUNT)
		.size(3)
		;
      // Initialize the cache manager
	DefaultCacheManager cacheManager = new DefaultCacheManager(builder.build());
    // Obtain the default cache
    Cache<Long, MoneyTransfert> cache = cacheManager.getCache("beosbank-dist");
      
	// Obtain the remote cache
	cache.addListener(new DatagridListener());
	// Create a Money Transfer Object from XML Message using BeaoIO API
	try {
		BeosBankCacheUtils.loadEntries(cache,inputFileNames);

		// Inspect the cache .
		System.out.println(cache.size());
		System.out.println(cache.get(3l));
		
		//Current node content
		cache.getAdvancedCache().withFlags(Flag.SKIP_REMOTE_LOOKUP)
        .entrySet().forEach(entry -> System.out.printf("%s = %s\n", entry.getKey(), entry.getValue().getDescription()));
		
		// Stop the cache
		cache.stop();

	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

}
 
Example 38
Project: JBoss-Developers-Guide   File: StatusUpdateDistributedCallable.java   View source code 5 votes vote down vote up
@Override
public void setEnvironment(Cache<Long, MoneyTransfert> cache, Set<Long> inputKeys) {
	this.cache=cache;
	this.inputKeys=inputKeys;
	System.out.println("StatusUpdateDistributedCallable.setEnvironment()");
	
}
 
Example 39
Project: JBoss-Developers-Guide   File: EmbeddedCacheDemo.java   View source code 5 votes vote down vote up
public static void main(String[] args) {

		String[] inputFileNames = { "data1.xml", "data2.xml", "data3.xml", "data4.xml", "data5.xml" };
		// Create a Money Transfer Object from XML Message using BeaoIO API
		try {
			StreamFactory factory = StreamFactory.newInstance();
			factory.loadResource("mapping.xml");
			Unmarshaller unmarshaller = factory.createUnmarshaller("MoneyTransferStream");

			String record;
			ConfigurationBuilder builder = new ConfigurationBuilder();
			Cache<String, Object> cache = new DefaultCacheManager(builder.build()).getCache();
			
			//Read Transactions and put in cache
			for (String inputFile : inputFileNames) {
				record = FileUtils.getContentsAsString(new File(INPUT_DIR + inputFile));
				MoneyTransfert mt = (MoneyTransfert) unmarshaller.unmarshal(record);
				cache.put(mt.getId() + "", mt);
			}

			//Inspect the cache .
			System.out.println(cache.size());
			System.out.println(cache.getStatus());
			System.out.println(cache.get("3"));

			//Stop the cache
			cache.stop();
			System.out.println(cache.getStatus());

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
 
Example 40
Project: JBoss-Developers-Guide   File: EmbeddedCacheListenerDemo.java   View source code 5 votes vote down vote up
public static void main(String[] args) {

		String[] inputFileNames = { "data1.xml", "data2.xml", "data3.xml", "data4.xml", "data5.xml" };
		// Create a Money Transfer Object from XML Message using BeaoIO API
		try {
			StreamFactory factory = StreamFactory.newInstance();
			factory.loadResource("mapping.xml");
			Unmarshaller unmarshaller = factory.createUnmarshaller("MoneyTransferStream");

			String record;
			ConfigurationBuilder builder = new ConfigurationBuilder();
			Cache<String, Object> cache = new DefaultCacheManager(builder.build()).getCache();
			
			cache.addListener(new DatagridListener());
			//Read Transactions and put in cache
			for (String inputFile : inputFileNames) {
				record = FileUtils.getContentsAsString(new File(INPUT_DIR + inputFile));
				MoneyTransfert mt = (MoneyTransfert) unmarshaller.unmarshal(record);
				cache.put(mt.getId() + "", mt);
			}

			//Inspect the cache .
			System.out.println(cache.size());
			System.out.println(cache.getStatus());
			System.out.println(cache.get("3"));

			//Stop the cache
			cache.stop();
			System.out.println(cache.getStatus());

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}