CustomHazelcastInstanceFactory.java
/*
* Copyright 2023 Global Crop Diversity Trust
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.genesys.spring.hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.hibernate.CacheEnvironment;
import com.hazelcast.hibernate.instance.DefaultHazelcastInstanceFactory;
import com.hazelcast.hibernate.instance.IHazelcastInstanceFactory;
import com.hazelcast.hibernate.instance.IHazelcastInstanceLoader;
import org.hibernate.cache.CacheException;
import java.util.Properties;
public class CustomHazelcastInstanceFactory implements IHazelcastInstanceFactory {
private static final String HZ_CLIENT_LOADER_CLASSNAME = "com.hazelcast.hibernate.instance.HazelcastClientLoader";
private static HazelcastInstance hazelcastInstance;
public static void setHazelcastInstance(HazelcastInstance hazelcastInstance) {
CustomHazelcastInstanceFactory.hazelcastInstance = hazelcastInstance;
}
public IHazelcastInstanceLoader createInstanceLoader(final Properties props) throws CacheException {
try {
if (props != null && CacheEnvironment.isNativeClient(props)) {
ClassLoader cl = DefaultHazelcastInstanceFactory.class.getClassLoader();
var loaderClass = cl.loadClass(HZ_CLIENT_LOADER_CLASSNAME);
IHazelcastInstanceLoader instanceLoader = (IHazelcastInstanceLoader) loaderClass.newInstance();
instanceLoader.configure(props);
return instanceLoader;
} else {
return new IHazelcastInstanceLoader() {
private boolean shutDown;
@Override
public void configure(Properties props) {
this.shutDown = CacheEnvironment.shutdownOnStop(props, true);
}
@Override
public HazelcastInstance loadInstance() throws CacheException {
return hazelcastInstance;
}
@Override
public void unloadInstance() throws CacheException {
if (!shutDown) {
return;
}
try {
hazelcastInstance.getLifecycleService().shutdown();
} catch (Exception e) {
throw new CacheException(e);
}
}
};
}
} catch (Exception e) {
throw new CacheException(e);
}
}
}