/* Copyright Dassault Systemes, 1999, 2010 */


package examples.development.applications.mdb;

import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

/**
 * This is a sample job monitor MDB application.  Job status events are written to the
 * application server stdout log.  This application must be packaged in an EAR and
 * deployed in the same cell (WebSphere) or domain (WebLogic) as the SEE application.
 *
 * When deployed in WebSphere, this MDB should be configured with the following
 * listener bindings:
 *
 * activation specification: fiper/act/jobmonitor
 * destination:              fiper/jms/jobmonitor
 * authentication alias:     fiperAdminAuth
 *
 * When deployed in WebLogic, the "mappedName" annotation attribute below will
 * automatically link this MDB to the appropriate messaging resources and no
 * additional configuration is required.
 */

@MessageDriven(mappedName = "fiper/jms/jobmonitor",
			   activationConfig = { @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Topic") ,
		@ActivationConfigProperty(propertyName = "subscriptionDurability", propertyValue = "NonDurable") })
public class ExampleJobMonitor
		implements MessageListener {

	/**
	 * Default constructor.
	 */
	public ExampleJobMonitor() {}

	/**
	 * @see MessageListener#onMessage(Message)
	 * The EJB container will call this method when a message is posted on the jobmonitor
	 * topic.
	 * @param message
	 */
	public void onMessage(Message message) {

		try {

			// Sanity checks

			if (!(message instanceof TextMessage)) {
				throw new Exception("Unexpected message type received by JobMonitor: " + message.getClass().getName());
			}

			// Get job ID and status.  We could also parse the XML body of the message
			// for this data (and more).

			String jobId = message.getStringProperty("jobId");
			if (jobId == null) {
				throw new Exception("Job status message does not contain \"jobId\" property.");
			}

			String jobStatus = message.getStringProperty("status");
			if (jobStatus == null) {
				throw new Exception("Job status message does not contain \"jobStatus\" property.");
			}

			String jobCC = message.getStringProperty("cc");
			if (jobCC == null) {
				jobCC = "n/a";    // Job CC is only valid when status=done
			}

			// Write job status to the server log
			System.out.println("==> Job '" + jobId + "' is in state '" + jobStatus + "' completion code '" + jobCC + "'");

			// Dump the XML too
			System.out.println(((TextMessage)message).getText());

		}
		catch (Throwable e) {
			System.out.println("ERROR: Failed processing job status message.");
			e.printStackTrace(System.out);
			return;
		}


	}

}

