Java Code Examples for org.infinispan.manager.DefaultCacheManager

The following are top voted examples for showing how to use org.infinispan.manager.DefaultCacheManager. 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: spring-data-snowdrop   File: InfinispanConfiguration.java   View source code 6 votes vote down vote up
@Bean(destroyMethod = "stop")
public EmbeddedCacheManager createCacheManager() {
    GlobalConfigurationBuilder globalCfg = new GlobalConfigurationBuilder();
    globalCfg.globalJmxStatistics().allowDuplicateDomains(true).disable(); // get rid of this?

    ConfigurationBuilder cacheCfg = new ConfigurationBuilder();
    cacheCfg.jmxStatistics().disable();
    cacheCfg.indexing()
        .index(Index.ALL)
        .addIndexedEntity(Fruit.class)
        .addIndexedEntity(CEntity.class)
        .addIndexedEntity(SimpleEntity.class)
        .addProperty("default.directory_provider", "local-heap")
        .addProperty("lucene_version", "LUCENE_CURRENT");

    return new DefaultCacheManager(globalCfg.build(), cacheCfg.build());
}
 
Example 2
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 3
Project: hacep   File: AbstractClusterTest.java   View source code 6 votes vote down vote up
private DefaultCacheManager clusteredCacheManager(CacheMode mode, int owners, RulesManager rulesManager) {
    ExecutorService executorService = Executors.newFixedThreadPool(4);
    HAKieSessionBuilder sessionBuilder = new HAKieSessionBuilder(rulesManager, executorService);

    GlobalConfiguration glob = new GlobalConfigurationBuilder().clusteredDefault()
            .transport().addProperty("configurationFile", System.getProperty("jgroups.configuration", "jgroups-test-tcp.xml"))
            .clusterName("HACEP")
            .globalJmxStatistics().allowDuplicateDomains(true).enable()
            .serialization()
            .addAdvancedExternalizer(new HAKieSession.HASessionExternalizer(sessionBuilder))
            .addAdvancedExternalizer(new HAKieSerializedSession.HASerializedSessionExternalizer(sessionBuilder))
            .addAdvancedExternalizer(new HAKieSessionDeltaEmpty.HASessionDeltaEmptyExternalizer(sessionBuilder))
            .addAdvancedExternalizer(new HAKieSessionDeltaFact.HASessionDeltaFactExternalizer())
            .build();

    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.invocationBatching().enable();
    configureCacheMode(configurationBuilder, mode, owners);

    org.infinispan.configuration.cache.Configuration loc = extendDefaultConfiguration(configurationBuilder).build();
    return new DefaultCacheManager(glob, loc, true);
}
 
Example 4
Project: zanata-mt   File: ResourceProducer.java   View source code 6 votes vote down vote up
@Produces
@ApplicationScoped
public EmbeddedCacheManager defaultClusteredCacheManager() {
    GlobalConfiguration g = new GlobalConfigurationBuilder()
            .clusteredDefault()
            .transport()
            .clusterName(MACHINE_TRANSLATIONS_CLUSTER)
            .globalJmxStatistics()
            .allowDuplicateDomains(true)
            .build();
    Configuration cfg = new ConfigurationBuilder()
            .clustering()
            .cacheMode(CacheMode.DIST_ASYNC)
            .eviction()
            .strategy(EvictionStrategy.LRU)
            .type(EvictionType.COUNT).size(150)
            .transaction()
            .transactionMode(TransactionMode.TRANSACTIONAL)
            .lockingMode(LockingMode.PESSIMISTIC)
            .build();
    return new DefaultCacheManager(g, cfg);
}
 
Example 5
Project: Camel   File: InfinispanConfigurationTestIT.java   View source code 6 votes vote down vote up
@Test
public void embeddedCacheWithFlagsTest() throws Exception {
    InfinispanConfiguration configuration = new InfinispanConfiguration();
    configuration.setHost("localhost");
    configuration.setCacheName("misc_cache");
    configuration.setCacheContainer(new DefaultCacheManager(true));
    configuration.setFlags(
        org.infinispan.context.Flag.SKIP_CACHE_LOAD,
        org.infinispan.context.Flag.SKIP_CACHE_STORE
    );

    InfinispanManager manager = new InfinispanManager(configuration);
    manager.start();

    BasicCache<Object, Object> cache = manager.getCache();
    assertNotNull(cache);
    assertTrue(cache instanceof DecoratedCache);

    DecoratedCache<Object, Object> decoratedCache = (DecoratedCache<Object, Object>)cache;
    assertTrue(decoratedCache.getFlags().contains(org.infinispan.context.Flag.SKIP_CACHE_LOAD));
    assertTrue(decoratedCache.getFlags().contains(org.infinispan.context.Flag.SKIP_CACHE_STORE));

    manager.getCacheContainer().stop();
    manager.stop();
}
 
Example 6
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 7
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 8
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 9
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 10
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 11
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 12
Project: owsi-core-parent   File: JpaMoreInfinispanConfig.java   View source code 6 votes vote down vote up
@Bean(destroyMethod = "stop")
public IInfinispanClusterService infinispanClusterService(IPropertyService propertyService, IRolesProvider rolesProvider,
		IActionFactory springActionFactory, IInfinispanClusterCheckerService infinispanClusterCheckerService,
		EntityManagerFactory entityManagerFactory) {
	if (propertyService.get(JpaMoreInfinispanPropertyIds.INFINISPAN_ENABLED)) {
		String nodeName = propertyService.get(JpaMoreInfinispanPropertyIds.INFINISPAN_NODE_NAME);
		Properties properties = new Properties();
		for (String key : propertyService.get(JpaMoreInfinispanPropertyIds.INFINISPAN_TRANSPORT_PROPERTIES)) {
			properties.put(key, propertyService.getAsString(JpaMoreInfinispanPropertyIds.transportProperty(key)));
		}
		GlobalConfiguration globalConfiguration =
				new GlobalDefaultReplicatedTransientConfigurationBuilder(properties).nodeName(nodeName).build();
		org.infinispan.configuration.cache.Configuration configuration =
				new DefaultReplicatedTransientConfigurationBuilder().build();
		EmbeddedCacheManager cacheManager = new DefaultCacheManager(globalConfiguration, configuration, false);
		
		InfinispanClusterServiceImpl cluster =
				new InfinispanClusterServiceImpl(nodeName, cacheManager, rolesProvider, springActionFactory,
						infinispanClusterCheckerService);
		cluster.init();
		return cluster;
	} else {
		return null;
	}
}
 
Example 13
Project: infinispan-avro   File: MetadataManager.java   View source code 6 votes vote down vote up
public MetadataManager(DefaultCacheManager cacheManager){
   Configuration cacheConfiguration = cacheManager.getCacheConfiguration(Support.AVRO_METADATA_CACHE_NAME);
   if (cacheConfiguration == null) {
      ConfigurationBuilder cfg = new ConfigurationBuilder();
      CacheMode cacheMode =
            cacheManager.getDefaultCacheConfiguration().clustering().cacheMode().equals(CacheMode.LOCAL)
                  ? CacheMode.LOCAL : CacheMode.REPL_SYNC;
      cfg
            .transaction().lockingMode(LockingMode.PESSIMISTIC).syncCommitPhase(true).syncRollbackPhase(true)
            .persistence().addSingleFileStore().location(System.getProperty("java.io.tmpdir") + "/" + cacheManager.getNodeAddress()) // mandatory
            .locking().isolationLevel(IsolationLevel.READ_COMMITTED).useLockStriping(false)
            .clustering().cacheMode(cacheMode)
            .stateTransfer().fetchInMemoryState(true)
            .dataContainer().keyEquivalence(new ByteArrayEquivalence()); // for HotRod compatibility
      if (cacheMode.equals(CacheMode.REPL_SYNC)) cfg.clustering().stateTransfer().awaitInitialTransfer(true);
      cacheManager.defineConfiguration(Support.AVRO_METADATA_CACHE_NAME, cfg.build());
      this.cacheManager = cacheManager;
      this.marshaller= Externalizer.getInstance();
      this.knownSchemas = new ConcurrentHashMap<>();
      knownSchemas.put(Request.getClassSchema().getFullName(), Request.getClassSchema());
      knownSchemas.put(Response.getClassSchema().getFullName(), Response.getClassSchema());
   }
}
 
Example 14
Project: hashaggregator   File: CacheStore.java   View source code 6 votes vote down vote up
public synchronized void init() {

        ConfigurationBuilder cfgBuilder = new ConfigurationBuilder();

        //ALERT CHANGING CONF HERE
//        cfgBuilder.persistence().passivation(true).addSingleFileStore().purgeOnStartup(true).location("/tmp/cachefiles/").create();
        cfgBuilder.eviction().strategy(EvictionStrategy.LRU).maxEntries(10)
                .persistence()
                .passivation(false).addSingleFileStore()
                .fetchPersistentState(true)
                .ignoreModifications(false)
                .purgeOnStartup(true).
                location("/tmp/cachefiles/").
                create();

        //cfgBuilder.eviction().create();

        Configuration configuration = cfgBuilder.build();
         manager = new DefaultCacheManager(configuration);
        manager.defineConfiguration("Cache1",configuration);


    }
 
Example 15
Project: elytron-web   File: InfinispanSessionManager.java   View source code 6 votes vote down vote up
@Override
public void start() {
    createdSessionCount.set(0);
    expiredSessionCount.set(0);
    // here we create a replicated cache using a cluster with name 'default-cluster'.
    // sessions are replicate across all nodes joining the same cluster.
    this.cacheManager = new DefaultCacheManager(
            GlobalConfigurationBuilder.defaultClusteredBuilder()
                    .globalJmxStatistics().cacheManagerName(deploymentName)
                    .transport().nodeName(deploymentName).clusterName("default-cluster")
                    .build(),
            new ConfigurationBuilder()
                    .clustering()
                    .cacheMode(CacheMode.REPL_SYNC)
                    .build()
    );
    this.sessions = cacheManager.getCache();
    startTime = System.currentTimeMillis();
}
 
Example 16
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 17
Project: teiid   File: AbstractInfinispanManagedConnectionFactory.java   View source code 6 votes vote down vote up
private CacheContainerWrapper createLocalCacheFromConfigFile()
		throws ResourceException {
	try {
		final DefaultCacheManager cc = new DefaultCacheManager(
				this.getConfigurationFileNameForLocalCache());

		LogManager
				.logInfo(LogConstants.CTX_CONNECTOR,
						"=== Using DefaultCacheManager (loaded by configuration) ==="); //$NON-NLS-1$

		return new LocalCacheWrapper(cc);

	} catch (IOException e) {
		throw new ResourceException(e);
	}
}
 
Example 18
Project: teiid   File: TestInfinispanConnection.java   View source code 6 votes vote down vote up
public static DefaultCacheManager createContainerForLucene()
		throws Exception {

    GlobalConfiguration glob = new GlobalConfigurationBuilder()
    .nonClusteredDefault() //Helper method that gets you a default constructed GlobalConfiguration, preconfigured for use in LOCAL mode
    .globalJmxStatistics().enable() //This method allows enables the jmx statistics of the global configuration.
   .jmxDomain("org.infinispan.trades.annotated." + ++cnt)  //prevent collision with non-transactional carmart
    .build(); //Builds  the GlobalConfiguration object
    Configuration loc = new ConfigurationBuilder()
	.indexing().enable().addProperty("hibernate.search.default.directory_provider", "filesystem").addProperty("hibernate.search.default.indexBase", "./target/lucene/indexes " + cnt)
    .clustering().cacheMode(CacheMode.LOCAL) //Set Cache mode to LOCAL - Data is not replicated.
    .transaction().transactionMode(TransactionMode.NON_TRANSACTIONAL)
    .eviction().maxEntries(100).strategy(EvictionStrategy.LIRS) //Sets  4 as maximum number of entries in a cache instance and uses the LIRS strategy - an efficient low inter-reference recency set replacement policy to improve buffer cache performance
    .persistence().passivation(false).addSingleFileStore().purgeOnStartup(true).location("./target/localcache/indexing/trades" + cnt) //Disable passivation and adds a SingleFileStore that is purged on Startup
    .build(); //Builds the Configuration object
	DefaultCacheManager container = new DefaultCacheManager(glob, loc, true);

	return container;
}
 
Example 19
Project: jdg-quickstarts   File: PlaygroundConfiguration.java   View source code 6 votes vote down vote up
private DefaultCacheManager buildCacheManager() {
    GlobalConfiguration glob = new GlobalConfigurationBuilder().clusteredDefault()

            //.transport().addProperty("configurationFile", System.getProperty("playground.jgroups.configuration", "default-jgroups-tcp.xml"))
            .transport().clusterName("PLAYGROUND")
            .globalJmxStatistics().allowDuplicateDomains(true).enable()
            .build();

    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.jmxStatistics().enable();
    configureCacheMode(configurationBuilder);

    if (persistence()) {
        configureCacheStore(configurationBuilder);
    }

    Configuration loc = configurationBuilder.transaction().transactionMode(TransactionMode.TRANSACTIONAL).transactionManagerLookup(new DummyTransactionManagerLookup()).build();
    return new DefaultCacheManager(glob, loc, true);
}
 
Example 20
Project: bigbase   File: PerfTest.java   View source code 6 votes vote down vote up
/**
 * Inits the cache infinispan.
 */
private static void initCacheInfinispan() {
	EmbeddedCacheManager manager = new DefaultCacheManager();
	Configuration config = new Configuration().fluent()
	  .eviction()
	    .maxEntries((int)sCacheItemsLimit).strategy(EvictionStrategy.LRU)
	    /*.wakeUpInterval(5000L)*/ // TODO - fix it 
	  .expiration()
	    .maxIdle(120000L)
	    .build();

	manager.defineConfiguration("name", config);
	ispnCache = manager.getCache("name");


}
 
Example 21
Project: hashaggregator   File: CacheStore.java   View source code 6 votes vote down vote up
public synchronized void init() {

        ConfigurationBuilder cfgBuilder = new ConfigurationBuilder();

        //ALERT CHANGING CONF HERE
//        cfgBuilder.persistence().passivation(true).addSingleFileStore().purgeOnStartup(true).location("/tmp/cachefiles/").create();
        cfgBuilder.eviction().strategy(EvictionStrategy.LRU).maxEntries(10)
                .persistence()
                .passivation(false).addSingleFileStore()
                .fetchPersistentState(true)
                .ignoreModifications(false)
                .purgeOnStartup(true).
                location("/tmp/cachefiles/").
                create();

        //cfgBuilder.eviction().create();

        Configuration configuration = cfgBuilder.build();
         manager = new DefaultCacheManager(configuration);
        manager.defineConfiguration("Cache1",configuration);


    }
 
Example 22
Project: marmotta   File: InfinispanEmbeddedCacheManager.java   View source code 6 votes vote down vote up
/**
 * Build a local cache configuration.
 * <p/>
 * In local cache mode, the cache is not shared among the servers in a cluster. Each machine keeps a local cache.
 * This allows quick startups and eliminates network traffic in the cluster, but subsequent requests to different
 * cluster members cannot benefit from the cached data.
 */
protected void buildLocalConfiguration() {
    GlobalConfiguration globalConfiguration = new GlobalConfigurationBuilder()
            .classLoader(InfinispanEmbeddedCacheManager.class.getClassLoader())
            .globalJmxStatistics()
                .jmxDomain("org.apache.marmotta.kiwi")
                .allowDuplicateDomains(true)
            .build();

    defaultConfiguration = new ConfigurationBuilder()
            .clustering()
                .cacheMode(CacheMode.LOCAL)
            .eviction()
                .strategy(EvictionStrategy.LIRS)
                .maxEntries(100000)
            .expiration()
                .lifespan(5, TimeUnit.MINUTES)
                .maxIdle(1, TimeUnit.MINUTES)
            .build();
    cacheManager = new DefaultCacheManager(globalConfiguration, defaultConfiguration, true);

    log.info("initialised Infinispan local cache manager");
}
 
Example 23
Project: khan-session   File: InfinispanLibrayImpl.java   View source code 6 votes vote down vote up
/**
 * 초기화
 * @param configFile
 * @param cacheName
 * @param loginCacheName
 * @throws IOException
 */
@Override
public void initialize(String configFile, String cacheName, String loginCacheName)
        throws IOException {
    try {
        StringUtils.isNotNull("configFile", configFile);

        cacheManager = new DefaultCacheManager(configFile);

        this.cacheName = cacheName;
        this.loginCacheName = loginCacheName;

        cache = cacheManager.getCache(cacheName);
        loginCache = cacheManager.getCache(loginCacheName);

        waitForConnectionReady();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 24
Project: hazelcast-simulator   File: InfinispanDriver.java   View source code 6 votes vote down vote up
@Override
public void startVendorInstance() throws Exception {
    String workerType = get("WORKER_TYPE");
    if ("javaclient".equals(workerType)) {
        Properties hotrodProperties = new Properties();
        hotrodProperties.setProperty("infinispan.client.hotrod.server_list", get("server_list"));
        Configuration configuration = new ConfigurationBuilder().withProperties(hotrodProperties).build();
        RemoteCacheManager remoteCacheManager = new RemoteCacheManager(configuration);
        this.cacheContainer = remoteCacheManager;
        remoteCacheManager.start();
    } else {
        DefaultCacheManager defaultCacheManager = new DefaultCacheManager("infinispan.xml");
        this.cacheContainer = defaultCacheManager;
        defaultCacheManager.start();

        HotRodServerConfiguration hotRodServerConfiguration = new HotRodServerConfigurationBuilder()
                .host(get("PRIVATE_ADDRESS")).port(11222).build();
        this.hotRodServer = new HotRodServer();
        hotRodServer.start(hotRodServerConfiguration, defaultCacheManager);
    }
}
 
Example 25
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 26
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 27
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 28
Project: spring4-sandbox   File: InfinispanEmbeddedCacheConfig.java   View source code 6 votes vote down vote up
@Override
@Bean
public CacheManager cacheManager() {

	return new SpringEmbeddedCacheManager(
			new DefaultCacheManager(
				new ConfigurationBuilder()
					.eviction()
						.maxEntries(20000)
						.strategy(EvictionStrategy.LIRS)
					.expiration()
						.wakeUpInterval(5000L)
						.maxIdle(120000L)
		           .build()
				)
			);
}
 
Example 29
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 30
Project: cas-5.1.0   File: InfinispanTicketRegistryConfiguration.java   View source code 5 votes vote down vote up
@Bean
public EmbeddedCacheManager cacheManager() {
    try {
        final Resource loc = casProperties.getTicket().getRegistry().getInfinispan().getConfigLocation();
        return new DefaultCacheManager(loc.getInputStream());
    } catch (final Exception e) {
        throw Throwables.propagate(e);
    }
}
 
Example 31
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 32
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 33
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 34
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();
		}

	}
 
Example 35
Project: spring-session-infinispan   File: EmbeddedCacheUtils.java   View source code 5 votes vote down vote up
static EmbeddedCacheManager cacheManager(String configurationPath) {
    try {
        return new DefaultCacheManager(configurationPath);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example 36
Project: hacep   File: DataGridManager.java   View source code 5 votes vote down vote up
public void startCacheInfo(String nodeName) {
    if (startedCacheInfo.compareAndSet(false, true)) {
        GlobalConfiguration globalConfiguration = new GlobalConfigurationBuilder().clusteredDefault()
                .transport().addProperty("configurationFile", System.getProperty("jgroups.configuration.info", "jgroups-tcp-info.xml"))
                .clusterName("HACEPINFO").nodeName(nodeName+"INFO")
                .globalJmxStatistics().allowDuplicateDomains(true).enable()
                .serialization()
                .build();

        ConfigurationBuilder commonConfigurationBuilder = new ConfigurationBuilder();
        commonConfigurationBuilder.clustering().cacheMode(CacheMode.REPL_SYNC);

        Configuration commonConfiguration = commonConfigurationBuilder.build();
        this.managerCacheInfo = new DefaultCacheManager(globalConfiguration, commonConfiguration, false);

        ConfigurationBuilder replicatedInfos = new ConfigurationBuilder();
        replicatedInfos.clustering().cacheMode(CacheMode.REPL_SYNC);

        if (persistence()) {
            replicatedInfos
                    .persistence()
                    .passivation(false)
                    .addSingleFileStore()
                    .shared(false)
                    .preload(true)
                    .fetchPersistentState(true)
                    .purgeOnStartup(false)
                    .location(location())
                    .async().threadPoolSize(threadPoolSize()).enabled(false)
                    .singleton().enabled(false);
        }

        this.managerCacheInfo.defineConfiguration(REPLICATED_CACHE_NAME, replicatedInfos.build());

        this.managerCacheInfo.start();
    }
}
 
Example 37
Project: the-deploy-master   File: CacheInstance.java   View source code 5 votes vote down vote up
public static synchronized Cache<String, String> getCache() {
	if (INSTANCE == null) {
		GlobalConfiguration gc = GlobalConfigurationBuilder.defaultClusteredBuilder()
				// Use this line for testing in Kubernetes. But it requires
				// additional configuration:
				// oc policy add-role-to-user view
				// system:serviceaccount:$(oc
				// project -q):default -n $(oc project -q)
				// And setting OPENSHIFT_KUBE_PING_NAMESPACE env variable to
				// your namespace
				.transport().defaultTransport()
				.addProperty("configurationFile", "default-configs/default-jgroups-kubernetes.xml")

				// Or use, multicast stack to simplify local testing:
				// .transport().defaultTransport().addProperty("configurationFile",
				// "default-configs/default-jgroups-udp.xml")
				.build();

		EmbeddedCacheManager manager = new DefaultCacheManager(gc);

		// And here are per-cache configuration, e.g. eviction, replication
		// scheme etc.
		ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
		configurationBuilder.clustering().cacheMode(CacheMode.REPL_ASYNC);
		manager.defineConfiguration("default", configurationBuilder.build());
		INSTANCE = manager.getCache("default");
	}
	return INSTANCE;
}
 
Example 38
Project: jdg7-example   File: JdgServiceBean.java   View source code 5 votes vote down vote up
@PostConstruct
void init() {
    try {
        System.setProperty("jgroups.join_timeout", "500"); // コーディネータ検出のタイムアウト
        System.setProperty("jgroups.udp.ip_ttl", "0"); // クラスタ検出を同一ホスト内のみに絞る
        
        manager = new DefaultCacheManager("my-infinispan.xml", true);
        for (String cacheName : manager.getCacheNames()) {
            manager.startCache(cacheName);
        }
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example 39
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: CacheStatisticsAutoConfigurationTests.java   View source code 5 votes vote down vote up
@Bean
public EmbeddedCacheManager embeddedCacheManager() throws IOException {
	Resource resource = new ClassPathResource("cache/test-infinispan.xml");
	InputStream in = resource.getInputStream();
	try {
		return new DefaultCacheManager(in);
	}
	finally {
		in.close();
	}
}
 
Example 40
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: InfinispanCacheConfiguration.java   View source code 5 votes vote down vote up
private EmbeddedCacheManager createEmbeddedCacheManager() throws IOException {
	Resource location = this.cacheProperties
			.resolveConfigLocation(this.cacheProperties.getInfinispan().getConfig());
	if (location != null) {
		InputStream in = location.getInputStream();
		try {
			return new DefaultCacheManager(in);
		}
		finally {
			in.close();
		}
	}
	return new DefaultCacheManager();
}