package com.ociweb.JavaAddLib;

import java.util.logging.ConsoleHandler;
import java.util.logging.Handler;
import java.util.logging.Logger;

public class CorbaBase {
	protected org.omg.CORBA.ORB _orb = null;
	
	public void init(String[] args) { 
		SetConsoleLogLevel(java.util.logging.Level.OFF);  // else failures are logged outside of the control of user code
		_orb = org.omg.CORBA.ORB.init(args, null);	
	}
	public void init(int nsPort) { init(nsPort, null); }
	public void init(int nsPort, String nsHost) {
		SetConsoleLogLevel(java.util.logging.Level.OFF);  // else failures are logged outside of the control of user code
        java.util.Properties props = new java.util.Properties();
        props.put("org.omg.CORBA.ORBInitialPort", String.valueOf(nsPort));
        if (nsHost != null)
        	props.put("org.omg.CORBA.ORBInitialHost", nsHost);
        _orb = org.omg.CORBA.ORB.init((String[])null, props);	
	}
	
	public void destroy() {
		if (_orb != null)
			_orb.destroy();
	}
	
	// http://stackoverflow.com/questions/470430/java-util-logging-logger-doesnt-respect-java-util-logging-level
	void SetConsoleLogLevel(java.util.logging.Level level) {
		 //get the top Logger:
	    Logger topLogger = java.util.logging.Logger.getLogger("");

	    // Handler for console (reuse it if it already exists)
	    Handler consoleHandler = null;
	    //see if there is already a console handler
	    for (Handler handler : topLogger.getHandlers()) {
	        if (handler instanceof ConsoleHandler) {
	            //found the console handler
	            consoleHandler = handler;
	            break;
	        }
	    }

	    if (consoleHandler == null) {
	        //there was no console handler found, create a new one
	        consoleHandler = new ConsoleHandler();
	        topLogger.addHandler(consoleHandler);
	    }

	    //set the console handler log level:
	    consoleHandler.setLevel(level);
	}
	
}
