package org.eclipse.hyades.logging.java.sample;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.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.ReportSituation;
import org.eclipse.hyades.logging.events.cbe.EventFactory;
import org.eclipse.hyades.logging.events.cbe.Situation;
import org.eclipse.hyades.logging.events.cbe.impl.EventFactoryContext;
import org.eclipse.hyades.logging.java.CommonBaseEventLogRecord;

/**********************************************************************
 * 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
 **********************************************************************/

/** 
 * CLASS: HyadesLoggingJava14Sample.java
 * 
 * 
 * DESCRIPTION:  Sample class to demonstrate the usage of the Hyades support for logging Common Base Event log records in JSR-047 logging APIs implemented in JDK 1.4.0 or above.
 * 
 * 
 * ASSUMPTIONS:  1) This class must be executed using JRE 1.4.0 or above.
 *               2) The required JAR files must be specified in the JVM's classpath system variable.
 *               3) JRE 1.4.0 or above must be specified in the PATH environment variable.
 *               4) 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.tests.logging.java.HyadesLoggingJava14Sample' logging agent is added to the Profiling and Logging preferences (Window --> Preferences --> Profiling and Logging --> Logging Agents --> New agent --> Add Agent).
 *               5) 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.
 *               6) When launching this application from the Profiling and Logging Perspective of the Workbench, the Hyades Data Collection Engine application or service is configured to use JRE 1.4.0 or above.
 *               7) The 'java.util.logging.config.file' environment variable is set to the Java logging configuration file's (HyadesLoggingJava14Sample.properties) absolute path and name.  For example, &lt;workspace&gt;/HyadesLoggingJava14Project/config/HyadesLoggingJava14Sample.properties 
 *                  where &lt;workspace&gt; is the absolute path to the workbench's workspace. 
 *
 *                 
 * DEPENDENCIES: The following JAR files are required to compile and execute HyadesLoggingJava14Sample.java:
 * 
 * 		         hexr.jar				-		org.eclipse.hyades.execution.remote
 * 		         hl14.jar				-		org.eclipse.hyades.logging.java14
 * 		         hlcore.jar				-		org.eclipse.hyades.logging.core
 * 		         hlcb101.jar			-		org.eclipse.hyades.logging.core
 *               common.jar             -       org.eclipse.emf.common\runtime
 *               ecore.jar              -       org.eclipse.emf.ecore\runtime
 *
 * 
 * @author	Paul E. Slauenwhite
 * @version	May 6, 2004
 * @since   1.0.1
 * @see		java.util.logging.Handler
 * @see		java.util.logging.Level
 * @see		java.util.logging.Logger
 * @see		org.eclipse.hyades.logging.java.CommonBaseEventLogRecord
 * @see		org.eclipse.hyades.logging.java.LoggingAgentHandler
 * @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 HyadesLoggingJava14Sample {

	//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 Java logger:
	private static final String LOGGERS_NAME = "org.eclipse.hyades.logging.java.sample.HyadesLoggingJava14Sample";

	/**
	 * 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 {

			//Load the Java logging configuration file:
			LogManager.getLogManager().readConfiguration();

			//Create a logger named 'org.eclipse.hyades.logging.java.sample.HyadesLoggingJava14Sample':
			Logger logger = Logger.getLogger(LOGGERS_NAME);

			//Set the logger to log all messages:
			logger.setLevel(Level.ALL);

			//NOTE: Alternatively, create and set the logger's Logging Agent handler programmatically:
			//Create a new instance of a Logging Agent handler:
			//Handler loggingAgentHandler = new LoggingAgentHandler();

			//NOTE: Alternatively, set the Logging Agent Handler's log record formatter programmatically via the handler.setFormatter() API:
			//Set the Logging Agent handler's log record formatter:
			//loggingAgentHandler.setFormatter(new XmlFormatter());

			//NOTE: Alternatively, set the Logging Agent Handler's log record filter programmatically via the handler.setFilter() API:
			//Set the Logging Agent handler's log record filter:
			//loggingAgentHandler.setFilter(new CommonBaseEventFilter());

			//NOTE: Alternatively, set the Logging Agent Handler's logging level programmatically via the handler.setLevel() API:
			//Set the Logging Agent handler's logging level:
			//loggingAgentHandler.setLevel(Level.SEVERE);

			//NOTE: Alternatively, set the logger's Logging Agent handler programmatically via the logger.addHandler() API:
			//Add the LoggingAgentHandler to the logger:
			//logger.addHandler(loggingAgentHandler);

			//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("HyadesLoggingJava14Sample");
			sourceComponentId.setSubComponent("HyadesLoggingJava14Sample.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) (60)));
			commonBaseEvent.setMsg("Java Common Base Event log message");

			//Create a new instance of a Common Base Event log record with the Common Base Event:
			CommonBaseEventLogRecord commonBaseEventLogRecord = new CommonBaseEventLogRecord(commonBaseEvent);

			//Set the Common Base Event log record's logger to the 'org.eclipse.hyades.logging.java.sample.HyadesLoggingJava14Sample' logger:
			commonBaseEventLogRecord.setLoggerName(LOGGERS_NAME);

			//Log the Common Base Event log record:
			logger.log(commonBaseEventLogRecord);

			//Log the an invalid log message (i.e. filtered by the LoggingAgentHandler):
			logger.log(Level.SEVERE, "Java invalid LoggingAgentHandler log message.");

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

			System.out.println("Please attach to the 'org.eclipse.hyades.logging.java.sample.HyadesLoggingJava14Sample' 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 (InterruptedException i) {
			}

			System.out.println("I");

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