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

import java.io.StringReader;
import java.util.concurrent.CountDownLatch;

import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.stream.StreamSource;

import junit.framework.TestCase;
import woolpack.LoadAllTests;

public class XmlTransformerFactoryTest extends TestCase {

	public void testTimeNewInstance() throws InterruptedException {
		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 XmlTransformerFactory factory = new XmlTransformerFactoryImpl();
							Thread.yield();
							final XmlTransformer transformer = factory
									.newInstance();
							Thread.yield();
							transformer
									.transform(
											new StreamSource(
													new StringReader(
															"<HTML><BODY>myxml</BODY></HTML>")),
											new DOMResult());
							Thread.yield();
						}
					} finally {
						latch.countDown();
					}
				}
			});
		}
		latch.await();
		System.out.println("XmlTransformerFactoryTest newInstance : "
				+ (System.currentTimeMillis() - t));
	}

	public void testTimeConcurrent() throws InterruptedException {
		final XmlTransformerFactory factory = new XmlTransformerFactorySemaphoreImpl(
				new XmlTransformerFactoryImpl(), LoadAllTests.MAX_THREAD);
		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 XmlTransformer transformer = factory
									.newInstance();
							Thread.yield();
							transformer
									.transform(
											new StreamSource(
													new StringReader(
															"<HTML><BODY>myxml</BODY></HTML>")),
											new DOMResult());
							Thread.yield();
						}
					} finally {
						latch.countDown();
					}
				}
			});
		}
		latch.await();
		System.out.println("XmlTransformerFactoryTest concurrent :"
				+ (System.currentTimeMillis() - t));
	}
}
