Java Code Examples for org.infinispan.manager.EmbeddedCacheManager

The following are top voted examples for showing how to use org.infinispan.manager.EmbeddedCacheManager. 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   Source Code and License 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: unitimes   File: AbstractServer.java   Source Code and License 6 votes vote down vote up
@Override
public void releaseMasterLockIfHeld() {
	if (iMasterThread != null) {
		iMasterThread.release();
	} else if (Boolean.TRUE.equals(getProperty("ReloadIsNeeded", Boolean.FALSE))) {
		iLog.info("Reloading server...");
		final Long sessionId = getAcademicSession().getUniqueId();
		loadOnMaster(new OnlineSectioningServerContext() {
			@Override
			public Long getAcademicSessionId() { return sessionId; }
			@Override
			public boolean isWaitTillStarted() { return false; }
			@Override
			public EmbeddedCacheManager getCacheManager() { return null; }
			@Override
			public LockService getLockService() { return null; }
		});
	}
}
 
Example 3
Project: unitimes   File: OnlineStudentSchedulingContainerRemote.java   Source Code and License 6 votes vote down vote up
@Override
   public OnlineSectioningServerContext getServerContext(final Long academicSessionId) {
	return new OnlineSectioningServerContext() {
		@Override
		public Long getAcademicSessionId() {
			return academicSessionId;
		}

		@Override
		public boolean isWaitTillStarted() {
			return false;
		}

		@Override
		public EmbeddedCacheManager getCacheManager() {
			return OnlineStudentSchedulingContainerRemote.this.getCacheManager();
		}

		@Override
		public LockService getLockService() {
			return iLockService;
		}
	};
}
 
Example 4
Project: unitimes   File: OnlineStudentSchedulingContainer.java   Source Code and License 6 votes vote down vote up
public OnlineSectioningServerContext getServerContext(final Long academicSessionId) {
	return new OnlineSectioningServerContext() {
		@Override
		public Long getAcademicSessionId() {
			return academicSessionId;
		}

		@Override
		public boolean isWaitTillStarted() {
			return false;
		}

		@Override
		public EmbeddedCacheManager getCacheManager() {
			return null;
		}

		@Override
		public LockService getLockService() {
			return null;
		}
	};
}
 
Example 5
Project: zanata-mt   File: ResourceProducer.java   Source Code and License 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 6
Project: owsi-core-parent   File: TestSimpleCluster.java   Source Code and License 6 votes vote down vote up
/**
 * Run multiple instances and check that all instances are online.
 * 
 * @throws ExecutionException 
 * @throws TimeoutException 
 */
@Test
public void testStart() throws IOException, InterruptedException, ExecutionException {
	int nodeNumber = 3;
	prepareCluster(nodeNumber, null);
	
	// start test instance
	EmbeddedCacheManager cacheManager = new TestCacheManagerBuilder("node main", null).build();
	this.cacheManager = cacheManager;
	cacheManager.start();
	
	LOGGER.debug("waiting nodes");
	try {
		waitNodes(cacheManager, nodeNumber + 1, 30, TimeUnit.SECONDS);
	} catch (TimeoutException e) {
		Assert.fail(String.format("Node number %d not reached before timeout", nodeNumber + 1));
	}
}
 
Example 7
Project: owsi-core-parent   File: SimpleProcess.java   Source Code and License 6 votes vote down vote up
@Override
public void run() {
	final EmbeddedCacheManager cacheManager = new TestCacheManagerBuilder(nodeName, taskName).build();
	cacheManager.start();
	
	while (!Thread.currentThread().isInterrupted()) {
		try {
			Object object = new Object();
			// synchronized to become object owner
			LOGGER.debug("Start main loop");
			synchronized (object) {
				object.wait();
			}
		} catch (InterruptedException e) {
			LOGGER.warn("Thread interrupted while wait");
			Thread.currentThread().interrupt();
		}
	}
}
 
Example 8
Project: owsi-core-parent   File: InfinispanClusterProcess.java   Source Code and License 6 votes vote down vote up
@Override
public void run() {
	final EmbeddedCacheManager cacheManager = new TestCacheManagerBuilder(nodeName, taskName).build();
	InfinispanClusterServiceImpl cluster =
			new InfinispanClusterServiceImpl(nodeName, cacheManager, new SimpleRolesProvider(), null, null);
	cluster.init();
	
	while (!Thread.currentThread().isInterrupted()) {
		try {
			Object object = new Object();
			// synchronized to become object owner
			LOGGER.debug("Start main loop");
			synchronized (object) {
				object.wait();
			}
		} catch (InterruptedException e) {
			LOGGER.warn("Thread interrupted while wait");
			Thread.currentThread().interrupt();
		}
	}
}
 
Example 9
Project: owsi-core-parent   File: JpaMoreInfinispanConfig.java   Source Code and License 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 10
Project: infinispan-avro   File: AvroWrapperIndexingTest.java   Source Code and License 6 votes vote down vote up
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
   ConfigurationBuilder cfg = getDefaultStandaloneCacheConfig(false);
   cfg.indexing().enable()
         .addProperty("default.directory_provider", "ram")
         .addProperty("lucene_version", "LUCENE_CURRENT");
   cfg.validate();
   
   Configuration configuration = cfg.build();
   assert cfg.clustering().cacheMode() == CacheMode.LOCAL;
   
   EmbeddedCacheManager cacheManager = new DefaultCacheManager(configuration);
   cacheManager.getCache();

   return cacheManager;
}
 
Example 11
Project: elytron-web   File: FormAuthenticationWithClusteredSSOTest.java   Source Code and License 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 12
Project: teiid   File: AbstractInfinispanManagedConnectionFactory.java   Source Code and License 6 votes vote down vote up
private CacheContainerWrapper createLocalCacheViaJNDI()
		throws ResourceException {

	String jndiName = getCacheJndiName();
	try {
		final Object cache = performJNDICacheLookup(jndiName);

		LogManager
				.logDetail(
						LogConstants.CTX_CONNECTOR,
						"=== Using CacheContainer (obtained by JNDI:", jndiName, "==="); //$NON-NLS-1 //$NON-NLS-2 		

		return new LocalCacheWrapper((EmbeddedCacheManager) cache);

	} catch (ResourceException re) {
		throw re;
	} catch (Exception err) {
		if (err instanceof RuntimeException)
			throw (RuntimeException) err;
		throw new ResourceException(err);
	}

}
 
Example 13
Project: unitime   File: AbstractServer.java   Source Code and License 6 votes vote down vote up
@Override
public void releaseMasterLockIfHeld() {
	if (iMasterThread != null) {
		iMasterThread.release();
	} else if (Boolean.TRUE.equals(getProperty("ReloadIsNeeded", Boolean.FALSE))) {
		iLog.info("Reloading server...");
		final Long sessionId = getAcademicSession().getUniqueId();
		loadOnMaster(new OnlineSectioningServerContext() {
			@Override
			public Long getAcademicSessionId() { return sessionId; }
			@Override
			public boolean isWaitTillStarted() { return false; }
			@Override
			public EmbeddedCacheManager getCacheManager() { return null; }
			@Override
			public LockService getLockService() { return null; }
		});
	}
}
 
Example 14
Project: unitime   File: OnlineStudentSchedulingContainerRemote.java   Source Code and License 6 votes vote down vote up
@Override
   public OnlineSectioningServerContext getServerContext(final Long academicSessionId) {
	return new OnlineSectioningServerContext() {
		@Override
		public Long getAcademicSessionId() {
			return academicSessionId;
		}

		@Override
		public boolean isWaitTillStarted() {
			return false;
		}

		@Override
		public EmbeddedCacheManager getCacheManager() {
			return OnlineStudentSchedulingContainerRemote.this.getCacheManager();
		}

		@Override
		public LockService getLockService() {
			return iLockService;
		}
	};
}
 
Example 15
Project: unitime   File: OnlineStudentSchedulingContainer.java   Source Code and License 6 votes vote down vote up
public OnlineSectioningServerContext getServerContext(final Long academicSessionId) {
	return new OnlineSectioningServerContext() {
		@Override
		public Long getAcademicSessionId() {
			return academicSessionId;
		}

		@Override
		public boolean isWaitTillStarted() {
			return false;
		}

		@Override
		public EmbeddedCacheManager getCacheManager() {
			return null;
		}

		@Override
		public LockService getLockService() {
			return null;
		}
	};
}
 
Example 16
Project: bigbase   File: PerfTest.java   Source Code and License 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 17
Project: cache2k-benchmark   File: InfinispanCacheFactory.java   Source Code and License 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 18
Project: infinispan-cachestore-leveldb   File: ConfigurationTest.java   Source Code and License 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 19
Project: infinispan-cachestore-leveldb   File: ConfigurationTest.java   Source Code and License 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 20
Project: infinispan-cachestore-mapdb   File: ConfigurationTest.java   Source Code and License 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 21
Project: ODL   File: ClusterManager.java   Source Code and License 6 votes vote down vote up
@Override
public Set<String> getCacheList(String containerName) {
    Set<String> perContainerCaches = new HashSet<String>();
    EmbeddedCacheManager manager = this.cm;
    if (manager == null) {
        return null;
    }
    for (String cacheName : manager.getCacheNames()) {
        if (cacheName.startsWith("{" + containerName + "}_")) {
            String[] res = cacheName.split("[{}]");
            if (res.length >= 4 && res[1].equals(containerName)
                    && res[2].equals("_")) {
                perContainerCaches.add(res[3]);
            }
        }
    }

    return (perContainerCaches);
}
 
Example 22
Project: ODL   File: ClusterManager.java   Source Code and License 6 votes vote down vote up
@Override
public Properties getCacheProperties(String containerName, String cacheName) {
    EmbeddedCacheManager manager = this.cm;
    if (manager == null) {
        return null;
    }
    String realCacheName = "{" + containerName + "}_{" + cacheName + "}";
    if (!manager.cacheExists(realCacheName)) {
        return null;
    }
    Configuration conf = manager.getCache(realCacheName).getAdvancedCache()
            .getCacheConfiguration();
    Properties p = new Properties();
    p.setProperty(IClusterServices.cacheProps.TRANSACTION_PROP.toString(),
            conf.transaction().toString());
    p.setProperty(IClusterServices.cacheProps.CLUSTERING_PROP.toString(),
            conf.clustering().toString());
    p.setProperty(IClusterServices.cacheProps.LOCKING_PROP.toString(), conf
            .locking().toString());
    return p;
}
 
Example 23
Project: ODL   File: ClusterManager.java   Source Code and License 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 24
Project: ODL   File: ClusterManager.java   Source Code and License 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 25
Project: ODL   File: ClusterManager.java   Source Code and License 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 26
Project: ODL   File: ClusterManager.java   Source Code and License 6 votes vote down vote up
private InetAddress addressToInetAddress(Address a) {
    EmbeddedCacheManager manager = this.cm;
    if ((manager == null) || (a == null)) {
        // In case we cannot fetch the information, lets assume we
        // are standby, so to have less responsibility.
        return null;
    }
    Transport t = manager.getTransport();
    if (t instanceof JGroupsTransport) {
        JGroupsTransport jt = (JGroupsTransport) t;
        Channel c = jt.getChannel();
        if (a instanceof JGroupsAddress) {
            JGroupsAddress ja = (JGroupsAddress) a;
            org.jgroups.Address phys = (org.jgroups.Address) c
                    .down(new Event(Event.GET_PHYSICAL_ADDRESS, ja
                            .getJGroupsAddress()));
            if (phys instanceof org.jgroups.stack.IpAddress) {
                InetAddress bindAddress = ((org.jgroups.stack.IpAddress) phys)
                        .getIpAddress();
                return bindAddress;
            }
        }
    }
    return null;
}
 
Example 27
Project: ODL   File: ClusterManager.java   Source Code and License 6 votes vote down vote up
@Override
public List<InetAddress> getClusteredControllers() {
    EmbeddedCacheManager manager = this.cm;
    if (manager == null) {
        return null;
    }
    List<Address> controllers = manager.getMembers();
    if ((controllers == null) || controllers.size() == 0) {
        return null;
    }

    List<InetAddress> clusteredControllers = new ArrayList<InetAddress>();
    for (Address a : controllers) {
        InetAddress inetAddress = addressToInetAddress(a);
        if (inetAddress != null
                && !inetAddress.getHostAddress().equals(loopbackAddress)) {
            clusteredControllers.add(inetAddress);
        }
    }
    return clusteredControllers;
}
 
Example 28
Project: ODL   File: ClusterManager.java   Source Code and License 6 votes vote down vote up
@Override
public void listenRoleChange(IListenRoleChange i)
        throws ListenRoleChangeAddException {
    EmbeddedCacheManager manager = this.cm;
    if (manager == null) {
        // In case we cannot fetch the information, lets assume we
        // are standby, so to have less responsibility.
        throw new ListenRoleChangeAddException();
    }

    if (this.roleChangeListeners == null) {
        this.roleChangeListeners = new HashSet<IListenRoleChange>();
        this.cacheManagerListener = new ViewChangedListener(
                this.roleChangeListeners);
        manager.addListener(this.cacheManagerListener);
    }

    if (this.roleChangeListeners != null) {
        this.roleChangeListeners.add(i);
    }
}
 
Example 29
Project: ODL   File: ClusterManager.java   Source Code and License 6 votes vote down vote up
@Override
public void unlistenRoleChange(IListenRoleChange i) {
    EmbeddedCacheManager manager = this.cm;
    if (manager == null) {
        // In case we cannot fetch the information, lets assume we
        // are standby, so to have less responsibility.
        return;
    }

    if (this.roleChangeListeners != null) {
        this.roleChangeListeners.remove(i);
    }

    if ((this.roleChangeListeners != null && this.roleChangeListeners
            .isEmpty())
            && (this.cacheManagerListener != null)) {
        manager.removeListener(this.cacheManagerListener);
        this.cacheManagerListener = null;
        this.roleChangeListeners = null;
    }
}
 
Example 30
Project: jipijapa   File: InfinispanRegionFactory.java   Source Code and License 6 votes vote down vote up
@Override
protected EmbeddedCacheManager createCacheManager(Properties properties) throws CacheException {
    // Find a suitable service name to represent this session factory instance
    String name = properties.getProperty(AvailableSettings.SESSION_FACTORY_NAME);
    String container = properties.getProperty(CACHE_CONTAINER, DEFAULT_CACHE_CONTAINER);
    HibernateSecondLevelCache.addSecondLevelCacheDependencies(properties, null);

    Properties cacheSettings = new Properties();
    cacheSettings.put(HibernateSecondLevelCache.CACHE_TYPE,CACHE_PRIVATE);
    cacheSettings.put(HibernateSecondLevelCache.CONTAINER, container);
    if (name != null) {
        cacheSettings.put(HibernateSecondLevelCache.NAME, name);
    }

    try {
        // start a private cache for non-JPA use and return the started cache.
        wrapper = Notification.startCache(Classification.INFINISPAN, cacheSettings);
        return (EmbeddedCacheManager)wrapper.getValue();
    } catch (Exception e) {
        throw new CacheException(e);
    }
}
 
Example 31
Project: jipijapa   File: InfinispanRegionFactory.java   Source Code and License 6 votes vote down vote up
@Override
protected EmbeddedCacheManager createCacheManager(Properties properties) throws CacheException {
    // Find a suitable service name to represent this session factory instance
    String name = properties.getProperty(AvailableSettings.SESSION_FACTORY_NAME);
    String container = properties.getProperty(CACHE_CONTAINER, DEFAULT_CACHE_CONTAINER);
    HibernateSecondLevelCache.addSecondLevelCacheDependencies(properties, null);

    Properties cacheSettings = new Properties();
    cacheSettings.put(HibernateSecondLevelCache.CACHE_TYPE,CACHE_PRIVATE);
    cacheSettings.put(HibernateSecondLevelCache.CONTAINER, container);
    if (name != null) {
        cacheSettings.put(HibernateSecondLevelCache.NAME, name);
    }


    try {
        // start a private cache for non-JPA use and return the started cache.
        wrapper = Notification.startCache(Classification.INFINISPAN, cacheSettings);
        return (EmbeddedCacheManager)wrapper.getValue();
    } catch (Exception e) {
        throw new CacheException(e);
    }
}
 
Example 32
Project: infinispan-cachestore-offheap   File: ConfigurationTest.java   Source Code and License 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 33
Project: cas-5.1.0   File: InfinispanTicketRegistryConfiguration.java   Source Code and License 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 34
Project: spring-data-snowdrop   File: SnowdropDataInfinispanEmbeddedAutoConfiguration.java   Source Code and License 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean(EntityToCacheMapper.class)
@ConditionalOnBean(EmbeddedCacheManager.class)
public EntityToCacheMapper createDefaultEntityToCacheMapper(final EmbeddedCacheManager cacheManager) {
    return new EntityToCacheMapper() {
        public <ID, T> Cache<ID, T> getCache(Class<T> entityClass) {
            return cacheManager.getCache(); // always return default cache
        }
    };
}
 
Example 35
Project: unitimes   File: MemoryCounter.java   Source Code and License 5 votes vote down vote up
private boolean skipObject(Object obj) {
	if (obj instanceof String) {
		// this will not cause a memory leak since
		// unused interned Strings will be thrown away
		if (obj == ((String) obj).intern()) {
			return true;
		}
	}
	if (obj instanceof Marshaller || obj instanceof EmbeddedCacheManager || obj instanceof Thread || obj instanceof Log || obj instanceof Logger || obj instanceof SolverContainer) return true;
	return (obj == null) || iVisited.containsKey(obj);
}
 
Example 36
Project: popular-movie-store   File: MovieDBHelper.java   Source Code and License 5 votes vote down vote up
@Autowired
public MovieDBHelper(RestTemplate restTemplate, MovieStoreProps movieStoreProps,
                     EmbeddedCacheManager cacheManager) {
    this.restTemplate = restTemplate;
    this.movieStoreProps = movieStoreProps;
    this.moviesCache = cacheManager
        .getCache(POPULAR_MOVIES_CACHE).getAdvancedCache();
}
 
Example 37
Project: spring-session-infinispan   File: EmbeddedCacheUtils.java   Source Code and License 5 votes vote down vote up
static EmbeddedCacheManager cacheManager(String configurationPath) {
    try {
        return new DefaultCacheManager(configurationPath);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example 38
Project: spring-session-infinispan   File: RemoteCacheUtils.java   Source Code and License 5 votes vote down vote up
static HotRodServer startCacheServerDefaultConfiguration(String cacheName, int port) {
    EmbeddedCacheManager embeddedCacheManager = EmbeddedCacheUtils.cacheManager(cacheName, defaultConfiguration());
    HotRodServer server = new HotRodServer();
    server.start(new HotRodServerConfigurationBuilder()
                    .host(HOST)
                    .port(port)
                    .build(),
            embeddedCacheManager);
    return server;
}
 
Example 39
Project: spring-session-infinispan   File: RemoteCacheUtils.java   Source Code and License 5 votes vote down vote up
static HotRodServer startCacheServerDefaultConfiguration(String cacheName, int port, Function<ConfigurationChildBuilder, ConfigurationChildBuilder> appendBuilder) {
    EmbeddedCacheManager embeddedCacheManager =
            EmbeddedCacheUtils.cacheManager(cacheName, appendBuilder.apply(defaultConfigurationBuilder()).build());
    HotRodServer server = new HotRodServer();
    server.start(new HotRodServerConfigurationBuilder()
                    .host(HOST)
                    .port(port)
                    .build(),
            embeddedCacheManager);
    return server;
}
 
Example 40
Project: spring-session-infinispan   File: RemoteCacheUtils.java   Source Code and License 5 votes vote down vote up
static HotRodServer startCacheServerConfigurationSpec(String configurationPath, int port, String... useCacheNames) {
    EmbeddedCacheManager embeddedCacheManager = EmbeddedCacheUtils.cacheManager(configurationPath);
    Arrays.stream(useCacheNames).forEach(cacheName -> embeddedCacheManager.getCache(cacheName));

    HotRodServer server = new HotRodServer();
    server.start(new HotRodServerConfigurationBuilder()
                    .host(HOST)
                    .port(port)
                    .build(),
            embeddedCacheManager);
    return server;
}
 
Example 41
Project: the-deploy-master   File: CacheInstance.java   Source Code and License 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 42
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: CacheStatisticsAutoConfigurationTests.java   Source Code and License 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 43
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: InfinispanCacheConfiguration.java   Source Code and License 5 votes vote down vote up
@Bean(destroyMethod = "stop")
@ConditionalOnMissingBean
public EmbeddedCacheManager infinispanCacheManager() throws IOException {
	EmbeddedCacheManager cacheManager = createEmbeddedCacheManager();
	List<String> cacheNames = this.cacheProperties.getCacheNames();
	if (!CollectionUtils.isEmpty(cacheNames)) {
		for (String cacheName : cacheNames) {
			cacheManager.defineConfiguration(cacheName,
					getDefaultCacheConfiguration());
		}
	}
	return cacheManager;
}
 
Example 44
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: InfinispanCacheConfiguration.java   Source Code and License 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();
}
 
Example 45
Project: wildfly-swarm   File: MyResource.java   Source Code and License 5 votes vote down vote up
@GET
@Produces("text/plain")
public String get() throws Exception {
    EmbeddedCacheManager cacheContainer
            = (EmbeddedCacheManager) new InitialContext().lookup("java:jboss/infinispan/container/server");
    Cache<String,String> cache = cacheContainer.getCache("server");
    if (cache.keySet().contains(key)) {
        return (String) cache.get(key);
    }

    String result = UUID.randomUUID().toString();
    cache.put(key, result);
    return result;
}
 
Example 46
Project: syndesis-rest   File: InfinispanCache.java   Source Code and License 5 votes vote down vote up
@Override
protected void before() throws Throwable {
    EmbeddedCacheManager manager = new DefaultCacheManager(
        new GlobalConfigurationBuilder().nonClusteredDefault().build(),
        new ConfigurationBuilder()
        .memory().evictionType(EvictionType.COUNT).size(100)
        .build()
    );
    caches = manager;
}
 
Example 47
Project: syndesis-rest   File: InfinispanCache.java   Source Code and License 5 votes vote down vote up
@Override
protected void before() throws Throwable {
    EmbeddedCacheManager manager = new DefaultCacheManager(
        new GlobalConfigurationBuilder().nonClusteredDefault().build(),
        new ConfigurationBuilder()
        .memory().evictionType(EvictionType.COUNT).size(100)
        .build()
    );
    caches = manager;
}
 
Example 48
Project: java-platform   File: SpringEmbeddedCacheManagerFactoryBean.java   Source Code and License 5 votes vote down vote up
/**
 * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
 */
@Override
public void afterPropertiesSet() throws Exception {
   logger.info("Initializing SpringEmbeddedCacheManager instance ...");

   final EmbeddedCacheManager nativeEmbeddedCacheManager = createBackingEmbeddedCacheManager();
   this.cacheManager = new SpringEmbeddedCacheManager(nativeEmbeddedCacheManager);

   logger.info("Successfully initialized SpringEmbeddedCacheManager instance ["
                     + this.cacheManager + "]");
}
 
Example 49
Project: spring-boot-concourse   File: CacheStatisticsAutoConfigurationTests.java   Source Code and License 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 50
Project: spring-boot-concourse   File: InfinispanCacheConfiguration.java   Source Code and License 5 votes vote down vote up
@Bean(destroyMethod = "stop")
@ConditionalOnMissingBean
public EmbeddedCacheManager infinispanCacheManager() throws IOException {
	EmbeddedCacheManager cacheManager = createEmbeddedCacheManager();
	List<String> cacheNames = this.cacheProperties.getCacheNames();
	if (!CollectionUtils.isEmpty(cacheNames)) {
		for (String cacheName : cacheNames) {
			cacheManager.defineConfiguration(cacheName,
					getDefaultCacheConfiguration());
		}
	}
	return cacheManager;
}
 
Example 51
Project: spring-boot-concourse   File: InfinispanCacheConfiguration.java   Source Code and License 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();
}
 
Example 52
Project: Camel   File: InfinispanUtil.java   Source Code and License 5 votes vote down vote up
public static boolean isEmbedded(BasicCacheContainer container) {
    try {
        return container instanceof EmbeddedCacheManager;
    } catch (Throwable e) {
        return false;
    }
}
 
Example 53
Project: infinispan-simple-tutorials   File: SpringBootApp.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {
    ApplicationContext ctx = SpringApplication.run(SpringBootApp.class, args);

    EmbeddedCacheManager cacheManager = ctx.getBean(EmbeddedCacheManager.class);
    Cache<Long, String> cache = cacheManager.getCache(CACHE_NAME);
    cache.put(System.currentTimeMillis(), "Infinispan");

    logger.info("Values from Cache: {}", cache.entrySet());
}
 
Example 54
Project: owsi-core-parent   File: InfinispanClusterServiceImpl.java   Source Code and License 5 votes vote down vote up
public InfinispanClusterServiceImpl(String nodeName, EmbeddedCacheManager cacheManager,
		IRolesProvider rolesProvider, IActionFactory actionFactory,
		IInfinispanClusterCheckerService infinispanClusterCheckerService) {
	super();
	this.nodeName = nodeName;
	this.cacheManager = cacheManager;
	this.rolesProvider = rolesProvider;
	this.actionFactory = actionFactory;
	// don't wait for delayed tasks after shutdown (even if already planned)
	initExecutor(this.executor);
	this.infinispanClusterCheckerService = infinispanClusterCheckerService;
	if (infinispanClusterCheckerService != null) {
		initExecutor(this.checkerExecutor);
	}
}
 
Example 55
Project: owsi-core-parent   File: TestMessage.java   Source Code and License 5 votes vote down vote up
/**
 * Simple messaging test.
 * 
 * @throws IOException
 * @throws InterruptedException
 * @throws ExecutionException
 * @throws TimeoutException
 */
@Test
public void testMessage() throws IOException, InterruptedException, ExecutionException, TimeoutException {
	final int nodeNumber = 3;
	
	// start test instance
	EmbeddedCacheManager cacheManager = new TestCacheManagerBuilder("node main", null).build();
	this.cacheManager = cacheManager;
	
	final Object monitor = new Object();
	final Map<Address, String> messages = Maps.newConcurrentMap();
	
	cacheManager.start();
	cacheManager.getCache(TestConstants.CACHE_DEFAULT).addListener(new NodeMessageListener<String>() {
		@Override
		public void onMessage(Message<String> value) {
			messages.put(value.getAddress(), value.getMessage());
			synchronized (monitor) {
				monitor.notify();
			}
		}
	});
	
	prepareCluster(nodeNumber, SimpleMessagingTask.class);
	
	// wait for n (n=nodeNumber) messages
	Callable<Boolean> test = new Callable<Boolean>() {
		@Override
		public Boolean call() throws Exception {
			return messages.keySet().size() >= nodeNumber;
		}
	};
	waitForEvent(monitor, test, 10, TimeUnit.SECONDS);
}
 
Example 56
Project: owsi-core-parent   File: TestCacheManagerBuilder.java   Source Code and License 5 votes vote down vote up
public EmbeddedCacheManager build() {
	PROCESS_ID = ManagementFactory.getRuntimeMXBean().getName().replaceAll("@.*", "");
	MDC.put("PID", PROCESS_ID);
	
	// udp + multicast is difficult to obtain in test environment
	Properties properties = new Properties();
	properties.put("configurationFile", "test-jgroups-tcp.xml");
	
	GlobalConfiguration globalConfiguration =
			new GlobalDefaultReplicatedTransientConfigurationBuilder(properties).nodeName(name).build();
	Configuration configuration =
			new DefaultReplicatedTransientConfigurationBuilder().build();
	EmbeddedCacheManager cacheManager = new DefaultCacheManager(globalConfiguration, configuration, false);
	cacheManager.getCache(TestConstants.CACHE_DEFAULT);
	
	if (taskName != null) {
		try {
			Class<?> clazz = Class.forName(taskName);
			Constructor<?> constructor = clazz.getConstructor(EmbeddedCacheManager.class);
			Runnable r = (Runnable) constructor.newInstance(cacheManager);
			
			Thread t = new Thread((Runnable) r);
			t.start();
		} catch (Exception e) {
			throw new IllegalStateException(e);
		}
	}
	
	return cacheManager;
}
 
Example 57
Project: contestparser   File: CacheStatisticsAutoConfigurationTests.java   Source Code and License 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 58
Project: contestparser   File: InfinispanCacheConfiguration.java   Source Code and License 5 votes vote down vote up
@Bean(destroyMethod = "stop")
@ConditionalOnMissingBean
public EmbeddedCacheManager infinispanCacheManager() throws IOException {
	EmbeddedCacheManager cacheManager = createEmbeddedCacheManager();
	List<String> cacheNames = this.cacheProperties.getCacheNames();
	if (!CollectionUtils.isEmpty(cacheNames)) {
		for (String cacheName : cacheNames) {
			cacheManager.defineConfiguration(cacheName,
					getDefaultCacheConfiguration());
		}
	}
	return cacheManager;
}
 
Example 59
Project: contestparser   File: InfinispanCacheConfiguration.java   Source Code and License 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();
}
 
Example 60
Project: infinispan-avro   File: QueryTest.java   Source Code and License 5 votes vote down vote up
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
   if (cacheManager != null)
      return cacheManager;

   GlobalConfigurationBuilder gcb = new GlobalConfigurationBuilder().clusteredDefault();
   ConfigurationBuilder builder = hotRodCacheConfiguration(getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, false));
   builder.indexing().enable()
         .addProperty("default.directory_provider", "ram")
         .addProperty("lucene_version", "LUCENE_CURRENT");
   builder.jmxStatistics().enable();

   cacheManager = TestCacheManagerFactory.createClusteredCacheManager(gcb, new ConfigurationBuilder());
   cacheManager.defineConfiguration(TEST_CACHE_NAME, builder.build());
   cache = cacheManager.getCache(TEST_CACHE_NAME);

   hotRodServer = HotRodClientTestingUtil.startHotRodServer(cacheManager);

   org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder =
         new org.infinispan.client.hotrod.configuration.ConfigurationBuilder();
   clientBuilder.addServer().host(hotRodServer.getAddress().host()).port(hotRodServer.getAddress().port());
   clientBuilder.marshaller(new Marshaller<>(Employee.class));
   remoteCacheManager = new RemoteCacheManager(clientBuilder.build());
   employeeCache = remoteCacheManager.getCache(TEST_CACHE_NAME);
   employeeQF = Search.getQueryFactory(employeeCache);

   Support.registerSchema(remoteCacheManager, Employee.getClassSchema());

   Thread.sleep(1000); // wait that the cluster forms

   return cacheManager;
}