001/* 002 * Copyright 2012-2017 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.boot.autoconfigure.hazelcast; 018 019import java.io.IOException; 020import java.net.URL; 021 022import com.hazelcast.config.Config; 023import com.hazelcast.config.XmlConfigBuilder; 024import com.hazelcast.core.Hazelcast; 025import com.hazelcast.core.HazelcastInstance; 026 027import org.springframework.core.io.Resource; 028import org.springframework.util.Assert; 029import org.springframework.util.ResourceUtils; 030import org.springframework.util.StringUtils; 031 032/** 033 * Factory that can be used to create a {@link HazelcastInstance}. 034 * 035 * @author Stephane Nicoll 036 * @author Phillip Webb 037 * @since 1.3.0 038 */ 039public class HazelcastInstanceFactory { 040 041 private final Config config; 042 043 /** 044 * Create a {@link HazelcastInstanceFactory} for the specified configuration location. 045 * @param configLocation the location of the configuration file 046 * @throws IOException if the configuration location could not be read 047 */ 048 public HazelcastInstanceFactory(Resource configLocation) throws IOException { 049 Assert.notNull(configLocation, "ConfigLocation must not be null"); 050 this.config = getConfig(configLocation); 051 } 052 053 /** 054 * Create a {@link HazelcastInstanceFactory} for the specified configuration. 055 * @param config the configuration 056 */ 057 public HazelcastInstanceFactory(Config config) { 058 Assert.notNull(config, "Config must not be null"); 059 this.config = config; 060 } 061 062 private Config getConfig(Resource configLocation) throws IOException { 063 URL configUrl = configLocation.getURL(); 064 Config config = new XmlConfigBuilder(configUrl).build(); 065 if (ResourceUtils.isFileURL(configUrl)) { 066 config.setConfigurationFile(configLocation.getFile()); 067 } 068 else { 069 config.setConfigurationUrl(configUrl); 070 } 071 return config; 072 } 073 074 /** 075 * Get the {@link HazelcastInstance}. 076 * @return the {@link HazelcastInstance} 077 */ 078 public HazelcastInstance getHazelcastInstance() { 079 if (StringUtils.hasText(this.config.getInstanceName())) { 080 return Hazelcast.getOrCreateHazelcastInstance(this.config); 081 } 082 return Hazelcast.newHazelcastInstance(this.config); 083 } 084 085}