Java Code Examples for com.hazelcast.core.HazelcastInstance

The following are top voted examples for showing how to use com.hazelcast.core.HazelcastInstance. 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: greycat   File: HazelcastScheduler.java   View source code 7 votes vote down vote up
public static void main(String[] args) {
    Config cfg = new Config();
    HazelcastInstance instance = Hazelcast.newHazelcastInstance(cfg);
    Map<Integer, String> mapCustomers = instance.getMap("customers");
    mapCustomers.put(1, "Joe");
    mapCustomers.put(2, "Ali");
    mapCustomers.put(3, "Avi");

    System.out.println("Customer with key 1: "+ mapCustomers.get(1));
    System.out.println("Map Size:" + mapCustomers.size());

    Queue<String> queueCustomers = instance.getQueue("customers");
    queueCustomers.offer("Tom");
    queueCustomers.offer("Mary");
    queueCustomers.offer("Jane");
    System.out.println("First customer: " + queueCustomers.poll());
    System.out.println("Second customer: "+ queueCustomers.peek());
    System.out.println("Queue size: " + queueCustomers.size());
}
 
Example 2
Project: springboot-shiro-cas-mybatis   File: HazelcastTicketRegistry.java   View source code 7 votes vote down vote up
/**
 * Instantiates a new Hazelcast ticket registry.
 *
 * @param hz                                   An instance of {@code HazelcastInstance}
 * @param mapName                              Name of map to use
 * @param ticketGrantingTicketTimeoutInSeconds TTL for TGT entries
 * @param serviceTicketTimeoutInSeconds        TTL for ST entries
 * @param pageSize                             the page size
 */
@Autowired
public HazelcastTicketRegistry(
    @Qualifier("hazelcast")
    final HazelcastInstance hz,
    @Value("${hz.mapname:tickets}")
    final String mapName,
    @Value("${tgt.maxTimeToLiveInSeconds:28800}")
    final long ticketGrantingTicketTimeoutInSeconds,
    @Value("${st.timeToKillInSeconds:10}")
    final long serviceTicketTimeoutInSeconds,
    @Value("${hz.page.size:500}")
    final int pageSize) {

    this.registry = hz.getMap(mapName);
    this.ticketGrantingTicketTimeoutInSeconds = ticketGrantingTicketTimeoutInSeconds;
    this.serviceTicketTimeoutInSeconds = serviceTicketTimeoutInSeconds;
    this.hz = hz;
    this.pageSize = pageSize;
}
 
Example 3
Project: xm-commons   File: XmConfigHazelcastConfiguration.java   View source code 7 votes vote down vote up
@Bean(TENANT_CONFIGURATION_HAZELCAST)
public HazelcastInstance tenantConfigurationHazelcast() throws IOException {
    log.info("{}", appProps.getHazelcast());

    Properties props = new Properties();
    props.putAll(appProps.getHazelcast());
    props.put(HAZELCAST_LOCAL_LOCAL_ADDRESS, InetUtils.getFirstNonLoopbackHostInfo().getIpAddress());

    String hazelcastConfigUrl = appProps.getHazelcast().get(HAZELCAST_CONFIG_URL_PROPERTY);
    InputStream in = context.getResource(hazelcastConfigUrl).getInputStream();

    Config config = new XmlConfigBuilder(in).setProperties(props).build();
    config.getNetworkConfig().setInterfaces(buildInterfaces(appProps.getHazelcast().get(INTERFACES)));
    HazelcastInstance hazelcastInstance = Hazelcast.newHazelcastInstance(config);
    return hazelcastInstance;
}
 
Example 4
Project: xm-ms-balance   File: CacheConfiguration.java   View source code 7 votes vote down vote up
@Bean
public HazelcastInstance hazelcastInstance(JHipsterProperties jHipsterProperties) {
    log.debug("Configuring Hazelcast");
    HazelcastInstance hazelCastInstance = Hazelcast.getHazelcastInstanceByName("balance");
    if (hazelCastInstance != null) {
        log.debug("Hazelcast already initialized");
        return hazelCastInstance;
    }
    Config config = new Config();
    config.setInstanceName("balance");
    config.getNetworkConfig().setPort(5701);
    config.getNetworkConfig().setPortAutoIncrement(true);

    // In development, remove multicast auto-configuration
    if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) {
        System.setProperty("hazelcast.local.localAddress", "127.0.0.1");

        config.getNetworkConfig().getJoin().getAwsConfig().setEnabled(false);
        config.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false);
        config.getNetworkConfig().getJoin().getTcpIpConfig().setEnabled(false);
    }
    config.getMapConfigs().put("default", initializeDefaultMapConfig());
    config.getMapConfigs().put("com.icthh.xm.ms.balance.domain.*", initializeDomainMapConfig(jHipsterProperties));
    return Hazelcast.newHazelcastInstance(config);
}
 
Example 5
Project: cas-5.1.0   File: HazelcastSessionConfiguration.java   View source code 6 votes vote down vote up
/**
 * Hazelcast instance that is used by the spring session
 * repository to broadcast session events. The name
 * of this bean must be left untouched.
 *
 * @return the hazelcast instance
 */
@Bean
public HazelcastInstance hazelcastInstance() {
    final Resource hzConfigResource = casProperties.getWebflow().getSession().getHzLocation();
    try {
        final URL configUrl = hzConfigResource.getURL();
        final Config config = new XmlConfigBuilder(hzConfigResource.getInputStream()).build();
        config.setConfigurationUrl(configUrl);
        config.setInstanceName(this.getClass().getSimpleName())
                .setProperty("hazelcast.logging.type", "slf4j")
                .setProperty("hazelcast.max.no.heartbeat.seconds", "300");
        return Hazelcast.newHazelcastInstance(config);
    } catch (final Exception e) {
        throw Throwables.propagate(e);
    }
}
 
Example 6
Project: testcontainers-hazelcast   File: TestScratchpad.java   View source code 6 votes vote down vote up
public static void main(String[] args) {
    //System.setProperty("hazelcast.http.healthcheck.enabled", "true");
    final HazelcastInstance hazelcastInstance = newHazelcastInstance();

    HazelcastInstanceImpl hazelcastInstance1 = ((HazelcastInstanceProxy) hazelcastInstance).getOriginal();
    final InternalPartitionService partitionService = hazelcastInstance1.node.getPartitionService();

    boolean memberStateSafe = partitionService.isMemberStateSafe();
    System.out.println("memberStateSafe = " + memberStateSafe);
    boolean clusterSafe = memberStateSafe && !partitionService.hasOnGoingMigration();
    System.out.println("clusterSafe = " + clusterSafe);
    long migrationQueueSize = partitionService.getMigrationQueueSize();
    System.out.println("migrationQueueSize = " + migrationQueueSize);


}
 
Example 7
Project: xm-ms-dashboard   File: CacheConfiguration.java   View source code 6 votes vote down vote up
@Bean
@Primary
public HazelcastInstance hazelcastInstance(JHipsterProperties jHipsterProperties) {
    log.debug("Configuring Hazelcast");
    HazelcastInstance hazelCastInstance = Hazelcast.getHazelcastInstanceByName("dashboard");
    if (hazelCastInstance != null) {
        log.debug("Hazelcast already initialized");
        return hazelCastInstance;
    }
    Config config = new Config();
    config.setInstanceName("dashboard");
    config.getNetworkConfig().setPort(5701);
    config.getNetworkConfig().setPortAutoIncrement(true);

    // In development, remove multicast auto-configuration
    if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) {
        System.setProperty("hazelcast.local.localAddress", "127.0.0.1");

        config.getNetworkConfig().getJoin().getAwsConfig().setEnabled(false);
        config.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false);
        config.getNetworkConfig().getJoin().getTcpIpConfig().setEnabled(false);
    }
    config.getMapConfigs().put("default", initializeDefaultMapConfig());
    config.getMapConfigs().put("com.icthh.xm.ms.dashboard.domain.*", initializeDomainMapConfig(jHipsterProperties));
    return Hazelcast.newHazelcastInstance(config);
}
 
Example 8
Project: xm-gate   File: CacheConfiguration.java   View source code 6 votes vote down vote up
@Bean
@Primary
public HazelcastInstance hazelcastInstance(JHipsterProperties jHipsterProperties) {
    log.debug("Configuring Hazelcast");
    HazelcastInstance hazelCastInstance = Hazelcast.getHazelcastInstanceByName("gate");
    if (hazelCastInstance != null) {
        log.debug("Hazelcast already initialized");
        return hazelCastInstance;
    }
    Config config = new Config();
    config.setInstanceName("gate");
    config.getNetworkConfig().setPort(5701);
    config.getNetworkConfig().setPortAutoIncrement(true);

    // In development, remove multicast auto-configuration
    if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) {
        System.setProperty("hazelcast.local.localAddress", "127.0.0.1");

        config.getNetworkConfig().getJoin().getAwsConfig().setEnabled(false);
        config.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false);
        config.getNetworkConfig().getJoin().getTcpIpConfig().setEnabled(false);
    }
    config.getMapConfigs().put("default", initializeDefaultMapConfig());
    config.getMapConfigs().put("com.icthh.xm.gate.domain.*", initializeDomainMapConfig(jHipsterProperties));
    return Hazelcast.newHazelcastInstance(config);
}
 
Example 9
Project: xm-ms-entity   File: CacheConfiguration.java   View source code 6 votes vote down vote up
@Bean
@Primary
public HazelcastInstance hazelcastInstance(JHipsterProperties jHipsterProperties) {
    log.debug("Configuring Hazelcast");
    HazelcastInstance hazelCastInstance = Hazelcast.getHazelcastInstanceByName("entity");
    if (hazelCastInstance != null) {
        log.debug("Hazelcast already initialized");
        return hazelCastInstance;
    }
    Config config = new Config();
    config.setInstanceName("entity");
    config.getNetworkConfig().setPort(5701);
    config.getNetworkConfig().setPortAutoIncrement(true);

    // In development, remove multicast auto-configuration
    if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) {
        System.setProperty("hazelcast.local.localAddress", "127.0.0.1");

        config.getNetworkConfig().getJoin().getAwsConfig().setEnabled(false);
        config.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false);
        config.getNetworkConfig().getJoin().getTcpIpConfig().setEnabled(false);
    }
    config.getMapConfigs().put("default", initializeDefaultMapConfig());
    config.getMapConfigs().put("com.icthh.xm.ms.entity.domain.*", initializeDomainMapConfig(jHipsterProperties));
    return Hazelcast.newHazelcastInstance(config);
}
 
Example 10
Project: Code4Health-Platform   File: CacheConfiguration.java   View source code 6 votes vote down vote up
@Bean
public HazelcastInstance hazelcastInstance(JHipsterProperties jHipsterProperties) {
    log.debug("Configuring Hazelcast");
    Config config = new Config();
    config.setInstanceName("operoncloudplatform");
    config.getNetworkConfig().setPort(5701);
    config.getNetworkConfig().setPortAutoIncrement(true);

    // In development, remove multicast auto-configuration
    if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) {
        System.setProperty("hazelcast.local.localAddress", "127.0.0.1");

        config.getNetworkConfig().getJoin().getAwsConfig().setEnabled(false);
        config.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false);
        config.getNetworkConfig().getJoin().getTcpIpConfig().setEnabled(false);
    }
    config.getMapConfigs().put("default", initializeDefaultMapConfig());
    config.getMapConfigs().put("cloud.operon.platform.domain.*", initializeDomainMapConfig(jHipsterProperties));
    return Hazelcast.newHazelcastInstance(config);
}
 
Example 11
Project: cas-server-4.2.1   File: HazelcastTicketRegistry.java   View source code 6 votes vote down vote up
/**
 * @param hz                                  An instance of {@code HazelcastInstance}
 * @param mapName                             Name of map to use
 * @param ticketGrantingTicketTimeoutInSeconds TTL for TGT entries
 * @param serviceTicketTimeoutInSeconds       TTL for ST entries
 */
@Autowired
public HazelcastTicketRegistry(
    @Qualifier("hazelcast")
    final HazelcastInstance hz,
    @Value("${hz.mapname:tickets}")
    final String mapName,
    @Value("${tgt.maxTimeToLiveInSeconds:28800}")
    final long ticketGrantingTicketTimeoutInSeconds,
    @Value("${st.timeToKillInSeconds:10}")
    final long serviceTicketTimeoutInSeconds) {

    this.registry = hz.getMap(mapName);
    this.ticketGrantingTicketTimeoutInSeconds = ticketGrantingTicketTimeoutInSeconds;
    this.serviceTicketTimeoutInSeconds = serviceTicketTimeoutInSeconds;
    this.hz = hz;
}
 
Example 12
Project: cyp2sql   File: KeyValueTest.java   View source code 6 votes vote down vote up
/**
 * Main method for executing the schema conversion to Hazelcast.
 * The method just needs to be called statically as it operates on files created during the initial
 * schema conversion process.
 */
public static void executeSchemaChange() {
    Config cfg = new Config();
    HazelcastInstance instance = Hazelcast.newHazelcastInstance(cfg);

    mapNodes = instance.getMap("nodes");
    mapEdges = instance.getMap("edges");
    mapLabels = instance.getMap("labels");
    mapOut = instance.getMap("out");
    mapIn = instance.getMap("in");

    nodesMap();
    edgesMap();

    exampleQueries();
}
 
Example 13
Project: xm-ms-config   File: TestConfiguration.java   View source code 6 votes vote down vote up
@Bean
@Primary
@SneakyThrows
public JGitRepository jGitRepository(ApplicationProperties applicationProperties, HazelcastInstance hazelcastInstance) {

    return new JGitRepository(applicationProperties.getGit(), new ReentrantLock()) {
        @Override
        protected void initRepository(){};
        @Override
        protected void pull(){};
        @Override
        protected void commitAndPush(String commitMsg){};
        @Override
        public List<com.icthh.xm.ms.configuration.domain.Configuration> findAll(){
            return emptyList();
        }
    };
}
 
Example 14
Project: xm-ms-config   File: LocalJGitRespotioryConfiguration.java   View source code 6 votes vote down vote up
@Bean
@Primary
@SneakyThrows
public JGitRepository jGitRepository(ApplicationProperties applicationProperties, HazelcastInstance hazelcastInstance) {
    File tmpDir = createTmpDir("work");
    tmpDir.mkdirs();

    ApplicationProperties.GitProperties gitProps = new ApplicationProperties.GitProperties();
    gitProps.setMaxWaitTimeSecond(30);

    final Git git = Git.init().setBare(false).setDirectory(tmpDir).call();

    return new JGitRepository(gitProps, new ReentrantLock()) {
        @Override
        protected void initRepository(){};
        @Override
        protected void pull(){};
        @Override
        protected void commitAndPush(String commitMsg){};
    };
}
 
Example 15
Project: chili-core   File: HazelMap.java   View source code 6 votes vote down vote up
/**
 * Initializes a new hazel async map.
 *
 * @param context the context requesting the map to be created.
 * @param future  called when the map is created.
 */
public HazelMap(Future<AsyncStorage> future, StorageContext<Value> context) {
    this.context = context;

    context.vertx().sharedData().<String, Value>getClusterWideMap(context.database(), cluster -> {
        if (cluster.succeeded()) {
            this.map = cluster.result();

            Optional<HazelcastInstance> hazel = Hazelcast.getAllHazelcastInstances().stream().findFirst();

            if (hazel.isPresent()) {
                HazelcastInstance instance = hazel.get();
                imap = instance.getMap(context.database());
                addIndex(Storable.idField);
                future.complete(this);
            } else {
                future.fail(CoreStrings.ERROR_NOT_CLUSTERED);
            }
        } else {
            future.fail(cluster.cause());
        }
    });
}
 
Example 16
Project: spring-boot-concourse   File: CacheAutoConfigurationTests.java   View source code 6 votes vote down vote up
@Test
public void hazelcastCacheWithMainHazelcastAutoConfigurationAndSeparateCacheConfig()
		throws IOException {
	String mainConfig = "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.xml";
	String cacheConfig = "org/springframework/boot/autoconfigure/cache/hazelcast-specific.xml";
	AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
	EnvironmentTestUtils.addEnvironment(applicationContext,
			"spring.cache.type=hazelcast",
			"spring.cache.hazelcast.config=" + cacheConfig,
			"spring.hazelcast.config=" + mainConfig);
	applicationContext.register(DefaultCacheConfiguration.class);
	applicationContext.register(HazelcastAndCacheConfiguration.class);
	applicationContext.refresh();
	this.context = applicationContext;
	HazelcastInstance hazelcastInstance = this.context
			.getBean(HazelcastInstance.class);
	HazelcastCacheManager cacheManager = validateCacheManager(
			HazelcastCacheManager.class);
	HazelcastInstance cacheHazelcastInstance = (HazelcastInstance) new DirectFieldAccessor(
			cacheManager).getPropertyValue("hazelcastInstance");
	assertThat(cacheHazelcastInstance).isNotEqualTo(hazelcastInstance); // Our custom
	assertThat(hazelcastInstance.getConfig().getConfigurationFile())
			.isEqualTo(new ClassPathResource(mainConfig).getFile());
	assertThat(cacheHazelcastInstance.getConfig().getConfigurationFile())
			.isEqualTo(new ClassPathResource(cacheConfig).getFile());
}
 
Example 17
Project: hazelcast-hibernate5   File: HazelcastQueryResultsRegionTest.java   View source code 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    mapConfig = mock(MapConfig.class);
    when(mapConfig.getMaxSizeConfig()).thenReturn(new MaxSizeConfig(maxSize, MaxSizeConfig.MaxSizePolicy.PER_NODE));
    when(mapConfig.getTimeToLiveSeconds()).thenReturn(timeout);

    config = mock(Config.class);
    when(config.findMapConfig(eq(REGION_NAME))).thenReturn(mapConfig);

    Cluster cluster = mock(Cluster.class);
    when(cluster.getClusterTime()).thenAnswer(new Answer<Long>() {
        @Override
        public Long answer(InvocationOnMock invocation) throws Throwable {
            return System.currentTimeMillis();
        }
    });

    instance = mock(HazelcastInstance.class);
    when(instance.getConfig()).thenReturn(config);
    when(instance.getCluster()).thenReturn(cluster);

    region = new HazelcastQueryResultsRegion(instance, REGION_NAME, new Properties());
}
 
Example 18
Project: hazelcast-zookeeper   File: HazelcastIntegrationTest.java   View source code 6 votes vote down vote up
@Test
public void testIntegration_urlNotConfigured() {
    exception.expect(IllegalStateException.class);
    exception.expectMessage("Zookeeper URL cannot be null.");

    Config config = new Config();
    config.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false);
    config.setProperty("hazelcast.discovery.enabled", "true");

    DiscoveryStrategyConfig discoveryStrategyConfig = new DiscoveryStrategyConfig(new ZookeeperDiscoveryStrategyFactory());
    config.getNetworkConfig().getJoin().getDiscoveryConfig().addDiscoveryStrategyConfig(discoveryStrategyConfig);

    HazelcastInstance instance1 = Hazelcast.newHazelcastInstance(config);
    HazelcastInstance instance2 = Hazelcast.newHazelcastInstance(config);

    int instance1Size = instance1.getCluster().getMembers().size();
    assertEquals(2, instance1Size);
    int instance2Size = instance2.getCluster().getMembers().size();
    assertEquals(2, instance2Size);
}
 
Example 19
Project: hazelcast-demo   File: ListenerDemo.java   View source code 6 votes vote down vote up
public static void main(String[] args) {
	HazelcastInstance ins = Hazelcast.newHazelcastInstance();
	IMap<Integer, String> map = ins.getMap("");
	map.addEntryListener(new ListenerExample(), true);//添加自定义监听器
	map.put(1, "Grand Theft Auto");
	map.put(1, "Final Fantasy");
	map.put(2, "World Of Warcraft");
	
	HazelcastInstance insex = Hazelcast.newHazelcastInstance();
	IMap<Integer, String> mapex = insex.getMap("");
	
	System.out.println(mapex.get(1));
	System.out.println(mapex.get(2));
	mapex.remove(1);
	mapex.remove(2);
	System.exit(0);
}
 
Example 20
Project: hazelcast-hibernate   File: CustomPropertiesTest.java   View source code 6 votes vote down vote up
@Test
public void testNamedInstance() {
    TestHazelcastFactory factory = new TestHazelcastFactory();
    Config config = new Config();
    config.setInstanceName("hibernate");
    HazelcastInstance hz = factory.newHazelcastInstance(config);
    Properties props = new Properties();
    props.setProperty(Environment.CACHE_REGION_FACTORY, HazelcastCacheRegionFactory.class.getName());
    props.put(CacheEnvironment.HAZELCAST_INSTANCE_NAME, "hibernate");
    props.put(CacheEnvironment.SHUTDOWN_ON_STOP, "false");
    props.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");

    Configuration configuration = new Configuration();
    configuration.addProperties(props);

    SessionFactory sf = configuration.buildSessionFactory();
    assertTrue(hz.equals(HazelcastAccessor.getHazelcastInstance(sf)));
    sf.close();
    assertTrue(hz.getLifecycleService().isRunning());
    factory.shutdownAll();
}
 
Example 21
Project: hazelcast-eureka   File: HazelcastClientTestCase.java   View source code 6 votes vote down vote up
@Test
public void testSimpleDiscovery(){
    ArgumentCaptor<InstanceInfo> captor = ArgumentCaptor.forClass(InstanceInfo.class);

    EurekaHttpResponse<Applications> response = generateMockResponse(Collections.<InstanceInfo>emptyList());
    when(requestHandler.getApplications()).thenReturn(response);

    HazelcastInstance hz1 = factory.newHazelcastInstance();
    HazelcastInstance hz2 = factory.newHazelcastInstance();

    verify(requestHandler, timeout(5000).times(2)).register(captor.capture());
    response = generateMockResponse(captor.getAllValues());
    when(requestHandler.getApplications()).thenReturn(response);

    assertClusterSizeEventually(2, hz1);
    assertClusterSizeEventually(2, hz2);

    HazelcastInstance client = factory.newHazelcastClient();
    reset(requestHandler);
    when(requestHandler.getApplications()).thenReturn(response);
    verify(requestHandler, timeout(1000).times(0)).register(Matchers.<InstanceInfo>any());
    assertClusterSizeEventually(2, client);
}
 
Example 22
Project: hazelcast-tomcat-sessionmanager   File: AbstractStickySessionsTest.java   View source code 6 votes vote down vote up
@Test(timeout = 80000)
public void testFailover() throws Exception {
    CookieStore cookieStore = new BasicCookieStore();
    String value = executeRequest("read", SERVER_PORT_1, cookieStore);
    assertEquals("null", value);

    executeRequest("write", SERVER_PORT_1, cookieStore);

    instance1.stop();

    HazelcastInstance hzInstance1 = Hazelcast.getHazelcastInstanceByName("hzInstance1");
    if (hzInstance1 != null) {
        hzInstance1.shutdown();
    }

    value = executeRequest("read", SERVER_PORT_2, cookieStore);
    assertEquals("value", value);
}
 
Example 23
Project: hazelcast-eureka   File: HazelcastClientTestCase.java   View source code 6 votes vote down vote up
@Test
public void testInstanceRegistrationUsingProvidedEurekaClient() {
    EurekaClient eurekaClient = mock(EurekaClient.class);
    ApplicationInfoManager applicationInfoManager = mock(ApplicationInfoManager.class);
    EurekaInstanceConfig eurekaInstanceConfig = mock(EurekaInstanceConfig.class);

    when(eurekaClient.getApplicationInfoManager()).thenReturn(applicationInfoManager);
    when(eurekaClient.getApplication(anyString())).thenReturn(new Application(APP_NAME));

    when(applicationInfoManager.getEurekaInstanceConfig()).thenReturn(eurekaInstanceConfig);
    when(eurekaInstanceConfig.getAppname()).thenReturn(APP_NAME);

    // use provided EurekaClient
    EurekaOneDiscoveryStrategyFactory.setEurekaClient(eurekaClient);

    HazelcastInstance hz1 = factory.newHazelcastInstance();
    HazelcastInstance hz2 = factory.newHazelcastInstance();
    
    verify(eurekaClient, times(2)).getApplicationInfoManager();
    verify(eurekaClient, times(2)).getApplication(APP_NAME);
    verify(applicationInfoManager, never()).setInstanceStatus(InstanceStatus.UP);
    verify(applicationInfoManager, never()).setInstanceStatus(any(InstanceStatus.class));

    assertClusterSizeEventually(2, hz1);
    assertClusterSizeEventually(2, hz2);
}
 
Example 24
Project: hazelcast-hibernate   File: CustomPropertiesTest.java   View source code 6 votes vote down vote up
@Test
public void testNamedInstance() {
    TestHazelcastFactory factory = new TestHazelcastFactory();
    Config config = new Config();
    config.setInstanceName("hibernate");
    HazelcastInstance hz = factory.newHazelcastInstance(config);
    Properties props = new Properties();
    props.setProperty(Environment.CACHE_REGION_FACTORY, HazelcastCacheRegionFactory.class.getName());
    props.put(CacheEnvironment.HAZELCAST_INSTANCE_NAME, "hibernate");
    props.put(CacheEnvironment.SHUTDOWN_ON_STOP, "false");
    props.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");

    Configuration configuration = new Configuration();
    configuration.addProperties(props);

    SessionFactory sf = configuration.buildSessionFactory();
    assertTrue(hz.equals(HazelcastAccessor.getHazelcastInstance(sf)));
    sf.close();
    assertTrue(hz.getLifecycleService().isRunning());
    factory.shutdownAll();
}
 
Example 25
Project: hazelcast-hibernate   File: HazelcastQueryResultsRegionTest.java   View source code 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    mapConfig = mock(MapConfig.class);
    when(mapConfig.getMaxSizeConfig()).thenReturn(new MaxSizeConfig(maxSize, MaxSizeConfig.MaxSizePolicy.PER_NODE));
    when(mapConfig.getTimeToLiveSeconds()).thenReturn(timeout);

    config = mock(Config.class);
    when(config.findMapConfig(eq(REGION_NAME))).thenReturn(mapConfig);

    Cluster cluster = mock(Cluster.class);
    when(cluster.getClusterTime()).thenAnswer(new Answer<Long>() {
        @Override
        public Long answer(InvocationOnMock invocation) throws Throwable {
            return System.currentTimeMillis();
        }
    });

    instance = mock(HazelcastInstance.class);
    when(instance.getConfig()).thenReturn(config);
    when(instance.getCluster()).thenReturn(cluster);

    region = new HazelcastQueryResultsRegion(instance, REGION_NAME, new Properties());
}
 
Example 26
Project: subzero   File: TestCustomerSerializers.java   View source code 6 votes vote down vote up
@Test
public void testGlobalCustomDelegateSerializationConfiguredProgrammaticallyForClientConfig() {
    Config memberConfig = new Config();
    SubZero.useAsGlobalSerializer(memberConfig);
    hazelcastFactory.newHazelcastInstance(memberConfig);

    String mapName = randomMapName();
    ClientConfig config = new ClientConfig();

    SubZero.useAsGlobalSerializer(config, MyGlobalDelegateSerlizationConfig.class);

    HazelcastInstance member = hazelcastFactory.newHazelcastClient(config);
    IMap<Integer, AnotherNonSerializableObject> myMap = member.getMap(mapName);
    myMap.put(0, new AnotherNonSerializableObject());
    AnotherNonSerializableObject fromCache = myMap.get(0);

    assertEquals("deserialized", fromCache.name);
}
 
Example 27
Project: hazelcast-hibernate   File: HibernateSerializationHookAvailableTest.java   View source code 6 votes vote down vote up
@Test
public void testAutoregistrationOnHibernate4Available()
        throws Exception {

    HazelcastInstance hz = Hazelcast.newHazelcastInstance();
    HazelcastInstanceImpl impl = (HazelcastInstanceImpl) ORIGINAL.get(hz);
    SerializationService ss = impl.getSerializationService();
    ConcurrentMap<Class, ?> typeMap = (ConcurrentMap<Class, ?>) TYPE_MAP.get(ss);

    boolean cacheKeySerializerFound = false;
    boolean cacheEntrySerializerFound = false;
    for (Class clazz : typeMap.keySet()) {
        if (clazz == CacheKey.class) {
            cacheKeySerializerFound = true;
        } else if (clazz == CacheEntry.class) {
            cacheEntrySerializerFound = true;
        }
    }

    assertTrue("CacheKey serializer not found", cacheKeySerializerFound);
    assertTrue("CacheEntry serializer not found", cacheEntrySerializerFound);
}
 
Example 28
Project: hazelcast-wm   File: AbstractWebFilterTest.java   View source code 6 votes vote down vote up
public ContainerContext(AbstractWebFilterTest test,
                        String serverXml1,
                        String serverXml2,
                        int serverPort1,
                        int serverPort2,
                        ServletContainer server1,
                        ServletContainer server2,
                        HazelcastInstance hz) {
    this.test = test;
    this.serverXml1 = serverXml1;
    this.serverXml2 = serverXml2;
    this.serverPort1 = serverPort1;
    this.serverPort2 = serverPort2;
    this.server1 = server1;
    this.server2 = server2;
    this.hz = hz;
}
 
Example 29
Project: hazelcast-hibernate5   File: HazelcastTimestampsRegionTest.java   View source code 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    mapConfig = mock(MapConfig.class);
    when(mapConfig.getMaxSizeConfig()).thenReturn(new MaxSizeConfig(50, MaxSizeConfig.MaxSizePolicy.PER_NODE));
    when(mapConfig.getTimeToLiveSeconds()).thenReturn(timeout);

    config = mock(Config.class);
    when(config.findMapConfig(eq(REGION_NAME))).thenReturn(mapConfig);

    Cluster cluster = mock(Cluster.class);
    when(cluster.getClusterTime()).thenAnswer(new Answer<Long>() {
        @Override
        public Long answer(InvocationOnMock invocation) throws Throwable {
            return System.currentTimeMillis();
        }
    });

    instance = mock(HazelcastInstance.class);
    when(instance.getConfig()).thenReturn(config);
    when(instance.getCluster()).thenReturn(cluster);

    cache = mock(RegionCache.class);

    region = new HazelcastTimestampsRegion<RegionCache>(instance, REGION_NAME, new Properties(), cache);
}
 
Example 30
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: CacheAutoConfigurationTests.java   View source code 6 votes vote down vote up
@Test
public void hazelcastCacheWithMainHazelcastAutoConfiguration() throws IOException {
	String mainConfig = "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.xml";
	AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
	EnvironmentTestUtils.addEnvironment(applicationContext,
			"spring.cache.type=hazelcast", "spring.hazelcast.config=" + mainConfig);
	applicationContext.register(DefaultCacheConfiguration.class);
	applicationContext.register(HazelcastAndCacheConfiguration.class);
	applicationContext.refresh();
	this.context = applicationContext;
	HazelcastCacheManager cacheManager = validateCacheManager(
			HazelcastCacheManager.class);
	HazelcastInstance hazelcastInstance = this.context
			.getBean(HazelcastInstance.class);
	assertThat(getHazelcastInstance(cacheManager)).isEqualTo(hazelcastInstance);
	assertThat(hazelcastInstance.getConfig().getConfigurationFile())
			.isEqualTo(new ClassPathResource(mainConfig).getFile());
}
 
Example 31
Project: spring-boot-concourse   File: HazelcastAutoConfigurationTests.java   View source code 6 votes vote down vote up
@Test
public void configInstanceWithName() {
	Config config = new Config("my-test-instance");
	HazelcastInstance existingHazelcastInstance = Hazelcast
			.newHazelcastInstance(config);
	try {
		load(HazelcastConfigWithName.class,
				"spring.hazelcast.config=this-is-ignored.xml");
		HazelcastInstance hazelcastInstance = this.context
				.getBean(HazelcastInstance.class);
		assertThat(hazelcastInstance.getConfig().getInstanceName())
				.isEqualTo("my-test-instance");
		// Should reuse any existing instance by default.
		assertThat(hazelcastInstance).isEqualTo(existingHazelcastInstance);
	}
	finally {
		existingHazelcastInstance.shutdown();
	}
}
 
Example 32
Project: hazelcast-jetty-sessionmanager   File: JettySessionUtils.java   View source code 6 votes vote down vote up
/**
 * Create hazelcast full instance.
 *
 * @param configLocation the config location
 * @return the hazelcast instance
 */
public static HazelcastInstance createHazelcastFullInstance(String configLocation) {
    Config config;
    try {
        if (configLocation == null) {
            config = new XmlConfigBuilder().build();
        } else {
            config = ConfigLoader.load(configLocation);
        }
    } catch (IOException e) {
        throw new RuntimeException("failed to load config", e);
    }

    checkNotNull(config, "failed to find configLocation: " + configLocation);

    config.setInstanceName(DEFAULT_INSTANCE_NAME);
    return Hazelcast.getOrCreateHazelcastInstance(config);
}
 
Example 33
Project: xm-uaa   File: CacheConfiguration.java   View source code 5 votes vote down vote up
@Bean
public HazelcastInstance hazelcastInstance(JHipsterProperties jHipsterProperties) {
    log.debug("Configuring Hazelcast");
    HazelcastInstance hazelCastInstance = Hazelcast.getHazelcastInstanceByName("uaa");
    if (hazelCastInstance != null) {
        log.debug("Hazelcast already initialized");
        return hazelCastInstance;
    }
    Config config = new Config();
    config.setInstanceName("uaa");
    config.getNetworkConfig().setPort(5701);
    config.getNetworkConfig().setPortAutoIncrement(true);

    // In development, remove multicast auto-configuration
    if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) {
        System.setProperty("hazelcast.local.localAddress", "127.0.0.1");

        config.getNetworkConfig().getJoin().getAwsConfig().setEnabled(false);
        config.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false);
        config.getNetworkConfig().getJoin().getTcpIpConfig().setEnabled(false);
    }
    config.getMapConfigs().put("default", initializeDefaultMapConfig());
    config.getMapConfigs().put("com.icthh.xm.uaa.domain.*", initializeDomainMapConfig(jHipsterProperties));
    // Uncomment if session needed
    //config.getMapConfigs().put("clustered-http-sessions", initializeClusteredSession(jHipsterProperties));
    return Hazelcast.newHazelcastInstance(config);
}
 
Example 34
Project: greycat   File: HazelcastTest.java   View source code 5 votes vote down vote up
public static void main(String[] args) {
    ClientConfig clientConfig = new ClientConfig();
    clientConfig.addAddress("127.0.0.1:5701");
    HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig);
    IMap map = client.getMap("customers");
    System.out.println("Map Size:" + map.size());

    client.getDurableExecutorService("hello").submit(new HazelcastJob(() -> System.out.println("Hello")));

}
 
Example 35
Project: springboot-shiro-cas-mybatis   File: HazelcastTicketRegistry.java   View source code 5 votes vote down vote up
/**
 * @param hz An instance of <code>HazelcastInstance</code>
 * @param mapName Name of map to use
 * @param ticketGrantingTicketTimoutInSeconds TTL for TGT entries
 * @param serviceTicketTimeoutInSeconds TTL for ST entries
 */
public HazelcastTicketRegistry(final HazelcastInstance hz,
                               final String mapName,
                               final long ticketGrantingTicketTimoutInSeconds,
                               final long serviceTicketTimeoutInSeconds) {

    logInitialization(hz, mapName, ticketGrantingTicketTimoutInSeconds, serviceTicketTimeoutInSeconds);
    this.registry = hz.getMap(mapName);
    this.ticketGrantingTicketTimoutInSeconds = ticketGrantingTicketTimoutInSeconds;
    this.serviceTicketTimeoutInSeconds = serviceTicketTimeoutInSeconds;
    this.hz = hz;
}
 
Example 36
Project: springboot-shiro-cas-mybatis   File: HazelcastTicketRegistry.java   View source code 5 votes vote down vote up
/**
 * @param hz An instance of <code>HazelcastInstance</code>
 * @param mapName Name of map to use
 * @param ticketGrantingTicketTimoutInSeconds TTL for TGT entries
 * @param serviceTicketTimeoutInSeconds TTL for ST entries
 */
private void logInitialization(final HazelcastInstance hz,
                               final String mapName,
                               final long ticketGrantingTicketTimoutInSeconds,
                               final long serviceTicketTimeoutInSeconds) {

    logger.info("Setting up Hazelcast Ticket Registry...");
    logger.debug("Hazelcast instance: {}", hz);
    logger.debug("TGT timeout: [{}s]", ticketGrantingTicketTimoutInSeconds);
    logger.debug("ST timeout: [{}s]", serviceTicketTimeoutInSeconds);
}
 
Example 37
Project: cas-5.1.0   File: HazelcastMonitor.java   View source code 5 votes vote down vote up
@Override
protected CacheStatistics[] getStatistics() {
    final List<CacheStatistics> statsList = new ArrayList<>();
    final HazelcastProperties hz = casProperties.getTicket().getRegistry().getHazelcast();
    LOGGER.debug("Locating hazelcast instance [{}]...", hz.getCluster().getInstanceName());
    final HazelcastInstance instance = Hazelcast.getHazelcastInstanceByName(hz.getCluster().getInstanceName());

    instance.getConfig().getMapConfigs().keySet().forEach(key -> {
        final IMap map = instance.getMap(key);
        LOGGER.debug("Starting to collect hazelcast statistics for map [{}] identified by key [{}]...", map, key);
        statsList.add(new HazelcastStatistics(map, hz.getCluster().getMembers().size()));
    });
    return statsList.toArray(new CacheStatistics[statsList.size()]);
}
 
Example 38
Project: cas-5.1.0   File: HazelcastTicketRegistry.java   View source code 5 votes vote down vote up
/**
 * Instantiates a new Hazelcast ticket ticketGrantingTicketsRegistry.
 *
 * @param hz       An instance of {@code HazelcastInstance}
 * @param plan     the plan
 * @param pageSize the page size
 */
public HazelcastTicketRegistry(final HazelcastInstance hz, final TicketCatalog plan, final int pageSize) {
    this.hazelcastInstance = hz;
    this.pageSize = pageSize;
    this.ticketCatalog = plan;

    LOGGER.info("Setting up Hazelcast Ticket Registry instance [{}]", this.hazelcastInstance);
}
 
Example 39
Project: teamcity-gradle-build-cache-plugin   File: BuildCachePage.java   View source code 5 votes vote down vote up
public void fillModel(@NotNull Map<String, Object> model, @NotNull HttpServletRequest request) {
    HazelcastInstance instance = Hazelcast.getHazelcastInstanceByName(INSTANCE_NAME);
    if (instance != null) {
        IMap<String, byte[]> taskCache = instance.getMap(TASK_CACHE_NAME);
        LocalMapStats statistics = taskCache.getLocalMapStats();
        model.put("statistics", statistics);
    }
}
 
Example 40
Project: testcontainers-hazelcast   File: MongoMapStore.java   View source code 5 votes vote down vote up
@Override
public void init(HazelcastInstance hazelcastInstance, Properties properties, String mapName) {
    String mongoUrl = (String) properties.get("mongo.url");
    String dbName = (String) properties.get("mongo.db");
    String collectionName = (String) properties.get("mongo.collection");
    this.mongoClient = new MongoClient(new MongoClientURI(mongoUrl));
    this.collection = mongoClient.getDatabase(dbName).getCollection(collectionName);
}