/*
 * 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.acquirable;

import java.util.concurrent.Semaphore;
import java.util.regex.Pattern;

import junit.framework.TestCase;
import woolpack.convert.ConvertUtils;
import woolpack.fn.Delegator;
import woolpack.fn.Fn;
import woolpack.fn.FnUtils;
import woolpack.fn.ThrowFn;
import woolpack.utils.Utils;

public class AcquireFnTest extends TestCase {
	public void testNormal() throws InterruptedException {
		final Fn<String, String> fn0 = ConvertUtils.convertRegExp(Pattern.compile("a(\\d\\d)"), "A$1");
		
		final Semaphore semaphore0 = new Semaphore(1, true);
		final Delegator<String, String> delegate = FnUtils.delegate();
		delegate.setFn(fn0);
		final Fn<String, String> fn = AcquirableUtils.acquire(
				FnUtils.switching(
						Utils.map("a00", (Acquirable) new TrySemaphore(semaphore0))),
				delegate,
				ConvertUtils.convertRegExp(Pattern.compile("a(\\d\\d)"), "Z$1"));
		
		// 実行権を取得するのに成功する。
		assertEquals("A00", fn.exec("a00"));
		semaphore0.acquire();
		// 実行権を取得するのに失敗する。処理をブロックしない。
		assertEquals("Z00", fn.exec("a00"));
		// 関係ないidのリクエストとは干渉しない。
		assertEquals("A01", fn.exec("a01"));
		// 取得した実行権を開放する。
		semaphore0.release();
		// 実行権を再取得するのに成功する。
		assertEquals("A00", fn.exec("a00"));
		
		// 委譲先で異常が発生した場合。
		delegate.setFn(new ThrowFn<String, String>(new NullPointerException()));
		try{
			fn.exec("a00");
			fail();
		} catch (final NullPointerException expected) {
		}
		delegate.setFn(fn0);
		// 実行権を再取得するのに成功する。
		assertEquals("A00", fn.exec("a00"));
	}
}
