/**
 * Copyright (c) 2000-2017 Liferay, Inc. All rights reserved.
 *
 * The contents of this file are subject to the terms of the Liferay Enterprise
 * pSubscription License ("License"). You may not use this file except in
 * compliance with the License. You can obtain a copy of the License by
 * contacting Liferay, Inc. See the License for the specific language governing
 * permissions and limitations under the License, including but not limited to
 * distribution rights of the Software.
 *
 *
 *
 */

package com.liferay.portal.kernel.cache;

import java.io.Serializable;

import java.util.Map;

/**
 * @author Shuyang Zhou
 */
public class PortalCacheMapSynchronizeUtil {

	public static <K extends Serializable, V> void synchronize(
		PortalCache<K, V> portalCache, Map<? extends K, ? extends V> map,
		Synchronizer<K, V> synchronizer) {

		portalCache.registerCacheListener(
			new SynchronizeCacheListener<K, V>(map, synchronizer));
	}

	public static interface Synchronizer<K extends Serializable, V> {

		public void onSynchronize(
			Map<? extends K, ? extends V> map, K key, V value);

	}

	private static class SynchronizeCacheListener<K extends Serializable, V>
		implements CacheListener<K, V> {

		public SynchronizeCacheListener(
			Map<? extends K, ? extends V> map,
			Synchronizer<K, V> synchronizer) {

			_map = map;
			_synchronizer = synchronizer;
		}

		@Override
		public void notifyEntryEvicted(
			PortalCache<K, V> portalCache, K key, V value) {

			_synchronizer.onSynchronize(_map, key, value);
		}

		@Override
		public void notifyEntryExpired(
			PortalCache<K, V> portalCache, K key, V value) {

			_synchronizer.onSynchronize(_map, key, value);
		}

		@Override
		public void notifyEntryPut(
			PortalCache<K, V> portalCache, K key, V value) {

			_synchronizer.onSynchronize(_map, key, value);
		}

		@Override
		public void notifyEntryRemoved(
			PortalCache<K, V> portalCache, K key, V value) {

			_synchronizer.onSynchronize(_map, key, value);
		}

		@Override
		public void notifyEntryUpdated(
			PortalCache<K, V> portalCache, K key, V value) {

			_synchronizer.onSynchronize(_map, key, value);
		}

		@Override
		public void notifyRemoveAll(PortalCache<K, V> portalCache) {
			_map.clear();
		}

		private Map<? extends K, ? extends V> _map;
		private Synchronizer<K, V> _synchronizer;

	}

}