package org.eclipse.hyades.tests.logging.commons;

/**********************************************************************
 * Copyright (c) 2003 Hyades project.
 * All rights reserved.   This program and the accompanying materials
 * are made available under the terms of the Common Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/cpl-v10.html
 * 
 * Contributors: 
 * IBM - Initial API and implementation
 **********************************************************************/

import java.net.InetAddress;
import java.net.UnknownHostException;

import org.apache.commons.logging.LogFactory;
import org.eclipse.hyades.logging.commons.Logger;
import org.eclipse.hyades.logging.core.Guid;
import org.eclipse.hyades.logging.events.cbe.CommonBaseEvent;
import org.eclipse.hyades.logging.events.cbe.ComponentIdentification;
import org.eclipse.hyades.logging.events.cbe.EventFactory;
import org.eclipse.hyades.logging.events.cbe.ReportSituation;
import org.eclipse.hyades.logging.events.cbe.Situation;
import org.eclipse.hyades.logging.events.cbe.impl.EventFactoryContext;

/** 
 * CLASS: CommonsLoggingTest.java
 * 
 * 
 * DESCRIPTION:  Sample class to demonstrate the usage of the Hyades support for logging Common Base Event log records in Apache Commons logging APIs.
 * 
 * 
 * ASSUMPTIONS:  1) The required JAR files must be specified in the JVM's classpath system variable.
 *               2) JRE must be specified in the PATH environment variable.
 *               3) When launching this application from the Profiling and Logging Perspective of the Workbench, logging is enabled in the Profiling and Logging preferences (Window --> Preferences --> Profiling and Logging --> Enable logging) 
 *                  and the 'org.eclipse.hyades.logging.commons.sample.CommonsLoggingTest' logging agent is added to the Profiling and Logging preferences (Window --> Preferences --> Profiling and Logging --> Logging Agents --> New agent --> Add Agent).
 *               4) When either launching this application from the Profiling and Logging Perspective of the Workbench or attaching to a logging agent using the Workbench, the Hyades Data Collection Engine application or service is configured and running.               
 *
 * 
 * DEPENDENCIES: The following JAR files are required to compile and execute CommonsLoggingTest.java:
 * 
 * 		         hexr.jar				-		org.eclipse.hyades.execution.remote
 * 		         hlcore.jar				-		org.eclipse.hyades.logging.core
 * 		         hlcbe101.jar 			-		org.eclipse.hyades.logging.core
 *               commons-logging.jar	-		org.apache.jakarta_commons_logging
 * 		         hlcommons.jar			-		org.eclipse.hyades.logging.commons
 *               common.jar             -       org.eclipse.emf.common\runtime
 *               ecore.jar              -       org.eclipse.emf.ecore\runtime
 *  
 * 
 * @author  Paul Slauenwhite
 * @version	May 6, 2004
 * @since   1.0.1
 * @see		org.apache.commons.logging.Log
 * @see		org.apache.commons.logging.LogFactory
 * @see		org.eclipse.hyades.logging.commons.Logger
 * @see		org.eclipse.hyades.logging.events.cbe.CommonBaseEvent 
 * @see		org.eclipse.hyades.logging.events.cbe.EventFactory
 * @see     org.eclipse.hyades.logging.events.cbe.impl.EventFactoryContext
 */

public class CommonsLoggingTest {

	//Amount of time (seconds) to wait to allow time to attach to the logging agent:
	private static final int WAITTIME = 30;

	//The name of the Apache Commons logger:
	private static final String LOGGERS_NAME = "org.eclipse.hyades.logging.commons.sample.CommonsLoggingTest";

	/**
	 * IP address (IPv4) of the local host, otherwise "127.0.0.1". 
	 */
	private static String localHostIP = null;

	static {
		try {
			localHostIP = InetAddress.getLocalHost().getHostAddress();
		}
		catch (UnknownHostException u) {
			localHostIP = "127.0.0.1";
		}
	}

	public static void main(String[] args) {

		try {

			//Set the Apache Common's logger:
			System.setProperty("org.apache.commons.logging.Log", "org.eclipse.hyades.logging.commons.Logger");

			//Retrieve the log factory based on the current Apache Commons configuration (org.apache.commons.logging.impl.LogFactoryImpl by default):
			LogFactory logFactory = LogFactory.getFactory();

			//Create a logger named 'org.eclipse.hyades.logging.commons.sample.CommonsLoggingTest':
			//NOTE: The retrieved logger must be down-casted to an org.eclipse.hyades.logging.commons.Logger.
			Logger logger = ((Logger) (logFactory.getInstance(LOGGERS_NAME)));

			//Set the logger to log warning or lower messages:
			logger.setLevel(Logger.WARN_LEVEL);

			//Retrieve the instance of the Event Factory:
			EventFactory eventFactory = EventFactoryContext.getInstance().getEventFactoryHome("org.eclipse.hyades.logging.events.cbe.impl.SimpleEventFactoryHomeImpl").getEventFactory(LOGGERS_NAME);

			//Create a new instance of a report situation:
			ReportSituation reportSituation = eventFactory.createReportSituation();
			reportSituation.setReasoningScope("INTERNAL");
			reportSituation.setReportCategory("LOG");

			//Create a new instance of a situation:
			Situation situation = eventFactory.createSituation();
			situation.setCategoryName("ReportSituation");
			situation.setSituationType(reportSituation);

			//Create a new instance of a Source Component:
			ComponentIdentification sourceComponentId = eventFactory.createComponentIdentification();
			sourceComponentId.setLocation(localHostIP);
			sourceComponentId.setLocationType("IPV4");
			sourceComponentId.setExecutionEnvironment("Java");
			sourceComponentId.setComponent("CommonsLoggingTest");
			sourceComponentId.setSubComponent("CommonsLoggingTest.main(String[] args)");
			sourceComponentId.setComponentIdType("Application");
			sourceComponentId.setComponentType("HyadesLoggingSamples");

			//Create a new instance of a Common Base Event:
			CommonBaseEvent commonBaseEvent = eventFactory.createCommonBaseEvent();

			//Set the event's globalInstanceId property with a new GUID:
	        commonBaseEvent.setGlobalInstanceId(Guid.generate());

	        commonBaseEvent.setSourceComponentId(sourceComponentId);
			commonBaseEvent.setSituation(situation);
			commonBaseEvent.setCreationTimeAsLong(System.currentTimeMillis());
			commonBaseEvent.setSeverity(((short) (10)));
			commonBaseEvent.setMsg("Apache Commons Common Base Event log message");

			//Log the Common Base Event log record:
			if (logger.isErrorEnabled()){
				logger.error(commonBaseEvent);
			}

			//Attempt to log a message at a higher logging level:
			if (logger.isDebugEnabled()){
				logger.debug("Apache Commons invalid log message.");
			}

			//Wait for 2 seconds until all log messages are written to the SimpleLog logger (i.e. standard error):
			try {
				Thread.sleep(2000);
			}
			catch (Throwable t) {
			}

			System.out.println("Please attach to the 'org.eclipse.hyades.logging.commons.sample.CommonsLoggingTest' logging agent in the next " + WAITTIME + " second" + (WAITTIME == 1 ? "" : "s") + ":");
			System.out.println("NOTE: When attaching to a logging agent using the Workbench, please remember to enable logging in the Profiling and Logging preferences (Window --> Preferences --> Profiling and Logging --> Enable logging) and the Hyades Data Collection Engine application or service is running.");

			//Create the timer scale:
			System.out.print("I");

			for (int counter = 0; counter < WAITTIME; counter++){
				System.out.print("-");
			}

			System.out.print("I\nI");

			//Increment the timer:
			try {

				for (int counter = 0; counter < WAITTIME; counter++) {

					System.out.print("-");

					Thread.sleep(1000);
				}
			}
			catch (Throwable t) {
			}

			System.out.println("I");

			System.out.println("CommonsLoggingTest successfully ended!");
		}
		catch (Throwable t) {
			System.out.println("ERROR - CommonsLoggingTest unsuccessfully ended!");
			System.out.println("REASON: " + t.getMessage());
		}
	}
}
