/*
 * Copyright 2006 Takahiro Nakamura.
 *
 * 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 woolpack.test.ee;

import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;

import javax.servlet.http.HttpSessionBindingListener;

import woolpack.utils.KeyIteratorMap;
import woolpack.utils.UtilsConstants;

/**
 * 静的メソッドの集まり。
 * @author nakamura
 *
 */
public class EETestUtils {

	private EETestUtils(){}// カバレージがここを通過してはいけない
	
	/**
	 * HttpSession における{@link HttpSessionBindingListener}の動作を模倣する{@link ConcurrentMap}を返す。
	 * @return HttpSession における{@link HttpSessionBindingListener}の動作を模倣する{@link ConcurrentMap}。
	 */
	public static ConcurrentMap<String,Object> generateSession(){
		final Map<String,Object> map = new HashMap<String,Object>();

		final Map<String,Object> map3 = new KeyIteratorMap<String,Object>(){

			@Override
			protected Iterator<String> getKeyIterator() {
				return new Iterator<String>(){
					private final Iterator<String> it = map.keySet().iterator();
					private String key;
					public boolean hasNext() {
						return it.hasNext();
					}
					public String next() {
						key = it.next();
						return key;
					}
					public void remove() {
						final Object value = getValue(key);
						if(value instanceof HttpSessionBindingListener){
							((HttpSessionBindingListener)value).valueUnbound(null);
						}
						it.remove();
					}
					
				};
			}

			@Override
			protected Object getValue(final Object key) {
				return map.get(key);
			}
			
			@Override public Object put(final String key, final Object value){
				final Object oldValue = map.put(key, value);
				if(oldValue instanceof HttpSessionBindingListener){
					((HttpSessionBindingListener)oldValue).valueUnbound(null);
				}
				if(value instanceof HttpSessionBindingListener){
					((HttpSessionBindingListener)value).valueBound(null);
				}
				return oldValue;
			}
		};
		final Map<String,Object> map5 = Collections.synchronizedMap(map3);
		return UtilsConstants.concurrentMap(map5, map5);
	}
}
