/*
 * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 * 
 * $Id: ExecutorServiceChecker.java 75003 2017-05-30 11:44:57Z jsupol $ 
 */

package com.sun.ts.tests.jaxrs.jaxrs21.ee.client.executor;

import java.io.Closeable;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientRequestFilter;
import javax.ws.rs.core.Response;

import com.sun.ts.tests.jaxrs.ee.rs.core.request.JAXRSClient;

public interface ExecutorServiceChecker extends Closeable {
	final static String THREADPREFIX = "JAXRS_TCK_THREAD";
	static final ThreadFactory THREAD_FACTORY = new ThreadFactory() {
		AtomicInteger ai = new AtomicInteger();

		@Override
		public Thread newThread(Runnable r) {
			return new Thread(r, THREADPREFIX + ai.incrementAndGet());
		}
	};
	final static ExecutorService EXECUTOR_SERVICE = Executors.newFixedThreadPool(5, THREAD_FACTORY);

	default Client createClient() {
		Client c = ClientBuilder.newBuilder().executorService(EXECUTOR_SERVICE).build();
		c.register(threadNameChecker());
		return c;
	}

	default ClientRequestFilter threadNameChecker() {
		return new ClientRequestFilter() {
			@Override
			public void filter(ClientRequestContext requestContext) throws IOException {
				Thread t = Thread.currentThread();
				if (!t.getName().startsWith(THREADPREFIX))
					requestContext
							.abortWith(Response.notAcceptable(null).entity("ThreadExecutor check failed").build());
				JAXRSClient.logMsg("[Client EXECUTOR SERVICE check]: running from thread", t.getName());
			}
		};
	}
		
	default void close() throws IOException {
		EXECUTOR_SERVICE.shutdown();
	}
}
