@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; }
/** * 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); } }
public static void main(String[] args) { try { // 获取配置文件磁盘路径 final String path = Thread.currentThread().getContextClassLoader().getResource("").toString() + DEF_CONFIG_FILE; // 构建XML配置 XmlConfigBuilder builder = new XmlConfigBuilder(path); // 配置对应的properties解析参数 builder.setProperties(getProperties()); // 创建Config Config config = builder.build(); // 输出Config参数 System.out.println(config.getGroupConfig().getName()); } catch (FileNotFoundException e) { e.printStackTrace(); } }
@Test public void testExternalRegistration(){ EurekaHttpResponse<Applications> response = generateMockResponse(Collections.<InstanceInfo>emptyList()); when(requestHandler.getApplications()).thenReturn(response); Config config = new XmlConfigBuilder().build(); DiscoveryConfig discoveryConfig = config.getNetworkConfig().getJoin().getDiscoveryConfig(); DiscoveryStrategyConfig strategyConfig = discoveryConfig.getDiscoveryStrategyConfigs().iterator().next(); strategyConfig.addProperty("self-registration", "false"); HazelcastInstance hz1 = factory.newHazelcastInstance(config); HazelcastInstance hz2 = factory.newHazelcastInstance(config); assertClusterSizeEventually(2, hz1); assertClusterSizeEventually(2, hz2); verify(requestHandler, after(5000).never()).register(any(InstanceInfo.class)); }
@Test public void testNamespaceRegistration(){ final String appName = "other"; final String namespace = "hz"; configure(namespace, appName); EurekaHttpResponse<Applications> response = generateMockResponse(Collections.<InstanceInfo>emptyList(), appName); when(requestHandler.getApplications()).thenReturn(response); Config config = new XmlConfigBuilder().build(); DiscoveryConfig discoveryConfig = config.getNetworkConfig().getJoin().getDiscoveryConfig(); DiscoveryStrategyConfig strategyConfig = discoveryConfig.getDiscoveryStrategyConfigs().iterator().next(); strategyConfig.addProperty("namespace", namespace); HazelcastInstance hz1 = factory.newHazelcastInstance(config); assertClusterSizeEventually(1, hz1); ArgumentCaptor<InstanceInfo> captor = ArgumentCaptor.forClass(InstanceInfo.class); verify(requestHandler, timeout(5000).atLeastOnce()).register(captor.capture()); String actual = captor.getValue().getAppName().toLowerCase(); assertThat(actual, is(appName)); }
private Config createConfig() { Config config; try { config = new XmlConfigBuilder(Application.class.getClassLoader().getResource(CONFIG_NAME)).build(); } catch (IOException e) { logger.error(e.getMessage(), e); throw new Error(e); } config.getSerializationConfig().addDataSerializableFactory(SerializableFactory.ID, new SerializableFactory()); config.getSerializationConfig().getSerializerConfigs().add(new SerializerConfig().setTypeClass(JsonNode.class) .setImplementation(JsonSerializer.makePlain(JsonNode.class))); return config; }
/** * 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); }
@Override public void configure(final Properties props) { String instanceName = CacheEnvironment.getInstanceName(props); if (!StringUtil.isNullOrEmptyAfterTrim(instanceName)) { LOGGER.info("Using existing HazelcastInstance [" + instanceName + "]."); this.existingInstanceName = instanceName; } else { String configResourcePath = CacheEnvironment.getConfigFilePath(props); if (!StringUtil.isNullOrEmptyAfterTrim(configResourcePath)) { try { this.config = ConfigLoader.load(configResourcePath); } catch (IOException e) { LOGGER.warning("IOException: " + e.getMessage()); } if (config == null) { throw new CacheException("Could not find configuration file: " + configResourcePath); } } else { this.config = new XmlConfigBuilder().build(); } } this.shutDown = CacheEnvironment.shutdownOnStop(props, (instanceName == null)); }
@Override public void configure(Properties props) { String instanceName = CacheEnvironment.getInstanceName(props); if (!StringUtil.isNullOrEmptyAfterTrim(instanceName)) { LOGGER.info("Using existing HazelcastInstance [" + instanceName + "]."); this.existingInstanceName = instanceName; } else { String configResourcePath = CacheEnvironment.getConfigFilePath(props); if (!StringUtil.isNullOrEmptyAfterTrim(configResourcePath)) { try { this.config = ConfigLoader.load(configResourcePath); } catch (IOException e) { LOGGER.warning("IOException: " + e.getMessage()); } if (config == null) { throw new CacheException("Could not find configuration file: " + configResourcePath); } } else { this.config = new XmlConfigBuilder().build(); } } this.shutDown = CacheEnvironment.shutdownOnStop(props, (instanceName == null)); }
@Test public void discoveryStrategyFactoryTest() { JCloudsDiscoveryStrategyFactory jCloudsDiscoveryStrategyFactory = new JCloudsDiscoveryStrategyFactory(); String xmlFileName = "test-jclouds-config.xml"; InputStream xmlResource = JCloudsDiscoveryFactoryTest.class.getClassLoader().getResourceAsStream(xmlFileName); Config config = new XmlConfigBuilder(xmlResource).build(); JoinConfig joinConfig = config.getNetworkConfig().getJoin(); DiscoveryConfig discoveryConfig = joinConfig.getDiscoveryConfig(); DiscoveryStrategyConfig providerConfig = discoveryConfig.getDiscoveryStrategyConfigs().iterator().next(); assertEquals(jCloudsDiscoveryStrategyFactory.getDiscoveryStrategyType(), JCloudsDiscoveryStrategy.class); assertEquals(JCloudsDiscoveryStrategy.class.getName(), providerConfig.getClassName()); assertEquals(jCloudsDiscoveryStrategyFactory.getConfigurationProperties().size(), providerConfig.getProperties().size()); assertTrue(jCloudsDiscoveryStrategyFactory. newDiscoveryStrategy(null, null, new HashMap<String, Comparable>()) instanceof DiscoveryStrategy); }
@Override protected void doStart() throws Exception { if (maximumRedeliveries < 0) { throw new IllegalArgumentException("Maximum redelivery retries must be zero or a positive integer."); } if (recoveryInterval < 0) { throw new IllegalArgumentException("Recovery interval must be zero or a positive integer."); } ObjectHelper.notEmpty(mapName, "repositoryName"); if (useLocalHzInstance) { Config cfg = new XmlConfigBuilder().build(); cfg.setProperty("hazelcast.version.check.enabled", "false"); hzInstance = Hazelcast.newHazelcastInstance(cfg); } else { ObjectHelper.notNull(hzInstance, "hzInstanse"); } cache = hzInstance.getMap(mapName); if (useRecovery) { persistedCache = hzInstance.getMap(persistenceMapName); } }
@Test public void test_simple_sequencer_initialization_declarative() throws Exception { ClassLoader classLoader = BasicTestCase.class.getClassLoader(); InputStream stream = classLoader.getResourceAsStream("hazelcast-node-configuration.xml"); Config config = new XmlConfigBuilder(stream).build(); TestHazelcastInstanceFactory factory = new TestHazelcastInstanceFactory(1); HazelcastInstance hazelcastInstance = factory.newHazelcastInstance(config); try { Snowcast snowcast = SnowcastSystem.snowcast(hazelcastInstance); SnowcastSequencer sequencer = buildSnowcastSequencer(snowcast); assertNotNull(sequencer); } finally { factory.shutdownAll(); } }
public static HazelcastInstanceProxy newHazelcastInstanceProxy(Config config) { if (config == null) { config = new XmlConfigBuilder().build(); } String name = config.getInstanceName(); if (name == null || name.trim().length() == 0) { name = "_hzInstance_" + factoryIdGen.incrementAndGet() + "_" + config.getGroupConfig().getName(); return newHazelcastInstanceProxy(config, name); } else { synchronized (INIT_LOCK) { if (factories.containsKey(name)) { throw new DuplicateInstanceNameException("HazelcastInstance with name '" + name + "' already exists!"); } return newHazelcastInstanceProxy(config, name); } } }
/** * Test for Issue 710 */ @Test public void testEvictedEntryNotNullAfterLockAndGet() throws Exception { String mapName = "testLock"; Config config = new XmlConfigBuilder().build(); MapConfig mapConfig = new MapConfig(); mapConfig.setName(mapName); mapConfig.setTimeToLiveSeconds(3); config.addMapConfig(mapConfig); HazelcastInstance h1 = Hazelcast.newHazelcastInstance(config); IMap<Object, Object> m1 = h1.getMap(mapName); m1.put(1, 1); assertEquals(1, m1.get(1)); Thread.sleep(5000); assertEquals(null, m1.get(1)); m1.lock(1); assertEquals(null, m1.get(1)); m1.put(1, 1); assertEquals(1, m1.get(1)); }
@Ignore @Test public void issue371NearCachePutGetRemove() throws Exception { // looks like passed ok final HazelcastInstance hz = Hazelcast.newHazelcastInstance(new XmlConfigBuilder(ClassLoader.getSystemResourceAsStream("hazelcast-issue371.xml")).build()); IMap<Object, Object> cache = hz.getMap("ipp-2nd-level-cache-near"); assertNotNull(cache); Object value = cache.get("my-key"); assertNull(value); value = cache.put("my-key", "my-value"); assertNull(value); value = cache.get("my-key"); assertEquals("my-value", value); value = cache.remove("my-key"); assertEquals("my-value", value); value = cache.get("my-key"); assertNull(value); }
@Ignore @Test public void issue371NearCachePutContainsNonexistentKey() throws Exception { // looks like passed ok final HazelcastInstance hz = Hazelcast.newHazelcastInstance(new XmlConfigBuilder(ClassLoader.getSystemResourceAsStream("hazelcast-issue371.xml")).build()); IMap<Object, Object> cache = hz.getMap("ipp-2nd-level-cache-near"); assertNotNull(cache); Object value = cache.get("my-key"); assertNull(value); boolean foundKey = cache.containsKey("my-key"); assertFalse(foundKey); value = cache.remove("my-key"); assertNull(value); value = cache.get("my-key"); assertNull(value); }
@Ignore @Test public void issue371NearCachePutContainsExistentKey() throws Exception { // hangs on, issue: // java.lang.IllegalStateException: Removed CacheEntry cannot be null // at com.hazelcast.impl.MapNearCache.invalidate(MapNearCache.java:181) final HazelcastInstance hz = Hazelcast.newHazelcastInstance(new XmlConfigBuilder(ClassLoader.getSystemResourceAsStream("hazelcast-issue371.xml")).build()); IMap<Object, Object> cache = hz.getMap("ipp-2nd-level-cache-near"); assertNotNull(cache); Object value = cache.get("my-key"); assertNull(value); value = cache.put("my-key", "my-value"); assertNull(value); boolean foundKey = cache.containsKey("my-key"); assertTrue(foundKey); value = cache.remove("my-key"); assertEquals("my-value", value); value = cache.get("my-key"); assertNull(value); }
@Test public void twoClientsAndTransaction() { Config config1 = new XmlConfigBuilder().build(); config1.setProperty(GroupProperties.PROP_WAIT_SECONDS_BEFORE_JOIN, "1"); Config config2 = new XmlConfigBuilder().build(); config2.setProperty(GroupProperties.PROP_WAIT_SECONDS_BEFORE_JOIN, "1"); GroupConfig gConfig1 = new GroupConfig("g1", "pg1"); GroupConfig gConfig2 = new GroupConfig("g2", "pg2"); config1.setGroupConfig(gConfig1); config2.setGroupConfig(gConfig2); HazelcastInstance h1 = Hazelcast.newHazelcastInstance(config1); HazelcastInstance h2 = Hazelcast.newHazelcastInstance(config2); HazelcastInstance client1 = TestUtility.newHazelcastClient(h1); HazelcastInstance client2 = TestUtility.newHazelcastClient(h2); Transaction t1 = client1.getTransaction(); Transaction t2 = client2.getTransaction(); t1.begin(); client1.getMap("map").put(1, 4); t1.commit(); client1.shutdown(); client2.shutdown(); h1.shutdown(); h2.shutdown(); }
public static HazelcastInstance findOrCreateMember(final String xmlConfiguration, String instanceName) throws IOException { final HazelcastInstance found = Hazelcast.getHazelcastInstanceByName(instanceName); if (found != null) { return found; } final Config config; if (xmlConfiguration != null) { config = new XmlConfigBuilder(IOs.findConfiguration(xmlConfiguration)).build(); } else { config = new XmlConfigBuilder().build(); } if (instanceName != null) { config.setInstanceName(instanceName); } return Hazelcast.newHazelcastInstance(config); }
public static HazelcastInstanceProxy newHazelcastInstanceProxy(Config config, Boolean liteMember) { if (config == null) { config = new XmlConfigBuilder().build(); } if (liteMember != null) { config.setLiteMember(liteMember); } String name = config.getInstanceName(); if (name == null || name.trim().length() == 0) { name = "_hzInstance_" + factoryIdGen.incrementAndGet() + "_" + config.getGroupConfig().getName(); return newHazelcastInstanceProxy(config, name); } else { synchronized (INIT_LOCK) { if (factories.containsKey(name)) { throw new DuplicateInstanceNameException("HazelcastInstance with name '" + name + "' already exists!"); } return newHazelcastInstanceProxy(config, name); } } }
@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))); return Hazelcast.newHazelcastInstance(config); }
public static HazelcastInstance getInstance() { if (hazelcastInstance == null) { Config config = new XmlConfigBuilder().build(); config.setInstanceName(Thread.currentThread().getName()); hazelcastInstance = Hazelcast.getOrCreateHazelcastInstance(config); } return hazelcastInstance; }
private static HazelcastInstance buildCluster(int memberCount) { Config config = new XmlConfigBuilder().build(); NetworkConfig networkConfig = config.getNetworkConfig(); networkConfig.getJoin().getMulticastConfig().setEnabled(false); networkConfig.getJoin().getTcpIpConfig().setEnabled(true); networkConfig.getJoin().getTcpIpConfig().setMembers(Arrays.asList(new String[] {"127.0.0.1"})); HazelcastInstance[] hazelcastInstances = new HazelcastInstance[memberCount]; for (int i = 0; i < memberCount; i++) { hazelcastInstances[i] = Hazelcast.newHazelcastInstance(config); } return hazelcastInstances[0]; }
private Config getConfig(Resource configLocation) throws IOException { URL configUrl = configLocation.getURL(); Config config = new XmlConfigBuilder(configUrl).build(); if (ResourceUtils.isFileURL(configUrl)) { config.setConfigurationFile(configLocation.getFile()); } else { config.setConfigurationUrl(configUrl); } return config; }
private void createOrGetInstance() throws DuplicateInstanceNameException { if (config == null) { config = new XmlConfigBuilder().build(); } config.setInstanceName(instanceName); instance = factory.newHazelcastInstance(config); }
@Test public void testParsing() { String xmlFileName = "test-jclouds-config.xml"; InputStream xmlResource = JCloudsDiscoveryFactoryTest.class.getClassLoader().getResourceAsStream(xmlFileName); Config config = new XmlConfigBuilder(xmlResource).build(); JoinConfig joinConfig = config.getNetworkConfig().getJoin(); AwsConfig awsConfig = joinConfig.getAwsConfig(); assertFalse(awsConfig.isEnabled()); TcpIpConfig tcpIpConfig = joinConfig.getTcpIpConfig(); assertFalse(tcpIpConfig.isEnabled()); MulticastConfig multicastConfig = joinConfig.getMulticastConfig(); assertFalse(multicastConfig.isEnabled()); DiscoveryConfig discoveryConfig = joinConfig.getDiscoveryConfig(); assertTrue(discoveryConfig.isEnabled()); assertEquals(1, discoveryConfig.getDiscoveryStrategyConfigs().size()); DiscoveryStrategyConfig providerConfig = discoveryConfig.getDiscoveryStrategyConfigs().iterator().next(); assertEquals(12, providerConfig.getProperties().size()); assertEquals("aws-ec2", providerConfig.getProperties().get("provider")); assertEquals("test", providerConfig.getProperties().get("identity")); assertEquals("test", providerConfig.getProperties().get("credential")); assertEquals("zone1,zone2", providerConfig.getProperties().get("zones")); assertEquals("region1,region2", providerConfig.getProperties().get("regions")); assertEquals("zone1,zone2", providerConfig.getProperties().get("zones")); assertEquals("tag1,tag2", providerConfig.getProperties().get("tag-keys")); assertEquals("tagvalue1,tagvalue2", providerConfig.getProperties().get("tag-values")); assertEquals("group", providerConfig.getProperties().get("group")); assertEquals("5702", providerConfig.getProperties().get("hz-port")); assertEquals("myfile.json", providerConfig.getProperties().get("credentialPath")); assertEquals("myRole", providerConfig.getProperties().get("role-name")); assertEquals("http://foo/bar", providerConfig.getProperties().get("endpoint")); }
@Test(expected = IllegalArgumentException.class) public void test_invalid_config_when_no_provider_is_set() { String propertiesUnderTest = "<property name=\"identity\">test</property>" + "<property name=\"credential\">test</property>"; String configXML = configTemplate.replace("${PROPERTIES_PLACE_HOLDER}", propertiesUnderTest); Config config = new XmlConfigBuilder(new ByteArrayInputStream(stringToBytes(configXML))).build(); Hazelcast.newHazelcastInstance(config); }
@Test(expected = UnsupportedOperationException.class) public void test_invalid_config_when_credential_and_credential_path_set_together() { String propertiesUnderTest = "<property name=\"provider\">test</property>" + "<property name=\"identity\">test</property>" + "<property name=\"credential\">test</property>" + "<property name=\"credentialPath\">test</property>"; String configXML = configTemplate.replace("${PROPERTIES_PLACE_HOLDER}", propertiesUnderTest); Config config = new XmlConfigBuilder(new ByteArrayInputStream(stringToBytes(configXML))).build(); Hazelcast.newHazelcastInstance(config); }
@Test(expected = InvalidConfigurationException.class) public void test_invalid_config_when_both_IAM_and_credential_set() { String propertiesUnderTest = "<property name=\"provider\">aws-ec2</property>" + "<property name=\"role-name\">test</property>" + "<property name=\"identity\">test</property>" + "<property name=\"credential\">test</property>"; String configXML = configTemplate.replace("${PROPERTIES_PLACE_HOLDER}", propertiesUnderTest); Config config = new XmlConfigBuilder(new ByteArrayInputStream(stringToBytes(configXML))).build(); Hazelcast.newHazelcastInstance(config); }
@Test(expected = InvalidConfigurationException.class) public void test_invalid_config_when_IAM_role_is_configured_with_nonEc2_Provider() { String propertiesUnderTest = "<property name=\"provider\">google-compute-engine</property>" + "<property name=\"role-name\">test</property>"; String configXML = configTemplate.replace("${PROPERTIES_PLACE_HOLDER}", propertiesUnderTest); Config config = new XmlConfigBuilder(new ByteArrayInputStream(stringToBytes(configXML))).build(); Hazelcast.newHazelcastInstance(config); }
@Test(expected = InvalidConfigurationException.class) public void test_invalid_config_when_tag_keys_and_values_have_different_sizes() { String propertiesUnderTest = "<property name=\"provider\">aws-ec2</property>" + "<property name=\"identity\">test</property>" + "<property name=\"credential\">test</property>" + "<property name=\"tag-keys\">tag1,tag2,tag3</property>" + "<property name=\"tag-values\">tag1,tag2</property>"; String configXML = configTemplate.replace("${PROPERTIES_PLACE_HOLDER}", propertiesUnderTest); Config config = new XmlConfigBuilder(new ByteArrayInputStream(stringToBytes(configXML))).build(); Hazelcast.newHazelcastInstance(config); }