/* Copyright (c) 2009, Oracle and/or its affiliates. All rights reserved. */

import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpServer;

public class DICOMServer {
	private HttpServer server;
	
	/**
	 * Start server on the specified port. 
	 */
	private void createServer(int port) throws IOException {
		try {	
			server = HttpServer.create(
			    new InetSocketAddress(port), 0);
			System.out.println(
			    "[LOG] Start server on port " + port);
		} catch (IOException e) {
			System.out.println("[ERROR] Start server");
			throw e;
		}
	}
	
	/**
	 * Start service on the realm of the server. 
	 */
	private void startService(DICOMService service, String realm) {
		/* 
		 * Set authenticator so that every HTTP request for the 
		 * service on that realm will be verified that it comes from 
		 * an authorized user.
		 */
		DICOMAuthenticator authenticator = 
		    new DICOMAuthenticator(realm);
		HttpContext httpContext = server.createContext(realm, service);		
		httpContext.setAuthenticator(authenticator);  
		
		/* Create a thread pool to execute all HTTP request. */
		server.setExecutor(Executors.newCachedThreadPool()); 
		
		/* Start the server. */
		server.start();
		System.out.println("[LOG] Start DICOM service");
	}
	
	/**
	 * Start the DICOM server with port 8080.
	 */
	public static void main(String[] args) {
		try {
			/* Create cache directory. */
			File cacheDir = new File("cache");
			if (cacheDir.exists() == false)
				cacheDir.mkdir();

			/* Create server. */
			DICOMServer dicomServer = new DICOMServer();
			dicomServer.createServer(8080);
			
			/* 
			 * Create a DICOM service. Set the table name in Oracle
			 * Database as data source and specify to load Oracle 
			 * DICOM data model. Then start the service.
			 */
			DICOMService service = new DICOMService();
			service.setDbName("medical_image_table");
			service.setDicomColumn("dicom");
			service.setThumbColumn("imageThumb");
			service.setDataModel(
			    "begin ord_dicom.setDataModel(); end; ");
			dicomServer.startService(service, "/"); 
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
