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

import java.util.concurrent.CountDownLatch;

import junit.framework.TestCase;

import org.w3c.dom.Node;

import woolpack.LoadAllTests;
import woolpack.fn.Fn;
import woolpack.xml.NodeFindable;
import woolpack.xml.NodeFindableFactory;
import woolpack.xml.XmlUtils;

public class NodeFindableLoadTest extends TestCase {
	private int count = 200; // LoadAllTests.TEST_COUNT;

	public void testTimeJavaxXmlXpath() throws InterruptedException {
		final Node node = XmlUtils.convert("<HTML><BODY>myxml</BODY></HTML>");
		final Fn<String, NodeFindable> factory = new NodeFindableFactory();
		final NodeFindable w = factory.exec("//BODY");
		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 < count; j++) {
							Thread.yield();
							w.evaluateOne(node);
							// final Node n = w.evaluateOne(node);
							// if(j == 0) {
							// System.out.println(n.getNodeName());
							// }
							Thread.yield();
						}
					} finally {
						latch.countDown();
					}
				}
			});
		}
		latch.await();
		System.out.println("NodeFindableLoadTest JavaxXmlXpath : "
				+ (System.currentTimeMillis() - t));
	}

	public void testTimeJXPath() throws InterruptedException {
		final Node node = XmlUtils.convert("<HTML><BODY>myxml</BODY></HTML>");
		final NodeFindable w = new JXP("//BODY");
		w.evaluateOne(node);
		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 < count; j++) {
							Thread.yield();
							w.evaluateOne(node);
							// final Node n = w.evaluateOne(node);
							// if(j == 0) {
							// System.out.println(n.getNodeName());
							// }
							Thread.yield();
						}
					} finally {
						latch.countDown();
					}
				}
			});
		}
		latch.await();
		System.out.println("NodeFindableLoadTest JXPath : "
				+ (System.currentTimeMillis() - t));
	}
}
