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

import java.util.HashMap;
import java.util.concurrent.CountDownLatch;

import junit.framework.TestCase;

import org.w3c.dom.Node;

import woolpack.LoadAllTests;
import woolpack.test.TestUtils;

public class CacheNodeLoadTest extends TestCase {

	public void testNoCache() throws InterruptedException {
		final DomExpression expression = new CacheNode(
				new HashMap<Object, Node>(),
				TestUtils
						.getToNodeForm("<SELECT name=\"name0\">"
								+ "<OPTION selected=\"true\" value=\"value0\" >label0</OPTION>"
								+ "<OPTION value=\"value1\" >label1</OPTION>"
								+ "</SELECT>"));

		final long t = System.currentTimeMillis();
		final CountDownLatch latch = new CountDownLatch(LoadAllTests.MAX_THREAD);
		for (int i = 0; i < LoadAllTests.MAX_THREAD; i++) {
			LoadAllTests.THREAD_POOL.execute(new Runnable() {
				public void run() {
					try {
						for (int j = 0; j < LoadAllTests.TEST_COUNT; j++) {
							Thread.yield();
							final DomContext context = new DomContext();
							context.setId("id0");
							Thread.yield();
							expression.interpret(context);
							Thread.yield();
						}
					} finally {
						latch.countDown();
					}
				}
			});
		}
		latch.await();
		System.out.println("CacheNodeLoadTest NoCache : "
				+ (System.currentTimeMillis() - t));
	}

	public void testCache() throws InterruptedException {
		final DomExpression expression = new CacheNode(
				new HashMap<Object, Node>(),
				TestUtils
						.getToNodeForm("<SELECT name=\"name0\">"
								+ "<OPTION selected=\"true\" value=\"value0\" >label0</OPTION>"
								+ "<OPTION value=\"value1\" >label1</OPTION>"
								+ "</SELECT>"));

		final long t = System.currentTimeMillis();
		final CountDownLatch latch = new CountDownLatch(LoadAllTests.MAX_THREAD);
		for (int i = 0; i < LoadAllTests.MAX_THREAD; i++) {
			LoadAllTests.THREAD_POOL.execute(new Runnable() {
				public void run() {
					try {
						for (int j = 0; j < LoadAllTests.TEST_COUNT; j++) {
							Thread.yield();
							final DomContext context = new DomContext();
							context.setId("id0");
							Thread.yield();
							expression.interpret(context);
							Thread.yield();
						}
					} finally {
						latch.countDown();
					}
				}
			});
		}
		latch.await();
		System.out.println("CacheNodeLoadTest Cache : "
				+ (System.currentTimeMillis() - t));
	}
}
